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