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