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