clock: Add GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC and related API
[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_unlocked:
942  * @clock: a #GstClock to use
943  * @external: an external clock time
944  *
945  * Converts the given @external clock time to the internal time of @clock,
946  * using the rate and reference time set with gst_clock_set_calibration().
947  * This function should be called with the clock's OBJECT_LOCK held and
948  * is mainly used by clock subclasses.
949  *
950  * This function is the reverse of gst_clock_adjust_unlocked().
951  *
952  * Returns: the internal time of the clock corresponding to @external.
953  */
954 GstClockTime
955 gst_clock_unadjust_unlocked (GstClock * clock, GstClockTime external)
956 {
957   GstClockTime ret, cinternal, cexternal, cnum, cdenom;
958   GstClockPrivate *priv = clock->priv;
959
960   /* get calibration values for readability */
961   cinternal = priv->internal_calibration;
962   cexternal = priv->external_calibration;
963   cnum = priv->rate_numerator;
964   cdenom = priv->rate_denominator;
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 >= cexternal)) {
972     ret = external - cexternal;
973     ret = gst_util_uint64_scale (ret, cdenom, cnum);
974     ret += cinternal;
975   } else {
976     ret = cexternal - external;
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   return ret;
984 }
985
986 /**
987  * gst_clock_get_internal_time:
988  * @clock: a #GstClock to query
989  *
990  * Gets the current internal time of the given clock. The time is returned
991  * unadjusted for the offset and the rate.
992  *
993  * Returns: the internal time of the clock. Or GST_CLOCK_TIME_NONE when
994  * given invalid input.
995  *
996  * MT safe.
997  */
998 GstClockTime
999 gst_clock_get_internal_time (GstClock * clock)
1000 {
1001   GstClockTime ret;
1002   GstClockClass *cclass;
1003
1004   g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);
1005
1006   if (G_UNLIKELY (GST_OBJECT_FLAG_IS_SET (clock,
1007               GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC) && !clock->priv->synced))
1008     GST_CAT_WARNING_OBJECT (GST_CAT_CLOCK, clock,
1009         "clocked is not synchronized yet");
1010
1011   cclass = GST_CLOCK_GET_CLASS (clock);
1012
1013   if (G_UNLIKELY (cclass->get_internal_time == NULL))
1014     goto not_supported;
1015
1016   ret = cclass->get_internal_time (clock);
1017
1018   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "internal time %" GST_TIME_FORMAT,
1019       GST_TIME_ARGS (ret));
1020
1021   return ret;
1022
1023   /* ERRORS */
1024 not_supported:
1025   {
1026     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1027         "internal time not supported, return 0");
1028     return G_GINT64_CONSTANT (0);
1029   }
1030 }
1031
1032 /**
1033  * gst_clock_get_time:
1034  * @clock: a #GstClock to query
1035  *
1036  * Gets the current time of the given clock. The time is always
1037  * monotonically increasing and adjusted according to the current
1038  * offset and rate.
1039  *
1040  * Returns: the time of the clock. Or GST_CLOCK_TIME_NONE when
1041  * given invalid input.
1042  *
1043  * MT safe.
1044  */
1045 GstClockTime
1046 gst_clock_get_time (GstClock * clock)
1047 {
1048   GstClockTime ret;
1049   gint seq;
1050
1051   g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);
1052
1053   do {
1054     /* reget the internal time when we retry to get the most current
1055      * timevalue */
1056     ret = gst_clock_get_internal_time (clock);
1057
1058     seq = read_seqbegin (clock);
1059     /* this will scale for rate and offset */
1060     ret = gst_clock_adjust_unlocked (clock, ret);
1061   } while (read_seqretry (clock, seq));
1062
1063   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "adjusted time %" GST_TIME_FORMAT,
1064       GST_TIME_ARGS (ret));
1065
1066   return ret;
1067 }
1068
1069 /**
1070  * gst_clock_set_calibration:
1071  * @clock: a #GstClock to calibrate
1072  * @internal: a reference internal time
1073  * @external: a reference external time
1074  * @rate_num: the numerator of the rate of the clock relative to its
1075  *            internal time 
1076  * @rate_denom: the denominator of the rate of the clock
1077  *
1078  * Adjusts the rate and time of @clock. A rate of 1/1 is the normal speed of
1079  * the clock. Values bigger than 1/1 make the clock go faster.
1080  *
1081  * @internal and @external are calibration parameters that arrange that
1082  * gst_clock_get_time() should have been @external at internal time @internal.
1083  * This internal time should not be in the future; that is, it should be less
1084  * than the value of gst_clock_get_internal_time() when this function is called.
1085  *
1086  * Subsequent calls to gst_clock_get_time() will return clock times computed as
1087  * follows:
1088  *
1089  * <programlisting>
1090  *   time = (internal_time - internal) * rate_num / rate_denom + external
1091  * </programlisting>
1092  *
1093  * This formula is implemented in gst_clock_adjust_unlocked(). Of course, it
1094  * tries to do the integer arithmetic as precisely as possible.
1095  *
1096  * Note that gst_clock_get_time() always returns increasing values so when you
1097  * move the clock backwards, gst_clock_get_time() will report the previous value
1098  * until the clock catches up.
1099  *
1100  * MT safe.
1101  */
1102 void
1103 gst_clock_set_calibration (GstClock * clock, GstClockTime internal, GstClockTime
1104     external, GstClockTime rate_num, GstClockTime rate_denom)
1105 {
1106   GstClockPrivate *priv;
1107
1108   g_return_if_fail (GST_IS_CLOCK (clock));
1109   g_return_if_fail (rate_num != GST_CLOCK_TIME_NONE);
1110   g_return_if_fail (rate_denom > 0 && rate_denom != GST_CLOCK_TIME_NONE);
1111
1112   priv = clock->priv;
1113
1114   write_seqlock (clock);
1115   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1116       "internal %" GST_TIME_FORMAT " external %" GST_TIME_FORMAT " %"
1117       G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT " = %f", GST_TIME_ARGS (internal),
1118       GST_TIME_ARGS (external), rate_num, rate_denom,
1119       gst_guint64_to_gdouble (rate_num) / gst_guint64_to_gdouble (rate_denom));
1120
1121   priv->internal_calibration = internal;
1122   priv->external_calibration = external;
1123   priv->rate_numerator = rate_num;
1124   priv->rate_denominator = rate_denom;
1125   write_sequnlock (clock);
1126 }
1127
1128 /**
1129  * gst_clock_get_calibration:
1130  * @clock: a #GstClock 
1131  * @internal: (out) (allow-none): a location to store the internal time
1132  * @external: (out) (allow-none): a location to store the external time
1133  * @rate_num: (out) (allow-none): a location to store the rate numerator
1134  * @rate_denom: (out) (allow-none): a location to store the rate denominator
1135  *
1136  * Gets the internal rate and reference time of @clock. See
1137  * gst_clock_set_calibration() for more information.
1138  *
1139  * @internal, @external, @rate_num, and @rate_denom can be left %NULL if the
1140  * caller is not interested in the values.
1141  *
1142  * MT safe.
1143  */
1144 void
1145 gst_clock_get_calibration (GstClock * clock, GstClockTime * internal,
1146     GstClockTime * external, GstClockTime * rate_num, GstClockTime * rate_denom)
1147 {
1148   gint seq;
1149   GstClockPrivate *priv;
1150
1151   g_return_if_fail (GST_IS_CLOCK (clock));
1152
1153   priv = clock->priv;
1154
1155   do {
1156     seq = read_seqbegin (clock);
1157     if (rate_num)
1158       *rate_num = priv->rate_numerator;
1159     if (rate_denom)
1160       *rate_denom = priv->rate_denominator;
1161     if (external)
1162       *external = priv->external_calibration;
1163     if (internal)
1164       *internal = priv->internal_calibration;
1165   } while (read_seqretry (clock, seq));
1166 }
1167
1168 /* will be called repeatedly to sample the master and slave clock
1169  * to recalibrate the clock  */
1170 static gboolean
1171 gst_clock_slave_callback (GstClock * master, GstClockTime time,
1172     GstClockID id, GstClock * clock)
1173 {
1174   GstClockTime stime, mtime;
1175   gdouble r_squared;
1176
1177   stime = gst_clock_get_internal_time (clock);
1178   mtime = gst_clock_get_time (master);
1179
1180   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1181       "master %" GST_TIME_FORMAT ", slave %" GST_TIME_FORMAT,
1182       GST_TIME_ARGS (mtime), GST_TIME_ARGS (stime));
1183
1184   gst_clock_add_observation (clock, stime, mtime, &r_squared);
1185
1186   /* FIXME, we can use the r_squared value to adjust the timeout
1187    * value of the clockid */
1188
1189   return TRUE;
1190 }
1191
1192 /**
1193  * gst_clock_set_master:
1194  * @clock: a #GstClock 
1195  * @master: (allow-none): a master #GstClock 
1196  *
1197  * Set @master as the master clock for @clock. @clock will be automatically
1198  * calibrated so that gst_clock_get_time() reports the same time as the
1199  * master clock.  
1200  * 
1201  * A clock provider that slaves its clock to a master can get the current
1202  * calibration values with gst_clock_get_calibration().
1203  *
1204  * @master can be %NULL in which case @clock will not be slaved anymore. It will
1205  * however keep reporting its time adjusted with the last configured rate 
1206  * and time offsets.
1207  *
1208  * Returns: %TRUE if the clock is capable of being slaved to a master clock. 
1209  * Trying to set a master on a clock without the 
1210  * #GST_CLOCK_FLAG_CAN_SET_MASTER flag will make this function return %FALSE.
1211  *
1212  * MT safe.
1213  */
1214 gboolean
1215 gst_clock_set_master (GstClock * clock, GstClock * master)
1216 {
1217   GstClock **master_p;
1218   GstClockPrivate *priv;
1219
1220   g_return_val_if_fail (GST_IS_CLOCK (clock), FALSE);
1221   g_return_val_if_fail (master != clock, FALSE);
1222
1223   GST_OBJECT_LOCK (clock);
1224   /* we always allow setting the master to NULL */
1225   if (master && !GST_OBJECT_FLAG_IS_SET (clock, GST_CLOCK_FLAG_CAN_SET_MASTER))
1226     goto not_supported;
1227   GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1228       "slaving %p to master clock %p", clock, master);
1229   GST_OBJECT_UNLOCK (clock);
1230
1231   priv = clock->priv;
1232
1233   GST_CLOCK_SLAVE_LOCK (clock);
1234   if (priv->clockid) {
1235     gst_clock_id_unschedule (priv->clockid);
1236     gst_clock_id_unref (priv->clockid);
1237     priv->clockid = NULL;
1238   }
1239   if (master) {
1240     priv->filling = TRUE;
1241     priv->time_index = 0;
1242     /* use the master periodic id to schedule sampling and
1243      * clock calibration. */
1244     priv->clockid = gst_clock_new_periodic_id (master,
1245         gst_clock_get_time (master), priv->timeout);
1246     gst_clock_id_wait_async (priv->clockid,
1247         (GstClockCallback) gst_clock_slave_callback,
1248         gst_object_ref (clock), (GDestroyNotify) gst_object_unref);
1249   }
1250   GST_CLOCK_SLAVE_UNLOCK (clock);
1251
1252   GST_OBJECT_LOCK (clock);
1253   master_p = &priv->master;
1254   gst_object_replace ((GstObject **) master_p, (GstObject *) master);
1255   GST_OBJECT_UNLOCK (clock);
1256
1257   return TRUE;
1258
1259   /* ERRORS */
1260 not_supported:
1261   {
1262     GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
1263         "cannot be slaved to a master clock");
1264     GST_OBJECT_UNLOCK (clock);
1265     return FALSE;
1266   }
1267 }
1268
1269 /**
1270  * gst_clock_get_master:
1271  * @clock: a #GstClock 
1272  *
1273  * Get the master clock that @clock is slaved to or %NULL when the clock is
1274  * not slaved to any master clock.
1275  *
1276  * Returns: (transfer full) (nullable): a master #GstClock or %NULL
1277  *     when this clock is not slaved to a master clock. Unref after
1278  *     usage.
1279  *
1280  * MT safe.
1281  */
1282 GstClock *
1283 gst_clock_get_master (GstClock * clock)
1284 {
1285   GstClock *result = NULL;
1286   GstClockPrivate *priv;
1287
1288   g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);
1289
1290   priv = clock->priv;
1291
1292   GST_OBJECT_LOCK (clock);
1293   if (priv->master)
1294     result = gst_object_ref (priv->master);
1295   GST_OBJECT_UNLOCK (clock);
1296
1297   return result;
1298 }
1299
1300 /**
1301  * gst_clock_add_observation:
1302  * @clock: a #GstClock 
1303  * @slave: a time on the slave
1304  * @master: a time on the master
1305  * @r_squared: (out): a pointer to hold the result
1306  *
1307  * The time @master of the master clock and the time @slave of the slave
1308  * clock are added to the list of observations. If enough observations
1309  * are available, a linear regression algorithm is run on the
1310  * observations and @clock is recalibrated.
1311  *
1312  * If this functions returns %TRUE, @r_squared will contain the 
1313  * correlation coefficient of the interpolation. A value of 1.0
1314  * means a perfect regression was performed. This value can
1315  * be used to control the sampling frequency of the master and slave
1316  * clocks.
1317  *
1318  * Returns: %TRUE if enough observations were added to run the 
1319  * regression algorithm.
1320  *
1321  * MT safe.
1322  */
1323 gboolean
1324 gst_clock_add_observation (GstClock * clock, GstClockTime slave,
1325     GstClockTime master, gdouble * r_squared)
1326 {
1327   GstClockTime m_num, m_denom, b, xbase;
1328
1329   if (!gst_clock_add_observation_unapplied (clock, slave, master, r_squared,
1330           &xbase, &b, &m_num, &m_denom))
1331     return FALSE;
1332
1333   /* if we have a valid regression, adjust the clock */
1334   gst_clock_set_calibration (clock, xbase, b, m_num, m_denom);
1335
1336   return TRUE;
1337 }
1338
1339 /**
1340  * gst_clock_add_observation_unapplied:
1341  * @clock: a #GstClock
1342  * @slave: a time on the slave
1343  * @master: a time on the master
1344  * @r_squared: (out): a pointer to hold the result
1345  * @internal: (out) (allow-none): a location to store the internal time
1346  * @external: (out) (allow-none): a location to store the external time
1347  * @rate_num: (out) (allow-none): a location to store the rate numerator
1348  * @rate_denom: (out) (allow-none): a location to store the rate denominator
1349  *
1350  * Add a clock observation to the internal slaving algorithm the same as
1351  * gst_clock_add_observation(), and return the result of the master clock
1352  * estimation, without updating the internal calibration.
1353  *
1354  * The caller can then take the results and call gst_clock_set_calibration()
1355  * with the values, or some modified version of them.
1356  *
1357  * Since: 1.6
1358  */
1359 gboolean
1360 gst_clock_add_observation_unapplied (GstClock * clock, GstClockTime slave,
1361     GstClockTime master, gdouble * r_squared,
1362     GstClockTime * internal, GstClockTime * external,
1363     GstClockTime * rate_num, GstClockTime * rate_denom)
1364 {
1365   GstClockTime m_num, m_denom, b, xbase;
1366   GstClockPrivate *priv;
1367   guint n;
1368
1369   g_return_val_if_fail (GST_IS_CLOCK (clock), FALSE);
1370   g_return_val_if_fail (r_squared != NULL, FALSE);
1371
1372   priv = clock->priv;
1373
1374   GST_CLOCK_SLAVE_LOCK (clock);
1375
1376   GST_CAT_LOG_OBJECT (GST_CAT_CLOCK, clock,
1377       "adding observation slave %" GST_TIME_FORMAT ", master %" GST_TIME_FORMAT,
1378       GST_TIME_ARGS (slave), GST_TIME_ARGS (master));
1379
1380   priv->times[(4 * priv->time_index)] = slave;
1381   priv->times[(4 * priv->time_index) + 2] = master;
1382
1383   priv->time_index++;
1384   if (G_UNLIKELY (priv->time_index == priv->window_size)) {
1385     priv->filling = FALSE;
1386     priv->time_index = 0;
1387   }
1388
1389   if (G_UNLIKELY (priv->filling && priv->time_index < priv->window_threshold))
1390     goto filling;
1391
1392   n = priv->filling ? priv->time_index : priv->window_size;
1393   if (!_priv_gst_do_linear_regression (priv->times, n, &m_num, &m_denom, &b,
1394           &xbase, r_squared))
1395     goto invalid;
1396
1397   GST_CLOCK_SLAVE_UNLOCK (clock);
1398
1399   GST_CAT_LOG_OBJECT (GST_CAT_CLOCK, clock,
1400       "adjusting clock to m=%" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT ", b=%"
1401       G_GUINT64_FORMAT " (rsquared=%g)", m_num, m_denom, b, *r_squared);
1402
1403   if (internal)
1404     *internal = xbase;
1405   if (external)
1406     *external = b;
1407   if (rate_num)
1408     *rate_num = m_num;
1409   if (rate_denom)
1410     *rate_denom = m_denom;
1411
1412   return TRUE;
1413
1414 filling:
1415   {
1416     GST_CLOCK_SLAVE_UNLOCK (clock);
1417     return FALSE;
1418   }
1419 invalid:
1420   {
1421     /* no valid regression has been done, ignore the result then */
1422     GST_CLOCK_SLAVE_UNLOCK (clock);
1423     return TRUE;
1424   }
1425 }
1426
1427 /**
1428  * gst_clock_set_timeout:
1429  * @clock: a #GstClock
1430  * @timeout: a timeout
1431  *
1432  * Set the amount of time, in nanoseconds, to sample master and slave
1433  * clocks
1434  */
1435 void
1436 gst_clock_set_timeout (GstClock * clock, GstClockTime timeout)
1437 {
1438   g_return_if_fail (GST_IS_CLOCK (clock));
1439
1440   GST_CLOCK_SLAVE_LOCK (clock);
1441   clock->priv->timeout = timeout;
1442   GST_CLOCK_SLAVE_UNLOCK (clock);
1443 }
1444
1445 /**
1446  * gst_clock_get_timeout:
1447  * @clock: a #GstClock
1448  *
1449  * Get the amount of time that master and slave clocks are sampled.
1450  *
1451  * Returns: the interval between samples.
1452  */
1453 GstClockTime
1454 gst_clock_get_timeout (GstClock * clock)
1455 {
1456   GstClockTime result;
1457
1458   g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);
1459
1460   GST_CLOCK_SLAVE_LOCK (clock);
1461   result = clock->priv->timeout;
1462   GST_CLOCK_SLAVE_UNLOCK (clock);
1463
1464   return result;
1465 }
1466
1467 static void
1468 gst_clock_set_property (GObject * object, guint prop_id,
1469     const GValue * value, GParamSpec * pspec)
1470 {
1471   GstClock *clock;
1472   GstClockPrivate *priv;
1473
1474   clock = GST_CLOCK (object);
1475   priv = clock->priv;
1476
1477   switch (prop_id) {
1478     case PROP_WINDOW_SIZE:
1479       GST_CLOCK_SLAVE_LOCK (clock);
1480       priv->window_size = g_value_get_int (value);
1481       priv->window_threshold = MIN (priv->window_threshold, priv->window_size);
1482       priv->times = g_renew (GstClockTime, priv->times, 4 * priv->window_size);
1483       /* restart calibration */
1484       priv->filling = TRUE;
1485       priv->time_index = 0;
1486       GST_CLOCK_SLAVE_UNLOCK (clock);
1487       break;
1488     case PROP_WINDOW_THRESHOLD:
1489       GST_CLOCK_SLAVE_LOCK (clock);
1490       priv->window_threshold = MIN (g_value_get_int (value), priv->window_size);
1491       GST_CLOCK_SLAVE_UNLOCK (clock);
1492       break;
1493     case PROP_TIMEOUT:
1494       gst_clock_set_timeout (clock, g_value_get_uint64 (value));
1495       break;
1496     default:
1497       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1498       break;
1499   }
1500 }
1501
1502 static void
1503 gst_clock_get_property (GObject * object, guint prop_id,
1504     GValue * value, GParamSpec * pspec)
1505 {
1506   GstClock *clock;
1507   GstClockPrivate *priv;
1508
1509   clock = GST_CLOCK (object);
1510   priv = clock->priv;
1511
1512   switch (prop_id) {
1513     case PROP_WINDOW_SIZE:
1514       GST_CLOCK_SLAVE_LOCK (clock);
1515       g_value_set_int (value, priv->window_size);
1516       GST_CLOCK_SLAVE_UNLOCK (clock);
1517       break;
1518     case PROP_WINDOW_THRESHOLD:
1519       GST_CLOCK_SLAVE_LOCK (clock);
1520       g_value_set_int (value, priv->window_threshold);
1521       GST_CLOCK_SLAVE_UNLOCK (clock);
1522       break;
1523     case PROP_TIMEOUT:
1524       g_value_set_uint64 (value, gst_clock_get_timeout (clock));
1525       break;
1526     default:
1527       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1528       break;
1529   }
1530 }
1531
1532
1533 /**
1534  * gst_clock_wait_for_sync:
1535  * @clock: a GstClock
1536  * @timeout: timeout for waiting or %GST_CLOCK_TIME_NONE
1537  *
1538  * Waits until @clock is synced for reporting the current time. If @timeout
1539  * is %GST_CLOCK_TIME_NONE it will wait forever, otherwise it will time out
1540  * after @timeout nanoseconds.
1541  *
1542  * For asynchronous waiting, the GstClock::synced signal can be used.
1543  *
1544  *
1545  * This returns immediately with TRUE if GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC
1546  * is not set on the clock, or if the clock is already synced.
1547  *
1548  * Returns: %TRUE if waiting was successful, or %FALSE on timeout
1549  *
1550  * Since: 1.6
1551  */
1552 gboolean
1553 gst_clock_wait_for_sync (GstClock * clock, GstClockTime timeout)
1554 {
1555   gboolean timed_out = FALSE;
1556
1557   g_return_val_if_fail (GST_IS_CLOCK (clock), FALSE);
1558
1559   GST_OBJECT_LOCK (clock);
1560   if (!GST_OBJECT_FLAG_IS_SET (clock, GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC)
1561       || clock->priv->synced) {
1562     GST_OBJECT_UNLOCK (clock);
1563     return TRUE;
1564   }
1565
1566   if (timeout != GST_CLOCK_TIME_NONE) {
1567     gint64 end_time = g_get_monotonic_time () + gst_util_uint64_scale (timeout,
1568         G_TIME_SPAN_SECOND, GST_SECOND);
1569
1570     while (!clock->priv->synced && !timed_out) {
1571       timed_out =
1572           !g_cond_wait_until (&clock->priv->sync_cond,
1573           GST_OBJECT_GET_LOCK (clock), end_time);
1574     }
1575   } else {
1576     timed_out = FALSE;
1577     while (!clock->priv->synced) {
1578       g_cond_wait (&clock->priv->sync_cond, GST_OBJECT_GET_LOCK (clock));
1579     }
1580   }
1581   GST_OBJECT_UNLOCK (clock);
1582
1583   return !timed_out;
1584 }
1585
1586 /**
1587  * gst_clock_is_synced:
1588  * @clock: a GstClock
1589  *
1590  * Checks if the clock is currently synced.
1591  *
1592  * This returns if GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC is not set on the clock.
1593  *
1594  * Returns: %TRUE if the clock is currently synced
1595  *
1596  * Since: 1.6
1597  */
1598 gboolean
1599 gst_clock_is_synced (GstClock * clock)
1600 {
1601   g_return_val_if_fail (GST_IS_CLOCK (clock), TRUE);
1602
1603   return !GST_OBJECT_FLAG_IS_SET (clock, GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC)
1604       || clock->priv->synced;
1605 }
1606
1607 /**
1608  * gst_clock_set_synced:
1609  * @clock: a GstClock
1610  * @synced: if the clock is synced
1611  *
1612  * Sets @clock to synced and emits the GstClock::synced signal, and wakes up any
1613  * thread waiting in gst_clock_wait_synced().
1614  *
1615  * This function must only be called if GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC
1616  * is set on the clock, and is intended to be called by subclasses only.
1617  *
1618  * Since: 1.6
1619  */
1620 void
1621 gst_clock_set_synced (GstClock * clock, gboolean synced)
1622 {
1623   g_return_if_fail (GST_IS_CLOCK (clock));
1624   g_return_if_fail (GST_OBJECT_FLAG_IS_SET (clock,
1625           GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC));
1626
1627   GST_OBJECT_LOCK (clock);
1628   if (clock->priv->synced != ! !synced) {
1629     clock->priv->synced = ! !synced;
1630     g_cond_signal (&clock->priv->sync_cond);
1631     GST_OBJECT_UNLOCK (clock);
1632     g_signal_emit (clock, gst_clock_signals[SIGNAL_SYNCED], 0, ! !synced);
1633   } else {
1634     GST_OBJECT_UNLOCK (clock);
1635   }
1636 }