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