gstfunnel: avoid access of freed pad
[platform/upstream/gstreamer.git] / 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., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /**
24  * SECTION:gstsystemclock
25  * @short_description: Default clock that uses the current system time
26  * @see_also: #GstClock
27  *
28  * The GStreamer core provides a GstSystemClock based on the system time.
29  * Asynchronous callbacks are scheduled from an internal thread.
30  *
31  * Clock implementors are encouraged to subclass this systemclock as it
32  * implements the async notification.
33  *
34  * Subclasses can however override all of the important methods for sync and
35  * async notifications to implement their own callback methods or blocking
36  * wait operations.
37  *
38  * Last reviewed on 2006-03-08 (0.10.4)
39  */
40
41 #include "gst_private.h"
42 #include "gstinfo.h"
43 #include "gstsystemclock.h"
44 #include "gstenumtypes.h"
45 #include "gstpoll.h"
46 #include "gstutils.h"
47 #include "glib-compat-private.h"
48
49 #include <errno.h>
50
51 #ifdef G_OS_WIN32
52 #  define WIN32_LEAN_AND_MEAN   /* prevents from including too many things */
53 #  include <windows.h>          /* QueryPerformance* stuff */
54 #  undef WIN32_LEAN_AND_MEAN
55 #  ifndef EWOULDBLOCK
56 #  define EWOULDBLOCK EAGAIN    /* This is just to placate gcc */
57 #  endif
58 #endif /* G_OS_WIN32 */
59
60 #define GET_ENTRY_STATUS(e)          ((GstClockReturn) g_atomic_int_get(&GST_CLOCK_ENTRY_STATUS(e)))
61 #define SET_ENTRY_STATUS(e,val)      (g_atomic_int_set(&GST_CLOCK_ENTRY_STATUS(e),(val)))
62 #define CAS_ENTRY_STATUS(e,old,val)  (g_atomic_int_compare_and_exchange(\
63                                        (&GST_CLOCK_ENTRY_STATUS(e)), (old), (val)))
64
65 /* Define this to get some extra debug about jitter from each clock_wait */
66 #undef WAIT_DEBUGGING
67
68 #define GST_SYSTEM_CLOCK_GET_COND(clock)        (&GST_SYSTEM_CLOCK_CAST(clock)->priv->entries_changed)
69 #define GST_SYSTEM_CLOCK_WAIT(clock)            g_cond_wait(GST_SYSTEM_CLOCK_GET_COND(clock),GST_OBJECT_GET_LOCK(clock))
70 #define GST_SYSTEM_CLOCK_TIMED_WAIT(clock,tv)   g_cond_timed_wait(GST_SYSTEM_CLOCK_GET_COND(clock),GST_OBJECT_GET_LOCK(clock),tv)
71 #define GST_SYSTEM_CLOCK_BROADCAST(clock)       g_cond_broadcast(GST_SYSTEM_CLOCK_GET_COND(clock))
72
73 struct _GstSystemClockPrivate
74 {
75   GThread *thread;              /* thread for async notify */
76   gboolean stopping;
77
78   GList *entries;
79   GCond entries_changed;
80
81   GstClockType clock_type;
82   GstPoll *timer;
83   gint wakeup_count;            /* the number of entries with a pending wakeup */
84   gboolean async_wakeup;        /* if the wakeup was because of a async list change */
85
86 #ifdef G_OS_WIN32
87   LARGE_INTEGER start;
88   LARGE_INTEGER frequency;
89 #endif                          /* G_OS_WIN32 */
90 };
91
92 #define GST_SYSTEM_CLOCK_GET_PRIVATE(obj)  \
93    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_SYSTEM_CLOCK, \
94         GstSystemClockPrivate))
95
96 #ifdef HAVE_POSIX_TIMERS
97 # ifdef HAVE_MONOTONIC_CLOCK
98 #  define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_MONOTONIC
99 # else
100 #  define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_REALTIME
101 # endif
102 #else
103 #define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_REALTIME
104 #endif
105
106 enum
107 {
108   PROP_0,
109   PROP_CLOCK_TYPE,
110   /* FILL ME */
111 };
112
113 /* the one instance of the systemclock */
114 static GstClock *_the_system_clock = NULL;
115
116 static void gst_system_clock_dispose (GObject * object);
117 static void gst_system_clock_set_property (GObject * object, guint prop_id,
118     const GValue * value, GParamSpec * pspec);
119 static void gst_system_clock_get_property (GObject * object, guint prop_id,
120     GValue * value, GParamSpec * pspec);
121
122 static GstClockTime gst_system_clock_get_internal_time (GstClock * clock);
123 static guint64 gst_system_clock_get_resolution (GstClock * clock);
124 static GstClockReturn gst_system_clock_id_wait_jitter (GstClock * clock,
125     GstClockEntry * entry, GstClockTimeDiff * jitter);
126 static GstClockReturn gst_system_clock_id_wait_jitter_unlocked
127     (GstClock * clock, GstClockEntry * entry, GstClockTimeDiff * jitter,
128     gboolean restart);
129 static GstClockReturn gst_system_clock_id_wait_async (GstClock * clock,
130     GstClockEntry * entry);
131 static void gst_system_clock_id_unschedule (GstClock * clock,
132     GstClockEntry * entry);
133 static void gst_system_clock_async_thread (GstClock * clock);
134 static gboolean gst_system_clock_start_async (GstSystemClock * clock);
135 static void gst_system_clock_add_wakeup (GstSystemClock * sysclock);
136
137 static GMutex _gst_sysclock_mutex;
138
139 /* static guint gst_system_clock_signals[LAST_SIGNAL] = { 0 }; */
140
141 #define gst_system_clock_parent_class parent_class
142 G_DEFINE_TYPE (GstSystemClock, gst_system_clock, GST_TYPE_CLOCK);
143
144 static void
145 gst_system_clock_class_init (GstSystemClockClass * klass)
146 {
147   GObjectClass *gobject_class;
148   GstClockClass *gstclock_class;
149
150   gobject_class = (GObjectClass *) klass;
151   gstclock_class = (GstClockClass *) klass;
152
153   g_type_class_add_private (klass, sizeof (GstSystemClockPrivate));
154
155   gobject_class->dispose = gst_system_clock_dispose;
156   gobject_class->set_property = gst_system_clock_set_property;
157   gobject_class->get_property = gst_system_clock_get_property;
158
159   g_object_class_install_property (gobject_class, PROP_CLOCK_TYPE,
160       g_param_spec_enum ("clock-type", "Clock type",
161           "The type of underlying clock implementation used",
162           GST_TYPE_CLOCK_TYPE, DEFAULT_CLOCK_TYPE,
163           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
164
165   gstclock_class->get_internal_time = gst_system_clock_get_internal_time;
166   gstclock_class->get_resolution = gst_system_clock_get_resolution;
167   gstclock_class->wait = gst_system_clock_id_wait_jitter;
168   gstclock_class->wait_async = gst_system_clock_id_wait_async;
169   gstclock_class->unschedule = gst_system_clock_id_unschedule;
170 }
171
172 static void
173 gst_system_clock_init (GstSystemClock * clock)
174 {
175   GstSystemClockPrivate *priv;
176
177   GST_OBJECT_FLAG_SET (clock,
178       GST_CLOCK_FLAG_CAN_DO_SINGLE_SYNC |
179       GST_CLOCK_FLAG_CAN_DO_SINGLE_ASYNC |
180       GST_CLOCK_FLAG_CAN_DO_PERIODIC_SYNC |
181       GST_CLOCK_FLAG_CAN_DO_PERIODIC_ASYNC);
182
183   clock->priv = priv = GST_SYSTEM_CLOCK_GET_PRIVATE (clock);
184
185   priv->clock_type = DEFAULT_CLOCK_TYPE;
186   priv->timer = gst_poll_new_timer ();
187
188   priv->entries = NULL;
189   g_cond_init (&priv->entries_changed);
190
191 #ifdef G_OS_WIN32
192   QueryPerformanceFrequency (&priv->frequency);
193   /* can be 0 if the hardware does not have hardware support */
194   if (priv->frequency.QuadPart != 0)
195     /* we take a base time so that time starts from 0 to ease debugging */
196     QueryPerformanceCounter (&priv->start);
197 #endif /* G_OS_WIN32 */
198
199 #if 0
200   /* Uncomment this to start the async clock thread straight away */
201   GST_OBJECT_LOCK (clock);
202   gst_system_clock_start_async (clock);
203   GST_OBJECT_UNLOCK (clock);
204 #endif
205 }
206
207 static void
208 gst_system_clock_dispose (GObject * object)
209 {
210   GstClock *clock = (GstClock *) object;
211   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
212   GstSystemClockPrivate *priv = sysclock->priv;
213   GList *entries;
214
215   /* else we have to stop the thread */
216   GST_OBJECT_LOCK (clock);
217   priv->stopping = TRUE;
218   /* unschedule all entries */
219   for (entries = priv->entries; entries; entries = g_list_next (entries)) {
220     GstClockEntry *entry = (GstClockEntry *) entries->data;
221
222     GST_CAT_DEBUG (GST_CAT_CLOCK, "unscheduling entry %p", entry);
223     SET_ENTRY_STATUS (entry, GST_CLOCK_UNSCHEDULED);
224   }
225   GST_SYSTEM_CLOCK_BROADCAST (clock);
226   gst_system_clock_add_wakeup (sysclock);
227   GST_OBJECT_UNLOCK (clock);
228
229   if (priv->thread)
230     g_thread_join (priv->thread);
231   priv->thread = NULL;
232   GST_CAT_DEBUG (GST_CAT_CLOCK, "joined thread");
233
234   g_list_foreach (priv->entries, (GFunc) gst_clock_id_unref, NULL);
235   g_list_free (priv->entries);
236   priv->entries = NULL;
237
238   gst_poll_free (priv->timer);
239   g_cond_clear (&priv->entries_changed);
240
241   G_OBJECT_CLASS (parent_class)->dispose (object);
242
243   if (_the_system_clock == clock) {
244     _the_system_clock = NULL;
245     GST_CAT_DEBUG (GST_CAT_CLOCK, "disposed system clock");
246   }
247 }
248
249 static void
250 gst_system_clock_set_property (GObject * object, guint prop_id,
251     const GValue * value, GParamSpec * pspec)
252 {
253   GstSystemClock *sysclock = GST_SYSTEM_CLOCK (object);
254
255   switch (prop_id) {
256     case PROP_CLOCK_TYPE:
257       sysclock->priv->clock_type = (GstClockType) g_value_get_enum (value);
258       GST_CAT_DEBUG (GST_CAT_CLOCK, "clock-type set to %d",
259           sysclock->priv->clock_type);
260       break;
261     default:
262       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
263       break;
264   }
265 }
266
267 static void
268 gst_system_clock_get_property (GObject * object, guint prop_id, GValue * value,
269     GParamSpec * pspec)
270 {
271   GstSystemClock *sysclock = GST_SYSTEM_CLOCK (object);
272
273   switch (prop_id) {
274     case PROP_CLOCK_TYPE:
275       g_value_set_enum (value, sysclock->priv->clock_type);
276       break;
277     default:
278       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
279       break;
280   }
281 }
282
283 /**
284  * gst_system_clock_obtain:
285  *
286  * Get a handle to the default system clock. The refcount of the
287  * clock will be increased so you need to unref the clock after
288  * usage.
289  *
290  * Returns: (transfer full): the default clock.
291  *
292  * MT safe.
293  */
294 GstClock *
295 gst_system_clock_obtain (void)
296 {
297   GstClock *clock;
298
299   g_mutex_lock (&_gst_sysclock_mutex);
300   clock = _the_system_clock;
301
302   if (clock == NULL) {
303     GST_CAT_DEBUG (GST_CAT_CLOCK, "creating new static system clock");
304     clock = g_object_new (GST_TYPE_SYSTEM_CLOCK,
305         "name", "GstSystemClock", NULL);
306
307     /* we created the global clock; take ownership so
308      * we can hand out instances later */
309     gst_object_ref_sink (clock);
310
311     _the_system_clock = clock;
312     g_mutex_unlock (&_gst_sysclock_mutex);
313   } else {
314     g_mutex_unlock (&_gst_sysclock_mutex);
315     GST_CAT_DEBUG (GST_CAT_CLOCK, "returning static system clock");
316   }
317
318   /* we ref it since we are a clock factory. */
319   gst_object_ref (clock);
320   return clock;
321 }
322
323 static void
324 gst_system_clock_remove_wakeup (GstSystemClock * sysclock)
325 {
326   g_return_if_fail (sysclock->priv->wakeup_count > 0);
327
328   sysclock->priv->wakeup_count--;
329   if (sysclock->priv->wakeup_count == 0) {
330     /* read the control socket byte when we removed the last wakeup count */
331     GST_CAT_DEBUG (GST_CAT_CLOCK, "reading control");
332     while (!gst_poll_read_control (sysclock->priv->timer)) {
333       g_warning ("gstsystemclock: read control failed, trying again\n");
334     }
335     GST_SYSTEM_CLOCK_BROADCAST (sysclock);
336   }
337   GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup count %d",
338       sysclock->priv->wakeup_count);
339 }
340
341 static void
342 gst_system_clock_add_wakeup (GstSystemClock * sysclock)
343 {
344   /* only write the control socket for the first wakeup */
345   if (sysclock->priv->wakeup_count == 0) {
346     GST_CAT_DEBUG (GST_CAT_CLOCK, "writing control");
347     while (!gst_poll_write_control (sysclock->priv->timer)) {
348       if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
349         g_warning
350             ("gstsystemclock: write control failed in wakeup_async, trying again: %d:%s\n",
351             errno, g_strerror (errno));
352       } else {
353         g_critical
354             ("gstsystemclock: write control failed in wakeup_async: %d:%s\n",
355             errno, g_strerror (errno));
356         return;
357       }
358     }
359   }
360   sysclock->priv->wakeup_count++;
361   GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup count %d",
362       sysclock->priv->wakeup_count);
363 }
364
365 static void
366 gst_system_clock_wait_wakeup (GstSystemClock * sysclock)
367 {
368   while (sysclock->priv->wakeup_count > 0) {
369     GST_SYSTEM_CLOCK_WAIT (sysclock);
370   }
371 }
372
373 /* this thread reads the sorted clock entries from the queue.
374  *
375  * It waits on each of them and fires the callback when the timeout occurs.
376  *
377  * When an entry in the queue was canceled before we wait for it, it is
378  * simply skipped.
379  *
380  * When waiting for an entry, it can become canceled, in that case we don't
381  * call the callback but move to the next item in the queue.
382  *
383  * MT safe.
384  */
385 static void
386 gst_system_clock_async_thread (GstClock * clock)
387 {
388   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
389   GstSystemClockPrivate *priv = sysclock->priv;
390
391   GST_CAT_DEBUG (GST_CAT_CLOCK, "enter system clock thread");
392   GST_OBJECT_LOCK (clock);
393   /* signal spinup */
394   GST_SYSTEM_CLOCK_BROADCAST (clock);
395   /* now enter our (almost) infinite loop */
396   while (!priv->stopping) {
397     GstClockEntry *entry;
398     GstClockTime requested;
399     GstClockReturn res;
400
401     /* check if something to be done */
402     while (priv->entries == NULL) {
403       GST_CAT_DEBUG (GST_CAT_CLOCK, "no clock entries, waiting..");
404       /* wait for work to do */
405       GST_SYSTEM_CLOCK_WAIT (clock);
406       GST_CAT_DEBUG (GST_CAT_CLOCK, "got signal");
407       /* clock was stopping, exit */
408       if (priv->stopping)
409         goto exit;
410     }
411
412     /* see if we have a pending wakeup because the order of the list
413      * changed. */
414     if (priv->async_wakeup) {
415       GST_CAT_DEBUG (GST_CAT_CLOCK, "clear async wakeup");
416       gst_system_clock_remove_wakeup (sysclock);
417       priv->async_wakeup = FALSE;
418     }
419
420     /* pick the next entry */
421     entry = priv->entries->data;
422     GST_OBJECT_UNLOCK (clock);
423
424     requested = entry->time;
425
426     /* now wait for the entry, we already hold the lock */
427     res =
428         gst_system_clock_id_wait_jitter_unlocked (clock, (GstClockID) entry,
429         NULL, FALSE);
430
431     GST_OBJECT_LOCK (clock);
432
433     switch (res) {
434       case GST_CLOCK_UNSCHEDULED:
435         /* entry was unscheduled, move to the next */
436         GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry %p unscheduled", entry);
437         goto next_entry;
438       case GST_CLOCK_OK:
439       case GST_CLOCK_EARLY:
440       {
441         /* entry timed out normally, fire the callback and move to the next
442          * entry */
443         GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry %p timed out", entry);
444         if (entry->func) {
445           /* unlock before firing the callback */
446           GST_OBJECT_UNLOCK (clock);
447           entry->func (clock, entry->time, (GstClockID) entry,
448               entry->user_data);
449           GST_OBJECT_LOCK (clock);
450         }
451         if (entry->type == GST_CLOCK_ENTRY_PERIODIC) {
452           GST_CAT_DEBUG (GST_CAT_CLOCK, "updating periodic entry %p", entry);
453           /* adjust time now */
454           entry->time = requested + entry->interval;
455           /* and resort the list now */
456           priv->entries =
457               g_list_sort (priv->entries, gst_clock_id_compare_func);
458           /* and restart */
459           continue;
460         } else {
461           GST_CAT_DEBUG (GST_CAT_CLOCK, "moving to next entry");
462           goto next_entry;
463         }
464       }
465       case GST_CLOCK_BUSY:
466         /* somebody unlocked the entry but is was not canceled, This means that
467          * either a new entry was added in front of the queue or some other entry
468          * was canceled. Whatever it is, pick the head entry of the list and
469          * continue waiting. */
470         GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry %p needs restart", entry);
471
472         /* we set the entry back to the OK state. This is needed so that the
473          * _unschedule() code can see if an entry is currently being waited
474          * on (when its state is BUSY). */
475         SET_ENTRY_STATUS (entry, GST_CLOCK_OK);
476         continue;
477       default:
478         GST_CAT_DEBUG (GST_CAT_CLOCK,
479             "strange result %d waiting for %p, skipping", res, entry);
480         g_warning ("%s: strange result %d waiting for %p, skipping",
481             GST_OBJECT_NAME (clock), res, entry);
482         goto next_entry;
483     }
484   next_entry:
485     /* we remove the current entry and unref it */
486     priv->entries = g_list_remove (priv->entries, entry);
487     gst_clock_id_unref ((GstClockID) entry);
488   }
489 exit:
490   /* signal exit */
491   GST_SYSTEM_CLOCK_BROADCAST (clock);
492   GST_OBJECT_UNLOCK (clock);
493   GST_CAT_DEBUG (GST_CAT_CLOCK, "exit system clock thread");
494 }
495
496 #ifdef HAVE_POSIX_TIMERS
497 static inline clockid_t
498 clock_type_to_posix_id (GstClockType clock_type)
499 {
500 #ifdef HAVE_MONOTONIC_CLOCK
501   if (clock_type == GST_CLOCK_TYPE_MONOTONIC)
502     return CLOCK_MONOTONIC;
503   else
504 #endif
505     return CLOCK_REALTIME;
506 }
507 #endif
508
509 /* MT safe */
510 static GstClockTime
511 gst_system_clock_get_internal_time (GstClock * clock)
512 {
513 #ifdef G_OS_WIN32
514   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
515
516   if (sysclock->priv->frequency.QuadPart != 0) {
517     LARGE_INTEGER now;
518
519     /* we prefer the highly accurate performance counters on windows */
520     QueryPerformanceCounter (&now);
521
522     return gst_util_uint64_scale (now.QuadPart - sysclock->priv->start.QuadPart,
523         GST_SECOND, sysclock->priv->frequency.QuadPart);
524   } else
525 #endif /* G_OS_WIN32 */
526 #if !defined HAVE_POSIX_TIMERS
527   {
528     GTimeVal timeval;
529
530     g_get_current_time (&timeval);
531
532     return GST_TIMEVAL_TO_TIME (timeval);
533   }
534 #else
535   {
536     GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
537     clockid_t ptype;
538     struct timespec ts;
539
540     ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
541
542     if (G_UNLIKELY (clock_gettime (ptype, &ts)))
543       return GST_CLOCK_TIME_NONE;
544
545     return GST_TIMESPEC_TO_TIME (ts);
546   }
547 #endif
548 }
549
550 static guint64
551 gst_system_clock_get_resolution (GstClock * clock)
552 {
553 #ifdef G_OS_WIN32
554   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
555
556   if (sysclock->priv->frequency.QuadPart != 0) {
557     return GST_SECOND / sysclock->priv->frequency.QuadPart;
558   } else
559 #endif /* G_OS_WIN32 */
560 #ifdef HAVE_POSIX_TIMERS
561   {
562     GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
563     clockid_t ptype;
564     struct timespec ts;
565
566     ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
567
568     if (G_UNLIKELY (clock_getres (ptype, &ts)))
569       return GST_CLOCK_TIME_NONE;
570
571     return GST_TIMESPEC_TO_TIME (ts);
572   }
573 #else
574   {
575     return 1 * GST_USECOND;
576   }
577 #endif
578 }
579
580 /* synchronously wait on the given GstClockEntry.
581  *
582  * We do this by blocking on the global GstPoll timer with
583  * the requested timeout. This allows us to unblock the
584  * entry by writing on the control fd.
585  *
586  * Note that writing the global GstPoll unlocks all waiting entries. So
587  * we need to check if an unlocked entry has changed when it unlocks.
588  *
589  * Entries that arrive too late are simply not waited on and a
590  * GST_CLOCK_EARLY result is returned.
591  *
592  * MT safe.
593  */
594 static GstClockReturn
595 gst_system_clock_id_wait_jitter_unlocked (GstClock * clock,
596     GstClockEntry * entry, GstClockTimeDiff * jitter, gboolean restart)
597 {
598   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
599   GstClockTime entryt, now;
600   GstClockTimeDiff diff;
601   GstClockReturn status;
602
603   if (G_UNLIKELY (GET_ENTRY_STATUS (entry) == GST_CLOCK_UNSCHEDULED))
604     return GST_CLOCK_UNSCHEDULED;
605
606   /* need to call the overridden method because we want to sync against the time
607    * of the clock, whatever the subclass uses as a clock. */
608   now = gst_clock_get_time (clock);
609
610   /* get the time of the entry */
611   entryt = GST_CLOCK_ENTRY_TIME (entry);
612
613   /* the diff of the entry with the clock is the amount of time we have to
614    * wait */
615   diff = GST_CLOCK_DIFF (now, entryt);
616   if (G_LIKELY (jitter))
617     *jitter = -diff;
618
619   GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p"
620       " time %" GST_TIME_FORMAT
621       " now %" GST_TIME_FORMAT
622       " diff (time-now) %" G_GINT64_FORMAT,
623       entry, GST_TIME_ARGS (entryt), GST_TIME_ARGS (now), diff);
624
625   if (G_LIKELY (diff > 0)) {
626 #ifdef WAIT_DEBUGGING
627     GstClockTime final;
628 #endif
629
630     while (TRUE) {
631       gint pollret;
632
633       do {
634         status = GET_ENTRY_STATUS (entry);
635
636         /* stop when we are unscheduled */
637         if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
638           goto done;
639
640         /* mark the entry as busy but watch out for intermediate unscheduled
641          * statuses */
642       } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_BUSY)));
643
644       /* now wait on the entry, it either times out or the fd is written. The
645        * status of the entry is only BUSY around the poll. */
646       pollret = gst_poll_wait (sysclock->priv->timer, diff);
647
648       /* get the new status, mark as DONE. We do this so that the unschedule
649        * function knows when we left the poll and doesn't need to wakeup the
650        * poll anymore. */
651       do {
652         status = GET_ENTRY_STATUS (entry);
653         /* we were unscheduled, exit immediately */
654         if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
655           break;
656       } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_DONE)));
657
658       GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p unlocked, status %d, ret %d",
659           entry, status, pollret);
660
661       if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
662         /* try to clean up The unschedule function managed to set the status to
663          * unscheduled. We now take the lock and mark the entry as unscheduled.
664          * This makes sure that the unschedule function doesn't perform a
665          * wakeup anymore. If the unschedule function has a change to perform
666          * the wakeup before us, we clean up here */
667         GST_OBJECT_LOCK (sysclock);
668         entry->unscheduled = TRUE;
669         if (entry->woken_up) {
670           gst_system_clock_remove_wakeup (sysclock);
671         }
672         GST_OBJECT_UNLOCK (sysclock);
673         goto done;
674       } else {
675         if (G_UNLIKELY (pollret != 0)) {
676           /* some other id got unlocked */
677           if (!restart) {
678             /* this can happen if the entry got unlocked because of an async
679              * entry was added to the head of the async queue. */
680             GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup waiting for entry %p", entry);
681             goto done;
682           }
683
684           /* wait till all the entries got woken up */
685           GST_OBJECT_LOCK (sysclock);
686           gst_system_clock_wait_wakeup (sysclock);
687           GST_OBJECT_UNLOCK (sysclock);
688
689           GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p needs to be restarted",
690               entry);
691         } else {
692           GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p unlocked after timeout",
693               entry);
694         }
695
696         /* reschedule if gst_poll_wait returned early or we have to reschedule after
697          * an unlock*/
698         now = gst_clock_get_time (clock);
699         diff = GST_CLOCK_DIFF (now, entryt);
700
701         if (diff <= 0) {
702           /* timeout, this is fine, we can report success now */
703           status = GST_CLOCK_OK;
704           SET_ENTRY_STATUS (entry, status);
705
706           GST_CAT_DEBUG (GST_CAT_CLOCK,
707               "entry %p finished, diff %" G_GINT64_FORMAT, entry, diff);
708
709 #ifdef WAIT_DEBUGGING
710           final = gst_system_clock_get_internal_time (clock);
711           GST_CAT_DEBUG (GST_CAT_CLOCK, "Waited for %" G_GINT64_FORMAT
712               " got %" G_GINT64_FORMAT " diff %" G_GINT64_FORMAT
713               " %g target-offset %" G_GINT64_FORMAT " %g", entryt, now,
714               now - entryt,
715               (double) (GstClockTimeDiff) (now - entryt) / GST_SECOND,
716               (final - target),
717               ((double) (GstClockTimeDiff) (final - target)) / GST_SECOND);
718 #endif
719           goto done;
720         } else {
721           GST_CAT_DEBUG (GST_CAT_CLOCK,
722               "entry %p restart, diff %" G_GINT64_FORMAT, entry, diff);
723         }
724       }
725     }
726   } else {
727     /* we are right on time or too late */
728     if (G_UNLIKELY (diff == 0))
729       status = GST_CLOCK_OK;
730     else
731       status = GST_CLOCK_EARLY;
732
733     SET_ENTRY_STATUS (entry, status);
734   }
735 done:
736   return status;
737 }
738
739 static GstClockReturn
740 gst_system_clock_id_wait_jitter (GstClock * clock, GstClockEntry * entry,
741     GstClockTimeDiff * jitter)
742 {
743   return gst_system_clock_id_wait_jitter_unlocked (clock, entry, jitter, TRUE);
744 }
745
746 /* Start the async clock thread. Must be called with the object lock
747  * held */
748 static gboolean
749 gst_system_clock_start_async (GstSystemClock * clock)
750 {
751   GError *error = NULL;
752   GstSystemClockPrivate *priv = clock->priv;
753
754   if (G_LIKELY (priv->thread != NULL))
755     return TRUE;                /* Thread already running. Nothing to do */
756
757   priv->thread = g_thread_try_new ("GstSystemClock",
758       (GThreadFunc) gst_system_clock_async_thread, clock, &error);
759
760   if (G_UNLIKELY (error))
761     goto no_thread;
762
763   /* wait for it to spin up */
764   GST_SYSTEM_CLOCK_WAIT (clock);
765
766   return TRUE;
767
768   /* ERRORS */
769 no_thread:
770   {
771     g_warning ("could not create async clock thread: %s", error->message);
772     g_error_free (error);
773   }
774   return FALSE;
775 }
776
777 /* Add an entry to the list of pending async waits. The entry is inserted
778  * in sorted order. If we inserted the entry at the head of the list, we
779  * need to signal the thread as it might either be waiting on it or waiting
780  * for a new entry.
781  *
782  * MT safe.
783  */
784 static GstClockReturn
785 gst_system_clock_id_wait_async (GstClock * clock, GstClockEntry * entry)
786 {
787   GstSystemClock *sysclock;
788   GstSystemClockPrivate *priv;
789   GstClockEntry *head;
790
791   sysclock = GST_SYSTEM_CLOCK_CAST (clock);
792   priv = sysclock->priv;
793
794   GST_CAT_DEBUG (GST_CAT_CLOCK, "adding async entry %p", entry);
795
796   GST_OBJECT_LOCK (clock);
797   /* Start the clock async thread if needed */
798   if (G_UNLIKELY (!gst_system_clock_start_async (sysclock)))
799     goto thread_error;
800
801   if (G_UNLIKELY (GET_ENTRY_STATUS (entry) == GST_CLOCK_UNSCHEDULED))
802     goto was_unscheduled;
803
804   if (priv->entries)
805     head = priv->entries->data;
806   else
807     head = NULL;
808
809   /* need to take a ref */
810   gst_clock_id_ref ((GstClockID) entry);
811   /* insert the entry in sorted order */
812   priv->entries = g_list_insert_sorted (priv->entries, entry,
813       gst_clock_id_compare_func);
814
815   /* only need to send the signal if the entry was added to the
816    * front, else the thread is just waiting for another entry and
817    * will get to this entry automatically. */
818   if (priv->entries->data == entry) {
819     GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry added to head %p", head);
820     if (head == NULL) {
821       /* the list was empty before, signal the cond so that the async thread can
822        * start taking a look at the queue */
823       GST_CAT_DEBUG (GST_CAT_CLOCK, "first entry, sending signal");
824       GST_SYSTEM_CLOCK_BROADCAST (clock);
825     } else {
826       GstClockReturn status;
827
828       status = GET_ENTRY_STATUS (head);
829       GST_CAT_DEBUG (GST_CAT_CLOCK, "head entry %p status %d", head, status);
830
831       if (status == GST_CLOCK_BUSY) {
832         GST_CAT_DEBUG (GST_CAT_CLOCK, "head entry is busy");
833         /* the async thread was waiting for an entry, unlock the wait so that it
834          * looks at the new head entry instead, we only need to do this once */
835         if (!priv->async_wakeup) {
836           GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup async thread");
837           priv->async_wakeup = TRUE;
838           gst_system_clock_add_wakeup (sysclock);
839         }
840       }
841     }
842   }
843   GST_OBJECT_UNLOCK (clock);
844
845   return GST_CLOCK_OK;
846
847   /* ERRORS */
848 thread_error:
849   {
850     /* Could not start the async clock thread */
851     GST_OBJECT_UNLOCK (clock);
852     return GST_CLOCK_ERROR;
853   }
854 was_unscheduled:
855   {
856     GST_OBJECT_UNLOCK (clock);
857     return GST_CLOCK_UNSCHEDULED;
858   }
859 }
860
861 /* unschedule an entry. This will set the state of the entry to GST_CLOCK_UNSCHEDULED
862  * and will signal any thread waiting for entries to recheck their entry.
863  * We cannot really decide if the signal is needed or not because the entry
864  * could be waited on in async or sync mode.
865  *
866  * MT safe.
867  */
868 static void
869 gst_system_clock_id_unschedule (GstClock * clock, GstClockEntry * entry)
870 {
871   GstSystemClock *sysclock;
872   GstClockReturn status;
873
874   sysclock = GST_SYSTEM_CLOCK_CAST (clock);
875
876   GST_CAT_DEBUG (GST_CAT_CLOCK, "unscheduling entry %p", entry);
877
878   GST_OBJECT_LOCK (clock);
879   /* change the entry status to unscheduled */
880   do {
881     status = GET_ENTRY_STATUS (entry);
882   } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status,
883               GST_CLOCK_UNSCHEDULED)));
884
885   if (G_LIKELY (status == GST_CLOCK_BUSY)) {
886     /* the entry was being busy, wake up all entries so that they recheck their
887      * status. We cannot wake up just one entry because allocating such a
888      * datastructure for each entry would be too heavy and unlocking an entry
889      * is usually done when shutting down or some other exceptional case. */
890     GST_CAT_DEBUG (GST_CAT_CLOCK, "entry was BUSY, doing wakeup");
891     if (!entry->unscheduled && !entry->woken_up) {
892       gst_system_clock_add_wakeup (sysclock);
893       entry->woken_up = TRUE;
894     }
895   }
896   GST_OBJECT_UNLOCK (clock);
897 }