2 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3 * 2004 Wim Taymans <wim@fluendo.com>
5 * gstsystemclock.c: Default clock, uses the system clock
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.
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.
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.
24 * SECTION:gstsystemclock
25 * @title: GstSystemClock
26 * @short_description: Default clock that uses the current system time
27 * @see_also: #GstClock
29 * The GStreamer core provides a GstSystemClock based on the system time.
30 * Asynchronous callbacks are scheduled from an internal thread.
32 * Clock implementors are encouraged to subclass this systemclock as it
33 * implements the async notification.
35 * Subclasses can however override all of the important methods for sync and
36 * async notifications to implement their own callback methods or blocking
40 #include "gst_private.h"
42 #include "gstsystemclock.h"
43 #include "gstenumtypes.h"
46 #include "glib-compat-private.h"
51 # define WIN32_LEAN_AND_MEAN /* prevents from including too many things */
52 # include <windows.h> /* QueryPerformance* stuff */
53 # undef WIN32_LEAN_AND_MEAN
55 # define EWOULDBLOCK EAGAIN /* This is just to placate gcc */
57 #endif /* G_OS_WIN32 */
60 #include <mach/mach_time.h>
63 /* Define this to get some extra debug about jitter from each clock_wait */
66 #define GST_SYSTEM_CLOCK_GET_LOCK(clock) GST_OBJECT_GET_LOCK(clock)
67 #define GST_SYSTEM_CLOCK_LOCK(clock) g_mutex_lock(GST_SYSTEM_CLOCK_GET_LOCK(clock))
68 #define GST_SYSTEM_CLOCK_UNLOCK(clock) g_mutex_unlock(GST_SYSTEM_CLOCK_GET_LOCK(clock))
69 #define GST_SYSTEM_CLOCK_GET_COND(clock) (&GST_SYSTEM_CLOCK_CAST(clock)->priv->entries_changed)
70 #define GST_SYSTEM_CLOCK_WAIT(clock) g_cond_wait(GST_SYSTEM_CLOCK_GET_COND(clock),GST_SYSTEM_CLOCK_GET_LOCK(clock))
71 #define GST_SYSTEM_CLOCK_BROADCAST(clock) g_cond_broadcast(GST_SYSTEM_CLOCK_GET_COND(clock))
73 #if defined(HAVE_FUTEX)
75 #include <linux/futex.h>
76 #include <sys/syscall.h>
78 #ifndef FUTEX_WAIT_BITSET_PRIVATE
79 #define FUTEX_WAIT_BITSET_PRIVATE FUTEX_WAIT_BITSET
81 #ifndef FUTEX_WAKE_PRIVATE
82 #define FUTEX_WAKE_PRIVATE FUTEX_WAKE
85 #define GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry) (&(entry)->lock)
86 #define GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry) (&(entry)->cond_val)
87 #define GST_SYSTEM_CLOCK_ENTRY_LOCK(entry) (g_mutex_lock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
88 #define GST_SYSTEM_CLOCK_ENTRY_UNLOCK(entry) (g_mutex_unlock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
89 #define GST_SYSTEM_CLOCK_ENTRY_WAIT_UNTIL(entry,ns) gst_futex_cond_wait_until(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry),GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry),(ns))
90 #define GST_SYSTEM_CLOCK_ENTRY_BROADCAST(entry) gst_futex_cond_broadcast(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry))
92 #define CLOCK_MIN_WAIT_TIME 100 /* ns */
94 typedef struct _GstClockEntryFutex GstClockEntryImpl;
95 struct _GstClockEntryFutex
99 GDestroyNotify destroy_entry;
101 gboolean initialized;
108 clear_entry (GstClockEntryImpl * entry)
110 g_mutex_clear (&entry->lock);
114 init_entry (GstClockEntryImpl * entry)
116 g_mutex_init (&entry->lock);
118 entry->destroy_entry = (GDestroyNotify) clear_entry;
122 gst_futex_cond_broadcast (guint * cond_val)
124 g_atomic_int_inc (cond_val);
126 syscall (__NR_futex, cond_val, (gsize) FUTEX_WAKE_PRIVATE, (gsize) INT_MAX,
131 gst_futex_cond_wait_until (guint * cond_val, GMutex * mutex, gint64 end_time)
141 end.tv_sec = end_time / 1000000000;
142 end.tv_nsec = end_time % 1000000000;
145 g_mutex_unlock (mutex);
146 /* we use FUTEX_WAIT_BITSET_PRIVATE rather than FUTEX_WAIT_PRIVATE to be
147 * able to use absolute time */
149 syscall (__NR_futex, cond_val, (gsize) FUTEX_WAIT_BITSET_PRIVATE,
150 (gsize) sampled, &end, NULL, FUTEX_BITSET_MATCH_ANY);
151 success = (res < 0 && errno == ETIMEDOUT) ? FALSE : TRUE;
152 g_mutex_lock (mutex);
157 #elif defined (G_OS_UNIX)
158 #define GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry) (&(entry)->lock)
159 #define GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry) (&(entry)->cond)
160 #define GST_SYSTEM_CLOCK_ENTRY_LOCK(entry) (pthread_mutex_lock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
161 #define GST_SYSTEM_CLOCK_ENTRY_UNLOCK(entry) (pthread_mutex_unlock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
162 #define GST_SYSTEM_CLOCK_ENTRY_WAIT_UNTIL(entry,ns) gst_pthread_cond_wait_until(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry),GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry),(ns))
163 #define GST_SYSTEM_CLOCK_ENTRY_BROADCAST(entry) pthread_cond_broadcast(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry))
165 #define CLOCK_MIN_WAIT_TIME 500 /* ns */
167 typedef struct _GstClockEntryPThread GstClockEntryImpl;
168 struct _GstClockEntryPThread
172 GDestroyNotify destroy_entry;
174 gboolean initialized;
177 pthread_mutex_t lock;
181 gst_pthread_cond_wait_until (pthread_cond_t * cond, pthread_mutex_t * lock,
187 #if defined (HAVE_PTHREAD_CONDATTR_SETCLOCK) && defined (CLOCK_MONOTONIC)
188 /* This is the exact check we used during init to set the clock to
189 * monotonic, so if we're in this branch, timedwait() will already be
190 * expecting a monotonic clock.
193 ts.tv_sec = end_time / 1000000000;
194 ts.tv_nsec = end_time % 1000000000;
196 if ((status = pthread_cond_timedwait (cond, lock, &ts)) == 0)
199 #elif defined (HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP)
200 /* end_time is given relative to the monotonic clock as returned by
201 * g_get_monotonic_time().
203 * Since this pthreads wants the relative time, convert it back again.
206 gint64 now = g_get_monotonic_time () * 1000;
212 relative = end_time - now;
214 ts.tv_sec = relative / 1000000000;
215 ts.tv_nsec = relative % 1000000000;
217 if ((status = pthread_cond_timedwait_relative_np (cond, lock, &ts)) == 0)
221 #error Cannot use pthread condition variables on your platform.
224 if (G_UNLIKELY (status != ETIMEDOUT)) {
225 g_error ("pthread_cond_timedwait returned %d", status);
232 clear_entry (GstClockEntryImpl * entry)
234 pthread_cond_destroy (&entry->cond);
235 pthread_mutex_destroy (&entry->lock);
239 init_entry (GstClockEntryImpl * entry)
241 pthread_mutexattr_t *m_pattr = NULL;
242 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
243 pthread_mutexattr_t m_attr;
245 pthread_condattr_t c_attr;
248 pthread_condattr_init (&c_attr);
250 #if defined (HAVE_PTHREAD_CONDATTR_SETCLOCK) && defined (CLOCK_MONOTONIC)
251 status = pthread_condattr_setclock (&c_attr, CLOCK_MONOTONIC);
252 if (G_UNLIKELY (status != 0)) {
253 g_error ("pthread_condattr_setclock returned %d", status);
255 #elif defined (HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE_NP)
257 #error Cannot use pthread condition variables on your platform.
260 status = pthread_cond_init (&entry->cond, &c_attr);
261 if (G_UNLIKELY (status != 0)) {
262 g_error ("pthread_cond_init returned %d", status);
265 pthread_condattr_destroy (&c_attr);
267 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
268 pthread_mutexattr_init (&m_attr);
269 pthread_mutexattr_settype (&m_attr, PTHREAD_MUTEX_ADAPTIVE_NP);
273 status = pthread_mutex_init (&entry->lock, m_pattr);
274 if (G_UNLIKELY (status != 0)) {
275 g_error ("pthread_mutex_init returned %d", status);
277 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
278 pthread_mutexattr_destroy (&m_attr);
281 entry->destroy_entry = (GDestroyNotify) clear_entry;
284 #define GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry) (&(entry)->lock)
285 #define GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry) (&(entry)->cond)
286 #define GST_SYSTEM_CLOCK_ENTRY_LOCK(entry) (g_mutex_lock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
287 #define GST_SYSTEM_CLOCK_ENTRY_UNLOCK(entry) (g_mutex_unlock(GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry)))
288 #define GST_SYSTEM_CLOCK_ENTRY_WAIT_UNTIL(entry,ns) g_cond_wait_until(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry),GST_SYSTEM_CLOCK_ENTRY_GET_LOCK(entry),((ns) / 1000))
289 #define GST_SYSTEM_CLOCK_ENTRY_BROADCAST(entry) g_cond_broadcast(GST_SYSTEM_CLOCK_ENTRY_GET_COND(entry))
291 #if defined (G_OS_WIN32)
292 /* min wait time is 1ms on windows with GCond */
293 #define CLOCK_MIN_WAIT_TIME GST_MSECOND
295 /* min wait time is 1us on non-windows with GCond */
296 #define CLOCK_MIN_WAIT_TIME GST_USECOND
299 typedef struct _GstClockEntryGLib GstClockEntryImpl;
300 struct _GstClockEntryGLib
304 GDestroyNotify destroy_entry;
306 gboolean initialized;
313 clear_entry (GstClockEntryImpl * entry)
315 g_cond_clear (&entry->cond);
316 g_mutex_clear (&entry->lock);
320 init_entry (GstClockEntryImpl * entry)
322 g_cond_init (&entry->cond);
323 g_mutex_init (&entry->lock);
325 entry->destroy_entry = (GDestroyNotify) clear_entry;
329 /* check that our impl is smaller than what will be allocated by gstclock.c */
330 G_STATIC_ASSERT (sizeof (GstClockEntryImpl) <=
331 sizeof (struct _GstClockEntryImpl));
333 /* Must be called with clock lock */
335 ensure_entry_initialized (GstClockEntryImpl * entry_impl)
337 if (!entry_impl->initialized) {
338 init_entry (entry_impl);
339 entry_impl->initialized = TRUE;
343 struct _GstSystemClockPrivate
345 GThread *thread; /* thread for async notify */
349 GCond entries_changed;
351 GstClockType clock_type;
354 LARGE_INTEGER frequency;
355 #endif /* G_OS_WIN32 */
357 struct mach_timebase_info mach_timebase;
361 #ifdef HAVE_POSIX_TIMERS
362 # ifdef HAVE_MONOTONIC_CLOCK
363 # define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_MONOTONIC
365 # define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_REALTIME
368 #define DEFAULT_CLOCK_TYPE GST_CLOCK_TYPE_MONOTONIC
378 /* the one instance of the systemclock */
379 static GstClock *_the_system_clock = NULL;
380 static gboolean _external_default_clock = FALSE;
382 static void gst_system_clock_dispose (GObject * object);
383 static void gst_system_clock_set_property (GObject * object, guint prop_id,
384 const GValue * value, GParamSpec * pspec);
385 static void gst_system_clock_get_property (GObject * object, guint prop_id,
386 GValue * value, GParamSpec * pspec);
388 static GstClockTime gst_system_clock_get_internal_time (GstClock * clock);
389 #if !defined HAVE_POSIX_TIMERS || !defined HAVE_CLOCK_GETTIME
390 static GstClockTime gst_system_clock_get_mono_time (GstSystemClock * clock);
391 static GstClockTime gst_system_clock_get_real_time ();
393 static guint64 gst_system_clock_get_resolution (GstClock * clock);
394 static GstClockReturn gst_system_clock_id_wait_jitter (GstClock * clock,
395 GstClockEntry * entry, GstClockTimeDiff * jitter);
396 static GstClockReturn gst_system_clock_id_wait_jitter_unlocked
397 (GstClock * clock, GstClockEntry * entry, GstClockTimeDiff * jitter,
399 static GstClockReturn gst_system_clock_id_wait_async (GstClock * clock,
400 GstClockEntry * entry);
401 static void gst_system_clock_id_unschedule (GstClock * clock,
402 GstClockEntry * entry);
403 static void gst_system_clock_async_thread (GstClock * clock);
404 static gboolean gst_system_clock_start_async (GstSystemClock * clock);
406 static GMutex _gst_sysclock_mutex;
408 /* static guint gst_system_clock_signals[LAST_SIGNAL] = { 0 }; */
410 #define gst_system_clock_parent_class parent_class
411 G_DEFINE_TYPE_WITH_PRIVATE (GstSystemClock, gst_system_clock, GST_TYPE_CLOCK);
414 gst_system_clock_class_init (GstSystemClockClass * klass)
416 GObjectClass *gobject_class;
417 GstClockClass *gstclock_class;
419 gobject_class = (GObjectClass *) klass;
420 gstclock_class = (GstClockClass *) klass;
422 gobject_class->dispose = gst_system_clock_dispose;
423 gobject_class->set_property = gst_system_clock_set_property;
424 gobject_class->get_property = gst_system_clock_get_property;
426 g_object_class_install_property (gobject_class, PROP_CLOCK_TYPE,
427 g_param_spec_enum ("clock-type", "Clock type",
428 "The type of underlying clock implementation used",
429 GST_TYPE_CLOCK_TYPE, DEFAULT_CLOCK_TYPE,
430 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
432 gstclock_class->get_internal_time = gst_system_clock_get_internal_time;
433 gstclock_class->get_resolution = gst_system_clock_get_resolution;
434 gstclock_class->wait = gst_system_clock_id_wait_jitter;
435 gstclock_class->wait_async = gst_system_clock_id_wait_async;
436 gstclock_class->unschedule = gst_system_clock_id_unschedule;
440 gst_system_clock_init (GstSystemClock * clock)
442 GstSystemClockPrivate *priv;
444 GST_OBJECT_FLAG_SET (clock,
445 GST_CLOCK_FLAG_CAN_DO_SINGLE_SYNC |
446 GST_CLOCK_FLAG_CAN_DO_SINGLE_ASYNC |
447 GST_CLOCK_FLAG_CAN_DO_PERIODIC_SYNC |
448 GST_CLOCK_FLAG_CAN_DO_PERIODIC_ASYNC);
450 clock->priv = priv = gst_system_clock_get_instance_private (clock);
452 priv->clock_type = DEFAULT_CLOCK_TYPE;
454 priv->entries = NULL;
455 g_cond_init (&priv->entries_changed);
458 QueryPerformanceFrequency (&priv->frequency);
459 #endif /* G_OS_WIN32 */
462 mach_timebase_info (&priv->mach_timebase);
466 /* Uncomment this to start the async clock thread straight away */
467 GST_SYSTEM_CLOCK_LOCK (clock);
468 gst_system_clock_start_async (clock);
469 GST_SYSTEM_CLOCK_UNLOCK (clock);
474 gst_system_clock_dispose (GObject * object)
476 GstClock *clock = (GstClock *) object;
477 GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
478 GstSystemClockPrivate *priv = sysclock->priv;
481 /* else we have to stop the thread */
482 GST_SYSTEM_CLOCK_LOCK (clock);
483 priv->stopping = TRUE;
484 /* unschedule all entries */
485 for (entries = priv->entries; entries; entries = g_list_next (entries)) {
486 GstClockEntryImpl *entry = (GstClockEntryImpl *) entries->data;
488 /* We don't need to take the entry lock here because the async thread
489 * would only ever look at the head entry, which is locked below and only
490 * accesses new entries with the clock lock, which we hold here.
492 GST_CLOCK_ENTRY_STATUS ((GstClockEntry *) entry) = GST_CLOCK_UNSCHEDULED;
494 /* Wake up only the head entry: the async thread would only be waiting for
495 * this one, not all of them. Once the head entry is unscheduled it tries
496 * to get the system clock lock (which we hold here) and then look for the
497 * next entry. Once it gets the lock it will notice that all further
498 * entries are unscheduled, would remove them one by one from the list and
500 if (!entries->prev) {
501 /* it was initialized before adding to the list */
502 g_assert (entry->initialized);
504 GST_SYSTEM_CLOCK_ENTRY_LOCK (entry);
505 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "unscheduling entry %p",
507 GST_SYSTEM_CLOCK_ENTRY_BROADCAST (entry);
508 GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
511 GST_SYSTEM_CLOCK_BROADCAST (clock);
512 GST_SYSTEM_CLOCK_UNLOCK (clock);
515 g_thread_join (priv->thread);
517 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "joined thread");
519 g_list_foreach (priv->entries, (GFunc) gst_clock_id_unref, NULL);
520 g_list_free (priv->entries);
521 priv->entries = NULL;
523 g_cond_clear (&priv->entries_changed);
525 G_OBJECT_CLASS (parent_class)->dispose (object);
527 if (_the_system_clock == clock) {
528 _the_system_clock = NULL;
529 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "disposed system clock");
534 gst_system_clock_set_property (GObject * object, guint prop_id,
535 const GValue * value, GParamSpec * pspec)
537 GstSystemClock *sysclock = GST_SYSTEM_CLOCK (object);
540 case PROP_CLOCK_TYPE:
541 sysclock->priv->clock_type = (GstClockType) g_value_get_enum (value);
542 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, sysclock, "clock-type set to %d",
543 sysclock->priv->clock_type);
546 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
552 gst_system_clock_get_property (GObject * object, guint prop_id, GValue * value,
555 GstSystemClock *sysclock = GST_SYSTEM_CLOCK (object);
558 case PROP_CLOCK_TYPE:
559 g_value_set_enum (value, sysclock->priv->clock_type);
562 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
568 * gst_system_clock_set_default:
569 * @new_clock: (allow-none): a #GstClock
571 * Sets the default system clock that can be obtained with
572 * gst_system_clock_obtain().
574 * This is mostly used for testing and debugging purposes when you
575 * want to have control over the time reported by the default system
583 gst_system_clock_set_default (GstClock * new_clock)
587 g_mutex_lock (&_gst_sysclock_mutex);
588 clock = _the_system_clock;
591 gst_object_unref (clock);
593 if (new_clock == NULL) {
594 GST_CAT_DEBUG (GST_CAT_CLOCK, "resetting default system clock");
595 _external_default_clock = FALSE;
597 GST_CAT_DEBUG (GST_CAT_CLOCK, "setting new default system clock to %p",
599 _external_default_clock = TRUE;
600 g_object_ref (new_clock);
602 _the_system_clock = new_clock;
603 g_mutex_unlock (&_gst_sysclock_mutex);
607 * gst_system_clock_obtain:
609 * Get a handle to the default system clock. The refcount of the
610 * clock will be increased so you need to unref the clock after
613 * Returns: (transfer full): the default clock.
618 gst_system_clock_obtain (void)
622 g_mutex_lock (&_gst_sysclock_mutex);
623 clock = _the_system_clock;
626 GST_CAT_DEBUG (GST_CAT_CLOCK, "creating new static system clock");
627 g_assert (!_external_default_clock);
628 clock = g_object_new (GST_TYPE_SYSTEM_CLOCK,
629 "name", "GstSystemClock", NULL);
631 /* Clear floating flag */
632 gst_object_ref_sink (clock);
633 GST_OBJECT_FLAG_SET (clock, GST_OBJECT_FLAG_MAY_BE_LEAKED);
634 _the_system_clock = clock;
635 g_mutex_unlock (&_gst_sysclock_mutex);
637 g_mutex_unlock (&_gst_sysclock_mutex);
638 GST_CAT_DEBUG (GST_CAT_CLOCK, "returning static system clock");
641 /* we ref it since we are a clock factory. */
642 gst_object_ref (clock);
646 /* this thread reads the sorted clock entries from the queue.
648 * It waits on each of them and fires the callback when the timeout occurs.
650 * When an entry in the queue was canceled before we wait for it, it is
653 * When waiting for an entry, it can become canceled, in that case we don't
654 * call the callback but move to the next item in the queue.
659 gst_system_clock_async_thread (GstClock * clock)
661 GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
662 GstSystemClockPrivate *priv = sysclock->priv;
663 GstClockReturn status;
664 gboolean entry_needs_unlock = FALSE;
666 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "enter system clock thread");
667 GST_SYSTEM_CLOCK_LOCK (clock);
669 GST_SYSTEM_CLOCK_BROADCAST (clock);
670 /* now enter our (almost) infinite loop */
671 while (!priv->stopping) {
672 GstClockEntry *entry;
673 GstClockTime requested;
676 /* check if something to be done */
677 while (priv->entries == NULL) {
678 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
679 "no clock entries, waiting..");
680 /* wait for work to do */
681 GST_SYSTEM_CLOCK_WAIT (clock);
682 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "got signal");
683 /* clock was stopping, exit */
688 /* pick the next entry */
689 entry = priv->entries->data;
691 /* it was initialized before adding to the list */
692 g_assert (((GstClockEntryImpl *) entry)->initialized);
694 /* unlocked before the next loop iteration at latest */
695 GST_SYSTEM_CLOCK_ENTRY_LOCK ((GstClockEntryImpl *) entry);
696 entry_needs_unlock = TRUE;
698 /* set entry status to busy before we release the clock lock */
699 status = GST_CLOCK_ENTRY_STATUS (entry);
701 /* check for unscheduled */
702 if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
703 /* entry was unscheduled, move to the next one */
704 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
705 "async entry %p unscheduled", entry);
706 GST_SYSTEM_CLOCK_UNLOCK (clock);
710 /* for periodic timers, status can be EARLY from a previous run */
711 if (G_UNLIKELY (status != GST_CLOCK_OK && status != GST_CLOCK_EARLY))
712 GST_CAT_ERROR_OBJECT (GST_CAT_CLOCK, clock,
713 "unexpected status %d for entry %p", status, entry);
715 /* mark the entry as busy */
716 GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_BUSY;
718 requested = entry->time;
720 /* needs to be locked again before the next loop iteration, and we only
721 * unlock it here so that gst_system_clock_id_wait_async() is guaranteed
722 * to see status==BUSY later and wakes up this thread, and dispose() does
723 * not override BUSY with UNSCHEDULED here. */
724 GST_SYSTEM_CLOCK_UNLOCK (clock);
726 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "waiting on entry %p", entry);
728 /* now wait for the entry */
730 gst_system_clock_id_wait_jitter_unlocked (clock, (GstClockID) entry,
734 case GST_CLOCK_UNSCHEDULED:
735 /* entry was unscheduled, move to the next */
736 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
737 "async entry %p unscheduled", entry);
740 case GST_CLOCK_EARLY:
742 GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
743 entry_needs_unlock = FALSE;
744 /* entry timed out normally, fire the callback and move to the next
746 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "async entry %p timed out",
749 /* unlock before firing the callback */
750 entry->func (clock, entry->time, (GstClockID) entry,
753 if (entry->type == GST_CLOCK_ENTRY_PERIODIC) {
754 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
755 "updating periodic entry %p", entry);
757 GST_SYSTEM_CLOCK_LOCK (clock);
758 /* adjust time now */
759 entry->time = requested + entry->interval;
760 /* and resort the list now */
762 g_list_sort (priv->entries, gst_clock_id_compare_func);
766 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "moving to next entry");
771 /* somebody unlocked the entry but is was not canceled, This means that
772 * a new entry was added in front of the queue. Pick the new head
773 * entry of the list and continue waiting. */
774 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
775 "async entry %p needs restart", entry);
777 /* we set the entry back to the OK state. This is needed so that the
778 * _unschedule() code can see if an entry is currently being waited
779 * on (when its state is BUSY). */
780 GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_OK;
781 if (entry_needs_unlock)
782 GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
783 GST_SYSTEM_CLOCK_LOCK (clock);
786 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
787 "strange result %d waiting for %p, skipping", res, entry);
788 g_warning ("%s: strange result %d waiting for %p, skipping",
789 GST_OBJECT_NAME (clock), res, entry);
793 if (entry_needs_unlock)
794 GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
795 GST_SYSTEM_CLOCK_LOCK (clock);
797 /* we remove the current entry and unref it */
798 priv->entries = g_list_remove (priv->entries, entry);
799 gst_clock_id_unref ((GstClockID) entry);
803 GST_SYSTEM_CLOCK_BROADCAST (clock);
804 GST_SYSTEM_CLOCK_UNLOCK (clock);
805 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "exit system clock thread");
808 #ifdef HAVE_POSIX_TIMERS
809 static inline clockid_t
810 clock_type_to_posix_id (GstClockType clock_type)
812 #ifdef HAVE_MONOTONIC_CLOCK
813 if (clock_type == GST_CLOCK_TYPE_MONOTONIC)
814 return CLOCK_MONOTONIC;
817 if (clock_type == GST_CLOCK_TYPE_TAI)
822 ("No CLOCK_TAI available on the system. Falling back to CLOCK_REALTIME");
824 return CLOCK_REALTIME;
830 gst_system_clock_get_internal_time (GstClock * clock)
832 GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
833 #if defined HAVE_POSIX_TIMERS && defined HAVE_CLOCK_GETTIME
834 // BSD and Linux' Posix timers and clock_gettime cover all of the different clock types
835 // without need for special handling so we'll use those.
839 ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
841 if (G_UNLIKELY (clock_gettime (ptype, &ts)))
842 return GST_CLOCK_TIME_NONE;
844 return GST_TIMESPEC_TO_TIME (ts);
846 if (sysclock->priv->clock_type == GST_CLOCK_TYPE_REALTIME) {
847 return gst_system_clock_get_real_time ();
849 return gst_system_clock_get_mono_time (sysclock);
851 #endif /* !HAVE_POSIX_TIMERS || !HAVE_CLOCK_GETTIME */
854 #if !defined HAVE_POSIX_TIMERS || !defined HAVE_CLOCK_GETTIME
856 gst_system_clock_get_real_time ()
858 gint64 rt_micros = g_get_real_time ();
859 // g_get_real_time returns microseconds but we need nanos, so we'll multiply by 1000
860 return ((guint64) rt_micros) * 1000;
864 gst_system_clock_get_mono_time (GstSystemClock * sysclock)
866 #if defined __APPLE__
867 uint64_t mach_t = mach_absolute_time ();
868 return gst_util_uint64_scale (mach_t, sysclock->priv->mach_timebase.numer,
869 sysclock->priv->mach_timebase.denom);
871 #if defined G_OS_WIN32
872 if (sysclock->priv->frequency.QuadPart != 0) {
875 /* we prefer the highly accurate performance counters on windows */
876 QueryPerformanceCounter (&now);
878 return gst_util_uint64_scale (now.QuadPart,
879 GST_SECOND, sysclock->priv->frequency.QuadPart);
881 #endif /* G_OS_WIN32 */
885 monotime = g_get_monotonic_time ();
887 return monotime * 1000;
889 #endif /* __APPLE__ */
891 #endif /* !HAVE_POSIX_TIMERS || !HAVE_CLOCK_GETTIME */
894 gst_system_clock_get_resolution (GstClock * clock)
896 GstSystemClock *sysclock = GST_SYSTEM_CLOCK_CAST (clock);
897 #if defined __APPLE__ || defined G_OS_WIN32
898 if (sysclock->priv->clock_type == GST_CLOCK_TYPE_REALTIME) {
899 return 1 * GST_USECOND;
902 #if defined __APPLE__
904 return gst_util_uint64_scale (GST_NSECOND,
905 sysclock->priv->mach_timebase.numer,
906 sysclock->priv->mach_timebase.denom);
908 #elif defined G_OS_WIN32
910 if (sysclock->priv->frequency.QuadPart != 0) {
911 return GST_SECOND / sysclock->priv->frequency.QuadPart;
913 return 1 * GST_USECOND;
916 #elif defined(HAVE_POSIX_TIMERS) && defined(HAVE_CLOCK_GETTIME)
920 ptype = clock_type_to_posix_id (sysclock->priv->clock_type);
922 if (G_UNLIKELY (clock_getres (ptype, &ts)))
923 return GST_CLOCK_TIME_NONE;
925 return GST_TIMESPEC_TO_TIME (ts);
927 return 1 * GST_USECOND;
928 #endif /* __APPLE__ */
931 /* synchronously wait on the given GstClockEntry.
933 * We do this by blocking on the entry specifically rather than a global
934 * condition variable so that each possible thread may be woken up
935 * individually. This ensures that we don't wake up possibly multiple threads
936 * when unscheduling an entry.
938 * Entries that arrive too late are simply not waited on and a
939 * GST_CLOCK_EARLY result is returned.
941 * This is called with the ENTRY_LOCK but not SYSTEM_CLOCK_LOCK!
945 static GstClockReturn
946 gst_system_clock_id_wait_jitter_unlocked (GstClock * clock,
947 GstClockEntry * entry, GstClockTimeDiff * jitter, gboolean restart)
949 GstClockTime entryt, now;
950 GstClockTimeDiff diff;
951 GstClockReturn status;
954 status = GST_CLOCK_ENTRY_STATUS (entry);
955 if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
956 return GST_CLOCK_UNSCHEDULED;
959 /* need to call the overridden method because we want to sync against the time
960 * of the clock, whatever the subclass uses as a clock. */
961 now = gst_clock_get_time (clock);
962 mono_ts = g_get_monotonic_time ();
964 /* get the time of the entry */
965 entryt = GST_CLOCK_ENTRY_TIME (entry);
967 /* the diff of the entry with the clock is the amount of time we have to
969 diff = GST_CLOCK_DIFF (now, entryt);
970 if (G_LIKELY (jitter))
973 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "entry %p"
974 " time %" GST_TIME_FORMAT
975 " now %" GST_TIME_FORMAT
976 " diff (time-now) %" G_GINT64_FORMAT,
977 entry, GST_TIME_ARGS (entryt), GST_TIME_ARGS (now), diff);
979 if (G_LIKELY (diff > CLOCK_MIN_WAIT_TIME)) {
980 #ifdef WAIT_DEBUGGING
987 #ifdef HAVE_CLOCK_NANOSLEEP
988 if (diff <= 500 * GST_USECOND) {
989 /* In order to provide more accurate wait, we will use BLOCKING
990 clock_nanosleep for any deadlines at or below 500us */
992 GST_TIME_TO_TIMESPEC (mono_ts * 1000 + diff, end);
993 GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
995 clock_nanosleep (CLOCK_MONOTONIC, TIMER_ABSTIME, &end, NULL) == 0;
996 GST_SYSTEM_CLOCK_ENTRY_LOCK ((GstClockEntryImpl *) entry);
999 if (diff < 2 * GST_MSECOND) {
1000 /* For any deadline within 2ms, we first use the regular non-blocking
1001 wait by reducing the diff accordingly */
1002 diff -= 500 * GST_USECOND;
1006 /* now wait on the entry, it either times out or the cond is signalled.
1007 * The status of the entry is BUSY only around the wait. */
1009 GST_SYSTEM_CLOCK_ENTRY_WAIT_UNTIL ((GstClockEntryImpl *) entry,
1010 mono_ts * 1000 + diff);
1012 #ifdef HAVE_CLOCK_NANOSLEEP
1016 /* get the new status, mark as DONE. We do this so that the unschedule
1017 * function knows when we left the poll and doesn't need to wakeup the
1019 status = GST_CLOCK_ENTRY_STATUS (entry);
1020 /* we were unscheduled, exit immediately */
1021 if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED))
1023 if (G_UNLIKELY (status != GST_CLOCK_BUSY))
1024 GST_CAT_ERROR_OBJECT (GST_CAT_CLOCK, clock,
1025 "unexpected status %d for entry %p", status, entry);
1026 GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_DONE;
1028 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1029 "entry %p unlocked, status %d", entry, status);
1031 if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
1035 /* some other id got unlocked */
1037 /* this can happen if the entry got unlocked because of an async
1038 * entry was added to the head of the async queue. */
1039 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1040 "wakeup waiting for entry %p", entry);
1044 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1045 "entry %p needs to be restarted", entry);
1047 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1048 "entry %p unlocked after timeout", entry);
1051 /* reschedule if gst_cond_wait_until returned early or we have to reschedule after
1053 mono_ts = g_get_monotonic_time ();
1054 now = gst_clock_get_time (clock);
1055 diff = GST_CLOCK_DIFF (now, entryt);
1057 if (diff <= CLOCK_MIN_WAIT_TIME) {
1058 /* timeout, this is fine, we can report success now */
1059 GST_CLOCK_ENTRY_STATUS (entry) = status = GST_CLOCK_OK;
1060 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1061 "entry %p finished, diff %" G_GINT64_FORMAT, entry, diff);
1063 #ifdef WAIT_DEBUGGING
1064 final = gst_system_clock_get_internal_time (clock);
1065 GST_CAT_DEBUG (GST_CAT_CLOCK, "Waited for %" G_GINT64_FORMAT
1066 " got %" G_GINT64_FORMAT " diff %" G_GINT64_FORMAT
1067 " %g target-offset %" G_GINT64_FORMAT " %g", entryt, now,
1069 (double) (GstClockTimeDiff) (now - entryt) / GST_SECOND,
1071 ((double) (GstClockTimeDiff) (final - target)) / GST_SECOND);
1075 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1076 "entry %p restart, diff %" G_GINT64_FORMAT, entry, diff);
1077 /* we are going to poll again, set status back to busy */
1078 GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_BUSY;
1083 /* we are right on time or too late */
1084 if (G_UNLIKELY (diff == 0)) {
1085 GST_CLOCK_ENTRY_STATUS (entry) = status = GST_CLOCK_OK;
1087 GST_CLOCK_ENTRY_STATUS (entry) = status = GST_CLOCK_EARLY;
1094 static GstClockReturn
1095 gst_system_clock_id_wait_jitter (GstClock * clock, GstClockEntry * entry,
1096 GstClockTimeDiff * jitter)
1098 GstClockReturn status;
1099 GstClockEntryImpl *entry_impl = (GstClockEntryImpl *) entry;
1101 GST_SYSTEM_CLOCK_LOCK (clock);
1102 ensure_entry_initialized (entry_impl);
1103 GST_SYSTEM_CLOCK_UNLOCK (clock);
1105 GST_SYSTEM_CLOCK_ENTRY_LOCK (entry_impl);
1106 status = GST_CLOCK_ENTRY_STATUS (entry);
1108 /* stop when we are unscheduled */
1109 if (G_UNLIKELY (status == GST_CLOCK_UNSCHEDULED)) {
1110 GST_SYSTEM_CLOCK_ENTRY_UNLOCK (entry_impl);
1114 if (G_UNLIKELY (status != GST_CLOCK_OK))
1115 GST_CAT_ERROR_OBJECT (GST_CAT_CLOCK, clock,
1116 "unexpected status %d for entry %p", status, entry);
1118 /* mark the entry as busy */
1119 GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_BUSY;
1121 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "waiting on entry %p", entry);
1124 gst_system_clock_id_wait_jitter_unlocked (clock, entry, jitter, TRUE);
1126 GST_SYSTEM_CLOCK_ENTRY_UNLOCK (entry_impl);
1131 /* Start the async clock thread. Must be called with the object lock
1134 gst_system_clock_start_async (GstSystemClock * clock)
1136 GError *error = NULL;
1137 GstSystemClockPrivate *priv = clock->priv;
1139 if (G_LIKELY (priv->thread != NULL))
1140 return TRUE; /* Thread already running. Nothing to do */
1142 priv->thread = g_thread_try_new ("GstSystemClock",
1143 (GThreadFunc) gst_system_clock_async_thread, clock, &error);
1145 if (G_UNLIKELY (error))
1148 /* wait for it to spin up */
1149 GST_SYSTEM_CLOCK_WAIT (clock);
1156 g_warning ("could not create async clock thread: %s", error->message);
1157 g_error_free (error);
1162 /* Add an entry to the list of pending async waits. The entry is inserted
1163 * in sorted order. If we inserted the entry at the head of the list, we
1164 * need to signal the thread as it might either be waiting on it or waiting
1169 static GstClockReturn
1170 gst_system_clock_id_wait_async (GstClock * clock, GstClockEntry * entry)
1172 GstSystemClock *sysclock;
1173 GstSystemClockPrivate *priv;
1174 GstClockEntry *head;
1176 sysclock = GST_SYSTEM_CLOCK_CAST (clock);
1177 priv = sysclock->priv;
1179 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "adding async entry %p", entry);
1181 GST_SYSTEM_CLOCK_LOCK (clock);
1182 /* Start the clock async thread if needed */
1183 if (G_UNLIKELY (!gst_system_clock_start_async (sysclock)))
1186 ensure_entry_initialized ((GstClockEntryImpl *) entry);
1187 GST_SYSTEM_CLOCK_ENTRY_LOCK ((GstClockEntryImpl *) entry);
1188 if (G_UNLIKELY (GST_CLOCK_ENTRY_STATUS (entry) == GST_CLOCK_UNSCHEDULED))
1189 goto was_unscheduled;
1190 GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
1193 head = priv->entries->data;
1197 /* need to take a ref */
1198 gst_clock_id_ref ((GstClockID) entry);
1200 /* insert the entry in sorted order */
1201 priv->entries = g_list_insert_sorted (priv->entries, entry,
1202 gst_clock_id_compare_func);
1204 /* only need to send the signal if the entry was added to the
1205 * front, else the thread is just waiting for another entry and
1206 * will get to this entry automatically. */
1207 if (priv->entries->data == entry) {
1208 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1209 "async entry added to head %p", head);
1211 /* the list was empty before, signal the cond so that the async thread can
1212 * start taking a look at the queue */
1213 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1214 "first entry, sending signal");
1215 GST_SYSTEM_CLOCK_BROADCAST (clock);
1217 GstClockReturn status;
1219 /* it was initialized before adding to the list */
1220 g_assert (((GstClockEntryImpl *) head)->initialized);
1222 GST_SYSTEM_CLOCK_ENTRY_LOCK ((GstClockEntryImpl *) head);
1223 status = GST_CLOCK_ENTRY_STATUS (head);
1224 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "head entry %p status %d",
1227 if (status == GST_CLOCK_BUSY) {
1228 /* the async thread was waiting for an entry, unlock the wait so that it
1229 * looks at the new head entry instead, we only need to do this once */
1230 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1231 "head entry was busy. Wakeup async thread");
1232 GST_SYSTEM_CLOCK_ENTRY_BROADCAST ((GstClockEntryImpl *) head);
1234 GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) head);
1237 GST_SYSTEM_CLOCK_UNLOCK (clock);
1239 return GST_CLOCK_OK;
1244 /* Could not start the async clock thread */
1245 GST_SYSTEM_CLOCK_UNLOCK (clock);
1246 return GST_CLOCK_ERROR;
1250 GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
1251 GST_SYSTEM_CLOCK_UNLOCK (clock);
1252 return GST_CLOCK_UNSCHEDULED;
1256 /* unschedule an entry. This will set the state of the entry to GST_CLOCK_UNSCHEDULED
1257 * and will signal any thread waiting for entries to recheck their entry.
1258 * We cannot really decide if the signal is needed or not because the entry
1259 * could be waited on in async or sync mode.
1264 gst_system_clock_id_unschedule (GstClock * clock, GstClockEntry * entry)
1266 GstClockReturn status;
1268 GST_SYSTEM_CLOCK_LOCK (clock);
1270 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "unscheduling entry %p time %"
1271 GST_TIME_FORMAT, entry, GST_TIME_ARGS (GST_CLOCK_ENTRY_TIME (entry)));
1273 ensure_entry_initialized ((GstClockEntryImpl *) entry);
1275 GST_SYSTEM_CLOCK_ENTRY_LOCK ((GstClockEntryImpl *) entry);
1276 /* change the entry status to unscheduled */
1277 status = GST_CLOCK_ENTRY_STATUS (entry);
1278 GST_CLOCK_ENTRY_STATUS (entry) = GST_CLOCK_UNSCHEDULED;
1280 if (G_LIKELY (status == GST_CLOCK_BUSY)) {
1281 /* the entry was being busy, wake up the entry */
1282 GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "entry was BUSY, doing wakeup");
1283 GST_SYSTEM_CLOCK_ENTRY_BROADCAST ((GstClockEntryImpl *) entry);
1285 GST_SYSTEM_CLOCK_ENTRY_UNLOCK ((GstClockEntryImpl *) entry);
1286 GST_SYSTEM_CLOCK_UNLOCK (clock);