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