tools: Count argc after parsing GOption on Windows
[platform/upstream/gstreamer.git] / subprojects / gstreamer / gst / gstsystemclock.c
1 /* GStreamer
2  * 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  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 /**
24  * SECTION:gstsystemclock
25  * @title: GstSystemClock
26  * @short_description: Default clock that uses the current system time
27  * @see_also: #GstClock
28  *
29  * The GStreamer core provides a GstSystemClock based on the system time.
30  * Asynchronous callbacks are scheduled from an internal thread.
31  *
32  * Clock implementors are encouraged to subclass this systemclock as it
33  * implements the async notification.
34  *
35  * Subclasses can however override all of the important methods for sync and
36  * async notifications to implement their own callback methods or blocking
37  * wait operations.
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 #include <errno.h>
49
50 #ifdef G_OS_WIN32
51 #  define WIN32_LEAN_AND_MEAN   /* prevents from including too many things */
52 #  include <windows.h>          /* QueryPerformance* stuff */
53 #  undef WIN32_LEAN_AND_MEAN
54 #  ifndef EWOULDBLOCK
55 #  define EWOULDBLOCK EAGAIN    /* This is just to placate gcc */
56 #  endif
57 #endif /* G_OS_WIN32 */
58
59 #ifdef __APPLE__
60 #include <mach/mach_time.h>
61 #endif
62
63 /* Define this to get some extra debug about jitter from each clock_wait */
64 #undef WAIT_DEBUGGING
65
66 #define GST_SYSTEM_CLOCK_GET_LOCK(clock)        GST_OBJECT_GET_LOCK(clock)
67 #define GST_SYSTEM_CLOCK_LOCK(clock)            g_mutex_lock(GST_SYSTEM_CLOCK_GET_LOCK(clock))
68 #define GST_SYSTEM_CLOCK_UNLOCK(clock)          g_mutex_unlock(GST_SYSTEM_CLOCK_GET_LOCK(clock))
69 #define GST_SYSTEM_CLOCK_GET_COND(clock)        (&GST_SYSTEM_CLOCK_CAST(clock)->priv->entries_changed)
70 #define GST_SYSTEM_CLOCK_WAIT(clock)            g_cond_wait(GST_SYSTEM_CLOCK_GET_COND(clock),GST_SYSTEM_CLOCK_GET_LOCK(clock))
71 #define GST_SYSTEM_CLOCK_BROADCAST(clock)       g_cond_broadcast(GST_SYSTEM_CLOCK_GET_COND(clock))
72
73 #if defined(HAVE_FUTEX) || defined(HAVE_FUTEX_TIME64)
74 #include <unistd.h>
75 #include <linux/futex.h>
76 #include <sys/syscall.h>
77
78 #if !defined(__NR_futex) && !defined(__NR_futex_time64)
79 #error "Neither __NR_futex nor __NR_futex_time64 are defined but were found by meson"
80 #endif
81
82 #ifndef FUTEX_WAIT_BITSET_PRIVATE
83 #define FUTEX_WAIT_BITSET_PRIVATE FUTEX_WAIT_BITSET
84 #endif
85 #ifndef FUTEX_WAKE_PRIVATE
86 #define FUTEX_WAKE_PRIVATE FUTEX_WAKE
87 #endif
88
89 #define GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)          (&(entry)->lock)
90 #define GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry)          (&(entry)->cond_val)
91 #define GST_SYSTEM_CLOCK_ENTRY_LOCK(entry)              (g_mutex_lock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
92 #define GST_SYSTEM_CLOCK_ENTRY_UNLOCK(entry)            (g_mutex_unlock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
93 #define GST_SYSTEM_CLOCK_ENTRY_WAIT_UNTIL(entry,ns)     gst_futex_cond_wait_until(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry),GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry),(ns))
94 #define GST_SYSTEM_CLOCK_ENTRY_BROADCAST(entry)         gst_futex_cond_broadcast(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry))
95
96 #define CLOCK_MIN_WAIT_TIME 100 /* ns */
97
98 typedef struct _GstClockEntryFutex GstClockEntryImpl;
99 struct _GstClockEntryFutex
100 {
101   GstClockEntry entry;
102   GWeakRef clock;
103   GDestroyNotify destroy_entry;
104
105   gboolean initialized;
106
107   GMutex lock;
108   guint cond_val;
109 };
110
111 static void
112 clear_entry (GstClockEntryImpl * entry)
113 {
114   g_mutex_clear (&entry->lock);
115 }
116
117 static void
118 init_entry (GstClockEntryImpl * entry)
119 {
120   g_mutex_init (&entry->lock);
121
122   entry->destroy_entry = (GDestroyNotify) clear_entry;
123 }
124
125 static void
126 gst_futex_cond_broadcast (guint * cond_val)
127 {
128   g_atomic_int_inc (cond_val);
129
130 #if defined(__NR_futex_time64)
131   {
132     int res;
133     res = syscall (__NR_futex_time64, cond_val, (gsize) FUTEX_WAKE_PRIVATE,
134         (gsize) INT_MAX, NULL);
135
136     /* If the syscall does not exist (`ENOSYS`), we retry again below with the
137      * normal `futex` syscall. This can happen if newer kernel headers are
138      * used than the kernel that is actually running.
139      */
140 #ifdef __NR_futex
141     if (res >= 0 || errno != ENOSYS) {
142 #else
143     {
144 #endif
145       return;
146     }
147   }
148 #endif
149
150 #if defined(__NR_futex)
151   syscall (__NR_futex, cond_val, (gsize) FUTEX_WAKE_PRIVATE, (gsize) INT_MAX,
152       NULL);
153 #endif
154 }
155
156 static gboolean
157 gst_futex_cond_wait_until (guint * cond_val, GMutex * mutex, gint64 end_time)
158 {
159   guint sampled;
160   int res;
161   gboolean success;
162
163   if (end_time < 0)
164     return FALSE;
165
166   sampled = *cond_val;
167   g_mutex_unlock (mutex);
168
169   /* `struct timespec` as defined by the libc headers does not necessarily
170    * have any relation to the one used by the kernel for the `futex` syscall.
171    *
172    * Specifically, the libc headers might use 64-bit `time_t` while the kernel
173    * headers use 32-bit `__kernel_old_time_t` on certain systems.
174    *
175    * To get around this problem we
176    *   a) check if `futex_time64` is available, which only exists on 32-bit
177    *      platforms and always uses 64-bit `time_t`.
178    *   b) otherwise (or if that returns `ENOSYS`), we call the normal `futex`
179    *      syscall with the `struct timespec_t` used by the kernel, which uses
180    *      `__kernel_long_t` for both its fields. We use that instead of
181    *      `__kernel_old_time_t` because it is equivalent and available in the
182    *      kernel headers for a longer time.
183    *
184    * Also some 32-bit systems do not define `__NR_futex` at all and only
185    * define `__NR_futex_time64`.
186    */
187
188 #ifdef __NR_futex_time64
189   {
190     struct
191     {
192       gint64 tv_sec;
193       gint64 tv_nsec;
194     } end;
195
196     end.tv_sec = end_time / 1000000000;
197     end.tv_nsec = end_time % 1000000000;
198
199     /* we use FUTEX_WAIT_BITSET_PRIVATE rather than FUTEX_WAIT_PRIVATE to be
200      * able to use absolute time */
201     res =
202         syscall (__NR_futex_time64, cond_val, (gsize) FUTEX_WAIT_BITSET_PRIVATE,
203         (gsize) sampled, &end, NULL, FUTEX_BITSET_MATCH_ANY);
204
205     /* If the syscall does not exist (`ENOSYS`), we retry again below with the
206      * normal `futex` syscall. This can happen if newer kernel headers are
207      * used than the kernel that is actually running.
208      */
209 #ifdef __NR_futex
210     if (res >= 0 || errno != ENOSYS) {
211 #else
212     {
213 #endif
214       success = (res < 0 && errno == ETIMEDOUT) ? FALSE : TRUE;
215       g_mutex_lock (mutex);
216
217       return success;
218     }
219   }
220 #endif
221
222 #ifdef __NR_futex
223   {
224     struct
225     {
226       __kernel_long_t tv_sec;
227       __kernel_long_t tv_nsec;
228     } end;
229
230     /* Make sure to only ever call this if the end time actually fits into the
231      * target type */
232     g_assert (sizeof (__kernel_long_t) >= 8
233         || end_time / 1000000000 <= G_MAXINT32);
234
235     end.tv_sec = end_time / 1000000000;
236     end.tv_nsec = end_time % 1000000000;
237
238     /* we use FUTEX_WAIT_BITSET_PRIVATE rather than FUTEX_WAIT_PRIVATE to be
239      * able to use absolute time */
240     res =
241         syscall (__NR_futex, cond_val, (gsize) FUTEX_WAIT_BITSET_PRIVATE,
242         (gsize) sampled, &end, NULL, FUTEX_BITSET_MATCH_ANY);
243     success = (res < 0 && errno == ETIMEDOUT) ? FALSE : TRUE;
244     g_mutex_lock (mutex);
245
246     return success;
247   }
248 #endif
249
250   /* We can't end up here because of the checks above */
251   g_assert_not_reached ();
252 }
253
254 #elif defined (G_OS_UNIX)
255 #define GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)          (&(entry)->lock)
256 #define GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry)          (&(entry)->cond)
257 #define GST_SYSTEM_CLOCK_ENTRY_LOCK(entry)              (pthread_mutex_lock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
258 #define GST_SYSTEM_CLOCK_ENTRY_UNLOCK(entry)            (pthread_mutex_unlock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
259 #define GST_SYSTEM_CLOCK_ENTRY_WAIT_UNTIL(entry,ns)     gst_pthread_cond_wait_until(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry),GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry),(ns))
260 #define GST_SYSTEM_CLOCK_ENTRY_BROADCAST(entry)         pthread_cond_broadcast(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry))
261
262 #define CLOCK_MIN_WAIT_TIME 500 /* ns */
263
264 typedef struct _GstClockEntryPThread GstClockEntryImpl;
265 struct _GstClockEntryPThread
266 {
267   GstClockEntry entry;
268   GWeakRef clock;
269   GDestroyNotify destroy_entry;
270
271   gboolean initialized;
272
273   pthread_cond_t cond;
274   pthread_mutex_t lock;
275 };
276
277 static gboolean
278 gst_pthread_cond_wait_until (pthread_cond_t * cond, pthread_mutex_t * lock,
279     guint64 end_time)
280 {
281   struct timespec ts;
282   gint status;
283
284 #if defined (HAVE_PTHREAD_CONDATTR_SETCLOCK) && defined (CLOCK_MONOTONIC)
285   /* This is the exact check we used during init to set the clock to
286    * monotonic, so if we're in this branch, timedwait() will already be
287    * expecting a monotonic clock.
288    */
289   {
290     ts.tv_sec = end_time / 1000000000;
291     ts.tv_nsec = end_time % 1000000000;
292
293     if ((status = pthread_cond_timedwait (cond, lock, &ts)) == 0)
294       return TRUE;
295   }
296 #elif defined (HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP)
297   /* end_time is given relative to the monotonic clock as returned by
298    * g_get_monotonic_time().
299    *
300    * Since this pthreads wants the relative time, convert it back again.
301    */
302   {
303     gint64 now = g_get_monotonic_time () * 1000;
304     gint64 relative;
305
306     if (end_time <= now)
307       return FALSE;
308
309     relative = end_time - now;
310
311     ts.tv_sec = relative / 1000000000;
312     ts.tv_nsec = relative % 1000000000;
313
314     if ((status = pthread_cond_timedwait_relative_np (cond, lock, &ts)) == 0)
315       return TRUE;
316   }
317 #else
318 #error Cannot use pthread condition variables on your platform.
319 #endif
320
321   if (G_UNLIKELY (status != ETIMEDOUT)) {
322     g_error ("pthread_cond_timedwait returned %d", status);
323   }
324
325   return FALSE;
326 }
327
328 static void
329 clear_entry (GstClockEntryImpl * entry)
330 {
331   pthread_cond_destroy (&entry->cond);
332   pthread_mutex_destroy (&entry->lock);
333 }
334
335 static void
336 init_entry (GstClockEntryImpl * entry)
337 {
338   pthread_mutexattr_t *m_pattr = NULL;
339 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
340   pthread_mutexattr_t m_attr;
341 #endif
342   pthread_condattr_t c_attr;
343   gint status;
344
345   pthread_condattr_init (&c_attr);
346
347 #if defined (HAVE_PTHREAD_CONDATTR_SETCLOCK) && defined (CLOCK_MONOTONIC)
348   status = pthread_condattr_setclock (&c_attr, CLOCK_MONOTONIC);
349   if (G_UNLIKELY (status != 0)) {
350     g_error ("pthread_condattr_setclock returned %d", status);
351   }
352 #elif defined (HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP)
353 #else
354 #error Cannot use pthread condition variables on your platform.
355 #endif
356
357   status = pthread_cond_init (&entry->cond, &c_attr);
358   if (G_UNLIKELY (status != 0)) {
359     g_error ("pthread_cond_init returned %d", status);
360   }
361
362   pthread_condattr_destroy (&c_attr);
363
364 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
365   pthread_mutexattr_init (&m_attr);
366   pthread_mutexattr_settype (&m_attr, PTHREAD_MUTEX_ADAPTIVE_NP);
367   m_pattr = &m_attr;
368 #endif
369
370   status = pthread_mutex_init (&entry->lock, m_pattr);
371   if (G_UNLIKELY (status != 0)) {
372     g_error ("pthread_mutex_init returned %d", status);
373   }
374 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
375   pthread_mutexattr_destroy (&m_attr);
376 #endif
377
378   entry->destroy_entry = (GDestroyNotify) clear_entry;
379 }
380 #else
381 #define GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)          (&(entry)->lock)
382 #define GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry)          (&(entry)->cond)
383 #define GST_SYSTEM_CLOCK_ENTRY_LOCK(entry)              (g_mutex_lock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
384 #define GST_SYSTEM_CLOCK_ENTRY_UNLOCK(entry)            (g_mutex_unlock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
385 #define GST_SYSTEM_CLOCK_ENTRY_WAIT_UNTIL(entry,ns)     g_cond_wait_until(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry),GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry),((ns) / 1000))
386 #define GST_SYSTEM_CLOCK_ENTRY_BROADCAST(entry)         g_cond_broadcast(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry))
387
388 #if defined (G_OS_WIN32)
389 /* min wait time is 1ms on windows with GCond */
390 #define CLOCK_MIN_WAIT_TIME GST_MSECOND
391 #else
392 /* min wait time is 1us on non-windows with GCond */
393 #define CLOCK_MIN_WAIT_TIME GST_USECOND
394 #endif
395
396 typedef struct _GstClockEntryGLib GstClockEntryImpl;
397 struct _GstClockEntryGLib
398 {
399   GstClockEntry entry;
400   GWeakRef clock;
401   GDestroyNotify destroy_entry;
402
403   gboolean initialized;
404
405   GMutex lock;
406   GCond cond;
407 };
408
409 static void
410 clear_entry (GstClockEntryImpl * entry)
411 {
412   g_cond_clear (&entry->cond);
413   g_mutex_clear (&entry->lock);
414 }
415
416 static void
417 init_entry (GstClockEntryImpl * entry)
418 {
419   g_cond_init (&entry->cond);
420   g_mutex_init (&entry->lock);
421
422   entry->destroy_entry = (GDestroyNotify) clear_entry;
423 }
424 #endif
425
426 /* check that our impl is smaller than what will be allocated by gstclock.c */
427 G_STATIC_ASSERT (sizeof (GstClockEntryImpl) <=
428     sizeof (struct _GstClockEntryImpl));
429
430 /* Must be called with clock lock */
431 static inline void
432 ensure_entry_initialized (GstClockEntryImpl * entry_impl)
433 {
434   if (!entry_impl->initialized) {
435     init_entry (entry_impl);
436     entry_impl->initialized = TRUE;
437   }
438 }
439
440 struct _GstSystemClockPrivate
441 {
442   GThread *thread;              /* thread for async notify */
443   gboolean stopping;
444
445   GList *entries;
446   GCond entries_changed;
447
448   GstClockType clock_type;
449
450 #ifdef G_OS_WIN32
451   LARGE_INTEGER frequency;
452 #endif                          /* G_OS_WIN32 */
453 #ifdef __APPLE__
454   struct mach_timebase_info mach_timebase;
455 #endif
456 };
457
458 #ifdef HAVE_POSIX_TIMERS
459 # ifdef HAVE_MONOTONIC_CLOCK
460 #  define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_MONOTONIC
461 # else
462 #  define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_REALTIME
463 # endif
464 #else
465 #define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_MONOTONIC
466 #endif
467
468 enum
469 {
470   PROP_0,
471   PROP_CLOCK_TYPE,
472   /* FILL ME */
473 };
474
475 /* the one instance of the systemclock */
476 static GstClock *_the_system_clock = NULL;
477 static gboolean _external_default_clock = FALSE;
478
479 static void gst_system_clock_dispose (GObject * object);
480 static void gst_system_clock_set_property (GObject * object, guint prop_id,
481     const GValue * value, GParamSpec * pspec);
482 static void gst_system_clock_get_property (GObject * object, guint prop_id,
483     GValue * value, GParamSpec * pspec);
484
485 static GstClockTime gst_system_clock_get_internal_time (GstClock * clock);
486 #if !defined HAVE_POSIX_TIMERS || !defined HAVE_CLOCK_GETTIME
487 static GstClockTime gst_system_clock_get_mono_time (GstSystemClock * clock);
488 static GstClockTime gst_system_clock_get_real_time ();
489 #endif
490 static guint64 gst_system_clock_get_resolution (GstClock * clock);
491 static GstClockReturn gst_system_clock_id_wait_jitter (GstClock * clock,
492     GstClockEntry * entry, GstClockTimeDiff * jitter);
493 static GstClockReturn gst_system_clock_id_wait_jitter_unlocked
494     (GstClock * clock, GstClockEntry * entry, GstClockTimeDiff * jitter,
495     gboolean restart);
496 static GstClockReturn gst_system_clock_id_wait_async (GstClock * clock,
497     GstClockEntry * entry);
498 static void gst_system_clock_id_unschedule (GstClock * clock,
499     GstClockEntry * entry);
500 static void gst_system_clock_async_thread (GstClock * clock);
501 static gboolean gst_system_clock_start_async (GstSystemClock * clock);
502
503 static GMutex _gst_sysclock_mutex;
504
505 /* static guint gst_system_clock_signals[LAST_SIGNAL] = { 0 }; */
506
507 #define gst_system_clock_parent_class parent_class
508 G_DEFINE_TYPE_WITH_PRIVATE (GstSystemClock, gst_system_clock, GST_TYPE_CLOCK);
509
510 static void
511 gst_system_clock_class_init (GstSystemClockClass * klass)
512 {
513   GObjectClass *gobject_class;
514   GstClockClass *gstclock_class;
515
516   gobject_class = (GObjectClass *) klass;
517   gstclock_class = (GstClockClass *) klass;
518
519   gobject_class->dispose = gst_system_clock_dispose;
520   gobject_class->set_property = gst_system_clock_set_property;
521   gobject_class->get_property = gst_system_clock_get_property;
522
523   g_object_class_install_property (gobject_class, PROP_CLOCK_TYPE,
524       g_param_spec_enum ("clock-type", "Clock type",
525           "The type of underlying clock implementation used",
526           GST_TYPE_CLOCK_TYPE, DEFAULT_CLOCK_TYPE,
527           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
528
529   gstclock_class->get_internal_time = gst_system_clock_get_internal_time;
530   gstclock_class->get_resolution = gst_system_clock_get_resolution;
531   gstclock_class->wait = gst_system_clock_id_wait_jitter;
532   gstclock_class->wait_async = gst_system_clock_id_wait_async;
533   gstclock_class->unschedule = gst_system_clock_id_unschedule;
534 }
535
536 static void
537 gst_system_clock_init (GstSystemClock * clock)
538 {
539   GstSystemClockPrivate *priv;
540
541   GST_OBJECT_FLAG_SET (clock,
542       GST_CLOCK_FLAG_CAN_DO_SINGLE_SYNC |
543       GST_CLOCK_FLAG_CAN_DO_SINGLE_ASYNC |
544       GST_CLOCK_FLAG_CAN_DO_PERIODIC_SYNC |
545       GST_CLOCK_FLAG_CAN_DO_PERIODIC_ASYNC);
546
547   clock->priv = priv = gst_system_clock_get_instance_private (clock);
548
549   priv->clock_type = DEFAULT_CLOCK_TYPE;
550
551   priv->entries = NULL;
552   g_cond_init (&priv->entries_changed);
553
554 #ifdef G_OS_WIN32
555   QueryPerformanceFrequency (&priv->frequency);
556 #endif /* G_OS_WIN32 */
557
558 #ifdef __APPLE__
559   mach_timebase_info (&priv->mach_timebase);
560 #endif
561
562 #if 0
563   /* Uncomment this to start the async clock thread straight away */
564   GST_SYSTEM_CLOCK_LOCK (clock);
565   gst_system_clock_start_async (clock);
566   GST_SYSTEM_CLOCK_UNLOCK (clock);
567 #endif
568 }
569
570 static void
571 gst_system_clock_dispose (GObject * object)
572 {
573   GstClock *clock = (GstClock *) object;
574   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
575   GstSystemClockPrivate *priv = sysclock->priv;
576   GList *entries;
577
578   /* else we have to stop the thread */
579   GST_SYSTEM_CLOCK_LOCK (clock);
580   priv->stopping = TRUE;
581   /* unschedule all entries */
582   for (entries = priv->entries; entries; entries = g_list_next (entries)) {
583     GstClockEntryImpl *entry = (GstClockEntryImpl *) entries->data;
584
585     /* We don't need to take the entry lock here because the async thread
586      * would only ever look at the head entry, which is locked below and only
587      * accesses new entries with the clock lock, which we hold here.
588      */
589     GST_CLOCK_ENTRY_STATUS ((GstClockEntry *) entry) = GST_CLOCK_UNSCHEDULED;
590
591     /* Wake up only the head entry: the async thread would only be waiting for
592      * this one, not all of them. Once the head entry is unscheduled it tries
593      * to get the system clock lock (which we hold here) and then look for the
594      * next entry. Once it gets the lock it will notice that all further
595      * entries are unscheduled, would remove them one by one from the list and
596      * then shut down. */
597     if (!entries->prev) {
598       /* it was initialized before adding to the list */
599       g_assert (entry->initialized);
600
601       GST_SYSTEM_CLOCK_ENTRY_LOCK (entry);
602       GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "unscheduling entry %p",
603           entry);
604       GST_SYSTEM_CLOCK_ENTRY_BROADCAST (entry);
605       GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
606     }
607   }
608   GST_SYSTEM_CLOCK_BROADCAST (clock);
609   GST_SYSTEM_CLOCK_UNLOCK (clock);
610
611   if (priv->thread)
612     g_thread_join (priv->thread);
613   priv->thread = NULL;
614   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "joined thread");
615
616   g_list_foreach (priv->entries, (GFunc) gst_clock_id_unref, NULL);
617   g_list_free (priv->entries);
618   priv->entries = NULL;
619
620   g_cond_clear (&priv->entries_changed);
621
622   G_OBJECT_CLASS (parent_class)->dispose (object);
623
624   if (_the_system_clock == clock) {
625     _the_system_clock = NULL;
626     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "disposed system clock");
627   }
628 }
629
630 static void
631 gst_system_clock_set_property (GObject * object, guint prop_id,
632     const GValue * value, GParamSpec * pspec)
633 {
634   GstSystemClock *sysclock = GST_SYSTEM_CLOCK (object);
635
636   switch (prop_id) {
637     case PROP_CLOCK_TYPE:
638       sysclock->priv->clock_type = (GstClockType) g_value_get_enum (value);
639       GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, sysclock, "clock-type set to %d",
640           sysclock->priv->clock_type);
641       break;
642     default:
643       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
644       break;
645   }
646 }
647
648 static void
649 gst_system_clock_get_property (GObject * object, guint prop_id, GValue * value,
650     GParamSpec * pspec)
651 {
652   GstSystemClock *sysclock = GST_SYSTEM_CLOCK (object);
653
654   switch (prop_id) {
655     case PROP_CLOCK_TYPE:
656       g_value_set_enum (value, sysclock->priv->clock_type);
657       break;
658     default:
659       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
660       break;
661   }
662 }
663
664 /**
665  * gst_system_clock_set_default:
666  * @new_clock: (allow-none): a #GstClock
667  *
668  * Sets the default system clock that can be obtained with
669  * gst_system_clock_obtain().
670  *
671  * This is mostly used for testing and debugging purposes when you
672  * want to have control over the time reported by the default system
673  * clock.
674  *
675  * MT safe.
676  *
677  * Since: 1.4
678  */
679 void
680 gst_system_clock_set_default (GstClock * new_clock)
681 {
682   GstClock *clock;
683
684   g_mutex_lock (&_gst_sysclock_mutex);
685   clock = _the_system_clock;
686
687   if (clock != NULL)
688     gst_object_unref (clock);
689
690   if (new_clock == NULL) {
691     GST_CAT_DEBUG (GST_CAT_CLOCK, "resetting default system clock");
692     _external_default_clock = FALSE;
693   } else {
694     GST_CAT_DEBUG (GST_CAT_CLOCK, "setting new default system clock to %p",
695         new_clock);
696     _external_default_clock = TRUE;
697     g_object_ref (new_clock);
698   }
699   _the_system_clock = new_clock;
700   g_mutex_unlock (&_gst_sysclock_mutex);
701 }
702
703 /**
704  * gst_system_clock_obtain:
705  *
706  * Get a handle to the default system clock. The refcount of the
707  * clock will be increased so you need to unref the clock after
708  * usage.
709  *
710  * Returns: (transfer full): the default clock.
711  *
712  * MT safe.
713  */
714 GstClock *
715 gst_system_clock_obtain (void)
716 {
717   GstClock *clock;
718
719   g_mutex_lock (&_gst_sysclock_mutex);
720   clock = _the_system_clock;
721
722   if (clock == NULL) {
723     GST_CAT_DEBUG (GST_CAT_CLOCK, "creating new static system clock");
724     g_assert (!_external_default_clock);
725     clock = g_object_new (GST_TYPE_SYSTEM_CLOCK,
726         "name", "GstSystemClock", NULL);
727
728     /* Clear floating flag */
729     gst_object_ref_sink (clock);
730     GST_OBJECT_FLAG_SET (clock, GST_OBJECT_FLAG_MAY_BE_LEAKED);
731     _the_system_clock = clock;
732     g_mutex_unlock (&_gst_sysclock_mutex);
733   } else {
734     g_mutex_unlock (&_gst_sysclock_mutex);
735     GST_CAT_DEBUG (GST_CAT_CLOCK, "returning static system clock");
736   }
737
738   /* we ref it since we are a clock factory. */
739   gst_object_ref (clock);
740   return clock;
741 }
742
743 /* this thread reads the sorted clock entries from the queue.
744  *
745  * It waits on each of them and fires the callback when the timeout occurs.
746  *
747  * When an entry in the queue was canceled before we wait for it, it is
748  * simply skipped.
749  *
750  * When waiting for an entry, it can become canceled, in that case we don't
751  * call the callback but move to the next item in the queue.
752  *
753  * MT safe.
754  */
755 static void
756 gst_system_clock_async_thread (GstClock * clock)
757 {
758   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
759   GstSystemClockPrivate *priv = sysclock->priv;
760   GstClockReturn status;
761   gboolean entry_needs_unlock = FALSE;
762
763   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "enter system clock thread");
764   GST_SYSTEM_CLOCK_LOCK (clock);
765   /* signal spinup */
766   GST_SYSTEM_CLOCK_BROADCAST (clock);
767   /* now enter our (almost) infinite loop */
768   while (!priv->stopping) {
769     GstClockEntry *entry;
770     GstClockTime requested;
771     GstClockReturn res;
772
773     /* check if something to be done */
774     while (priv->entries == NULL) {
775       GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
776           "no clock entries, waiting..");
777       /* wait for work to do */
778       GST_SYSTEM_CLOCK_WAIT (clock);
779       GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "got signal");
780       /* clock was stopping, exit */
781       if (priv->stopping)
782         goto exit;
783     }
784
785     /* pick the next entry */
786     entry = priv->entries->data;
787
788     /* it was initialized before adding to the list */
789     g_assert (((GstClockEntryImpl *) entry)->initialized);
790
791     /* unlocked before the next loop iteration at latest */
792     GST_SYSTEM_CLOCK_ENTRY_LOCK ((GstClockEntryImpl *) entry);
793     entry_needs_unlock = TRUE;
794
795     /* set entry status to busy before we release the clock lock */
796     status = GST_CLOCK_ENTRY_STATUS (entry);
797
798     /* check for unscheduled */
799     if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
800       /* entry was unscheduled, move to the next one */
801       GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
802           "async entry %p unscheduled", entry);
803       GST_SYSTEM_CLOCK_UNLOCK (clock);
804       goto next_entry;
805     }
806
807     /* for periodic timers, status can be EARLY from a previous run */
808     if (G_UNLIKELY (status != GST_CLOCK_OK && status != GST_CLOCK_EARLY))
809       GST_CAT_ERROR_OBJECT (GST_CAT_CLOCK, clock,
810           "unexpected status %d for entry %p", status, entry);
811
812     /* mark the entry as busy */
813     GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_BUSY;
814
815     requested = entry->time;
816
817     /* needs to be locked again before the next loop iteration, and we only
818      * unlock it here so that gst_system_clock_id_wait_async() is guaranteed
819      * to see status==BUSY later and wakes up this thread, and dispose() does
820      * not override BUSY with UNSCHEDULED here. */
821     GST_SYSTEM_CLOCK_UNLOCK (clock);
822
823     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "waiting on entry %p", entry);
824
825     /* now wait for the entry */
826     res =
827         gst_system_clock_id_wait_jitter_unlocked (clock, (GstClockID) entry,
828         NULL, FALSE);
829
830     switch (res) {
831       case GST_CLOCK_UNSCHEDULED:
832         /* entry was unscheduled, move to the next */
833         GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
834             "async entry %p unscheduled", entry);
835         goto next_entry;
836       case GST_CLOCK_OK:
837       case GST_CLOCK_EARLY:
838       {
839         GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
840         entry_needs_unlock = FALSE;
841         /* entry timed out normally, fire the callback and move to the next
842          * entry */
843         GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "async entry %p timed out",
844             entry);
845         if (entry->func) {
846           /* unlock before firing the callback */
847           entry->func (clock, entry->time, (GstClockID) entry,
848               entry->user_data);
849         }
850         if (entry->type == GST_CLOCK_ENTRY_PERIODIC) {
851           GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
852               "updating periodic entry %p", entry);
853
854           GST_SYSTEM_CLOCK_LOCK (clock);
855           /* adjust time now */
856           entry->time = requested + entry->interval;
857           /* and resort the list now */
858           priv->entries =
859               g_list_sort (priv->entries, gst_clock_id_compare_func);
860           /* and restart */
861           continue;
862         } else {
863           GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "moving to next entry");
864           goto next_entry;
865         }
866       }
867       case GST_CLOCK_BUSY:
868         /* somebody unlocked the entry but is was not canceled, This means that
869          * a new entry was added in front of the queue. Pick the new head
870          * entry of the list and continue waiting. */
871         GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
872             "async entry %p needs restart", entry);
873
874         /* we set the entry back to the OK state. This is needed so that the
875          * _unschedule() code can see if an entry is currently being waited
876          * on (when its state is BUSY). */
877         GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_OK;
878         if (entry_needs_unlock)
879           GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
880         GST_SYSTEM_CLOCK_LOCK (clock);
881         continue;
882       default:
883         GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
884             "strange result %d waiting for %p, skipping", res, entry);
885         g_warning ("%s: strange result %d waiting for %p, skipping",
886             GST_OBJECT_NAME (clock), res, entry);
887         goto next_entry;
888     }
889   next_entry:
890     if (entry_needs_unlock)
891       GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
892     GST_SYSTEM_CLOCK_LOCK (clock);
893
894     /* we remove the current entry and unref it */
895     priv->entries = g_list_remove (priv->entries, entry);
896     gst_clock_id_unref ((GstClockID) entry);
897   }
898 exit:
899   /* signal exit */
900   GST_SYSTEM_CLOCK_BROADCAST (clock);
901   GST_SYSTEM_CLOCK_UNLOCK (clock);
902   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "exit system clock thread");
903 }
904
905 #ifdef HAVE_POSIX_TIMERS
906 static inline clockid_t
907 clock_type_to_posix_id (GstClockType clock_type)
908 {
909 #ifdef HAVE_MONOTONIC_CLOCK
910   if (clock_type == GST_CLOCK_TYPE_MONOTONIC)
911     return CLOCK_MONOTONIC;
912   else
913 #endif
914   if (clock_type == GST_CLOCK_TYPE_TAI)
915 #ifdef CLOCK_TAI
916     return CLOCK_TAI;
917 #else
918     GST_ERROR
919         ("No CLOCK_TAI available on the system. Falling back to CLOCK_REALTIME");
920 #endif
921   return CLOCK_REALTIME;
922 }
923 #endif
924
925 /* MT safe */
926 static GstClockTime
927 gst_system_clock_get_internal_time (GstClock * clock)
928 {
929   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
930 #if defined HAVE_POSIX_TIMERS && defined HAVE_CLOCK_GETTIME
931   // BSD and Linux' Posix timers and clock_gettime cover all of the different clock types
932   // without need for special handling so we'll use those.
933   clockid_t ptype;
934   struct timespec ts;
935
936   ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
937
938   if (G_UNLIKELY (clock_gettime (ptype, &ts)))
939     return GST_CLOCK_TIME_NONE;
940
941   return GST_TIMESPEC_TO_TIME (ts);
942 #else
943   if (sysclock->priv->clock_type == GST_CLOCK_TYPE_REALTIME) {
944     return gst_system_clock_get_real_time ();
945   } else {
946     return gst_system_clock_get_mono_time (sysclock);
947   }
948 #endif /* !HAVE_POSIX_TIMERS || !HAVE_CLOCK_GETTIME */
949 }
950
951 #if !defined HAVE_POSIX_TIMERS || !defined HAVE_CLOCK_GETTIME
952 static GstClockTime
953 gst_system_clock_get_real_time ()
954 {
955   gint64 rt_micros = g_get_real_time ();
956   // g_get_real_time returns microseconds but we need nanos, so we'll multiply by 1000
957   return ((guint64) rt_micros) * 1000;
958 }
959
960 static GstClockTime
961 gst_system_clock_get_mono_time (GstSystemClock * sysclock)
962 {
963 #if defined __APPLE__
964   uint64_t mach_t = mach_absolute_time ();
965   return gst_util_uint64_scale (mach_t, sysclock->priv->mach_timebase.numer,
966       sysclock->priv->mach_timebase.denom);
967 #else
968 #if defined G_OS_WIN32
969   if (sysclock->priv->frequency.QuadPart != 0) {
970     LARGE_INTEGER now;
971
972     /* we prefer the highly accurate performance counters on windows */
973     QueryPerformanceCounter (&now);
974
975     return gst_util_uint64_scale (now.QuadPart,
976         GST_SECOND, sysclock->priv->frequency.QuadPart);
977   } else
978 #endif /* G_OS_WIN32 */
979   {
980     gint64 monotime;
981
982     monotime = g_get_monotonic_time ();
983
984     return monotime * 1000;
985   }
986 #endif /* __APPLE__ */
987 }
988 #endif /* !HAVE_POSIX_TIMERS || !HAVE_CLOCK_GETTIME */
989
990 static guint64
991 gst_system_clock_get_resolution (GstClock * clock)
992 {
993   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
994 #if defined __APPLE__ || defined G_OS_WIN32
995   if (sysclock->priv->clock_type == GST_CLOCK_TYPE_REALTIME) {
996     return 1 * GST_USECOND;
997   } else
998 #endif
999 #if defined __APPLE__
1000   {
1001     return gst_util_uint64_scale (GST_NSECOND,
1002         sysclock->priv->mach_timebase.numer,
1003         sysclock->priv->mach_timebase.denom);
1004   }
1005 #elif defined G_OS_WIN32
1006   {
1007     if (sysclock->priv->frequency.QuadPart != 0) {
1008       return GST_SECOND / sysclock->priv->frequency.QuadPart;
1009     } else {
1010       return 1 * GST_USECOND;
1011     }
1012   }
1013 #elif defined(HAVE_POSIX_TIMERS) && defined(HAVE_CLOCK_GETTIME)
1014     clockid_t ptype;
1015   struct timespec ts;
1016
1017   ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
1018
1019   if (G_UNLIKELY (clock_getres (ptype, &ts)))
1020     return GST_CLOCK_TIME_NONE;
1021
1022   return GST_TIMESPEC_TO_TIME (ts);
1023 #else
1024     return 1 * GST_USECOND;
1025 #endif /* __APPLE__ */
1026 }
1027
1028 /* synchronously wait on the given GstClockEntry.
1029  *
1030  * We do this by blocking on the entry specifically rather than a global
1031  * condition variable so that each possible thread may be woken up
1032  * individually. This ensures that we don't wake up possibly multiple threads
1033  * when unscheduling an entry.
1034  *
1035  * Entries that arrive too late are simply not waited on and a
1036  * GST_CLOCK_EARLY result is returned.
1037  *
1038  * This is called with the ENTRY_LOCK but not SYSTEM_CLOCK_LOCK!
1039  *
1040  * MT safe.
1041  */
1042 static GstClockReturn
1043 gst_system_clock_id_wait_jitter_unlocked (GstClock * clock,
1044     GstClockEntry * entry, GstClockTimeDiff * jitter, gboolean restart)
1045 {
1046   GstClockTime entryt, now;
1047   GstClockTimeDiff diff;
1048   GstClockReturn status;
1049   gint64 mono_ts;
1050
1051   status = GST_CLOCK_ENTRY_STATUS (entry);
1052   if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
1053     return GST_CLOCK_UNSCHEDULED;
1054   }
1055
1056   /* need to call the overridden method because we want to sync against the time
1057    * of the clock, whatever the subclass uses as a clock. */
1058   now = gst_clock_get_time (clock);
1059   mono_ts = g_get_monotonic_time ();
1060
1061   /* get the time of the entry */
1062   entryt = GST_CLOCK_ENTRY_TIME (entry);
1063
1064   /* the diff of the entry with the clock is the amount of time we have to
1065    * wait */
1066   diff = GST_CLOCK_DIFF (now, entryt);
1067   if (G_LIKELY (jitter))
1068     *jitter = -diff;
1069
1070   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "entry %p"
1071       " time %" GST_TIME_FORMAT
1072       " now %" GST_TIME_FORMAT
1073       " diff (time-now) %" G_GINT64_FORMAT,
1074       entry, GST_TIME_ARGS (entryt), GST_TIME_ARGS (now), diff);
1075
1076   if (G_LIKELY (diff > CLOCK_MIN_WAIT_TIME)) {
1077 #ifdef WAIT_DEBUGGING
1078     GstClockTime final;
1079 #endif
1080
1081     while (TRUE) {
1082       gboolean waitret;
1083
1084 #ifdef HAVE_CLOCK_NANOSLEEP
1085       if (diff <= 500 * GST_USECOND) {
1086         /* In order to provide more accurate wait, we will use BLOCKING
1087            clock_nanosleep for any deadlines at or below 500us */
1088         struct timespec end;
1089         GST_TIME_TO_TIMESPEC (mono_ts * 1000 + diff, end);
1090         GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
1091         waitret =
1092             clock_nanosleep (CLOCK_MONOTONIC, TIMER_ABSTIME, &end, NULL) == 0;
1093         GST_SYSTEM_CLOCK_ENTRY_LOCK ((GstClockEntryImpl *) entry);
1094       } else {
1095
1096         if (diff < 2 * GST_MSECOND) {
1097           /* For any deadline within 2ms, we first use the regular non-blocking
1098              wait by reducing the diff accordingly */
1099           diff -= 500 * GST_USECOND;
1100         }
1101 #endif
1102
1103         /* now wait on the entry, it either times out or the cond is signalled.
1104          * The status of the entry is BUSY only around the wait. */
1105         waitret =
1106             GST_SYSTEM_CLOCK_ENTRY_WAIT_UNTIL ((GstClockEntryImpl *) entry,
1107             mono_ts * 1000 + diff);
1108
1109 #ifdef HAVE_CLOCK_NANOSLEEP
1110       }
1111 #endif
1112
1113       /* get the new status, mark as DONE. We do this so that the unschedule
1114        * function knows when we left the poll and doesn't need to wakeup the
1115        * poll anymore. */
1116       status = GST_CLOCK_ENTRY_STATUS (entry);
1117       /* we were unscheduled, exit immediately */
1118       if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
1119         break;
1120       if (G_UNLIKELY (status != GST_CLOCK_BUSY))
1121         GST_CAT_ERROR_OBJECT (GST_CAT_CLOCK, clock,
1122             "unexpected status %d for entry %p", status, entry);
1123       GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_DONE;
1124
1125       GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1126           "entry %p unlocked, status %d", entry, status);
1127
1128       if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
1129         goto done;
1130       } else {
1131         if (waitret) {
1132           /* some other id got unlocked */
1133           if (!restart) {
1134             /* this can happen if the entry got unlocked because of an async
1135              * entry was added to the head of the async queue. */
1136             GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1137                 "wakeup waiting for entry %p", entry);
1138             goto done;
1139           }
1140
1141           GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1142               "entry %p needs to be restarted", entry);
1143         } else {
1144           GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1145               "entry %p unlocked after timeout", entry);
1146         }
1147
1148         /* reschedule if gst_cond_wait_until returned early or we have to reschedule after
1149          * an unlock*/
1150         mono_ts = g_get_monotonic_time ();
1151         now = gst_clock_get_time (clock);
1152         diff = GST_CLOCK_DIFF (now, entryt);
1153
1154         if (diff <= CLOCK_MIN_WAIT_TIME) {
1155           /* timeout, this is fine, we can report success now */
1156           GST_CLOCK_ENTRY_STATUS (entry) = status = GST_CLOCK_OK;
1157           GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1158               "entry %p finished, diff %" G_GINT64_FORMAT, entry, diff);
1159
1160 #ifdef WAIT_DEBUGGING
1161           final = gst_system_clock_get_internal_time (clock);
1162           GST_CAT_DEBUG (GST_CAT_CLOCK, "Waited for %" G_GINT64_FORMAT
1163               " got %" G_GINT64_FORMAT " diff %" G_GINT64_FORMAT
1164               " %g target-offset %" G_GINT64_FORMAT " %g", entryt, now,
1165               now - entryt,
1166               (double) (GstClockTimeDiff) (now - entryt) / GST_SECOND,
1167               (final - target),
1168               ((double) (GstClockTimeDiff) (final - target)) / GST_SECOND);
1169 #endif
1170           goto done;
1171         } else {
1172           GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1173               "entry %p restart, diff %" G_GINT64_FORMAT, entry, diff);
1174           /* we are going to poll again, set status back to busy */
1175           GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_BUSY;
1176         }
1177       }
1178     }
1179   } else {
1180     /* we are right on time or too late */
1181     if (G_UNLIKELY (diff == 0)) {
1182       GST_CLOCK_ENTRY_STATUS (entry) = status = GST_CLOCK_OK;
1183     } else {
1184       GST_CLOCK_ENTRY_STATUS (entry) = status = GST_CLOCK_EARLY;
1185     }
1186   }
1187 done:
1188   return status;
1189 }
1190
1191 static GstClockReturn
1192 gst_system_clock_id_wait_jitter (GstClock * clock, GstClockEntry * entry,
1193     GstClockTimeDiff * jitter)
1194 {
1195   GstClockReturn status;
1196   GstClockEntryImpl *entry_impl = (GstClockEntryImpl *) entry;
1197
1198   GST_SYSTEM_CLOCK_LOCK (clock);
1199   ensure_entry_initialized (entry_impl);
1200   GST_SYSTEM_CLOCK_UNLOCK (clock);
1201
1202   GST_SYSTEM_CLOCK_ENTRY_LOCK (entry_impl);
1203   status = GST_CLOCK_ENTRY_STATUS (entry);
1204
1205   /* stop when we are unscheduled */
1206   if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
1207     GST_SYSTEM_CLOCK_ENTRY_UNLOCK (entry_impl);
1208     return status;
1209   }
1210
1211   if (G_UNLIKELY (status != GST_CLOCK_OK))
1212     GST_CAT_ERROR_OBJECT (GST_CAT_CLOCK, clock,
1213         "unexpected status %d for entry %p", status, entry);
1214
1215   /* mark the entry as busy */
1216   GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_BUSY;
1217
1218   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "waiting on entry %p", entry);
1219
1220   status =
1221       gst_system_clock_id_wait_jitter_unlocked (clock, entry, jitter, TRUE);
1222
1223   GST_SYSTEM_CLOCK_ENTRY_UNLOCK (entry_impl);
1224
1225   return status;
1226 }
1227
1228 /* Start the async clock thread. Must be called with the object lock
1229  * held */
1230 static gboolean
1231 gst_system_clock_start_async (GstSystemClock * clock)
1232 {
1233   GError *error = NULL;
1234   GstSystemClockPrivate *priv = clock->priv;
1235
1236   if (G_LIKELY (priv->thread != NULL))
1237     return TRUE;                /* Thread already running. Nothing to do */
1238
1239   priv->thread = g_thread_try_new ("GstSystemClock",
1240       (GThreadFunc) gst_system_clock_async_thread, clock, &error);
1241
1242   if (G_UNLIKELY (error))
1243     goto no_thread;
1244
1245   /* wait for it to spin up */
1246   GST_SYSTEM_CLOCK_WAIT (clock);
1247
1248   return TRUE;
1249
1250   /* ERRORS */
1251 no_thread:
1252   {
1253     g_warning ("could not create async clock thread: %s", error->message);
1254     g_error_free (error);
1255   }
1256   return FALSE;
1257 }
1258
1259 /* Add an entry to the list of pending async waits. The entry is inserted
1260  * in sorted order. If we inserted the entry at the head of the list, we
1261  * need to signal the thread as it might either be waiting on it or waiting
1262  * for a new entry.
1263  *
1264  * MT safe.
1265  */
1266 static GstClockReturn
1267 gst_system_clock_id_wait_async (GstClock * clock, GstClockEntry * entry)
1268 {
1269   GstSystemClock *sysclock;
1270   GstSystemClockPrivate *priv;
1271   GstClockEntry *head;
1272
1273   sysclock = GST_SYSTEM_CLOCK_CAST (clock);
1274   priv = sysclock->priv;
1275
1276   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "adding async entry %p", entry);
1277
1278   GST_SYSTEM_CLOCK_LOCK (clock);
1279   /* Start the clock async thread if needed */
1280   if (G_UNLIKELY (!gst_system_clock_start_async (sysclock)))
1281     goto thread_error;
1282
1283   ensure_entry_initialized ((GstClockEntryImpl *) entry);
1284   GST_SYSTEM_CLOCK_ENTRY_LOCK ((GstClockEntryImpl *) entry);
1285   if (G_UNLIKELY (GST_CLOCK_ENTRY_STATUS (entry) == GST_CLOCK_UNSCHEDULED))
1286     goto was_unscheduled;
1287   GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
1288
1289   if (priv->entries)
1290     head = priv->entries->data;
1291   else
1292     head = NULL;
1293
1294   /* need to take a ref */
1295   gst_clock_id_ref ((GstClockID) entry);
1296
1297   /* insert the entry in sorted order */
1298   priv->entries = g_list_insert_sorted (priv->entries, entry,
1299       gst_clock_id_compare_func);
1300
1301   /* only need to send the signal if the entry was added to the
1302    * front, else the thread is just waiting for another entry and
1303    * will get to this entry automatically. */
1304   if (priv->entries->data == entry) {
1305     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1306         "async entry added to head %p", head);
1307     if (head == NULL) {
1308       /* the list was empty before, signal the cond so that the async thread can
1309        * start taking a look at the queue */
1310       GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1311           "first entry, sending signal");
1312       GST_SYSTEM_CLOCK_BROADCAST (clock);
1313     } else {
1314       GstClockReturn status;
1315
1316       /* it was initialized before adding to the list */
1317       g_assert (((GstClockEntryImpl *) head)->initialized);
1318
1319       GST_SYSTEM_CLOCK_ENTRY_LOCK ((GstClockEntryImpl *) head);
1320       status = GST_CLOCK_ENTRY_STATUS (head);
1321       GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "head entry %p status %d",
1322           head, status);
1323
1324       if (status == GST_CLOCK_BUSY) {
1325         /* the async thread was waiting for an entry, unlock the wait so that it
1326          * looks at the new head entry instead, we only need to do this once */
1327         GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1328             "head entry was busy. Wakeup async thread");
1329         GST_SYSTEM_CLOCK_ENTRY_BROADCAST ((GstClockEntryImpl *) head);
1330       }
1331       GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) head);
1332     }
1333   }
1334   GST_SYSTEM_CLOCK_UNLOCK (clock);
1335
1336   return GST_CLOCK_OK;
1337
1338   /* ERRORS */
1339 thread_error:
1340   {
1341     /* Could not start the async clock thread */
1342     GST_SYSTEM_CLOCK_UNLOCK (clock);
1343     return GST_CLOCK_ERROR;
1344   }
1345 was_unscheduled:
1346   {
1347     GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
1348     GST_SYSTEM_CLOCK_UNLOCK (clock);
1349     return GST_CLOCK_UNSCHEDULED;
1350   }
1351 }
1352
1353 /* unschedule an entry. This will set the state of the entry to GST_CLOCK_UNSCHEDULED
1354  * and will signal any thread waiting for entries to recheck their entry.
1355  * We cannot really decide if the signal is needed or not because the entry
1356  * could be waited on in async or sync mode.
1357  *
1358  * MT safe.
1359  */
1360 static void
1361 gst_system_clock_id_unschedule (GstClock * clock, GstClockEntry * entry)
1362 {
1363   GstClockReturn status;
1364
1365   GST_SYSTEM_CLOCK_LOCK (clock);
1366
1367   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "unscheduling entry %p time %"
1368       GST_TIME_FORMAT, entry, GST_TIME_ARGS (GST_CLOCK_ENTRY_TIME (entry)));
1369
1370   ensure_entry_initialized ((GstClockEntryImpl *) entry);
1371
1372   GST_SYSTEM_CLOCK_ENTRY_LOCK ((GstClockEntryImpl *) entry);
1373   /* change the entry status to unscheduled */
1374   status = GST_CLOCK_ENTRY_STATUS (entry);
1375   GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_UNSCHEDULED;
1376
1377   if (G_LIKELY (status == GST_CLOCK_BUSY)) {
1378     /* the entry was being busy, wake up the entry */
1379     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "entry was BUSY, doing wakeup");
1380     GST_SYSTEM_CLOCK_ENTRY_BROADCAST ((GstClockEntryImpl *) entry);
1381   }
1382   GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
1383   GST_SYSTEM_CLOCK_UNLOCK (clock);
1384 }