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