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