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