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