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