tee: Check for the removed pad flag also in the slow pushing path
[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 -
586             sysclock->priv->start.QuadPart) * sysclock->priv->ratio);
587   } else
588 #endif /* G_OS_WIN32 */
589 #if !defined HAVE_POSIX_TIMERS || !defined HAVE_CLOCK_GETTIME
590   {
591     GTimeVal timeval;
592
593     g_get_current_time (&timeval);
594
595     return GST_TIMEVAL_TO_TIME (timeval);
596   }
597 #else
598   {
599     GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
600     clockid_t ptype;
601     struct timespec ts;
602
603     ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
604
605     if (G_UNLIKELY (clock_gettime (ptype, &ts)))
606       return GST_CLOCK_TIME_NONE;
607
608     return GST_TIMESPEC_TO_TIME (ts);
609   }
610 #endif
611 #endif /* __APPLE__ */
612 }
613
614 static guint64
615 gst_system_clock_get_resolution (GstClock * clock)
616 {
617 #if defined __APPLE__
618   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
619   return gst_util_uint64_scale (GST_NSECOND,
620       sysclock->priv->mach_timebase.numer, sysclock->priv->mach_timebase.denom);
621 #else
622 #ifdef G_OS_WIN32
623   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
624
625   if (sysclock->priv->frequency.QuadPart != 0) {
626     return GST_SECOND / sysclock->priv->frequency.QuadPart;
627   } else
628 #endif /* G_OS_WIN32 */
629 #if defined(HAVE_POSIX_TIMERS) && defined(HAVE_CLOCK_GETTIME)
630   {
631     GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
632     clockid_t ptype;
633     struct timespec ts;
634
635     ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
636
637     if (G_UNLIKELY (clock_getres (ptype, &ts)))
638       return GST_CLOCK_TIME_NONE;
639
640     return GST_TIMESPEC_TO_TIME (ts);
641   }
642 #else
643   {
644     return 1 * GST_USECOND;
645   }
646 #endif
647 #endif /* __APPLE__ */
648 }
649
650 static inline void
651 gst_system_clock_cleanup_unscheduled (GstSystemClock * sysclock,
652     GstClockEntry * entry)
653 {
654   /* try to clean up.
655    * The unschedule function managed to set the status to
656    * unscheduled. We now take the lock and mark the entry as unscheduled.
657    * This makes sure that the unschedule function doesn't perform a
658    * wakeup anymore. If the unschedule function has a change to perform
659    * the wakeup before us, we clean up here */
660   GST_OBJECT_LOCK (sysclock);
661   entry->unscheduled = TRUE;
662   if (entry->woken_up) {
663     gst_system_clock_remove_wakeup (sysclock);
664   }
665   GST_OBJECT_UNLOCK (sysclock);
666 }
667
668 /* synchronously wait on the given GstClockEntry.
669  *
670  * We do this by blocking on the global GstPoll timer with
671  * the requested timeout. This allows us to unblock the
672  * entry by writing on the control fd.
673  *
674  * Note that writing the global GstPoll unlocks all waiting entries. So
675  * we need to check if an unlocked entry has changed when it unlocks.
676  *
677  * Entries that arrive too late are simply not waited on and a
678  * GST_CLOCK_EARLY result is returned.
679  *
680  * MT safe.
681  */
682 static GstClockReturn
683 gst_system_clock_id_wait_jitter_unlocked (GstClock * clock,
684     GstClockEntry * entry, GstClockTimeDiff * jitter, gboolean restart)
685 {
686   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
687   GstClockTime entryt, now;
688   GstClockTimeDiff diff;
689   GstClockReturn status;
690
691   status = GET_ENTRY_STATUS (entry);
692   if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
693     gst_system_clock_cleanup_unscheduled (sysclock, entry);
694     return GST_CLOCK_UNSCHEDULED;
695   }
696
697   /* need to call the overridden method because we want to sync against the time
698    * of the clock, whatever the subclass uses as a clock. */
699   now = gst_clock_get_time (clock);
700
701   /* get the time of the entry */
702   entryt = GST_CLOCK_ENTRY_TIME (entry);
703
704   /* the diff of the entry with the clock is the amount of time we have to
705    * wait */
706   diff = GST_CLOCK_DIFF (now, entryt);
707   if (G_LIKELY (jitter))
708     *jitter = -diff;
709
710   GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p"
711       " time %" GST_TIME_FORMAT
712       " now %" GST_TIME_FORMAT
713       " diff (time-now) %" G_GINT64_FORMAT,
714       entry, GST_TIME_ARGS (entryt), GST_TIME_ARGS (now), diff);
715
716   if (G_LIKELY (diff > 0)) {
717 #ifdef WAIT_DEBUGGING
718     GstClockTime final;
719 #endif
720
721     while (TRUE) {
722       gint pollret;
723
724       /* now wait on the entry, it either times out or the fd is written. The
725        * status of the entry is BUSY only around the poll. */
726       pollret = gst_poll_wait (sysclock->priv->timer, diff);
727
728       /* get the new status, mark as DONE. We do this so that the unschedule
729        * function knows when we left the poll and doesn't need to wakeup the
730        * poll anymore. */
731       do {
732         status = GET_ENTRY_STATUS (entry);
733         /* we were unscheduled, exit immediately */
734         if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
735           break;
736         if (G_UNLIKELY (status != GST_CLOCK_BUSY))
737           GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
738               status, entry);
739       } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_DONE)));
740
741       GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p unlocked, status %d, ret %d",
742           entry, status, pollret);
743
744       if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
745         gst_system_clock_cleanup_unscheduled (sysclock, entry);
746         goto done;
747       } else {
748         if (G_UNLIKELY (pollret != 0)) {
749           /* some other id got unlocked */
750           if (!restart) {
751             /* this can happen if the entry got unlocked because of an async
752              * entry was added to the head of the async queue. */
753             GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup waiting for entry %p", entry);
754             goto done;
755           }
756
757           /* wait till all the entries got woken up */
758           GST_OBJECT_LOCK (sysclock);
759           gst_system_clock_wait_wakeup (sysclock);
760           GST_OBJECT_UNLOCK (sysclock);
761
762           GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p needs to be restarted",
763               entry);
764         } else {
765           GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p unlocked after timeout",
766               entry);
767         }
768
769         /* reschedule if gst_poll_wait returned early or we have to reschedule after
770          * an unlock*/
771         now = gst_clock_get_time (clock);
772         diff = GST_CLOCK_DIFF (now, entryt);
773
774         if (diff <= 0) {
775           /* timeout, this is fine, we can report success now */
776           if (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, GST_CLOCK_DONE,
777                       GST_CLOCK_OK))) {
778             status = GET_ENTRY_STATUS (entry);
779             if (status != GST_CLOCK_UNSCHEDULED)
780               GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
781                   status, entry);
782             goto done;
783           } else {
784             status = GST_CLOCK_OK;
785           }
786
787           GST_CAT_DEBUG (GST_CAT_CLOCK,
788               "entry %p finished, diff %" G_GINT64_FORMAT, entry, diff);
789
790 #ifdef WAIT_DEBUGGING
791           final = gst_system_clock_get_internal_time (clock);
792           GST_CAT_DEBUG (GST_CAT_CLOCK, "Waited for %" G_GINT64_FORMAT
793               " got %" G_GINT64_FORMAT " diff %" G_GINT64_FORMAT
794               " %g target-offset %" G_GINT64_FORMAT " %g", entryt, now,
795               now - entryt,
796               (double) (GstClockTimeDiff) (now - entryt) / GST_SECOND,
797               (final - target),
798               ((double) (GstClockTimeDiff) (final - target)) / GST_SECOND);
799 #endif
800           goto done;
801         } else {
802           GST_CAT_DEBUG (GST_CAT_CLOCK,
803               "entry %p restart, diff %" G_GINT64_FORMAT, entry, diff);
804           /* we are going to poll again, set status back to busy */
805           do {
806             status = GET_ENTRY_STATUS (entry);
807             /* we were unscheduled, exit immediately */
808             if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
809               goto done;
810             if (G_UNLIKELY (status != GST_CLOCK_DONE))
811               GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
812                   status, entry);
813           } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status,
814                       GST_CLOCK_BUSY)));
815         }
816       }
817     }
818   } else {
819     /* we are right on time or too late */
820     if (G_UNLIKELY (diff == 0)) {
821       if (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_OK))) {
822         status = GET_ENTRY_STATUS (entry);
823         if (G_LIKELY (status == GST_CLOCK_UNSCHEDULED))
824           gst_system_clock_cleanup_unscheduled (sysclock, entry);
825         else
826           GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
827               status, entry);
828       } else {
829         status = GST_CLOCK_OK;
830       }
831     } else {
832       if (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_EARLY))) {
833         status = GET_ENTRY_STATUS (entry);
834         if (G_LIKELY (status == GST_CLOCK_UNSCHEDULED))
835           gst_system_clock_cleanup_unscheduled (sysclock, entry);
836         else
837           GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
838               status, entry);
839       } else {
840         status = GST_CLOCK_EARLY;
841       }
842     }
843   }
844 done:
845   return status;
846 }
847
848 static GstClockReturn
849 gst_system_clock_id_wait_jitter (GstClock * clock, GstClockEntry * entry,
850     GstClockTimeDiff * jitter)
851 {
852   GstClockReturn status;
853   do {
854     status = GET_ENTRY_STATUS (entry);
855
856     /* stop when we are unscheduled */
857     if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
858       return status;
859
860     if (G_UNLIKELY (status != GST_CLOCK_OK))
861       GST_CAT_ERROR (GST_CAT_CLOCK, "unexpected status %d for entry %p",
862           status, entry);
863
864     /* mark the entry as busy but watch out for intermediate unscheduled
865      * statuses */
866   } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_BUSY)));
867
868   return gst_system_clock_id_wait_jitter_unlocked (clock, entry, jitter, TRUE);
869 }
870
871 /* Start the async clock thread. Must be called with the object lock
872  * held */
873 static gboolean
874 gst_system_clock_start_async (GstSystemClock * clock)
875 {
876   GError *error = NULL;
877   GstSystemClockPrivate *priv = clock->priv;
878
879   if (G_LIKELY (priv->thread != NULL))
880     return TRUE;                /* Thread already running. Nothing to do */
881
882   priv->thread = g_thread_try_new ("GstSystemClock",
883       (GThreadFunc) gst_system_clock_async_thread, clock, &error);
884
885   if (G_UNLIKELY (error))
886     goto no_thread;
887
888   /* wait for it to spin up */
889   GST_SYSTEM_CLOCK_WAIT (clock);
890
891   return TRUE;
892
893   /* ERRORS */
894 no_thread:
895   {
896     g_warning ("could not create async clock thread: %s", error->message);
897     g_error_free (error);
898   }
899   return FALSE;
900 }
901
902 /* Add an entry to the list of pending async waits. The entry is inserted
903  * in sorted order. If we inserted the entry at the head of the list, we
904  * need to signal the thread as it might either be waiting on it or waiting
905  * for a new entry.
906  *
907  * MT safe.
908  */
909 static GstClockReturn
910 gst_system_clock_id_wait_async (GstClock * clock, GstClockEntry * entry)
911 {
912   GstSystemClock *sysclock;
913   GstSystemClockPrivate *priv;
914   GstClockEntry *head;
915
916   sysclock = GST_SYSTEM_CLOCK_CAST (clock);
917   priv = sysclock->priv;
918
919   GST_CAT_DEBUG (GST_CAT_CLOCK, "adding async entry %p", entry);
920
921   GST_OBJECT_LOCK (clock);
922   /* Start the clock async thread if needed */
923   if (G_UNLIKELY (!gst_system_clock_start_async (sysclock)))
924     goto thread_error;
925
926   if (G_UNLIKELY (GET_ENTRY_STATUS (entry) == GST_CLOCK_UNSCHEDULED))
927     goto was_unscheduled;
928
929   if (priv->entries)
930     head = priv->entries->data;
931   else
932     head = NULL;
933
934   /* need to take a ref */
935   gst_clock_id_ref ((GstClockID) entry);
936   /* insert the entry in sorted order */
937   priv->entries = g_list_insert_sorted (priv->entries, entry,
938       gst_clock_id_compare_func);
939
940   /* only need to send the signal if the entry was added to the
941    * front, else the thread is just waiting for another entry and
942    * will get to this entry automatically. */
943   if (priv->entries->data == entry) {
944     GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry added to head %p", head);
945     if (head == NULL) {
946       /* the list was empty before, signal the cond so that the async thread can
947        * start taking a look at the queue */
948       GST_CAT_DEBUG (GST_CAT_CLOCK, "first entry, sending signal");
949       GST_SYSTEM_CLOCK_BROADCAST (clock);
950     } else {
951       GstClockReturn status;
952
953       status = GET_ENTRY_STATUS (head);
954       GST_CAT_DEBUG (GST_CAT_CLOCK, "head entry %p status %d", head, status);
955
956       if (status == GST_CLOCK_BUSY) {
957         GST_CAT_DEBUG (GST_CAT_CLOCK, "head entry is busy");
958         /* the async thread was waiting for an entry, unlock the wait so that it
959          * looks at the new head entry instead, we only need to do this once */
960         if (!priv->async_wakeup) {
961           GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup async thread");
962           priv->async_wakeup = TRUE;
963           gst_system_clock_add_wakeup (sysclock);
964         }
965       }
966     }
967   }
968   GST_OBJECT_UNLOCK (clock);
969
970   return GST_CLOCK_OK;
971
972   /* ERRORS */
973 thread_error:
974   {
975     /* Could not start the async clock thread */
976     GST_OBJECT_UNLOCK (clock);
977     return GST_CLOCK_ERROR;
978   }
979 was_unscheduled:
980   {
981     GST_OBJECT_UNLOCK (clock);
982     return GST_CLOCK_UNSCHEDULED;
983   }
984 }
985
986 /* unschedule an entry. This will set the state of the entry to GST_CLOCK_UNSCHEDULED
987  * and will signal any thread waiting for entries to recheck their entry.
988  * We cannot really decide if the signal is needed or not because the entry
989  * could be waited on in async or sync mode.
990  *
991  * MT safe.
992  */
993 static void
994 gst_system_clock_id_unschedule (GstClock * clock, GstClockEntry * entry)
995 {
996   GstSystemClock *sysclock;
997   GstClockReturn status;
998
999   sysclock = GST_SYSTEM_CLOCK_CAST (clock);
1000
1001   GST_CAT_DEBUG (GST_CAT_CLOCK, "unscheduling entry %p", entry);
1002
1003   GST_OBJECT_LOCK (clock);
1004   /* change the entry status to unscheduled */
1005   do {
1006     status = GET_ENTRY_STATUS (entry);
1007   } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status,
1008               GST_CLOCK_UNSCHEDULED)));
1009
1010   if (G_LIKELY (status == GST_CLOCK_BUSY)) {
1011     /* the entry was being busy, wake up all entries so that they recheck their
1012      * status. We cannot wake up just one entry because allocating such a
1013      * datastructure for each entry would be too heavy and unlocking an entry
1014      * is usually done when shutting down or some other exceptional case. */
1015     GST_CAT_DEBUG (GST_CAT_CLOCK, "entry was BUSY, doing wakeup");
1016     if (!entry->unscheduled && !entry->woken_up) {
1017       gst_system_clock_add_wakeup (sysclock);
1018       entry->woken_up = TRUE;
1019     }
1020   }
1021   GST_OBJECT_UNLOCK (clock);
1022 }