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