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