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