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