gstpad: Fix non-serialized sticky event push
[platform/upstream/gstreamer.git] / subprojects / gstreamer / gst / gstclock.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *                    2004 Wim Taymans <wim@fluendo.com>
5  *
6  * gstclock.c: Clock subsystem for maintaining time sync
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 /**
25  * SECTION:gstclock
26  * @title: GstClock
27  * @short_description: Abstract class for global clocks
28  * @see_also: #GstSystemClock, #GstPipeline
29  *
30  * GStreamer uses a global clock to synchronize the plugins in a pipeline.
31  * Different clock implementations are possible by implementing this abstract
32  * base class or, more conveniently, by subclassing #GstSystemClock.
33  *
34  * The #GstClock returns a monotonically increasing time with the method
35  * gst_clock_get_time(). Its accuracy and base time depend on the specific
36  * clock implementation but time is always expressed in nanoseconds. Since the
37  * baseline of the clock is undefined, the clock time returned is not
38  * meaningful in itself, what matters are the deltas between two clock times.
39  * The time returned by a clock is called the absolute time.
40  *
41  * The pipeline uses the clock to calculate the running time. Usually all
42  * renderers synchronize to the global clock using the buffer timestamps, the
43  * #GST_EVENT_SEGMENT events and the element's base time, see #GstPipeline.
44  *
45  * A clock implementation can support periodic and single shot clock
46  * notifications both synchronous and asynchronous.
47  *
48  * One first needs to create a #GstClockID for the periodic or single shot
49  * notification using gst_clock_new_single_shot_id() or
50  * gst_clock_new_periodic_id().
51  *
52  * To perform a blocking wait for the specific time of the #GstClockID use
53  * gst_clock_id_wait(). To receive a callback when the specific time is reached
54  * in the clock use gst_clock_id_wait_async(). Both these calls can be
55  * interrupted with the gst_clock_id_unschedule() call. If the blocking wait is
56  * unscheduled a return value of #GST_CLOCK_UNSCHEDULED is returned.
57  *
58  * Periodic callbacks scheduled async will be repeatedly called automatically
59  * until they are unscheduled. To schedule a sync periodic callback,
60  * gst_clock_id_wait() should be called repeatedly.
61  *
62  * The async callbacks can happen from any thread, either provided by the core
63  * or from a streaming thread. The application should be prepared for this.
64  *
65  * A #GstClockID that has been unscheduled cannot be used again for any wait
66  * operation, a new #GstClockID should be created and the old unscheduled one
67  * should be destroyed with gst_clock_id_unref().
68  *
69  * It is possible to perform a blocking wait on the same #GstClockID from
70  * multiple threads. However, registering the same #GstClockID for multiple
71  * async notifications is not possible, the callback will only be called for
72  * the thread registering the entry last.
73  *
74  * None of the wait operations unref the #GstClockID, the owner is responsible
75  * for unreffing the ids itself. This holds for both periodic and single shot
76  * notifications. The reason being that the owner of the #GstClockID has to
77  * keep a handle to the #GstClockID to unblock the wait on FLUSHING events or
78  * state changes and if the entry would be unreffed automatically, the handle
79  * might become invalid without any notification.
80  *
81  * These clock operations do not operate on the running time, so the callbacks
82  * will also occur when not in PLAYING state as if the clock just keeps on
83  * running. Some clocks however do not progress when the element that provided
84  * the clock is not PLAYING.
85  *
86  * When a clock has the #GST_CLOCK_FLAG_CAN_SET_MASTER flag set, it can be
87  * slaved to another #GstClock with gst_clock_set_master(). The clock will
88  * then automatically be synchronized to this master clock by repeatedly
89  * sampling the master clock and the slave clock and recalibrating the slave
90  * clock with gst_clock_set_calibration(). This feature is mostly useful for
91  * plugins that have an internal clock but must operate with another clock
92  * selected by the #GstPipeline.  They can track the offset and rate difference
93  * of their internal clock relative to the master clock by using the
94  * gst_clock_get_calibration() function.
95  *
96  * The master/slave synchronisation can be tuned with the #GstClock:timeout,
97  * #GstClock:window-size and #GstClock:window-threshold properties.
98  * The #GstClock:timeout property defines the interval to sample the master
99  * clock and run the calibration functions. #GstClock:window-size defines the
100  * number of samples to use when calibrating and #GstClock:window-threshold
101  * defines the minimum number of samples before the calibration is performed.
102  */
103
104 #include "gst_private.h"
105 #include <time.h>
106
107 #include "gstclock.h"
108 #include "gstinfo.h"
109 #include "gstutils.h"
110 #include "glib-compat-private.h"
111
112 /* #define DEBUGGING_ENABLED */
113
114 #define DEFAULT_WINDOW_SIZE             32
115 #define DEFAULT_WINDOW_THRESHOLD        4
116 #define DEFAULT_TIMEOUT                 GST_SECOND / 10
117
118 enum
119 {
120   PROP_0,
121   PROP_WINDOW_SIZE,
122   PROP_WINDOW_THRESHOLD,
123   PROP_TIMEOUT
124 };
125
126 enum
127 {
128   SIGNAL_SYNCED,
129   SIGNAL_LAST
130 };
131
132 #define GST_CLOCK_SLAVE_LOCK(clock)     g_mutex_lock (&GST_CLOCK_CAST (clock)->priv->slave_lock)
133 #define GST_CLOCK_SLAVE_UNLOCK(clock)   g_mutex_unlock (&GST_CLOCK_CAST (clock)->priv->slave_lock)
134
135 struct _GstClockPrivate
136 {
137   GMutex slave_lock;            /* order: SLAVE_LOCK, OBJECT_LOCK */
138
139   GCond sync_cond;
140
141   /* with LOCK */
142   GstClockTime internal_calibration;
143   GstClockTime external_calibration;
144   GstClockTime rate_numerator;
145   GstClockTime rate_denominator;
146   GstClockTime last_time;
147
148   /* with LOCK */
149   GstClockTime resolution;
150
151   /* for master/slave clocks */
152   GstClock *master;
153
154   /* with SLAVE_LOCK */
155   gboolean filling;
156   gint window_size;
157   gint window_threshold;
158   gint time_index;
159   GstClockTime timeout;
160   GstClockTime *times;
161   GstClockTime *times_temp;
162   GstClockID clockid;
163
164   gint pre_count;
165   gint post_count;
166
167   gboolean synced;
168
169   GWeakRef *clock_weakref;
170 };
171
172 typedef struct _GstClockEntryImpl GstClockEntryImpl;
173
174 #define GST_CLOCK_ENTRY_CLOCK_WEAK_REF(entry) (((GstClockEntryImpl *)(entry))->clock)
175
176 /* seqlocks */
177 #define read_seqbegin(clock)                                   \
178   g_atomic_int_get (&clock->priv->post_count);
179
180 static inline gboolean
181 read_seqretry (GstClock * clock, gint seq)
182 {
183   /* no retry if the seqnum did not change */
184   if (G_LIKELY (seq == g_atomic_int_get (&clock->priv->pre_count)))
185     return FALSE;
186
187   /* wait for the writer to finish and retry */
188   GST_OBJECT_LOCK (clock);
189   GST_OBJECT_UNLOCK (clock);
190   return TRUE;
191 }
192
193 #define write_seqlock(clock)                      \
194 G_STMT_START {                                    \
195   GST_OBJECT_LOCK (clock);                        \
196   g_atomic_int_inc (&clock->priv->pre_count);     \
197 } G_STMT_END;
198
199 #define write_sequnlock(clock)                    \
200 G_STMT_START {                                    \
201   g_atomic_int_inc (&clock->priv->post_count);    \
202   GST_OBJECT_UNLOCK (clock);                      \
203 } G_STMT_END;
204
205 #ifndef GST_DISABLE_GST_DEBUG
206 static const gchar *
207 gst_clock_return_get_name (GstClockReturn ret)
208 {
209   switch (ret) {
210     case GST_CLOCK_OK:
211       return "ok";
212     case GST_CLOCK_EARLY:
213       return "early";
214     case GST_CLOCK_UNSCHEDULED:
215       return "unscheduled";
216     case GST_CLOCK_BUSY:
217       return "busy";
218     case GST_CLOCK_BADTIME:
219       return "bad-time";
220     case GST_CLOCK_ERROR:
221       return "error";
222     case GST_CLOCK_UNSUPPORTED:
223       return "unsupported";
224     case GST_CLOCK_DONE:
225       return "done";
226     default:
227       break;
228   }
229
230   return "unknown";
231 }
232 #endif /* GST_DISABLE_GST_DEBUG */
233
234 static void gst_clock_dispose (GObject * object);
235 static void gst_clock_finalize (GObject * object);
236
237 static void gst_clock_set_property (GObject * object, guint prop_id,
238     const GValue * value, GParamSpec * pspec);
239 static void gst_clock_get_property (GObject * object, guint prop_id,
240     GValue * value, GParamSpec * pspec);
241
242 static guint gst_clock_signals[SIGNAL_LAST] = { 0 };
243
244 static GstClockID
245 gst_clock_entry_new (GstClock * clock, GstClockTime time,
246     GstClockTime interval, GstClockEntryType type)
247 {
248   GstClockEntry *entry;
249
250   entry = (GstClockEntry *) g_slice_new0 (GstClockEntryImpl);
251
252   /* FIXME: add tracer hook for struct allocations such as clock entries */
253
254   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
255       "created entry %p, time %" GST_TIME_FORMAT, entry, GST_TIME_ARGS (time));
256
257   entry->refcount = 1;
258 #ifndef GST_REMOVE_DEPRECATED
259 #ifndef GST_DISABLE_DEPRECATED
260   entry->clock = clock;
261 #else
262   entry->_clock = clock;
263 #endif
264 #endif
265   GST_CLOCK_ENTRY_CLOCK_WEAK_REF (entry) =
266       g_atomic_rc_box_acquire (clock->priv->clock_weakref);
267   entry->type = type;
268   entry->time = time;
269   entry->interval = interval;
270   entry->status = GST_CLOCK_OK;
271   entry->func = NULL;
272   entry->user_data = NULL;
273   entry->destroy_data = NULL;
274   entry->unscheduled = FALSE;
275   entry->woken_up = FALSE;
276
277   return (GstClockID) entry;
278 }
279
280 /* WARNING : Does not modify the refcount
281  * WARNING : Do not use if a pending clock operation is happening on that entry */
282 static gboolean
283 gst_clock_entry_reinit (GstClock * clock, GstClockEntry * entry,
284     GstClockTime time, GstClockTime interval, GstClockEntryType type)
285 {
286   g_return_val_if_fail (entry->status != GST_CLOCK_BUSY, FALSE);
287   g_return_val_if_fail (gst_clock_id_uses_clock ((GstClockID) entry, clock),
288       FALSE);
289
290   entry->type = type;
291   entry->time = time;
292   entry->interval = interval;
293   entry->status = GST_CLOCK_OK;
294   entry->unscheduled = FALSE;
295   entry->woken_up = FALSE;
296
297   return TRUE;
298 }
299
300 /**
301  * gst_clock_single_shot_id_reinit:
302  * @clock: a #GstClock
303  * @id: a #GstClockID
304  * @time: The requested time.
305  *
306  * Reinitializes the provided single shot @id to the provided time. Does not
307  * modify the reference count.
308  *
309  * Returns: %TRUE if the GstClockID could be reinitialized to the provided
310  * @time, else %FALSE.
311  */
312 gboolean
313 gst_clock_single_shot_id_reinit (GstClock * clock, GstClockID id,
314     GstClockTime time)
315 {
316   g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (time), FALSE);
317
318   return gst_clock_entry_reinit (clock, (GstClockEntry *) id, time,
319       GST_CLOCK_TIME_NONE, GST_CLOCK_ENTRY_SINGLE);
320 }
321
322 /**
323  * gst_clock_periodic_id_reinit:
324  * @clock: a #GstClock
325  * @id: a #GstClockID
326  * @start_time: the requested start time
327  * @interval: the requested interval
328  *
329  * Reinitializes the provided periodic @id to the provided start time and
330  * interval. Does not modify the reference count.
331  *
332  * Returns: %TRUE if the GstClockID could be reinitialized to the provided
333  * @time, else %FALSE.
334  */
335 gboolean
336 gst_clock_periodic_id_reinit (GstClock * clock, GstClockID id,
337     GstClockTime start_time, GstClockTime interval)
338 {
339   g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (start_time), FALSE);
340   g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (interval), FALSE);
341
342   return gst_clock_entry_reinit (clock, (GstClockEntry *) id, start_time,
343       interval, GST_CLOCK_ENTRY_PERIODIC);
344 }
345
346 /**
347  * gst_clock_id_ref:
348  * @id: The #GstClockID to ref
349  *
350  * Increases the refcount of given @id.
351  *
352  * Returns: (transfer full): The same #GstClockID with increased refcount.
353  */
354 GstClockID
355 gst_clock_id_ref (GstClockID id)
356 {
357   g_return_val_if_fail (id != NULL, NULL);
358
359   g_atomic_int_inc (&((GstClockEntry *) id)->refcount);
360
361   return id;
362 }
363
364 static void
365 _gst_clock_id_free (GstClockID id)
366 {
367   GstClockEntry *entry;
368   GstClockEntryImpl *entry_impl;
369   g_return_if_fail (id != NULL);
370
371   GST_CAT_DEBUG (GST_CAT_CLOCK, "freed entry %p", id);
372   entry = (GstClockEntry *) id;
373   if (entry->destroy_data)
374     entry->destroy_data (entry->user_data);
375
376   entry_impl = (GstClockEntryImpl *) id;
377   if (entry_impl->destroy_entry)
378     entry_impl->destroy_entry (entry_impl);
379
380   g_atomic_rc_box_release_full (GST_CLOCK_ENTRY_CLOCK_WEAK_REF (entry),
381       (GDestroyNotify) g_weak_ref_clear);
382
383   /* FIXME: add tracer hook for struct allocations such as clock entries */
384
385   g_slice_free (GstClockEntryImpl, (GstClockEntryImpl *) id);
386 }
387
388 /**
389  * gst_clock_id_unref:
390  * @id: (transfer full): The #GstClockID to unref
391  *
392  * Unrefs given @id. When the refcount reaches 0 the
393  * #GstClockID will be freed.
394  */
395 void
396 gst_clock_id_unref (GstClockID id)
397 {
398   gint zero;
399
400   g_return_if_fail (id != NULL);
401
402   zero = g_atomic_int_dec_and_test (&((GstClockEntry *) id)->refcount);
403   /* if we ended up with the refcount at zero, free the id */
404   if (zero) {
405     _gst_clock_id_free (id);
406   }
407 }
408
409 /**
410  * gst_clock_new_single_shot_id:
411  * @clock: The #GstClockID to get a single shot notification from
412  * @time: the requested time
413  *
414  * Gets a #GstClockID from @clock to trigger a single shot
415  * notification at the requested time.
416  *
417  * Returns: (transfer full): a #GstClockID that can be used to request the
418  *     time notification.
419  */
420 GstClockID
421 gst_clock_new_single_shot_id (GstClock * clock, GstClockTime time)
422 {
423   g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);
424   g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (time), NULL);
425
426   return gst_clock_entry_new (clock,
427       time, GST_CLOCK_TIME_NONE, GST_CLOCK_ENTRY_SINGLE);
428 }
429
430 /**
431  * gst_clock_new_periodic_id:
432  * @clock: The #GstClockID to get a periodic notification id from
433  * @start_time: the requested start time
434  * @interval: the requested interval
435  *
436  * Gets an ID from @clock to trigger a periodic notification.
437  * The periodic notifications will start at time @start_time and
438  * will then be fired with the given @interval.
439  *
440  * Returns: (transfer full): a #GstClockID that can be used to request the
441  *     time notification.
442  */
443 GstClockID
444 gst_clock_new_periodic_id (GstClock * clock, GstClockTime start_time,
445     GstClockTime interval)
446 {
447   g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);
448   g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (start_time), NULL);
449   g_return_val_if_fail (interval != 0, NULL);
450   g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (interval), NULL);
451
452   return gst_clock_entry_new (clock,
453       start_time, interval, GST_CLOCK_ENTRY_PERIODIC);
454 }
455
456 /**
457  * gst_clock_id_compare_func:
458  * @id1: A #GstClockID
459  * @id2: A #GstClockID to compare with
460  *
461  * Compares the two #GstClockID instances. This function can be used
462  * as a GCompareFunc when sorting ids.
463  *
464  * Returns: negative value if `a < b`; zero if `a = b`; positive value if `a > b`
465  */
466 gint
467 gst_clock_id_compare_func (gconstpointer id1, gconstpointer id2)
468 {
469   GstClockEntry *entry1, *entry2;
470
471   entry1 = (GstClockEntry *) id1;
472   entry2 = (GstClockEntry *) id2;
473
474   if (GST_CLOCK_ENTRY_TIME (entry1) > GST_CLOCK_ENTRY_TIME (entry2)) {
475     return 1;
476   }
477   if (GST_CLOCK_ENTRY_TIME (entry1) < GST_CLOCK_ENTRY_TIME (entry2)) {
478     return -1;
479   }
480   return 0;
481 }
482
483 /**
484  * gst_clock_id_get_time:
485  * @id: The #GstClockID to query
486  *
487  * Gets the time of the clock ID
488  *
489  * Returns: the time of the given clock id.
490  */
491 GstClockTime
492 gst_clock_id_get_time (GstClockID id)
493 {
494   g_return_val_if_fail (id != NULL, GST_CLOCK_TIME_NONE);
495
496   return GST_CLOCK_ENTRY_TIME ((GstClockEntry *) id);
497 }
498
499 /**
500  * gst_clock_id_wait:
501  * @id: The #GstClockID to wait on
502  * @jitter: (out) (allow-none): a pointer that will contain the jitter,
503  *     can be %NULL.
504  *
505  * Performs a blocking wait on @id.
506  * @id should have been created with gst_clock_new_single_shot_id()
507  * or gst_clock_new_periodic_id() and should not have been unscheduled
508  * with a call to gst_clock_id_unschedule().
509  *
510  * If the @jitter argument is not %NULL and this function returns #GST_CLOCK_OK
511  * or #GST_CLOCK_EARLY, it will contain the difference
512  * against the clock and the time of @id when this method was
513  * called.
514  * Positive values indicate how late @id was relative to the clock
515  * (in which case this function will return #GST_CLOCK_EARLY).
516  * Negative values indicate how much time was spent waiting on the clock
517  * before this function returned.
518  *
519  * Returns: the result of the blocking wait. #GST_CLOCK_EARLY will be returned
520  * if the current clock time is past the time of @id, #GST_CLOCK_OK if
521  * @id was scheduled in time. #GST_CLOCK_UNSCHEDULED if @id was
522  * unscheduled with gst_clock_id_unschedule().
523  */
524 GstClockReturn
525 gst_clock_id_wait (GstClockID id, GstClockTimeDiff * jitter)
526 {
527   GstClockEntry *entry;
528   GstClock *clock;
529   GstClockReturn res;
530   GstClockTime requested;
531   GstClockClass *cclass;
532
533   g_return_val_if_fail (id != NULL, GST_CLOCK_ERROR);
534
535   entry = (GstClockEntry *) id;
536   requested = GST_CLOCK_ENTRY_TIME (entry);
537
538   clock = g_weak_ref_get (GST_CLOCK_ENTRY_CLOCK_WEAK_REF (entry));
539   if (G_UNLIKELY (clock == NULL))
540     goto invalid_entry;
541
542   /* can't sync on invalid times */
543   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (requested)))
544     goto invalid_time;
545
546   cclass = GST_CLOCK_GET_CLASS (clock);
547
548   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "waiting on clock entry %p", id);
549
550   /* if we have a wait_jitter function, use that */
551   if (G_UNLIKELY (cclass->wait == NULL))
552     goto not_supported;
553
554   res = cclass->wait (clock, entry, jitter);
555
556   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
557       "done waiting entry %p, res: %d (%s)", id, res,
558       gst_clock_return_get_name (res));
559
560   if (entry->type == GST_CLOCK_ENTRY_PERIODIC)
561     entry->time = requested + entry->interval;
562
563   gst_object_unref (clock);
564   return res;
565
566   /* ERRORS */
567 invalid_time:
568   {
569     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
570         "invalid time requested, returning _BADTIME");
571     gst_object_unref (clock);
572     return GST_CLOCK_BADTIME;
573   }
574 not_supported:
575   {
576     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "clock wait is not supported");
577     gst_object_unref (clock);
578     return GST_CLOCK_UNSUPPORTED;
579   }
580 invalid_entry:
581   {
582     GST_CAT_DEBUG (GST_CAT_CLOCK, "clock entry %p lost its clock", id);
583     return GST_CLOCK_ERROR;
584   }
585 }
586
587 /**
588  * gst_clock_id_wait_async:
589  * @id: a #GstClockID to wait on
590  * @func: The callback function
591  * @user_data: User data passed in the callback
592  * @destroy_data: #GDestroyNotify for user_data
593  *
594  * Registers a callback on the given #GstClockID @id with the given
595  * function and user_data. When passing a #GstClockID with an invalid
596  * time to this function, the callback will be called immediately
597  * with  a time set to %GST_CLOCK_TIME_NONE. The callback will
598  * be called when the time of @id has been reached.
599  *
600  * The callback @func can be invoked from any thread, either provided by the
601  * core or from a streaming thread. The application should be prepared for this.
602  *
603  * Returns: the result of the non blocking wait.
604  */
605 GstClockReturn
606 gst_clock_id_wait_async (GstClockID id,
607     GstClockCallback func, gpointer user_data, GDestroyNotify destroy_data)
608 {
609   GstClockEntry *entry;
610   GstClock *clock;
611   GstClockReturn res;
612   GstClockClass *cclass;
613   GstClockTime requested;
614
615   g_return_val_if_fail (id != NULL, GST_CLOCK_ERROR);
616   g_return_val_if_fail (func != NULL, GST_CLOCK_ERROR);
617
618   entry = (GstClockEntry *) id;
619   requested = GST_CLOCK_ENTRY_TIME (entry);
620   clock = g_weak_ref_get (GST_CLOCK_ENTRY_CLOCK_WEAK_REF (entry));
621   if (G_UNLIKELY (clock == NULL))
622     goto invalid_entry;
623
624   /* can't sync on invalid times */
625   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (requested)))
626     goto invalid_time;
627
628   cclass = GST_CLOCK_GET_CLASS (clock);
629
630   if (G_UNLIKELY (cclass->wait_async == NULL))
631     goto not_supported;
632
633   entry->func = func;
634   entry->user_data = user_data;
635   entry->destroy_data = destroy_data;
636
637   res = cclass->wait_async (clock, entry);
638
639   gst_object_unref (clock);
640   return res;
641
642   /* ERRORS */
643 invalid_time:
644   {
645     (func) (clock, GST_CLOCK_TIME_NONE, id, user_data);
646     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
647         "invalid time requested, returning _BADTIME");
648     gst_object_unref (clock);
649     return GST_CLOCK_BADTIME;
650   }
651 not_supported:
652   {
653     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "clock wait is not supported");
654     gst_object_unref (clock);
655     return GST_CLOCK_UNSUPPORTED;
656   }
657 invalid_entry:
658   {
659     GST_CAT_DEBUG (GST_CAT_CLOCK, "clock entry %p lost its clock", id);
660     return GST_CLOCK_ERROR;
661   }
662 }
663
664 /**
665  * gst_clock_id_unschedule:
666  * @id: The id to unschedule
667  *
668  * Cancels an outstanding request with @id. This can either
669  * be an outstanding async notification or a pending sync notification.
670  * After this call, @id cannot be used anymore to receive sync or
671  * async notifications, you need to create a new #GstClockID.
672  */
673 void
674 gst_clock_id_unschedule (GstClockID id)
675 {
676   GstClockEntry *entry;
677   GstClock *clock;
678   GstClockClass *cclass;
679
680   g_return_if_fail (id != NULL);
681
682   entry = (GstClockEntry *) id;
683   clock = g_weak_ref_get (GST_CLOCK_ENTRY_CLOCK_WEAK_REF (entry));
684   if (G_UNLIKELY (clock == NULL))
685     goto invalid_entry;
686
687   cclass = GST_CLOCK_GET_CLASS (clock);
688
689   if (G_LIKELY (cclass->unschedule))
690     cclass->unschedule (clock, entry);
691
692   gst_object_unref (clock);
693   return;
694
695 invalid_entry:
696   {
697     GST_CAT_DEBUG (GST_CAT_CLOCK, "clock entry %p lost its clock", id);
698     return;
699   }
700 }
701
702
703 /*
704  * GstClock abstract base class implementation
705  */
706 #define gst_clock_parent_class parent_class
707 G_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE (GstClock, gst_clock, GST_TYPE_OBJECT);
708
709 static void
710 gst_clock_class_init (GstClockClass * klass)
711 {
712   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
713
714   gobject_class->dispose = gst_clock_dispose;
715   gobject_class->finalize = gst_clock_finalize;
716   gobject_class->set_property = gst_clock_set_property;
717   gobject_class->get_property = gst_clock_get_property;
718
719   g_object_class_install_property (gobject_class, PROP_WINDOW_SIZE,
720       g_param_spec_int ("window-size", "Window size",
721           "The size of the window used to calculate rate and offset", 2, 1024,
722           DEFAULT_WINDOW_SIZE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
723   g_object_class_install_property (gobject_class, PROP_WINDOW_THRESHOLD,
724       g_param_spec_int ("window-threshold", "Window threshold",
725           "The threshold to start calculating rate and offset", 2, 1024,
726           DEFAULT_WINDOW_THRESHOLD,
727           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
728   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
729       g_param_spec_uint64 ("timeout", "Timeout",
730           "The amount of time, in nanoseconds, to sample master and slave clocks",
731           0, G_MAXUINT64, DEFAULT_TIMEOUT,
732           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
733
734   /**
735    * GstClock::synced:
736    * @self: the clock
737    * @synced: if the clock is synced now
738    *
739    * Signaled on clocks with %GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC set once
740    * the clock is synchronized, or when it completely lost synchronization.
741    * This signal will not be emitted on clocks without the flag.
742    *
743    * This signal will be emitted from an arbitrary thread, most likely not
744    * the application's main thread.
745    *
746    * Since: 1.6
747    */
748   gst_clock_signals[SIGNAL_SYNCED] =
749       g_signal_new ("synced", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
750       0, NULL, NULL, NULL, G_TYPE_NONE, 1, G_TYPE_BOOLEAN);
751 }
752
753 static void
754 gst_clock_init (GstClock * clock)
755 {
756   GstClockPrivate *priv;
757
758   clock->priv = priv = gst_clock_get_instance_private (clock);
759
760   priv->last_time = 0;
761
762   priv->internal_calibration = 0;
763   priv->external_calibration = 0;
764   priv->rate_numerator = 1;
765   priv->rate_denominator = 1;
766
767   g_mutex_init (&priv->slave_lock);
768   g_cond_init (&priv->sync_cond);
769   priv->window_size = DEFAULT_WINDOW_SIZE;
770   priv->window_threshold = DEFAULT_WINDOW_THRESHOLD;
771   priv->filling = TRUE;
772   priv->time_index = 0;
773   priv->timeout = DEFAULT_TIMEOUT;
774   priv->times = g_new0 (GstClockTime, 4 * priv->window_size);
775   priv->times_temp = priv->times + 2 * priv->window_size;
776   /*
777    * An atomically ref-counted wrapper around a GWeakRef for this GstClock,
778    * created by the clock and shared with all its clock entries.
779    *
780    * This exists because g_weak_ref_ operations are quite expensive and operate
781    * with a global GRWLock. _get takes a reader lock, _init and _clear take
782    * a writer lock. We want to avoid having to instantiate a new GWeakRef for
783    * every clock entry.
784    */
785   priv->clock_weakref = g_atomic_rc_box_new (GWeakRef);
786   g_weak_ref_init (priv->clock_weakref, clock);
787 }
788
789 static void
790 gst_clock_dispose (GObject * object)
791 {
792   GstClock *clock = GST_CLOCK (object);
793   GstClock **master_p;
794
795   GST_OBJECT_LOCK (clock);
796   master_p = &clock->priv->master;
797   gst_object_replace ((GstObject **) master_p, NULL);
798   GST_OBJECT_UNLOCK (clock);
799
800   G_OBJECT_CLASS (parent_class)->dispose (object);
801 }
802
803 static void
804 gst_clock_finalize (GObject * object)
805 {
806   GstClock *clock = GST_CLOCK (object);
807
808   GST_CLOCK_SLAVE_LOCK (clock);
809   if (clock->priv->clockid) {
810     gst_clock_id_unschedule (clock->priv->clockid);
811     gst_clock_id_unref (clock->priv->clockid);
812     clock->priv->clockid = NULL;
813   }
814   g_free (clock->priv->times);
815   clock->priv->times = NULL;
816   clock->priv->times_temp = NULL;
817   GST_CLOCK_SLAVE_UNLOCK (clock);
818
819   g_atomic_rc_box_release_full (clock->priv->clock_weakref,
820       (GDestroyNotify) g_weak_ref_clear);
821   g_mutex_clear (&clock->priv->slave_lock);
822   g_cond_clear (&clock->priv->sync_cond);
823
824   G_OBJECT_CLASS (parent_class)->finalize (object);
825 }
826
827 /**
828  * gst_clock_set_resolution:
829  * @clock: a #GstClock
830  * @resolution: The resolution to set
831  *
832  * Sets the accuracy of the clock. Some clocks have the possibility to operate
833  * with different accuracy at the expense of more resource usage. There is
834  * normally no need to change the default resolution of a clock. The resolution
835  * of a clock can only be changed if the clock has the
836  * #GST_CLOCK_FLAG_CAN_SET_RESOLUTION flag set.
837  *
838  * Returns: the new resolution of the clock.
839  */
840 GstClockTime
841 gst_clock_set_resolution (GstClock * clock, GstClockTime resolution)
842 {
843   GstClockPrivate *priv;
844   GstClockClass *cclass;
845
846   g_return_val_if_fail (GST_IS_CLOCK (clock), 0);
847   g_return_val_if_fail (resolution != 0, 0);
848
849   cclass = GST_CLOCK_GET_CLASS (clock);
850   priv = clock->priv;
851
852   if (cclass->change_resolution)
853     priv->resolution =
854         cclass->change_resolution (clock, priv->resolution, resolution);
855
856   return priv->resolution;
857 }
858
859 /**
860  * gst_clock_get_resolution:
861  * @clock: a #GstClock
862  *
863  * Gets the accuracy of the clock. The accuracy of the clock is the granularity
864  * of the values returned by gst_clock_get_time().
865  *
866  * Returns: the resolution of the clock in units of #GstClockTime.
867  */
868 GstClockTime
869 gst_clock_get_resolution (GstClock * clock)
870 {
871   GstClockClass *cclass;
872
873   g_return_val_if_fail (GST_IS_CLOCK (clock), 0);
874
875   cclass = GST_CLOCK_GET_CLASS (clock);
876
877   if (cclass->get_resolution)
878     return cclass->get_resolution (clock);
879
880   return 1;
881 }
882
883 /* FIXME 2.0: Remove clock parameter below */
884 /**
885  * gst_clock_adjust_with_calibration:
886  * @clock: (allow-none): a #GstClock to use
887  * @internal_target: a clock time
888  * @cinternal: a reference internal time
889  * @cexternal: a reference external time
890  * @cnum: the numerator of the rate of the clock relative to its
891  *        internal time
892  * @cdenom: the denominator of the rate of the clock
893  *
894  * Converts the given @internal_target clock time to the external time,
895  * using the passed calibration parameters. This function performs the
896  * same calculation as gst_clock_adjust_unlocked() when called using the
897  * current calibration parameters, but doesn't ensure a monotonically
898  * increasing result as gst_clock_adjust_unlocked() does.
899  *
900  * Note: The @clock parameter is unused and can be NULL
901  *
902  * Returns: the converted time of the clock.
903  *
904  * Since: 1.6
905  */
906 GstClockTime
907 gst_clock_adjust_with_calibration (GstClock * clock,
908     GstClockTime internal_target, GstClockTime cinternal,
909     GstClockTime cexternal, GstClockTime cnum, GstClockTime cdenom)
910 {
911   GstClockTime ret;
912
913   /* avoid divide by 0 */
914   if (G_UNLIKELY (cdenom == 0))
915     cnum = cdenom = 1;
916
917   /* The formula is (internal - cinternal) * cnum / cdenom + cexternal
918    *
919    * Since we do math on unsigned 64-bit ints we have to special case for
920    * internal < cinternal to get the sign right. this case is not very common,
921    * though.
922    */
923   if (G_LIKELY (internal_target >= cinternal)) {
924     ret = internal_target - cinternal;
925     ret = gst_util_uint64_scale (ret, cnum, cdenom);
926     ret += cexternal;
927   } else {
928     ret = cinternal - internal_target;
929     ret = gst_util_uint64_scale (ret, cnum, cdenom);
930     /* clamp to 0 */
931     if (G_LIKELY (cexternal > ret))
932       ret = cexternal - ret;
933     else
934       ret = 0;
935   }
936
937   return ret;
938 }
939
940 /**
941  * gst_clock_adjust_unlocked:
942  * @clock: a #GstClock to use
943  * @internal: a clock time
944  *
945  * Converts the given @internal clock time to the external time, adjusting for the
946  * rate and reference time set with gst_clock_set_calibration() and making sure
947  * that the returned time is increasing. This function should be called with the
948  * clock's OBJECT_LOCK held and is mainly used by clock subclasses.
949  *
950  * This function is the reverse of gst_clock_unadjust_unlocked().
951  *
952  * Returns: the converted time of the clock.
953  */
954 GstClockTime
955 gst_clock_adjust_unlocked (GstClock * clock, GstClockTime internal)
956 {
957   GstClockTime ret, cinternal, cexternal, cnum, cdenom;
958   GstClockPrivate *priv = clock->priv;
959
960   /* get calibration values for readability */
961   cinternal = priv->internal_calibration;
962   cexternal = priv->external_calibration;
963   cnum = priv->rate_numerator;
964   cdenom = priv->rate_denominator;
965
966   ret =
967       gst_clock_adjust_with_calibration (clock, internal, cinternal, cexternal,
968       cnum, cdenom);
969
970   /* make sure the time is increasing */
971   priv->last_time = MAX (ret, priv->last_time);
972
973   return priv->last_time;
974 }
975
976 /* FIXME 2.0: Remove clock parameter below */
977 /**
978  * gst_clock_unadjust_with_calibration:
979  * @clock: (allow-none): a #GstClock to use
980  * @external_target: a clock time
981  * @cinternal: a reference internal time
982  * @cexternal: a reference external time
983  * @cnum: the numerator of the rate of the clock relative to its
984  *        internal time
985  * @cdenom: the denominator of the rate of the clock
986  *
987  * Converts the given @external_target clock time to the internal time,
988  * using the passed calibration parameters. This function performs the
989  * same calculation as gst_clock_unadjust_unlocked() when called using the
990  * current calibration parameters.
991  *
992  * Note: The @clock parameter is unused and can be NULL
993  *
994  * Returns: the converted time of the clock.
995  *
996  * Since: 1.8
997  */
998 GstClockTime
999 gst_clock_unadjust_with_calibration (GstClock * clock,
1000     GstClockTime external_target, GstClockTime cinternal,
1001     GstClockTime cexternal, GstClockTime cnum, GstClockTime cdenom)
1002 {
1003   GstClockTime ret;
1004
1005   /* avoid divide by 0 */
1006   if (G_UNLIKELY (cnum == 0))
1007     cnum = cdenom = 1;
1008
1009   /* The formula is (external - cexternal) * cdenom / cnum + cinternal */
1010   if (G_LIKELY (external_target >= cexternal)) {
1011     ret = external_target - cexternal;
1012     ret = gst_util_uint64_scale (ret, cdenom, cnum);
1013     ret += cinternal;
1014   } else {
1015     ret = cexternal - external_target;
1016     ret = gst_util_uint64_scale (ret, cdenom, cnum);
1017     if (G_LIKELY (cinternal > ret))
1018       ret = cinternal - ret;
1019     else
1020       ret = 0;
1021   }
1022
1023   return ret;
1024 }
1025
1026 /**
1027  * gst_clock_unadjust_unlocked:
1028  * @clock: a #GstClock to use
1029  * @external: an external clock time
1030  *
1031  * Converts the given @external clock time to the internal time of @clock,
1032  * using the rate and reference time set with gst_clock_set_calibration().
1033  * This function should be called with the clock's OBJECT_LOCK held and
1034  * is mainly used by clock subclasses.
1035  *
1036  * This function is the reverse of gst_clock_adjust_unlocked().
1037  *
1038  * Returns: the internal time of the clock corresponding to @external.
1039  */
1040 GstClockTime
1041 gst_clock_unadjust_unlocked (GstClock * clock, GstClockTime external)
1042 {
1043   GstClockTime cinternal, cexternal, cnum, cdenom;
1044   GstClockPrivate *priv = clock->priv;
1045
1046   /* get calibration values for readability */
1047   cinternal = priv->internal_calibration;
1048   cexternal = priv->external_calibration;
1049   cnum = priv->rate_numerator;
1050   cdenom = priv->rate_denominator;
1051
1052   return gst_clock_unadjust_with_calibration (clock, external, cinternal,
1053       cexternal, cnum, cdenom);
1054 }
1055
1056 /**
1057  * gst_clock_get_internal_time:
1058  * @clock: a #GstClock to query
1059  *
1060  * Gets the current internal time of the given clock. The time is returned
1061  * unadjusted for the offset and the rate.
1062  *
1063  * Returns: the internal time of the clock. Or %GST_CLOCK_TIME_NONE when
1064  * given invalid input.
1065  */
1066 GstClockTime
1067 gst_clock_get_internal_time (GstClock * clock)
1068 {
1069   GstClockTime ret;
1070   GstClockClass *cclass;
1071
1072   g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);
1073
1074   if (G_UNLIKELY (GST_OBJECT_FLAG_IS_SET (clock,
1075               GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC) && !clock->priv->synced))
1076     GST_CAT_WARNING_OBJECT (GST_CAT_CLOCK, clock,
1077         "clock is not synchronized yet");
1078
1079   cclass = GST_CLOCK_GET_CLASS (clock);
1080
1081   if (G_UNLIKELY (cclass->get_internal_time == NULL))
1082     goto not_supported;
1083
1084   ret = cclass->get_internal_time (clock);
1085
1086   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "internal time %" GST_TIME_FORMAT,
1087       GST_TIME_ARGS (ret));
1088
1089   return ret;
1090
1091   /* ERRORS */
1092 not_supported:
1093   {
1094     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1095         "internal time not supported, return 0");
1096     return G_GINT64_CONSTANT (0);
1097   }
1098 }
1099
1100 /**
1101  * gst_clock_get_time:
1102  * @clock: a #GstClock to query
1103  *
1104  * Gets the current time of the given clock. The time is always
1105  * monotonically increasing and adjusted according to the current
1106  * offset and rate.
1107  *
1108  * Returns: the time of the clock. Or %GST_CLOCK_TIME_NONE when
1109  * given invalid input.
1110  */
1111 GstClockTime
1112 gst_clock_get_time (GstClock * clock)
1113 {
1114   GstClockTime ret;
1115   gint seq;
1116
1117   g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);
1118
1119   do {
1120     /* reget the internal time when we retry to get the most current
1121      * timevalue */
1122     ret = gst_clock_get_internal_time (clock);
1123
1124     seq = read_seqbegin (clock);
1125     /* this will scale for rate and offset */
1126     ret = gst_clock_adjust_unlocked (clock, ret);
1127   } while (read_seqretry (clock, seq));
1128
1129   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "adjusted time %" GST_TIME_FORMAT,
1130       GST_TIME_ARGS (ret));
1131
1132   return ret;
1133 }
1134
1135 /**
1136  * gst_clock_set_calibration:
1137  * @clock: a #GstClock to calibrate
1138  * @internal: a reference internal time
1139  * @external: a reference external time
1140  * @rate_num: the numerator of the rate of the clock relative to its
1141  *            internal time
1142  * @rate_denom: the denominator of the rate of the clock
1143  *
1144  * Adjusts the rate and time of @clock. A rate of 1/1 is the normal speed of
1145  * the clock. Values bigger than 1/1 make the clock go faster.
1146  *
1147  * @internal and @external are calibration parameters that arrange that
1148  * gst_clock_get_time() should have been @external at internal time @internal.
1149  * This internal time should not be in the future; that is, it should be less
1150  * than the value of gst_clock_get_internal_time() when this function is called.
1151  *
1152  * Subsequent calls to gst_clock_get_time() will return clock times computed as
1153  * follows:
1154  *
1155  * ``` C
1156  *   time = (internal_time - internal) * rate_num / rate_denom + external
1157  * ```
1158  *
1159  * This formula is implemented in gst_clock_adjust_unlocked(). Of course, it
1160  * tries to do the integer arithmetic as precisely as possible.
1161  *
1162  * Note that gst_clock_get_time() always returns increasing values so when you
1163  * move the clock backwards, gst_clock_get_time() will report the previous value
1164  * until the clock catches up.
1165  */
1166 void
1167 gst_clock_set_calibration (GstClock * clock, GstClockTime internal, GstClockTime
1168     external, GstClockTime rate_num, GstClockTime rate_denom)
1169 {
1170   GstClockPrivate *priv;
1171
1172   g_return_if_fail (GST_IS_CLOCK (clock));
1173   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (internal));
1174   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (external));
1175   g_return_if_fail (rate_num != GST_CLOCK_TIME_NONE);
1176   g_return_if_fail (rate_denom > 0 && rate_denom != GST_CLOCK_TIME_NONE);
1177
1178   priv = clock->priv;
1179
1180   write_seqlock (clock);
1181   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1182       "internal %" GST_TIME_FORMAT " external %" GST_TIME_FORMAT " %"
1183       G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT " = %f", GST_TIME_ARGS (internal),
1184       GST_TIME_ARGS (external), rate_num, rate_denom,
1185       gst_guint64_to_gdouble (rate_num) / gst_guint64_to_gdouble (rate_denom));
1186
1187   priv->internal_calibration = internal;
1188   priv->external_calibration = external;
1189   priv->rate_numerator = rate_num;
1190   priv->rate_denominator = rate_denom;
1191   write_sequnlock (clock);
1192 }
1193
1194 /**
1195  * gst_clock_get_calibration:
1196  * @clock: a #GstClock
1197  * @internal: (out) (allow-none): a location to store the internal time
1198  * @external: (out) (allow-none): a location to store the external time
1199  * @rate_num: (out) (allow-none): a location to store the rate numerator
1200  * @rate_denom: (out) (allow-none): a location to store the rate denominator
1201  *
1202  * Gets the internal rate and reference time of @clock. See
1203  * gst_clock_set_calibration() for more information.
1204  *
1205  * @internal, @external, @rate_num, and @rate_denom can be left %NULL if the
1206  * caller is not interested in the values.
1207  */
1208 void
1209 gst_clock_get_calibration (GstClock * clock, GstClockTime * internal,
1210     GstClockTime * external, GstClockTime * rate_num, GstClockTime * rate_denom)
1211 {
1212   gint seq;
1213   GstClockPrivate *priv;
1214
1215   g_return_if_fail (GST_IS_CLOCK (clock));
1216
1217   priv = clock->priv;
1218
1219   do {
1220     seq = read_seqbegin (clock);
1221     if (rate_num)
1222       *rate_num = priv->rate_numerator;
1223     if (rate_denom)
1224       *rate_denom = priv->rate_denominator;
1225     if (external)
1226       *external = priv->external_calibration;
1227     if (internal)
1228       *internal = priv->internal_calibration;
1229   } while (read_seqretry (clock, seq));
1230 }
1231
1232 /* will be called repeatedly to sample the master and slave clock
1233  * to recalibrate the clock  */
1234 static gboolean
1235 gst_clock_slave_callback (GstClock * master, GstClockTime time,
1236     GstClockID id, GstClock * clock)
1237 {
1238   GstClockTime stime, mtime;
1239   gdouble r_squared;
1240
1241   if (!gst_clock_is_synced (clock)) {
1242     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1243         "Slave clock is not synced yet");
1244     return TRUE;
1245   }
1246
1247   stime = gst_clock_get_internal_time (clock);
1248   mtime = gst_clock_get_time (master);
1249
1250   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1251       "master %" GST_TIME_FORMAT ", slave %" GST_TIME_FORMAT,
1252       GST_TIME_ARGS (mtime), GST_TIME_ARGS (stime));
1253
1254   gst_clock_add_observation (clock, stime, mtime, &r_squared);
1255
1256   /* FIXME, we can use the r_squared value to adjust the timeout
1257    * value of the clockid */
1258
1259   return TRUE;
1260 }
1261
1262 /**
1263  * gst_clock_set_master:
1264  * @clock: a #GstClock
1265  * @master: (allow-none): a master #GstClock
1266  *
1267  * Sets @master as the master clock for @clock. @clock will be automatically
1268  * calibrated so that gst_clock_get_time() reports the same time as the
1269  * master clock.
1270  *
1271  * A clock provider that slaves its clock to a master can get the current
1272  * calibration values with gst_clock_get_calibration().
1273  *
1274  * @master can be %NULL in which case @clock will not be slaved anymore. It will
1275  * however keep reporting its time adjusted with the last configured rate
1276  * and time offsets.
1277  *
1278  * Returns: %TRUE if the clock is capable of being slaved to a master clock.
1279  * Trying to set a master on a clock without the
1280  * #GST_CLOCK_FLAG_CAN_SET_MASTER flag will make this function return %FALSE.
1281  */
1282 gboolean
1283 gst_clock_set_master (GstClock * clock, GstClock * master)
1284 {
1285   GstClock **master_p;
1286   GstClockPrivate *priv;
1287
1288   g_return_val_if_fail (GST_IS_CLOCK (clock), FALSE);
1289   g_return_val_if_fail (master != clock, FALSE);
1290
1291   GST_OBJECT_LOCK (clock);
1292   /* we always allow setting the master to NULL */
1293   if (master && !GST_OBJECT_FLAG_IS_SET (clock, GST_CLOCK_FLAG_CAN_SET_MASTER))
1294     goto not_supported;
1295   if (master && !gst_clock_is_synced (master))
1296     goto master_not_synced;
1297
1298   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1299       "slaving %p to master clock %p", clock, master);
1300   GST_OBJECT_UNLOCK (clock);
1301
1302   priv = clock->priv;
1303
1304   GST_CLOCK_SLAVE_LOCK (clock);
1305   if (priv->clockid) {
1306     gst_clock_id_unschedule (priv->clockid);
1307     gst_clock_id_unref (priv->clockid);
1308     priv->clockid = NULL;
1309   }
1310   if (master) {
1311     priv->filling = TRUE;
1312     priv->time_index = 0;
1313     /* use the master periodic id to schedule sampling and
1314      * clock calibration. */
1315     priv->clockid = gst_clock_new_periodic_id (master,
1316         gst_clock_get_time (master), priv->timeout);
1317     gst_clock_id_wait_async (priv->clockid,
1318         (GstClockCallback) gst_clock_slave_callback,
1319         gst_object_ref (clock), (GDestroyNotify) gst_object_unref);
1320   }
1321   GST_CLOCK_SLAVE_UNLOCK (clock);
1322
1323   GST_OBJECT_LOCK (clock);
1324   master_p = &priv->master;
1325   gst_object_replace ((GstObject **) master_p, (GstObject *) master);
1326   GST_OBJECT_UNLOCK (clock);
1327
1328   return TRUE;
1329
1330   /* ERRORS */
1331 not_supported:
1332   {
1333     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1334         "cannot be slaved to a master clock");
1335     GST_OBJECT_UNLOCK (clock);
1336     return FALSE;
1337   }
1338
1339 master_not_synced:
1340   {
1341     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, master,
1342         "master clock is not synced yet");
1343     GST_OBJECT_UNLOCK (clock);
1344     return FALSE;
1345   }
1346 }
1347
1348 /**
1349  * gst_clock_get_master:
1350  * @clock: a #GstClock
1351  *
1352  * Gets the master clock that @clock is slaved to or %NULL when the clock is
1353  * not slaved to any master clock.
1354  *
1355  * Returns: (transfer full) (nullable): a master #GstClock or %NULL
1356  *     when this clock is not slaved to a master clock.
1357  */
1358 GstClock *
1359 gst_clock_get_master (GstClock * clock)
1360 {
1361   GstClock *result = NULL;
1362   GstClockPrivate *priv;
1363
1364   g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);
1365
1366   priv = clock->priv;
1367
1368   GST_OBJECT_LOCK (clock);
1369   if (priv->master)
1370     result = gst_object_ref (priv->master);
1371   GST_OBJECT_UNLOCK (clock);
1372
1373   return result;
1374 }
1375
1376 /**
1377  * gst_clock_id_get_clock:
1378  * @id: a #GstClockID
1379  *
1380  * This function returns the underlying clock.
1381  *
1382  * Returns: (transfer full) (nullable): a #GstClock or %NULL when the
1383  *     underlying clock has been freed.
1384  * Since: 1.16
1385  */
1386 GstClock *
1387 gst_clock_id_get_clock (GstClockID id)
1388 {
1389   GstClockEntry *entry;
1390
1391   g_return_val_if_fail (id != NULL, NULL);
1392
1393   entry = (GstClockEntry *) id;
1394   return g_weak_ref_get (GST_CLOCK_ENTRY_CLOCK_WEAK_REF (entry));
1395 }
1396
1397 /**
1398  * gst_clock_id_uses_clock:
1399  * @id: a #GstClockID to check
1400  * @clock: a #GstClock to compare against
1401  *
1402  * This function returns whether @id uses @clock as the underlying clock.
1403  * @clock can be NULL, in which case the return value indicates whether
1404  * the underlying clock has been freed.  If this is the case, the @id is
1405  * no longer usable and should be freed.
1406  *
1407  * Returns: whether the clock @id uses the same underlying #GstClock @clock.
1408  * Since: 1.16
1409  */
1410 gboolean
1411 gst_clock_id_uses_clock (GstClockID id, GstClock * clock)
1412 {
1413   GstClockEntry *entry;
1414   GstClock *entry_clock;
1415   gboolean ret = FALSE;
1416
1417   g_return_val_if_fail (id != NULL, FALSE);
1418   g_return_val_if_fail (clock != NULL, FALSE);
1419
1420   entry = (GstClockEntry *) id;
1421   entry_clock = g_weak_ref_get (GST_CLOCK_ENTRY_CLOCK_WEAK_REF (entry));
1422   if (entry_clock == clock)
1423     ret = TRUE;
1424
1425   if (G_LIKELY (entry_clock != NULL))
1426     gst_object_unref (entry_clock);
1427
1428   return ret;
1429 }
1430
1431
1432 /**
1433  * gst_clock_add_observation:
1434  * @clock: a #GstClock
1435  * @slave: a time on the slave
1436  * @master: a time on the master
1437  * @r_squared: (out): a pointer to hold the result
1438  *
1439  * The time @master of the master clock and the time @slave of the slave
1440  * clock are added to the list of observations. If enough observations
1441  * are available, a linear regression algorithm is run on the
1442  * observations and @clock is recalibrated.
1443  *
1444  * If this functions returns %TRUE, @r_squared will contain the
1445  * correlation coefficient of the interpolation. A value of 1.0
1446  * means a perfect regression was performed. This value can
1447  * be used to control the sampling frequency of the master and slave
1448  * clocks.
1449  *
1450  * Returns: %TRUE if enough observations were added to run the
1451  * regression algorithm.
1452  */
1453 gboolean
1454 gst_clock_add_observation (GstClock * clock, GstClockTime slave,
1455     GstClockTime master, gdouble * r_squared)
1456 {
1457   GstClockTime m_num, m_denom, b, xbase;
1458
1459   if (!gst_clock_add_observation_unapplied (clock, slave, master, r_squared,
1460           &xbase, &b, &m_num, &m_denom))
1461     return FALSE;
1462
1463   /* if we have a valid regression, adjust the clock */
1464   gst_clock_set_calibration (clock, xbase, b, m_num, m_denom);
1465
1466   return TRUE;
1467 }
1468
1469 /**
1470  * gst_clock_add_observation_unapplied:
1471  * @clock: a #GstClock
1472  * @slave: a time on the slave
1473  * @master: a time on the master
1474  * @r_squared: (out): a pointer to hold the result
1475  * @internal: (out) (allow-none): a location to store the internal time
1476  * @external: (out) (allow-none): a location to store the external time
1477  * @rate_num: (out) (allow-none): a location to store the rate numerator
1478  * @rate_denom: (out) (allow-none): a location to store the rate denominator
1479  *
1480  * Add a clock observation to the internal slaving algorithm the same as
1481  * gst_clock_add_observation(), and return the result of the master clock
1482  * estimation, without updating the internal calibration.
1483  *
1484  * The caller can then take the results and call gst_clock_set_calibration()
1485  * with the values, or some modified version of them.
1486  *
1487  * Returns: %TRUE if enough observations were added to run the
1488  * regression algorithm.
1489  * Since: 1.6
1490  */
1491 gboolean
1492 gst_clock_add_observation_unapplied (GstClock * clock, GstClockTime slave,
1493     GstClockTime master, gdouble * r_squared,
1494     GstClockTime * internal, GstClockTime * external,
1495     GstClockTime * rate_num, GstClockTime * rate_denom)
1496 {
1497   GstClockTime m_num, m_denom, b, xbase;
1498   GstClockPrivate *priv;
1499   guint n;
1500
1501   g_return_val_if_fail (GST_IS_CLOCK (clock), FALSE);
1502   g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (slave), FALSE);
1503   g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (master), FALSE);
1504   g_return_val_if_fail (r_squared != NULL, FALSE);
1505
1506   priv = clock->priv;
1507
1508   GST_CLOCK_SLAVE_LOCK (clock);
1509
1510   GST_CAT_LOG_OBJECT (GST_CAT_CLOCK, clock,
1511       "adding observation slave %" GST_TIME_FORMAT ", master %" GST_TIME_FORMAT,
1512       GST_TIME_ARGS (slave), GST_TIME_ARGS (master));
1513
1514   priv->times[(2 * priv->time_index)] = slave;
1515   priv->times[(2 * priv->time_index) + 1] = master;
1516
1517   priv->time_index++;
1518   if (G_UNLIKELY (priv->time_index == priv->window_size)) {
1519     priv->filling = FALSE;
1520     priv->time_index = 0;
1521   }
1522
1523   if (G_UNLIKELY (priv->filling && priv->time_index < priv->window_threshold))
1524     goto filling;
1525
1526   n = priv->filling ? priv->time_index : priv->window_size;
1527   if (!gst_calculate_linear_regression (priv->times, priv->times_temp, n,
1528           &m_num, &m_denom, &b, &xbase, r_squared))
1529     goto invalid;
1530
1531   GST_CLOCK_SLAVE_UNLOCK (clock);
1532
1533   GST_CAT_LOG_OBJECT (GST_CAT_CLOCK, clock,
1534       "adjusting clock to m=%" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT ", b=%"
1535       G_GUINT64_FORMAT " (rsquared=%g)", m_num, m_denom, b, *r_squared);
1536
1537   if (internal)
1538     *internal = xbase;
1539   if (external)
1540     *external = b;
1541   if (rate_num)
1542     *rate_num = m_num;
1543   if (rate_denom)
1544     *rate_denom = m_denom;
1545
1546   return TRUE;
1547
1548 filling:
1549   {
1550     GST_CLOCK_SLAVE_UNLOCK (clock);
1551     return FALSE;
1552   }
1553 invalid:
1554   {
1555     /* no valid regression has been done, ignore the result then */
1556     GST_CLOCK_SLAVE_UNLOCK (clock);
1557     return FALSE;
1558   }
1559 }
1560
1561 /**
1562  * gst_clock_set_timeout:
1563  * @clock: a #GstClock
1564  * @timeout: a timeout
1565  *
1566  * Sets the amount of time, in nanoseconds, to sample master and slave
1567  * clocks
1568  */
1569 void
1570 gst_clock_set_timeout (GstClock * clock, GstClockTime timeout)
1571 {
1572   g_return_if_fail (GST_IS_CLOCK (clock));
1573
1574   GST_CLOCK_SLAVE_LOCK (clock);
1575   clock->priv->timeout = timeout;
1576   GST_CLOCK_SLAVE_UNLOCK (clock);
1577 }
1578
1579 /**
1580  * gst_clock_get_timeout:
1581  * @clock: a #GstClock
1582  *
1583  * Gets the amount of time that master and slave clocks are sampled.
1584  *
1585  * Returns: the interval between samples.
1586  */
1587 GstClockTime
1588 gst_clock_get_timeout (GstClock * clock)
1589 {
1590   GstClockTime result;
1591
1592   g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);
1593
1594   GST_CLOCK_SLAVE_LOCK (clock);
1595   result = clock->priv->timeout;
1596   GST_CLOCK_SLAVE_UNLOCK (clock);
1597
1598   return result;
1599 }
1600
1601 static void
1602 gst_clock_set_property (GObject * object, guint prop_id,
1603     const GValue * value, GParamSpec * pspec)
1604 {
1605   GstClock *clock;
1606   GstClockPrivate *priv;
1607
1608   clock = GST_CLOCK (object);
1609   priv = clock->priv;
1610
1611   switch (prop_id) {
1612     case PROP_WINDOW_SIZE:
1613       GST_CLOCK_SLAVE_LOCK (clock);
1614       priv->window_size = g_value_get_int (value);
1615       priv->window_threshold = MIN (priv->window_threshold, priv->window_size);
1616       priv->times = g_renew (GstClockTime, priv->times, 4 * priv->window_size);
1617       priv->times_temp = priv->times + 2 * priv->window_size;
1618       /* restart calibration */
1619       priv->filling = TRUE;
1620       priv->time_index = 0;
1621       GST_CLOCK_SLAVE_UNLOCK (clock);
1622       break;
1623     case PROP_WINDOW_THRESHOLD:
1624       GST_CLOCK_SLAVE_LOCK (clock);
1625       priv->window_threshold = MIN (g_value_get_int (value), priv->window_size);
1626       GST_CLOCK_SLAVE_UNLOCK (clock);
1627       break;
1628     case PROP_TIMEOUT:
1629       gst_clock_set_timeout (clock, g_value_get_uint64 (value));
1630       break;
1631     default:
1632       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1633       break;
1634   }
1635 }
1636
1637 static void
1638 gst_clock_get_property (GObject * object, guint prop_id,
1639     GValue * value, GParamSpec * pspec)
1640 {
1641   GstClock *clock;
1642   GstClockPrivate *priv;
1643
1644   clock = GST_CLOCK (object);
1645   priv = clock->priv;
1646
1647   switch (prop_id) {
1648     case PROP_WINDOW_SIZE:
1649       GST_CLOCK_SLAVE_LOCK (clock);
1650       g_value_set_int (value, priv->window_size);
1651       GST_CLOCK_SLAVE_UNLOCK (clock);
1652       break;
1653     case PROP_WINDOW_THRESHOLD:
1654       GST_CLOCK_SLAVE_LOCK (clock);
1655       g_value_set_int (value, priv->window_threshold);
1656       GST_CLOCK_SLAVE_UNLOCK (clock);
1657       break;
1658     case PROP_TIMEOUT:
1659       g_value_set_uint64 (value, gst_clock_get_timeout (clock));
1660       break;
1661     default:
1662       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1663       break;
1664   }
1665 }
1666
1667
1668 /**
1669  * gst_clock_wait_for_sync:
1670  * @clock: a GstClock
1671  * @timeout: timeout for waiting or %GST_CLOCK_TIME_NONE
1672  *
1673  * Waits until @clock is synced for reporting the current time. If @timeout
1674  * is %GST_CLOCK_TIME_NONE it will wait forever, otherwise it will time out
1675  * after @timeout nanoseconds.
1676  *
1677  * For asynchronous waiting, the #GstClock::synced signal can be used.
1678  *
1679  * This returns immediately with %TRUE if %GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC
1680  * is not set on the clock, or if the clock is already synced.
1681  *
1682  * Returns: %TRUE if waiting was successful, or %FALSE on timeout
1683  *
1684  * Since: 1.6
1685  */
1686 gboolean
1687 gst_clock_wait_for_sync (GstClock * clock, GstClockTime timeout)
1688 {
1689   gboolean timed_out = FALSE;
1690
1691   g_return_val_if_fail (GST_IS_CLOCK (clock), FALSE);
1692
1693   GST_OBJECT_LOCK (clock);
1694   if (!GST_OBJECT_FLAG_IS_SET (clock, GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC)
1695       || clock->priv->synced) {
1696     GST_OBJECT_UNLOCK (clock);
1697     return TRUE;
1698   }
1699
1700   if (timeout != GST_CLOCK_TIME_NONE) {
1701     gint64 end_time = g_get_monotonic_time () + gst_util_uint64_scale (timeout,
1702         G_TIME_SPAN_SECOND, GST_SECOND);
1703
1704     while (!clock->priv->synced && !timed_out) {
1705       timed_out =
1706           !g_cond_wait_until (&clock->priv->sync_cond,
1707           GST_OBJECT_GET_LOCK (clock), end_time);
1708     }
1709   } else {
1710     timed_out = FALSE;
1711     while (!clock->priv->synced) {
1712       g_cond_wait (&clock->priv->sync_cond, GST_OBJECT_GET_LOCK (clock));
1713     }
1714   }
1715   GST_OBJECT_UNLOCK (clock);
1716
1717   return !timed_out;
1718 }
1719
1720 /**
1721  * gst_clock_is_synced:
1722  * @clock: a GstClock
1723  *
1724  * Checks if the clock is currently synced, by looking at whether
1725  * %GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC is set.
1726  *
1727  * Returns: %TRUE if the clock is currently synced
1728  *
1729  * Since: 1.6
1730  */
1731 gboolean
1732 gst_clock_is_synced (GstClock * clock)
1733 {
1734   g_return_val_if_fail (GST_IS_CLOCK (clock), TRUE);
1735
1736   return !GST_OBJECT_FLAG_IS_SET (clock, GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC)
1737       || clock->priv->synced;
1738 }
1739
1740 /**
1741  * gst_clock_set_synced:
1742  * @clock: a GstClock
1743  * @synced: if the clock is synced
1744  *
1745  * Sets @clock to synced and emits the #GstClock::synced signal, and wakes up any
1746  * thread waiting in gst_clock_wait_for_sync().
1747  *
1748  * This function must only be called if %GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC
1749  * is set on the clock, and is intended to be called by subclasses only.
1750  *
1751  * Since: 1.6
1752  */
1753 void
1754 gst_clock_set_synced (GstClock * clock, gboolean synced)
1755 {
1756   g_return_if_fail (GST_IS_CLOCK (clock));
1757   g_return_if_fail (GST_OBJECT_FLAG_IS_SET (clock,
1758           GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC));
1759
1760   GST_OBJECT_LOCK (clock);
1761   if (clock->priv->synced != ! !synced) {
1762     clock->priv->synced = ! !synced;
1763     g_cond_signal (&clock->priv->sync_cond);
1764     GST_OBJECT_UNLOCK (clock);
1765     g_signal_emit (clock, gst_clock_signals[SIGNAL_SYNCED], 0, ! !synced);
1766   } else {
1767     GST_OBJECT_UNLOCK (clock);
1768   }
1769 }