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