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