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