ec32adf3623172c11e78cc00a920d9ab57d6134f
[platform/upstream/gstreamer.git] / gst / gstsystemclock.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2004 Wim Taymans <wim@fluendo.com>
4  *
5  * gstsystemclock.c: Default clock, uses the system clock
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 /**
24  * SECTION:gstsystemclock
25  * @short_description: Default clock that uses the current system time
26  * @see_also: #GstClock
27  *
28  * The GStreamer core provides a GstSystemClock based on the system time.
29  * Asynchronous callbacks are scheduled from an internal thread.
30  *
31  * Clock implementors are encouraged to subclass this systemclock as it
32  * implements the async notification.
33  *
34  * Subclasses can however override all of the important methods for sync and
35  * async notifications to implement their own callback methods or blocking
36  * wait operations.
37  *
38  * Last reviewed on 2006-03-08 (0.10.4)
39  */
40
41 #include "gst_private.h"
42 #include "gstinfo.h"
43 #include "gstsystemclock.h"
44 #include "gstenumtypes.h"
45 #include "gstpoll.h"
46 #include "gstutils.h"
47 #include "glib-compat-private.h"
48
49 #include <errno.h>
50
51 #ifdef G_OS_WIN32
52 #  define WIN32_LEAN_AND_MEAN   /* prevents from including too many things */
53 #  include <windows.h>          /* QueryPerformance* stuff */
54 #  undef WIN32_LEAN_AND_MEAN
55 #  ifndef EWOULDBLOCK
56 #  define EWOULDBLOCK EAGAIN    /* This is just to placate gcc */
57 #  endif
58 #endif /* G_OS_WIN32 */
59
60 #define GET_ENTRY_STATUS(e)          ((GstClockReturn) g_atomic_int_get(&GST_CLOCK_ENTRY_STATUS(e)))
61 #define SET_ENTRY_STATUS(e,val)      (g_atomic_int_set(&GST_CLOCK_ENTRY_STATUS(e),(val)))
62 #define CAS_ENTRY_STATUS(e,old,val)  (g_atomic_int_compare_and_exchange(\
63                                        (&GST_CLOCK_ENTRY_STATUS(e)), (old), (val)))
64
65 /* Define this to get some extra debug about jitter from each clock_wait */
66 #undef WAIT_DEBUGGING
67
68 #define GST_SYSTEM_CLOCK_GET_COND(clock)        (&GST_SYSTEM_CLOCK_CAST(clock)->priv->entries_changed)
69 #define GST_SYSTEM_CLOCK_WAIT(clock)            g_cond_wait(GST_SYSTEM_CLOCK_GET_COND(clock),GST_OBJECT_GET_LOCK(clock))
70 #define GST_SYSTEM_CLOCK_TIMED_WAIT(clock,tv)   g_cond_timed_wait(GST_SYSTEM_CLOCK_GET_COND(clock),GST_OBJECT_GET_LOCK(clock),tv)
71 #define GST_SYSTEM_CLOCK_BROADCAST(clock)       g_cond_broadcast(GST_SYSTEM_CLOCK_GET_COND(clock))
72
73 struct _GstSystemClockPrivate
74 {
75   GThread *thread;              /* thread for async notify */
76   gboolean stopping;
77
78   GList *entries;
79   GCond entries_changed;
80
81   GstClockType clock_type;
82   GstPoll *timer;
83   gint wakeup_count;            /* the number of entries with a pending wakeup */
84   gboolean async_wakeup;        /* if the wakeup was because of a async list change */
85
86 #ifdef G_OS_WIN32
87   LARGE_INTEGER start;
88   LARGE_INTEGER frequency;
89 #endif                          /* G_OS_WIN32 */
90 };
91
92 #define GST_SYSTEM_CLOCK_GET_PRIVATE(obj)  \
93    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_SYSTEM_CLOCK, \
94         GstSystemClockPrivate))
95
96 #ifdef HAVE_POSIX_TIMERS
97 # ifdef HAVE_MONOTONIC_CLOCK
98 #  define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_MONOTONIC
99 # else
100 #  define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_REALTIME
101 # endif
102 #else
103 #define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_REALTIME
104 #endif
105
106 enum
107 {
108   PROP_0,
109   PROP_CLOCK_TYPE,
110   /* FILL ME */
111 };
112
113 /* the one instance of the systemclock */
114 static GstClock *_the_system_clock = NULL;
115 static gboolean _external_default_clock = FALSE;
116
117 static void gst_system_clock_dispose (GObject * object);
118 static void gst_system_clock_set_property (GObject * object, guint prop_id,
119     const GValue * value, GParamSpec * pspec);
120 static void gst_system_clock_get_property (GObject * object, guint prop_id,
121     GValue * value, GParamSpec * pspec);
122
123 static GstClockTime gst_system_clock_get_internal_time (GstClock * clock);
124 static guint64 gst_system_clock_get_resolution (GstClock * clock);
125 static GstClockReturn gst_system_clock_id_wait_jitter (GstClock * clock,
126     GstClockEntry * entry, GstClockTimeDiff * jitter);
127 static GstClockReturn gst_system_clock_id_wait_jitter_unlocked
128     (GstClock * clock, GstClockEntry * entry, GstClockTimeDiff * jitter,
129     gboolean restart);
130 static GstClockReturn gst_system_clock_id_wait_async (GstClock * clock,
131     GstClockEntry * entry);
132 static void gst_system_clock_id_unschedule (GstClock * clock,
133     GstClockEntry * entry);
134 static void gst_system_clock_async_thread (GstClock * clock);
135 static gboolean gst_system_clock_start_async (GstSystemClock * clock);
136 static void gst_system_clock_add_wakeup (GstSystemClock * sysclock);
137
138 static GMutex _gst_sysclock_mutex;
139
140 /* static guint gst_system_clock_signals[LAST_SIGNAL] = { 0 }; */
141
142 #define gst_system_clock_parent_class parent_class
143 G_DEFINE_TYPE (GstSystemClock, gst_system_clock, GST_TYPE_CLOCK);
144
145 static void
146 gst_system_clock_class_init (GstSystemClockClass * klass)
147 {
148   GObjectClass *gobject_class;
149   GstClockClass *gstclock_class;
150
151   gobject_class = (GObjectClass *) klass;
152   gstclock_class = (GstClockClass *) klass;
153
154   g_type_class_add_private (klass, sizeof (GstSystemClockPrivate));
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_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 #if 0
201   /* Uncomment this to start the async clock thread straight away */
202   GST_OBJECT_LOCK (clock);
203   gst_system_clock_start_async (clock);
204   GST_OBJECT_UNLOCK (clock);
205 #endif
206 }
207
208 static void
209 gst_system_clock_dispose (GObject * object)
210 {
211   GstClock *clock = (GstClock *) object;
212   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
213   GstSystemClockPrivate *priv = sysclock->priv;
214   GList *entries;
215
216   /* else we have to stop the thread */
217   GST_OBJECT_LOCK (clock);
218   priv->stopping = TRUE;
219   /* unschedule all entries */
220   for (entries = priv->entries; entries; entries = g_list_next (entries)) {
221     GstClockEntry *entry = (GstClockEntry *) entries->data;
222
223     GST_CAT_DEBUG (GST_CAT_CLOCK, "unscheduling entry %p", entry);
224     SET_ENTRY_STATUS (entry, GST_CLOCK_UNSCHEDULED);
225   }
226   GST_SYSTEM_CLOCK_BROADCAST (clock);
227   gst_system_clock_add_wakeup (sysclock);
228   GST_OBJECT_UNLOCK (clock);
229
230   if (priv->thread)
231     g_thread_join (priv->thread);
232   priv->thread = NULL;
233   GST_CAT_DEBUG (GST_CAT_CLOCK, "joined thread");
234
235   g_list_foreach (priv->entries, (GFunc) gst_clock_id_unref, NULL);
236   g_list_free (priv->entries);
237   priv->entries = NULL;
238
239   gst_poll_free (priv->timer);
240   g_cond_clear (&priv->entries_changed);
241
242   G_OBJECT_CLASS (parent_class)->dispose (object);
243
244   if (_the_system_clock == clock) {
245     _the_system_clock = NULL;
246     GST_CAT_DEBUG (GST_CAT_CLOCK, "disposed system clock");
247   }
248 }
249
250 static void
251 gst_system_clock_set_property (GObject * object, guint prop_id,
252     const GValue * value, GParamSpec * pspec)
253 {
254   GstSystemClock *sysclock = GST_SYSTEM_CLOCK (object);
255
256   switch (prop_id) {
257     case PROP_CLOCK_TYPE:
258       sysclock->priv->clock_type = (GstClockType) g_value_get_enum (value);
259       GST_CAT_DEBUG (GST_CAT_CLOCK, "clock-type set to %d",
260           sysclock->priv->clock_type);
261       break;
262     default:
263       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
264       break;
265   }
266 }
267
268 static void
269 gst_system_clock_get_property (GObject * object, guint prop_id, GValue * value,
270     GParamSpec * pspec)
271 {
272   GstSystemClock *sysclock = GST_SYSTEM_CLOCK (object);
273
274   switch (prop_id) {
275     case PROP_CLOCK_TYPE:
276       g_value_set_enum (value, sysclock->priv->clock_type);
277       break;
278     default:
279       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
280       break;
281   }
282 }
283
284 /**
285  * gst_system_clock_set_default:
286  * @new_clock: a #GstClock
287  *
288  * Sets the default system clock that can be obtained with
289  * gst_system_clock_obtain.
290  *
291  * This is mostly used for testing and debugging purposes when you
292  * want to have control over the time reported by the default system
293  * clock.
294  *
295  * MT safe.
296  *
297  * Since: 1.4
298  */
299 void
300 gst_system_clock_set_default (GstClock * new_clock)
301 {
302   GstClock *clock;
303
304   g_mutex_lock (&_gst_sysclock_mutex);
305   clock = _the_system_clock;
306
307   if (clock != NULL)
308     g_object_unref (clock);
309
310   if (new_clock == NULL) {
311     GST_CAT_DEBUG (GST_CAT_CLOCK, "resetting default system clock");
312     _external_default_clock = FALSE;
313   } else {
314     GST_CAT_DEBUG (GST_CAT_CLOCK, "setting new default system clock to %p",
315         new_clock);
316     _external_default_clock = TRUE;
317     g_object_ref (new_clock);
318   }
319   _the_system_clock = new_clock;
320   g_mutex_unlock (&_gst_sysclock_mutex);
321 }
322
323 /**
324  * gst_system_clock_obtain:
325  *
326  * Get a handle to the default system clock. The refcount of the
327  * clock will be increased so you need to unref the clock after
328  * usage.
329  *
330  * Returns: (transfer full): the default clock.
331  *
332  * MT safe.
333  */
334 GstClock *
335 gst_system_clock_obtain (void)
336 {
337   GstClock *clock;
338
339   g_mutex_lock (&_gst_sysclock_mutex);
340   clock = _the_system_clock;
341
342   if (clock == NULL) {
343     GST_CAT_DEBUG (GST_CAT_CLOCK, "creating new static system clock");
344     g_assert (_external_default_clock == FALSE);
345     clock = g_object_new (GST_TYPE_SYSTEM_CLOCK,
346         "name", "GstSystemClock", NULL);
347
348     g_assert (!g_object_is_floating (G_OBJECT (clock)));
349
350     _the_system_clock = clock;
351     g_mutex_unlock (&_gst_sysclock_mutex);
352   } else {
353     g_mutex_unlock (&_gst_sysclock_mutex);
354     GST_CAT_DEBUG (GST_CAT_CLOCK, "returning static system clock");
355   }
356
357   /* we ref it since we are a clock factory. */
358   gst_object_ref (clock);
359   return clock;
360 }
361
362 static void
363 gst_system_clock_remove_wakeup (GstSystemClock * sysclock)
364 {
365   g_return_if_fail (sysclock->priv->wakeup_count > 0);
366
367   sysclock->priv->wakeup_count--;
368   if (sysclock->priv->wakeup_count == 0) {
369     /* read the control socket byte when we removed the last wakeup count */
370     GST_CAT_DEBUG (GST_CAT_CLOCK, "reading control");
371     while (!gst_poll_read_control (sysclock->priv->timer)) {
372       g_warning ("gstsystemclock: read control failed, trying again\n");
373     }
374     GST_SYSTEM_CLOCK_BROADCAST (sysclock);
375   }
376   GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup count %d",
377       sysclock->priv->wakeup_count);
378 }
379
380 static void
381 gst_system_clock_add_wakeup (GstSystemClock * sysclock)
382 {
383   /* only write the control socket for the first wakeup */
384   if (sysclock->priv->wakeup_count == 0) {
385     GST_CAT_DEBUG (GST_CAT_CLOCK, "writing control");
386     while (!gst_poll_write_control (sysclock->priv->timer)) {
387       if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
388         g_warning
389             ("gstsystemclock: write control failed in wakeup_async, trying again: %d:%s\n",
390             errno, g_strerror (errno));
391       } else {
392         g_critical
393             ("gstsystemclock: write control failed in wakeup_async: %d:%s\n",
394             errno, g_strerror (errno));
395         return;
396       }
397     }
398   }
399   sysclock->priv->wakeup_count++;
400   GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup count %d",
401       sysclock->priv->wakeup_count);
402 }
403
404 static void
405 gst_system_clock_wait_wakeup (GstSystemClock * sysclock)
406 {
407   while (sysclock->priv->wakeup_count > 0) {
408     GST_SYSTEM_CLOCK_WAIT (sysclock);
409   }
410 }
411
412 /* this thread reads the sorted clock entries from the queue.
413  *
414  * It waits on each of them and fires the callback when the timeout occurs.
415  *
416  * When an entry in the queue was canceled before we wait for it, it is
417  * simply skipped.
418  *
419  * When waiting for an entry, it can become canceled, in that case we don't
420  * call the callback but move to the next item in the queue.
421  *
422  * MT safe.
423  */
424 static void
425 gst_system_clock_async_thread (GstClock * clock)
426 {
427   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
428   GstSystemClockPrivate *priv = sysclock->priv;
429
430   GST_CAT_DEBUG (GST_CAT_CLOCK, "enter system clock thread");
431   GST_OBJECT_LOCK (clock);
432   /* signal spinup */
433   GST_SYSTEM_CLOCK_BROADCAST (clock);
434   /* now enter our (almost) infinite loop */
435   while (!priv->stopping) {
436     GstClockEntry *entry;
437     GstClockTime requested;
438     GstClockReturn res;
439
440     /* check if something to be done */
441     while (priv->entries == NULL) {
442       GST_CAT_DEBUG (GST_CAT_CLOCK, "no clock entries, waiting..");
443       /* wait for work to do */
444       GST_SYSTEM_CLOCK_WAIT (clock);
445       GST_CAT_DEBUG (GST_CAT_CLOCK, "got signal");
446       /* clock was stopping, exit */
447       if (priv->stopping)
448         goto exit;
449     }
450
451     /* see if we have a pending wakeup because the order of the list
452      * changed. */
453     if (priv->async_wakeup) {
454       GST_CAT_DEBUG (GST_CAT_CLOCK, "clear async wakeup");
455       gst_system_clock_remove_wakeup (sysclock);
456       priv->async_wakeup = FALSE;
457     }
458
459     /* pick the next entry */
460     entry = priv->entries->data;
461     GST_OBJECT_UNLOCK (clock);
462
463     requested = entry->time;
464
465     /* now wait for the entry, we already hold the lock */
466     res =
467         gst_system_clock_id_wait_jitter_unlocked (clock, (GstClockID) entry,
468         NULL, FALSE);
469
470     GST_OBJECT_LOCK (clock);
471
472     switch (res) {
473       case GST_CLOCK_UNSCHEDULED:
474         /* entry was unscheduled, move to the next */
475         GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry %p unscheduled", entry);
476         goto next_entry;
477       case GST_CLOCK_OK:
478       case GST_CLOCK_EARLY:
479       {
480         /* entry timed out normally, fire the callback and move to the next
481          * entry */
482         GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry %p timed out", entry);
483         if (entry->func) {
484           /* unlock before firing the callback */
485           GST_OBJECT_UNLOCK (clock);
486           entry->func (clock, entry->time, (GstClockID) entry,
487               entry->user_data);
488           GST_OBJECT_LOCK (clock);
489         }
490         if (entry->type == GST_CLOCK_ENTRY_PERIODIC) {
491           GST_CAT_DEBUG (GST_CAT_CLOCK, "updating periodic entry %p", entry);
492           /* adjust time now */
493           entry->time = requested + entry->interval;
494           /* and resort the list now */
495           priv->entries =
496               g_list_sort (priv->entries, gst_clock_id_compare_func);
497           /* and restart */
498           continue;
499         } else {
500           GST_CAT_DEBUG (GST_CAT_CLOCK, "moving to next entry");
501           goto next_entry;
502         }
503       }
504       case GST_CLOCK_BUSY:
505         /* somebody unlocked the entry but is was not canceled, This means that
506          * either a new entry was added in front of the queue or some other entry
507          * was canceled. Whatever it is, pick the head entry of the list and
508          * continue waiting. */
509         GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry %p needs restart", entry);
510
511         /* we set the entry back to the OK state. This is needed so that the
512          * _unschedule() code can see if an entry is currently being waited
513          * on (when its state is BUSY). */
514         SET_ENTRY_STATUS (entry, GST_CLOCK_OK);
515         continue;
516       default:
517         GST_CAT_DEBUG (GST_CAT_CLOCK,
518             "strange result %d waiting for %p, skipping", res, entry);
519         g_warning ("%s: strange result %d waiting for %p, skipping",
520             GST_OBJECT_NAME (clock), res, entry);
521         goto next_entry;
522     }
523   next_entry:
524     /* we remove the current entry and unref it */
525     priv->entries = g_list_remove (priv->entries, entry);
526     gst_clock_id_unref ((GstClockID) entry);
527   }
528 exit:
529   /* signal exit */
530   GST_SYSTEM_CLOCK_BROADCAST (clock);
531   GST_OBJECT_UNLOCK (clock);
532   GST_CAT_DEBUG (GST_CAT_CLOCK, "exit system clock thread");
533 }
534
535 #ifdef HAVE_POSIX_TIMERS
536 static inline clockid_t
537 clock_type_to_posix_id (GstClockType clock_type)
538 {
539 #ifdef HAVE_MONOTONIC_CLOCK
540   if (clock_type == GST_CLOCK_TYPE_MONOTONIC)
541     return CLOCK_MONOTONIC;
542   else
543 #endif
544     return CLOCK_REALTIME;
545 }
546 #endif
547
548 /* MT safe */
549 static GstClockTime
550 gst_system_clock_get_internal_time (GstClock * clock)
551 {
552 #ifdef G_OS_WIN32
553   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
554
555   if (sysclock->priv->frequency.QuadPart != 0) {
556     LARGE_INTEGER now;
557
558     /* we prefer the highly accurate performance counters on windows */
559     QueryPerformanceCounter (&now);
560
561     return gst_util_uint64_scale (now.QuadPart - sysclock->priv->start.QuadPart,
562         GST_SECOND, sysclock->priv->frequency.QuadPart);
563   } else
564 #endif /* G_OS_WIN32 */
565 #if !defined HAVE_POSIX_TIMERS || !defined HAVE_CLOCK_GETTIME
566   {
567     GTimeVal timeval;
568
569     g_get_current_time (&timeval);
570
571     return GST_TIMEVAL_TO_TIME (timeval);
572   }
573 #else
574   {
575     GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
576     clockid_t ptype;
577     struct timespec ts;
578
579     ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
580
581     if (G_UNLIKELY (clock_gettime (ptype, &ts)))
582       return GST_CLOCK_TIME_NONE;
583
584     return GST_TIMESPEC_TO_TIME (ts);
585   }
586 #endif
587 }
588
589 static guint64
590 gst_system_clock_get_resolution (GstClock * clock)
591 {
592 #ifdef G_OS_WIN32
593   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
594
595   if (sysclock->priv->frequency.QuadPart != 0) {
596     return GST_SECOND / sysclock->priv->frequency.QuadPart;
597   } else
598 #endif /* G_OS_WIN32 */
599 #if defined(HAVE_POSIX_TIMERS) && defined(HAVE_CLOCK_GETTIME)
600   {
601     GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
602     clockid_t ptype;
603     struct timespec ts;
604
605     ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
606
607     if (G_UNLIKELY (clock_getres (ptype, &ts)))
608       return GST_CLOCK_TIME_NONE;
609
610     return GST_TIMESPEC_TO_TIME (ts);
611   }
612 #else
613   {
614     return 1 * GST_USECOND;
615   }
616 #endif
617 }
618
619 /* synchronously wait on the given GstClockEntry.
620  *
621  * We do this by blocking on the global GstPoll timer with
622  * the requested timeout. This allows us to unblock the
623  * entry by writing on the control fd.
624  *
625  * Note that writing the global GstPoll unlocks all waiting entries. So
626  * we need to check if an unlocked entry has changed when it unlocks.
627  *
628  * Entries that arrive too late are simply not waited on and a
629  * GST_CLOCK_EARLY result is returned.
630  *
631  * MT safe.
632  */
633 static GstClockReturn
634 gst_system_clock_id_wait_jitter_unlocked (GstClock * clock,
635     GstClockEntry * entry, GstClockTimeDiff * jitter, gboolean restart)
636 {
637   GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
638   GstClockTime entryt, now;
639   GstClockTimeDiff diff;
640   GstClockReturn status;
641
642   if (G_UNLIKELY (GET_ENTRY_STATUS (entry) == GST_CLOCK_UNSCHEDULED))
643     return GST_CLOCK_UNSCHEDULED;
644
645   /* need to call the overridden method because we want to sync against the time
646    * of the clock, whatever the subclass uses as a clock. */
647   now = gst_clock_get_time (clock);
648
649   /* get the time of the entry */
650   entryt = GST_CLOCK_ENTRY_TIME (entry);
651
652   /* the diff of the entry with the clock is the amount of time we have to
653    * wait */
654   diff = GST_CLOCK_DIFF (now, entryt);
655   if (G_LIKELY (jitter))
656     *jitter = -diff;
657
658   GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p"
659       " time %" GST_TIME_FORMAT
660       " now %" GST_TIME_FORMAT
661       " diff (time-now) %" G_GINT64_FORMAT,
662       entry, GST_TIME_ARGS (entryt), GST_TIME_ARGS (now), diff);
663
664   if (G_LIKELY (diff > 0)) {
665 #ifdef WAIT_DEBUGGING
666     GstClockTime final;
667 #endif
668
669     while (TRUE) {
670       gint pollret;
671
672       do {
673         status = GET_ENTRY_STATUS (entry);
674
675         /* stop when we are unscheduled */
676         if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
677           goto done;
678
679         /* mark the entry as busy but watch out for intermediate unscheduled
680          * statuses */
681       } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_BUSY)));
682
683       /* now wait on the entry, it either times out or the fd is written. The
684        * status of the entry is only BUSY around the poll. */
685       pollret = gst_poll_wait (sysclock->priv->timer, diff);
686
687       /* get the new status, mark as DONE. We do this so that the unschedule
688        * function knows when we left the poll and doesn't need to wakeup the
689        * poll anymore. */
690       do {
691         status = GET_ENTRY_STATUS (entry);
692         /* we were unscheduled, exit immediately */
693         if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
694           break;
695       } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status, GST_CLOCK_DONE)));
696
697       GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p unlocked, status %d, ret %d",
698           entry, status, pollret);
699
700       if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
701         /* try to clean up The unschedule function managed to set the status to
702          * unscheduled. We now take the lock and mark the entry as unscheduled.
703          * This makes sure that the unschedule function doesn't perform a
704          * wakeup anymore. If the unschedule function has a change to perform
705          * the wakeup before us, we clean up here */
706         GST_OBJECT_LOCK (sysclock);
707         entry->unscheduled = TRUE;
708         if (entry->woken_up) {
709           gst_system_clock_remove_wakeup (sysclock);
710         }
711         GST_OBJECT_UNLOCK (sysclock);
712         goto done;
713       } else {
714         if (G_UNLIKELY (pollret != 0)) {
715           /* some other id got unlocked */
716           if (!restart) {
717             /* this can happen if the entry got unlocked because of an async
718              * entry was added to the head of the async queue. */
719             GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup waiting for entry %p", entry);
720             goto done;
721           }
722
723           /* wait till all the entries got woken up */
724           GST_OBJECT_LOCK (sysclock);
725           gst_system_clock_wait_wakeup (sysclock);
726           GST_OBJECT_UNLOCK (sysclock);
727
728           GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p needs to be restarted",
729               entry);
730         } else {
731           GST_CAT_DEBUG (GST_CAT_CLOCK, "entry %p unlocked after timeout",
732               entry);
733         }
734
735         /* reschedule if gst_poll_wait returned early or we have to reschedule after
736          * an unlock*/
737         now = gst_clock_get_time (clock);
738         diff = GST_CLOCK_DIFF (now, entryt);
739
740         if (diff <= 0) {
741           /* timeout, this is fine, we can report success now */
742           status = GST_CLOCK_OK;
743           SET_ENTRY_STATUS (entry, status);
744
745           GST_CAT_DEBUG (GST_CAT_CLOCK,
746               "entry %p finished, diff %" G_GINT64_FORMAT, entry, diff);
747
748 #ifdef WAIT_DEBUGGING
749           final = gst_system_clock_get_internal_time (clock);
750           GST_CAT_DEBUG (GST_CAT_CLOCK, "Waited for %" G_GINT64_FORMAT
751               " got %" G_GINT64_FORMAT " diff %" G_GINT64_FORMAT
752               " %g target-offset %" G_GINT64_FORMAT " %g", entryt, now,
753               now - entryt,
754               (double) (GstClockTimeDiff) (now - entryt) / GST_SECOND,
755               (final - target),
756               ((double) (GstClockTimeDiff) (final - target)) / GST_SECOND);
757 #endif
758           goto done;
759         } else {
760           GST_CAT_DEBUG (GST_CAT_CLOCK,
761               "entry %p restart, diff %" G_GINT64_FORMAT, entry, diff);
762         }
763       }
764     }
765   } else {
766     /* we are right on time or too late */
767     if (G_UNLIKELY (diff == 0))
768       status = GST_CLOCK_OK;
769     else
770       status = GST_CLOCK_EARLY;
771
772     SET_ENTRY_STATUS (entry, status);
773   }
774 done:
775   return status;
776 }
777
778 static GstClockReturn
779 gst_system_clock_id_wait_jitter (GstClock * clock, GstClockEntry * entry,
780     GstClockTimeDiff * jitter)
781 {
782   return gst_system_clock_id_wait_jitter_unlocked (clock, entry, jitter, TRUE);
783 }
784
785 /* Start the async clock thread. Must be called with the object lock
786  * held */
787 static gboolean
788 gst_system_clock_start_async (GstSystemClock * clock)
789 {
790   GError *error = NULL;
791   GstSystemClockPrivate *priv = clock->priv;
792
793   if (G_LIKELY (priv->thread != NULL))
794     return TRUE;                /* Thread already running. Nothing to do */
795
796   priv->thread = g_thread_try_new ("GstSystemClock",
797       (GThreadFunc) gst_system_clock_async_thread, clock, &error);
798
799   if (G_UNLIKELY (error))
800     goto no_thread;
801
802   /* wait for it to spin up */
803   GST_SYSTEM_CLOCK_WAIT (clock);
804
805   return TRUE;
806
807   /* ERRORS */
808 no_thread:
809   {
810     g_warning ("could not create async clock thread: %s", error->message);
811     g_error_free (error);
812   }
813   return FALSE;
814 }
815
816 /* Add an entry to the list of pending async waits. The entry is inserted
817  * in sorted order. If we inserted the entry at the head of the list, we
818  * need to signal the thread as it might either be waiting on it or waiting
819  * for a new entry.
820  *
821  * MT safe.
822  */
823 static GstClockReturn
824 gst_system_clock_id_wait_async (GstClock * clock, GstClockEntry * entry)
825 {
826   GstSystemClock *sysclock;
827   GstSystemClockPrivate *priv;
828   GstClockEntry *head;
829
830   sysclock = GST_SYSTEM_CLOCK_CAST (clock);
831   priv = sysclock->priv;
832
833   GST_CAT_DEBUG (GST_CAT_CLOCK, "adding async entry %p", entry);
834
835   GST_OBJECT_LOCK (clock);
836   /* Start the clock async thread if needed */
837   if (G_UNLIKELY (!gst_system_clock_start_async (sysclock)))
838     goto thread_error;
839
840   if (G_UNLIKELY (GET_ENTRY_STATUS (entry) == GST_CLOCK_UNSCHEDULED))
841     goto was_unscheduled;
842
843   if (priv->entries)
844     head = priv->entries->data;
845   else
846     head = NULL;
847
848   /* need to take a ref */
849   gst_clock_id_ref ((GstClockID) entry);
850   /* insert the entry in sorted order */
851   priv->entries = g_list_insert_sorted (priv->entries, entry,
852       gst_clock_id_compare_func);
853
854   /* only need to send the signal if the entry was added to the
855    * front, else the thread is just waiting for another entry and
856    * will get to this entry automatically. */
857   if (priv->entries->data == entry) {
858     GST_CAT_DEBUG (GST_CAT_CLOCK, "async entry added to head %p", head);
859     if (head == NULL) {
860       /* the list was empty before, signal the cond so that the async thread can
861        * start taking a look at the queue */
862       GST_CAT_DEBUG (GST_CAT_CLOCK, "first entry, sending signal");
863       GST_SYSTEM_CLOCK_BROADCAST (clock);
864     } else {
865       GstClockReturn status;
866
867       status = GET_ENTRY_STATUS (head);
868       GST_CAT_DEBUG (GST_CAT_CLOCK, "head entry %p status %d", head, status);
869
870       if (status == GST_CLOCK_BUSY) {
871         GST_CAT_DEBUG (GST_CAT_CLOCK, "head entry is busy");
872         /* the async thread was waiting for an entry, unlock the wait so that it
873          * looks at the new head entry instead, we only need to do this once */
874         if (!priv->async_wakeup) {
875           GST_CAT_DEBUG (GST_CAT_CLOCK, "wakeup async thread");
876           priv->async_wakeup = TRUE;
877           gst_system_clock_add_wakeup (sysclock);
878         }
879       }
880     }
881   }
882   GST_OBJECT_UNLOCK (clock);
883
884   return GST_CLOCK_OK;
885
886   /* ERRORS */
887 thread_error:
888   {
889     /* Could not start the async clock thread */
890     GST_OBJECT_UNLOCK (clock);
891     return GST_CLOCK_ERROR;
892   }
893 was_unscheduled:
894   {
895     GST_OBJECT_UNLOCK (clock);
896     return GST_CLOCK_UNSCHEDULED;
897   }
898 }
899
900 /* unschedule an entry. This will set the state of the entry to GST_CLOCK_UNSCHEDULED
901  * and will signal any thread waiting for entries to recheck their entry.
902  * We cannot really decide if the signal is needed or not because the entry
903  * could be waited on in async or sync mode.
904  *
905  * MT safe.
906  */
907 static void
908 gst_system_clock_id_unschedule (GstClock * clock, GstClockEntry * entry)
909 {
910   GstSystemClock *sysclock;
911   GstClockReturn status;
912
913   sysclock = GST_SYSTEM_CLOCK_CAST (clock);
914
915   GST_CAT_DEBUG (GST_CAT_CLOCK, "unscheduling entry %p", entry);
916
917   GST_OBJECT_LOCK (clock);
918   /* change the entry status to unscheduled */
919   do {
920     status = GET_ENTRY_STATUS (entry);
921   } while (G_UNLIKELY (!CAS_ENTRY_STATUS (entry, status,
922               GST_CLOCK_UNSCHEDULED)));
923
924   if (G_LIKELY (status == GST_CLOCK_BUSY)) {
925     /* the entry was being busy, wake up all entries so that they recheck their
926      * status. We cannot wake up just one entry because allocating such a
927      * datastructure for each entry would be too heavy and unlocking an entry
928      * is usually done when shutting down or some other exceptional case. */
929     GST_CAT_DEBUG (GST_CAT_CLOCK, "entry was BUSY, doing wakeup");
930     if (!entry->unscheduled && !entry->woken_up) {
931       gst_system_clock_add_wakeup (sysclock);
932       entry->woken_up = TRUE;
933     }
934   }
935   GST_OBJECT_UNLOCK (clock);
936 }