gstsystemclock.c 32 KB
Newer Older
1 2
/* GStreamer
 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3
 *                    2004 Wim Taymans <wim@fluendo.com>
4
 *
5
 * gstsystemclock.c: Default clock, uses the system clock
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
19 20
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
21
 */
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
22

Stefan Kost's avatar
Stefan Kost committed
23 24
/**
 * SECTION:gstsystemclock
25
 * @title: GstSystemClock
Stefan Kost's avatar
Stefan Kost committed
26 27 28
 * @short_description: Default clock that uses the current system time
 * @see_also: #GstClock
 *
Wim Taymans's avatar
Wim Taymans committed
29 30 31 32 33 34 35 36 37
 * The GStreamer core provides a GstSystemClock based on the system time.
 * Asynchronous callbacks are scheduled from an internal thread.
 *
 * Clock implementors are encouraged to subclass this systemclock as it
 * implements the async notification.
 *
 * Subclasses can however override all of the important methods for sync and
 * async notifications to implement their own callback methods or blocking
 * wait operations.
Stefan Kost's avatar
Stefan Kost committed
38
 */
39 40

#include "gst_private.h"
41
#include "gstinfo.h"
42
#include "gstsystemclock.h"
43
#include "gstenumtypes.h"
44
#include "gstpoll.h"
45
#include "gstutils.h"
46
#include "glib-compat-private.h"
47

48 49
#include <errno.h>

50 51 52 53
#ifdef G_OS_WIN32
#  define WIN32_LEAN_AND_MEAN   /* prevents from including too many things */
#  include <windows.h>          /* QueryPerformance* stuff */
#  undef WIN32_LEAN_AND_MEAN
54
#  ifndef EWOULDBLOCK
55
#  define EWOULDBLOCK EAGAIN    /* This is just to placate gcc */
56
#  endif
57 58
#endif /* G_OS_WIN32 */

59 60 61 62
#ifdef __APPLE__
#include <mach/mach_time.h>
#endif

63
#define GET_ENTRY_STATUS(e)          ((GstClockReturn) g_atomic_int_get(&GST_CLOCK_ENTRY_STATUS(e)))
64
#define SET_ENTRY_STATUS(e,val)      (g_atomic_int_set(&GST_CLOCK_ENTRY_STATUS(e),(val)))
65
#define CAS_ENTRY_STATUS(e,old,val)  (g_atomic_int_compare_and_exchange(\
66
                                       (&GST_CLOCK_ENTRY_STATUS(e)), (old), (val)))
67

68 69 70
/* Define this to get some extra debug about jitter from each clock_wait */
#undef WAIT_DEBUGGING

Wim Taymans's avatar
Wim Taymans committed
71 72 73 74 75
#define GST_SYSTEM_CLOCK_GET_COND(clock)        (&GST_SYSTEM_CLOCK_CAST(clock)->priv->entries_changed)
#define GST_SYSTEM_CLOCK_WAIT(clock)            g_cond_wait(GST_SYSTEM_CLOCK_GET_COND(clock),GST_OBJECT_GET_LOCK(clock))
#define GST_SYSTEM_CLOCK_TIMED_WAIT(clock,tv)   g_cond_timed_wait(GST_SYSTEM_CLOCK_GET_COND(clock),GST_OBJECT_GET_LOCK(clock),tv)
#define GST_SYSTEM_CLOCK_BROADCAST(clock)       g_cond_broadcast(GST_SYSTEM_CLOCK_GET_COND(clock))

76 77
struct _GstSystemClockPrivate
{
78 79 80
  GThread *thread;              /* thread for async notify */
  gboolean stopping;

Wim Taymans's avatar
Wim Taymans committed
81 82
  GList *entries;
  GCond entries_changed;
83

84 85
  GstClockType clock_type;
  GstPoll *timer;
86 87
  gint wakeup_count;            /* the number of entries with a pending wakeup */
  gboolean async_wakeup;        /* if the wakeup was because of a async list change */
88 89 90 91

#ifdef G_OS_WIN32
  LARGE_INTEGER start;
  LARGE_INTEGER frequency;
92
  guint64 ratio;
93
#endif                          /* G_OS_WIN32 */
94 95 96
#ifdef __APPLE__
  struct mach_timebase_info mach_timebase;
#endif
97 98
};

99 100 101 102 103 104 105 106 107 108
#ifdef HAVE_POSIX_TIMERS
# ifdef HAVE_MONOTONIC_CLOCK
#  define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_MONOTONIC
# else
#  define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_REALTIME
# endif
#else
#define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_REALTIME
#endif

109 110 111 112 113 114 115
enum
{
  PROP_0,
  PROP_CLOCK_TYPE,
  /* FILL ME */
};

116
/* the one instance of the systemclock */
117
static GstClock *_the_system_clock = NULL;
118
static gboolean _external_default_clock = FALSE;
119

120
static void gst_system_clock_dispose (GObject * object);
121 122 123 124
static void gst_system_clock_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
static void gst_system_clock_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);
125

126 127
static GstClockTime gst_system_clock_get_internal_time (GstClock * clock);
static guint64 gst_system_clock_get_resolution (GstClock * clock);
128 129 130
static GstClockReturn gst_system_clock_id_wait_jitter (GstClock * clock,
    GstClockEntry * entry, GstClockTimeDiff * jitter);
static GstClockReturn gst_system_clock_id_wait_jitter_unlocked
131 132
    (GstClock * clock, GstClockEntry * entry, GstClockTimeDiff * jitter,
    gboolean restart);
133 134 135
static GstClockReturn gst_system_clock_id_wait_async (GstClock * clock,
    GstClockEntry * entry);
static void gst_system_clock_id_unschedule (GstClock * clock,
136
    GstClockEntry * entry);
137
static void gst_system_clock_async_thread (GstClock * clock);
138
static gboolean gst_system_clock_start_async (GstSystemClock * clock);
139
static void gst_system_clock_add_wakeup (GstSystemClock * sysclock);
140

141
static GMutex _gst_sysclock_mutex;
142 143 144

/* static guint gst_system_clock_signals[LAST_SIGNAL] = { 0 }; */

Wim Taymans's avatar
Wim Taymans committed
145
#define gst_system_clock_parent_class parent_class
146
G_DEFINE_TYPE_WITH_PRIVATE (GstSystemClock, gst_system_clock, GST_TYPE_CLOCK);
147 148

static void
149
gst_system_clock_class_init (GstSystemClockClass * klass)
150 151 152 153
{
  GObjectClass *gobject_class;
  GstClockClass *gstclock_class;

154 155
  gobject_class = (GObjectClass *) klass;
  gstclock_class = (GstClockClass *) klass;
156

157
  gobject_class->dispose = gst_system_clock_dispose;
158 159 160 161 162 163
  gobject_class->set_property = gst_system_clock_set_property;
  gobject_class->get_property = gst_system_clock_get_property;

  g_object_class_install_property (gobject_class, PROP_CLOCK_TYPE,
      g_param_spec_enum ("clock-type", "Clock type",
          "The type of underlying clock implementation used",
164 165
          GST_TYPE_CLOCK_TYPE, DEFAULT_CLOCK_TYPE,
          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
Wim Taymans's avatar
Wim Taymans committed
166

167 168
  gstclock_class->get_internal_time = gst_system_clock_get_internal_time;
  gstclock_class->get_resolution = gst_system_clock_get_resolution;
Wim Taymans's avatar
Wim Taymans committed
169
  gstclock_class->wait = gst_system_clock_id_wait_jitter;
170 171
  gstclock_class->wait_async = gst_system_clock_id_wait_async;
  gstclock_class->unschedule = gst_system_clock_id_unschedule;
172 173 174
}

static void
175
gst_system_clock_init (GstSystemClock * clock)
176
{
Wim Taymans's avatar
Wim Taymans committed
177 178
  GstSystemClockPrivate *priv;

179
  GST_OBJECT_FLAG_SET (clock,
180 181 182
      GST_CLOCK_FLAG_CAN_DO_SINGLE_SYNC |
      GST_CLOCK_FLAG_CAN_DO_SINGLE_ASYNC |
      GST_CLOCK_FLAG_CAN_DO_PERIODIC_SYNC |
183
      GST_CLOCK_FLAG_CAN_DO_PERIODIC_ASYNC);
184

185
  clock->priv = priv = gst_system_clock_get_instance_private (clock);
Wim Taymans's avatar
Wim Taymans committed
186 187 188

  priv->clock_type = DEFAULT_CLOCK_TYPE;
  priv->timer = gst_poll_new_timer ();
189

Wim Taymans's avatar
Wim Taymans committed
190 191
  priv->entries = NULL;
  g_cond_init (&priv->entries_changed);
192

193
#ifdef G_OS_WIN32
Wim Taymans's avatar
Wim Taymans committed
194
  QueryPerformanceFrequency (&priv->frequency);
195
  /* can be 0 if the hardware does not have hardware support */
Wim Taymans's avatar
Wim Taymans committed
196
  if (priv->frequency.QuadPart != 0)
197
    /* we take a base time so that time starts from 0 to ease debugging */
Wim Taymans's avatar
Wim Taymans committed
198
    QueryPerformanceCounter (&priv->start);
199
  priv->ratio = GST_SECOND / priv->frequency.QuadPart;
200 201
#endif /* G_OS_WIN32 */

202 203 204 205
#ifdef __APPLE__
  mach_timebase_info (&priv->mach_timebase);
#endif

206 207
#if 0
  /* Uncomment this to start the async clock thread straight away */
208
  GST_OBJECT_LOCK (clock);
209
  gst_system_clock_start_async (clock);
210
  GST_OBJECT_UNLOCK (clock);
211
#endif
212 213
}

Wim Taymans's avatar
Wim Taymans committed
214
static void
215
gst_system_clock_dispose (GObject * object)
Wim Taymans's avatar
Wim Taymans committed
216
{
Benjamin Otte's avatar
Benjamin Otte committed
217
  GstClock *clock = (GstClock *) object;
218
  GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
Wim Taymans's avatar
Wim Taymans committed
219
  GstSystemClockPrivate *priv = sysclock->priv;
220
  GList *entries;
Benjamin Otte's avatar
Benjamin Otte committed
221

222
  /* else we have to stop the thread */
223
  GST_OBJECT_LOCK (clock);
Wim Taymans's avatar
Wim Taymans committed
224
  priv->stopping = TRUE;
225
  /* unschedule all entries */
Wim Taymans's avatar
Wim Taymans committed
226
  for (entries = priv->entries; entries; entries = g_list_next (entries)) {
227
    GstClockEntry *entry = (GstClockEntry *) entries->data;
228

229
    GST_CAT_DEBUG (GST_CAT_CLOCK, "unscheduling entry %p", entry);
230
    SET_ENTRY_STATUS (entry, GST_CLOCK_UNSCHEDULED);
231
  }
Wim Taymans's avatar
Wim Taymans committed
232
  GST_SYSTEM_CLOCK_BROADCAST (clock);
233
  gst_system_clock_add_wakeup (sysclock);
234
  GST_OBJECT_UNLOCK (clock);
235

Wim Taymans's avatar
Wim Taymans committed
236 237 238
  if (priv->thread)
    g_thread_join (priv->thread);
  priv->thread = NULL;
239
  GST_CAT_DEBUG (GST_CAT_CLOCK, "joined thread");
240

Wim Taymans's avatar
Wim Taymans committed
241 242 243
  g_list_foreach (priv->entries, (GFunc) gst_clock_id_unref, NULL);
  g_list_free (priv->entries);
  priv->entries = NULL;
244

Wim Taymans's avatar
Wim Taymans committed
245 246
  gst_poll_free (priv->timer);
  g_cond_clear (&priv->entries_changed);
247

248 249 250 251 252
  G_OBJECT_CLASS (parent_class)->dispose (object);

  if (_the_system_clock == clock) {
    _the_system_clock = NULL;
    GST_CAT_DEBUG (GST_CAT_CLOCK, "disposed system clock");
Benjamin Otte's avatar
Benjamin Otte committed
253
  }
Wim Taymans's avatar
Wim Taymans committed
254 255
}

256 257 258 259 260 261 262 263
static void
gst_system_clock_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstSystemClock *sysclock = GST_SYSTEM_CLOCK (object);

  switch (prop_id) {
    case PROP_CLOCK_TYPE:
264
      sysclock->priv->clock_type = (GstClockType) g_value_get_enum (value);
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
      GST_CAT_DEBUG (GST_CAT_CLOCK, "clock-type set to %d",
          sysclock->priv->clock_type);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_system_clock_get_property (GObject * object, guint prop_id, GValue * value,
    GParamSpec * pspec)
{
  GstSystemClock *sysclock = GST_SYSTEM_CLOCK (object);

  switch (prop_id) {
    case PROP_CLOCK_TYPE:
      g_value_set_enum (value, sysclock->priv->clock_type);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

290 291
/**
 * gst_system_clock_set_default:
292
 * @new_clock: (allow-none): a #GstClock
293 294
 *
 * Sets the default system clock that can be obtained with
295
 * gst_system_clock_obtain().
296 297 298 299 300 301
 *
 * This is mostly used for testing and debugging purposes when you
 * want to have control over the time reported by the default system
 * clock.
 *
 * MT safe.
302 303
 *
 * Since: 1.4
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
 */
void
gst_system_clock_set_default (GstClock * new_clock)
{
  GstClock *clock;

  g_mutex_lock (&_gst_sysclock_mutex);
  clock = _the_system_clock;

  if (clock != NULL)
    g_object_unref (clock);

  if (new_clock == NULL) {
    GST_CAT_DEBUG (GST_CAT_CLOCK, "resetting default system clock");
    _external_default_clock = FALSE;
  } else {
    GST_CAT_DEBUG (GST_CAT_CLOCK, "setting new default system clock to %p",
        new_clock);
    _external_default_clock = TRUE;
    g_object_ref (new_clock);
  }
  _the_system_clock = new_clock;
  g_mutex_unlock (&_gst_sysclock_mutex);
}

Wim Taymans's avatar
Wim Taymans committed
329
/**
330
 * gst_system_clock_obtain:
Wim Taymans's avatar
Wim Taymans committed
331
 *
332
 * Get a handle to the default system clock. The refcount of the
333
 * clock will be increased so you need to unref the clock after
334
 * usage.
Wim Taymans's avatar
Wim Taymans committed
335
 *
336
 * Returns: (transfer full): the default clock.
337 338
 *
 * MT safe.
Wim Taymans's avatar
Wim Taymans committed
339
 */
340
GstClock *
341 342
gst_system_clock_obtain (void)
{
343
  GstClock *clock;
Wim Taymans's avatar
Wim Taymans committed
344

345
  g_mutex_lock (&_gst_sysclock_mutex);
346
  clock = _the_system_clock;
347

348
  if (clock == NULL) {
349
    GST_CAT_DEBUG (GST_CAT_CLOCK, "creating new static system clock");
350
    g_assert (!_external_default_clock);
351 352
    clock = g_object_new (GST_TYPE_SYSTEM_CLOCK,
        "name", "GstSystemClock", NULL);
Wim Taymans's avatar
Wim Taymans committed
353

354 355
    /* Clear floating flag */
    gst_object_ref_sink (clock);
Wim Taymans's avatar
Wim Taymans committed
356
    _the_system_clock = clock;
357
    g_mutex_unlock (&_gst_sysclock_mutex);
358
  } else {
359
    g_mutex_unlock (&_gst_sysclock_mutex);
360
    GST_CAT_DEBUG (GST_CAT_CLOCK, "returning static system clock");
361
  }
Wim Taymans's avatar
Wim Taymans committed
362

363
  /* we ref it since we are a clock factory. */
364
  gst_object_ref (clock);
Wim Taymans's avatar
Wim Taymans committed
365
  return clock;
366 367
}

368
static void
369
gst_system_clock_remove_wakeup (GstSystemClock * sysclock)
370
{
371 372 373
  g_return_if_fail (sysclock->priv->wakeup_count > 0);

  sysclock->priv->wakeup_count--;
374 375 376 377 378 379 380 381 382
  GST_CAT_DEBUG (GST_CAT_CLOCK, "reading control");
  while (!gst_poll_read_control (sysclock->priv->timer)) {
    if (errno == EWOULDBLOCK) {
      /* Try again and give other threads the chance to do something */
      g_thread_yield ();
      continue;
    } else {
      /* Critical error, GstPoll will have printed a critical warning already */
      break;
383 384
    }
  }
385
  GST_SYSTEM_CLOCK_BROADCAST (sysclock);
386 387
  GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup count %d",
      sysclock->priv->wakeup_count);
388 389 390
}

static void
391
gst_system_clock_add_wakeup (GstSystemClock * sysclock)
392
{
393 394
  GST_CAT_DEBUG (GST_CAT_CLOCK, "writing control");
  gst_poll_write_control (sysclock->priv->timer);
395 396 397 398
  sysclock->priv->wakeup_count++;
  GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup count %d",
      sysclock->priv->wakeup_count);
}
399

400 401 402
static void
gst_system_clock_wait_wakeup (GstSystemClock * sysclock)
{
403
  while (sysclock->priv->wakeup_count > 0) {
Wim Taymans's avatar
Wim Taymans committed
404
    GST_SYSTEM_CLOCK_WAIT (sysclock);
405 406 407
  }
}

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
408
/* this thread reads the sorted clock entries from the queue.
409 410 411
 *
 * It waits on each of them and fires the callback when the timeout occurs.
 *
412 413
 * When an entry in the queue was canceled before we wait for it, it is
 * simply skipped.
414
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
415
 * When waiting for an entry, it can become canceled, in that case we don't
416 417 418 419 420 421 422
 * call the callback but move to the next item in the queue.
 *
 * MT safe.
 */
static void
gst_system_clock_async_thread (GstClock * clock)
{
423
  GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
Wim Taymans's avatar
Wim Taymans committed
424
  GstSystemClockPrivate *priv = sysclock->priv;
425
  GstClockReturn status;
426 427

  GST_CAT_DEBUG (GST_CAT_CLOCK, "enter system clock thread");
428
  GST_OBJECT_LOCK (clock);
429
  /* signal spinup */
Wim Taymans's avatar
Wim Taymans committed
430
  GST_SYSTEM_CLOCK_BROADCAST (clock);
431
  /* now enter our (almost) infinite loop */
Wim Taymans's avatar
Wim Taymans committed
432
  while (!priv->stopping) {
433
    GstClockEntry *entry;
434
    GstClockTime requested;
435 436 437
    GstClockReturn res;

    /* check if something to be done */
Wim Taymans's avatar
Wim Taymans committed
438
    while (priv->entries == NULL) {
439
      GST_CAT_DEBUG (GST_CAT_CLOCK, "no clock entries, waiting..");
440
      /* wait for work to do */
Wim Taymans's avatar
Wim Taymans committed
441
      GST_SYSTEM_CLOCK_WAIT (clock);
442 443
      GST_CAT_DEBUG (GST_CAT_CLOCK, "got signal");
      /* clock was stopping, exit */
Wim Taymans's avatar
Wim Taymans committed
444
      if (priv->stopping)
445 446 447
        goto exit;
    }

448 449
    /* see if we have a pending wakeup because the order of the list
     * changed. */
Wim Taymans's avatar
Wim Taymans committed
450
    if (priv->async_wakeup) {
451 452
      GST_CAT_DEBUG (GST_CAT_CLOCK, "clear async wakeup");
      gst_system_clock_remove_wakeup (sysclock);
Wim Taymans's avatar
Wim Taymans committed
453
      priv->async_wakeup = FALSE;
454 455
    }

456
    /* pick the next entry */
Wim Taymans's avatar
Wim Taymans committed
457
    entry = priv->entries->data;
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478

    /* set entry status to busy before we release the clock lock */
    do {
      status = GET_ENTRY_STATUS (entry);

      /* check for unscheduled */
      if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
        /* entry was unscheduled, move to the next one */
        GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry %p unscheduled", entry);
        goto next_entry;
      }

      /* for periodic timers, status can be EARLY from a previous run */
      if (G_UNLIKELY (status != GST_CLOCK_OK && status != GST_CLOCK_EARLY))
        GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
            status, entry);

      /* mark the entry as busy but watch out for intermediate unscheduled
       * statuses */
    } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_BUSY)));

479
    GST_OBJECT_UNLOCK (clock);
480

481 482
    requested = entry->time;

483
    /* now wait for the entry */
484 485
    res =
        gst_system_clock_id_wait_jitter_unlocked (clock, (GstClockID) entry,
486
        NULL, FALSE);
487

488 489
    GST_OBJECT_LOCK (clock);

490 491 492 493 494 495 496 497 498 499
    switch (res) {
      case GST_CLOCK_UNSCHEDULED:
        /* entry was unscheduled, move to the next */
        GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry %p unscheduled", entry);
        goto next_entry;
      case GST_CLOCK_OK:
      case GST_CLOCK_EARLY:
      {
        /* entry timed out normally, fire the callback and move to the next
         * entry */
500
        GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry %p timed out", entry);
501
        if (entry->func) {
502
          /* unlock before firing the callback */
503
          GST_OBJECT_UNLOCK (clock);
504 505
          entry->func (clock, entry->time, (GstClockID) entry,
              entry->user_data);
506
          GST_OBJECT_LOCK (clock);
507 508
        }
        if (entry->type == GST_CLOCK_ENTRY_PERIODIC) {
Wim Taymans's avatar
Wim Taymans committed
509
          GST_CAT_DEBUG (GST_CAT_CLOCK, "updating periodic entry %p", entry);
510
          /* adjust time now */
511
          entry->time = requested + entry->interval;
512
          /* and resort the list now */
Wim Taymans's avatar
Wim Taymans committed
513 514
          priv->entries =
              g_list_sort (priv->entries, gst_clock_id_compare_func);
515 516 517
          /* and restart */
          continue;
        } else {
518
          GST_CAT_DEBUG (GST_CAT_CLOCK, "moving to next entry");
519 520 521 522 523
          goto next_entry;
        }
      }
      case GST_CLOCK_BUSY:
        /* somebody unlocked the entry but is was not canceled, This means that
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
524
         * either a new entry was added in front of the queue or some other entry
525 526 527
         * was canceled. Whatever it is, pick the head entry of the list and
         * continue waiting. */
        GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry %p needs restart", entry);
Wim Taymans's avatar
Wim Taymans committed
528

529 530 531
        /* we set the entry back to the OK state. This is needed so that the
         * _unschedule() code can see if an entry is currently being waited
         * on (when its state is BUSY). */
532
        SET_ENTRY_STATUS (entry, GST_CLOCK_OK);
533 534 535 536
        continue;
      default:
        GST_CAT_DEBUG (GST_CAT_CLOCK,
            "strange result %d waiting for %p, skipping", res, entry);
537 538
        g_warning ("%s: strange result %d waiting for %p, skipping",
            GST_OBJECT_NAME (clock), res, entry);
539 540 541 542
        goto next_entry;
    }
  next_entry:
    /* we remove the current entry and unref it */
Wim Taymans's avatar
Wim Taymans committed
543
    priv->entries = g_list_remove (priv->entries, entry);
544 545 546 547
    gst_clock_id_unref ((GstClockID) entry);
  }
exit:
  /* signal exit */
Wim Taymans's avatar
Wim Taymans committed
548
  GST_SYSTEM_CLOCK_BROADCAST (clock);
549
  GST_OBJECT_UNLOCK (clock);
550 551 552
  GST_CAT_DEBUG (GST_CAT_CLOCK, "exit system clock thread");
}

553 554 555 556 557 558 559 560 561 562 563 564 565
#ifdef HAVE_POSIX_TIMERS
static inline clockid_t
clock_type_to_posix_id (GstClockType clock_type)
{
#ifdef HAVE_MONOTONIC_CLOCK
  if (clock_type == GST_CLOCK_TYPE_MONOTONIC)
    return CLOCK_MONOTONIC;
  else
#endif
    return CLOCK_REALTIME;
}
#endif

566
/* MT safe */
567
static GstClockTime
568
gst_system_clock_get_internal_time (GstClock * clock)
569
{
570 571 572 573 574 575
#if defined __APPLE__
  GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
  uint64_t mach_t = mach_absolute_time ();
  return gst_util_uint64_scale (mach_t, sysclock->priv->mach_timebase.numer,
      sysclock->priv->mach_timebase.denom);
#else
576
#ifdef G_OS_WIN32
577 578 579
  GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);

  if (sysclock->priv->frequency.QuadPart != 0) {
580 581 582 583
    LARGE_INTEGER now;

    /* we prefer the highly accurate performance counters on windows */
    QueryPerformanceCounter (&now);
584

585 586
    return ((now.QuadPart -
            sysclock->priv->start.QuadPart) * sysclock->priv->ratio);
587 588
  } else
#endif /* G_OS_WIN32 */
LRN's avatar
LRN committed
589
#if !defined HAVE_POSIX_TIMERS || !defined HAVE_CLOCK_GETTIME
590 591
  {
    GTimeVal timeval;
592

593
    g_get_current_time (&timeval);
594

595 596
    return GST_TIMEVAL_TO_TIME (timeval);
  }
597
#else
598 599 600 601 602 603
  {
    GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
    clockid_t ptype;
    struct timespec ts;

    ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
604

605 606
    if (G_UNLIKELY (clock_gettime (ptype, &ts)))
      return GST_CLOCK_TIME_NONE;
607

608 609
    return GST_TIMESPEC_TO_TIME (ts);
  }
610
#endif
611
#endif /* __APPLE__ */
612 613 614
}

static guint64
615
gst_system_clock_get_resolution (GstClock * clock)
616
{
617 618 619 620 621
#if defined __APPLE__
  GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
  return gst_util_uint64_scale (GST_NSECOND,
      sysclock->priv->mach_timebase.numer, sysclock->priv->mach_timebase.denom);
#else
622
#ifdef G_OS_WIN32
623 624 625
  GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);

  if (sysclock->priv->frequency.QuadPart != 0) {
626 627 628
    return GST_SECOND / sysclock->priv->frequency.QuadPart;
  } else
#endif /* G_OS_WIN32 */
LRN's avatar
LRN committed
629
#if defined(HAVE_POSIX_TIMERS) && defined(HAVE_CLOCK_GETTIME)
630 631 632 633
  {
    GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
    clockid_t ptype;
    struct timespec ts;
634

635
    ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
636

637 638
    if (G_UNLIKELY (clock_getres (ptype, &ts)))
      return GST_CLOCK_TIME_NONE;
639

640 641
    return GST_TIMESPEC_TO_TIME (ts);
  }
642
#else
643 644 645
  {
    return 1 * GST_USECOND;
  }
646
#endif
647
#endif /* __APPLE__ */
648 649
}

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
static inline void
gst_system_clock_cleanup_unscheduled (GstSystemClock * sysclock,
    GstClockEntry * entry)
{
  /* try to clean up.
   * The unschedule function managed to set the status to
   * unscheduled. We now take the lock and mark the entry as unscheduled.
   * This makes sure that the unschedule function doesn't perform a
   * wakeup anymore. If the unschedule function has a change to perform
   * the wakeup before us, we clean up here */
  GST_OBJECT_LOCK (sysclock);
  entry->unscheduled = TRUE;
  if (entry->woken_up) {
    gst_system_clock_remove_wakeup (sysclock);
  }
  GST_OBJECT_UNLOCK (sysclock);
}

668 669
/* synchronously wait on the given GstClockEntry.
 *
670 671 672
 * We do this by blocking on the global GstPoll timer with
 * the requested timeout. This allows us to unblock the
 * entry by writing on the control fd.
673
 *
674
 * Note that writing the global GstPoll unlocks all waiting entries. So
675 676 677 678 679 680 681 682
 * we need to check if an unlocked entry has changed when it unlocks.
 *
 * Entries that arrive too late are simply not waited on and a
 * GST_CLOCK_EARLY result is returned.
 *
 * MT safe.
 */
static GstClockReturn
683
gst_system_clock_id_wait_jitter_unlocked (GstClock * clock,
684
    GstClockEntry * entry, GstClockTimeDiff * jitter, gboolean restart)
685
{
686
  GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
687
  GstClockTime entryt, now;
688
  GstClockTimeDiff diff;
689 690
  GstClockReturn status;

691
  status = GET_ENTRY_STATUS (entry);
692 693
  if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
    gst_system_clock_cleanup_unscheduled (sysclock, entry);
694
    return GST_CLOCK_UNSCHEDULED;
695
  }
696

697 698
  /* need to call the overridden method because we want to sync against the time
   * of the clock, whatever the subclass uses as a clock. */
699
  now = gst_clock_get_time (clock);
700 701

  /* get the time of the entry */
702
  entryt = GST_CLOCK_ENTRY_TIME (entry);
703

704 705
  /* the diff of the entry with the clock is the amount of time we have to
   * wait */
706 707 708
  diff = GST_CLOCK_DIFF (now, entryt);
  if (G_LIKELY (jitter))
    *jitter = -diff;
709

710
  GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p"
711
      " time %" GST_TIME_FORMAT
712
      " now %" GST_TIME_FORMAT
713
      " diff (time-now) %" G_GINT64_FORMAT,
714
      entry, GST_TIME_ARGS (entryt), GST_TIME_ARGS (now), diff);
715

716
  if (G_LIKELY (diff > 0)) {
717
#ifdef WAIT_DEBUGGING
718
    GstClockTime final;
719 720
#endif

721
    while (TRUE) {
722
      gint pollret;
723

724
      /* now wait on the entry, it either times out or the fd is written. The
725
       * status of the entry is BUSY only around the poll. */
726 727
      pollret = gst_poll_wait (sysclock->priv->timer, diff);

728 729 730 731 732 733 734 735
      /* get the new status, mark as DONE. We do this so that the unschedule
       * function knows when we left the poll and doesn't need to wakeup the
       * poll anymore. */
      do {
        status = GET_ENTRY_STATUS (entry);
        /* we were unscheduled, exit immediately */
        if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
          break;
736 737 738
        if (G_UNLIKELY (status != GST_CLOCK_BUSY))
          GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
              status, entry);
739 740 741 742 743 744
      } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_DONE)));

      GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p unlocked, status %d, ret %d",
          entry, status, pollret);

      if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
745
        gst_system_clock_cleanup_unscheduled (sysclock, entry);
746
        goto done;
747
      } else {
748
        if (G_UNLIKELY (pollret != 0)) {
749 750 751 752 753
          /* some other id got unlocked */
          if (!restart) {
            /* this can happen if the entry got unlocked because of an async
             * entry was added to the head of the async queue. */
            GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup waiting for entry %p", entry);
754
            goto done;
755 756
          }

757
          /* wait till all the entries got woken up */
758
          GST_OBJECT_LOCK (sysclock);
759
          gst_system_clock_wait_wakeup (sysclock);
760
          GST_OBJECT_UNLOCK (sysclock);
761 762 763 764 765 766 767 768 769 770

          GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p needs to be restarted",
              entry);
        } else {
          GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p unlocked after timeout",
              entry);
        }

        /* reschedule if gst_poll_wait returned early or we have to reschedule after
         * an unlock*/
771 772
        now = gst_clock_get_time (clock);
        diff = GST_CLOCK_DIFF (now, entryt);
773 774 775

        if (diff <= 0) {
          /* timeout, this is fine, we can report success now */
776 777
          if (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, GST_CLOCK_DONE,
                      GST_CLOCK_OK))) {
778
            status = GET_ENTRY_STATUS (entry);
779 780 781
            if (status != GST_CLOCK_UNSCHEDULED)
              GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
                  status, entry);
782 783 784 785
            goto done;
          } else {
            status = GST_CLOCK_OK;
          }
786 787 788 789 790 791 792 793 794 795 796 797 798

          GST_CAT_DEBUG (GST_CAT_CLOCK,
              "entry %p finished, diff %" G_GINT64_FORMAT, entry, diff);

#ifdef WAIT_DEBUGGING
          final = gst_system_clock_get_internal_time (clock);
          GST_CAT_DEBUG (GST_CAT_CLOCK, "Waited for %" G_GINT64_FORMAT
              " got %" G_GINT64_FORMAT " diff %" G_GINT64_FORMAT
              " %g target-offset %" G_GINT64_FORMAT " %g", entryt, now,
              now - entryt,
              (double) (GstClockTimeDiff) (now - entryt) / GST_SECOND,
              (final - target),
              ((double) (GstClockTimeDiff) (final - target)) / GST_SECOND);
799
#endif
800
          goto done;
801 802 803
        } else {
          GST_CAT_DEBUG (GST_CAT_CLOCK,
              "entry %p restart, diff %" G_GINT64_FORMAT, entry, diff);
804 805 806 807 808 809 810 811 812 813 814
          /* we are going to poll again, set status back to busy */
          do {
            status = GET_ENTRY_STATUS (entry);
            /* we were unscheduled, exit immediately */
            if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
              goto done;
            if (G_UNLIKELY (status != GST_CLOCK_DONE))
              GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
                  status, entry);
          } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status,
                      GST_CLOCK_BUSY)));
815
        }
816 817
      }
    }
818
  } else {
819
    /* we are right on time or too late */
820 821 822
    if (G_UNLIKELY (diff == 0)) {
      if (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_OK))) {
        status = GET_ENTRY_STATUS (entry);
823 824 825
        if (G_LIKELY (status == GST_CLOCK_UNSCHEDULED))
          gst_system_clock_cleanup_unscheduled (sysclock, entry);
        else
826 827
          GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
              status, entry);
828 829 830 831 832 833
      } else {
        status = GST_CLOCK_OK;
      }
    } else {
      if (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_EARLY))) {
        status = GET_ENTRY_STATUS (entry);
834 835 836
        if (G_LIKELY (status == GST_CLOCK_UNSCHEDULED))
          gst_system_clock_cleanup_unscheduled (sysclock, entry);
        else
837 838
          GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
              status, entry);
839 840 841 842
      } else {
        status = GST_CLOCK_EARLY;
      }
    }
843
  }
844 845
done:
  return status;
846 847 848
}

static GstClockReturn
849 850
gst_system_clock_id_wait_jitter (GstClock * clock, GstClockEntry * entry,
    GstClockTimeDiff * jitter)
851
{
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  GstClockReturn status;
  do {
    status = GET_ENTRY_STATUS (entry);

    /* stop when we are unscheduled */
    if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
      return status;

    if (G_UNLIKELY (status != GST_CLOCK_OK))
      GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
          status, entry);

    /* mark the entry as busy but watch out for intermediate unscheduled
     * statuses */
  } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_BUSY)));

868
  return gst_system_clock_id_wait_jitter_unlocked (clock, entry, jitter, TRUE);
869 870
}

871 872 873 874 875 876
/* Start the async clock thread. Must be called with the object lock
 * held */
static gboolean
gst_system_clock_start_async (GstSystemClock * clock)
{
  GError *error = NULL;
Wim Taymans's avatar
Wim Taymans committed
877
  GstSystemClockPrivate *priv = clock->priv;
878

Wim Taymans's avatar
Wim Taymans committed
879
  if (G_LIKELY (priv->thread != NULL))
880 881
    return TRUE;                /* Thread already running. Nothing to do */

Wim Taymans's avatar
Wim Taymans committed
882
  priv->thread = g_thread_try_new ("GstSystemClock",
883 884
      (GThreadFunc) gst_system_clock_async_thread, clock, &error);

885
  if (G_UNLIKELY (error))
886 887 888
    goto no_thread;

  /* wait for it to spin up */
Wim Taymans's avatar
Wim Taymans committed
889
  GST_SYSTEM_CLOCK_WAIT (clock);
890 891 892 893 894 895 896

  return TRUE;

  /* ERRORS */
no_thread:
  {
    g_warning ("could not create async clock thread: %s", error->message);
897
    g_error_free (error);
898 899 900 901
  }
  return FALSE;
}

902 903 904
/* Add an entry to the list of pending async waits. The entry is inserted
 * in sorted order. If we inserted the entry at the head of the list, we
 * need to signal the thread as it might either be waiting on it or waiting
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
905
 * for a new entry.
906 907 908 909 910 911
 *
 * MT safe.
 */
static GstClockReturn
gst_system_clock_id_wait_async (GstClock * clock, GstClockEntry * entry)
{
912
  GstSystemClock *sysclock;
Wim Taymans's avatar
Wim Taymans committed
913
  GstSystemClockPrivate *priv;
914
  GstClockEntry *head;
915 916

  sysclock = GST_SYSTEM_CLOCK_CAST (clock);
Wim Taymans's avatar
Wim Taymans committed
917
  priv = sysclock->priv;
918

919
  GST_CAT_DEBUG (GST_CAT_CLOCK, "adding async entry %p", entry);
920

921
  GST_OBJECT_LOCK (clock);
922
  /* Start the clock async thread if needed */
923
  if (G_UNLIKELY (!gst_system_clock_start_async (sysclock)))
924 925
    goto thread_error;

926
  if (G_UNLIKELY (GET_ENTRY_STATUS (entry) == GST_CLOCK_UNSCHEDULED))
927 928
    goto was_unscheduled;

Wim Taymans's avatar
Wim Taymans committed
929 930
  if (priv->entries)
    head = priv->entries->data;
931 932
  else
    head = NULL;
933

934 935 936
  /* need to take a ref */
  gst_clock_id_ref ((GstClockID) entry);
  /* insert the entry in sorted order */
Wim Taymans's avatar
Wim Taymans committed
937
  priv->entries = g_list_insert_sorted (priv->entries, entry,
938 939 940 941 942
      gst_clock_id_compare_func);

  /* only need to send the signal if the entry was added to the
   * front, else the thread is just waiting for another entry and
   * will get to this entry automatically. */
Wim Taymans's avatar
Wim Taymans committed
943
  if (priv->entries->data == entry) {
944
    GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry added to head %p", head);
945
    if (head == NULL) {
946 947
      /* the list was empty before, signal the cond so that the async thread can
       * start taking a look at the queue */
948
      GST_CAT_DEBUG (GST_CAT_CLOCK, "first entry, sending signal");
Wim Taymans's avatar
Wim Taymans committed
949
      GST_SYSTEM_CLOCK_BROADCAST (clock);
950
    } else {
951 952 953 954 955 956 957
      GstClockReturn status;

      status = GET_ENTRY_STATUS (head);
      GST_CAT_DEBUG (GST_CAT_CLOCK, "head entry %p status %d", head, status);

      if (status == GST_CLOCK_BUSY) {
        GST_CAT_DEBUG (GST_CAT_CLOCK, "head entry is busy");
958 959
        /* the async thread was waiting for an entry, unlock the wait so that it
         * looks at the new head entry instead, we only need to do this once */
Wim Taymans's avatar
Wim Taymans committed
960
        if (!priv->async_wakeup) {
961
          GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup async thread");
Wim Taymans's avatar
Wim Taymans committed
962
          priv->async_wakeup = TRUE;
963 964 965
          gst_system_clock_add_wakeup (sysclock);
        }
      }
966
    }
967
  }
968
  GST_OBJECT_UNLOCK (clock);
969 970

  return GST_CLOCK_OK;
971

972
  /* ERRORS */
973
thread_error:
974 975 976 977 978 979 980 981 982 983
  {
    /* Could not start the async clock thread */
    GST_OBJECT_UNLOCK (clock);
    return GST_CLOCK_ERROR;
  }
was_unscheduled:
  {
    GST_OBJECT_UNLOCK (clock);
    return GST_CLOCK_UNSCHEDULED;
  }
984
}
985

986
/* unschedule an entry. This will set the state of the entry to GST_CLOCK_UNSCHEDULED
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
987
 * and will signal any thread waiting for entries to recheck their entry.
988 989 990 991 992
 * We cannot really decide if the signal is needed or not because the entry
 * could be waited on in async or sync mode.
 *
 * MT safe.
 */
993
static void
994
gst_system_clock_id_unschedule (GstClock * clock, GstClockEntry * entry)
995
{
996
  GstSystemClock *sysclock;
997
  GstClockReturn status;
998 999 1000

  sysclock = GST_SYSTEM_CLOCK_CAST (clock);

1001
  GST_CAT_DEBUG (GST_CAT_CLOCK, "unscheduling entry %p", entry);
1002

1003
  GST_OBJECT_LOCK (clock);
1004 1005 1006 1007 1008 1009 1010
  /* change the entry status to unscheduled */
  do {
    status = GET_ENTRY_STATUS (entry);
  } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status,
              GST_CLOCK_UNSCHEDULED)));

  if (G_LIKELY (status == GST_CLOCK_BUSY)) {
1011 1012
    /* the entry was being busy, wake up all entries so that they recheck their
     * status. We cannot wake up just one entry because allocating such a
1013
     * datastructure for each entry would be too heavy and unlocking an entry
1014
     * is usually done when shutting down or some other exceptional case. */
1015
    GST_CAT_DEBUG (GST_CAT_CLOCK, "entry was BUSY, doing wakeup");
1016 1017 1018 1019
    if (!entry->unscheduled && !entry->woken_up) {
      gst_system_clock_add_wakeup (sysclock);
      entry->woken_up = TRUE;
    }