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