gstclock.c 37.8 KB
Newer Older
1 2 3
/* GStreamer
 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
 *                    2000 Wim Taymans <wtay@chello.be>
4
 *                    2004 Wim Taymans <wim@fluendo.com>
5 6
 *
 * gstclock.c: Clock subsystem for maintaining time sync
Wim Taymans's avatar
Wim Taymans committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
23

24 25 26
/**
 * SECTION:gstclock
 * @short_description: Abstract class for global clocks
Wim Taymans's avatar
Wim Taymans committed
27
 * @see_also: #GstSystemClock, #GstPipeline
28
 *
Wim Taymans's avatar
Wim Taymans committed
29
 * GStreamer uses a global clock to synchronize the plugins in a pipeline.
30 31 32
 * Different clock implementations are possible by implementing this abstract
 * base class.
 *
Wim Taymans's avatar
Wim Taymans committed
33
 * The #GstClock returns a monotonically increasing time with the method
Wim Taymans's avatar
Wim Taymans committed
34 35
 * gst_clock_get_time(). Its accuracy and base time depend on the specific
 * clock implementation but time is always expressed in nanoseconds. Since the
Wim Taymans's avatar
Wim Taymans committed
36
 * baseline of the clock is undefined, the clock time returned is not
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
37
 * meaningful in itself, what matters are the deltas between two clock times.
Wim Taymans's avatar
Wim Taymans committed
38
 * The time returned by a clock is called the absolute time.
Wim Taymans's avatar
Wim Taymans committed
39
 *
Wim Taymans's avatar
Wim Taymans committed
40
 * The pipeline uses the clock to calculate the stream time. Usually all
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
41
 * renderers synchronize to the global clock using the buffer timestamps, the
Wim Taymans's avatar
Wim Taymans committed
42
 * newsegment events and the element's base time, see #GstPipeline.
Wim Taymans's avatar
Wim Taymans committed
43
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
44 45
 * A clock implementation can support periodic and single shot clock
 * notifications both synchronous and asynchronous.
Wim Taymans's avatar
Wim Taymans committed
46 47
 *
 * One first needs to create a #GstClockID for the periodic or single shot
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
48 49
 * notification using gst_clock_new_single_shot_id() or
 * gst_clock_new_periodic_id().
Wim Taymans's avatar
Wim Taymans committed
50 51 52
 *
 * To perform a blocking wait for the specific time of the #GstClockID use the
 * gst_clock_id_wait(). To receive a callback when the specific time is reached
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
53 54 55
 * in the clock use gst_clock_id_wait_async(). Both these calls can be
 * interrupted with the gst_clock_id_unschedule() call. If the blocking wait is
 * unscheduled a return value of GST_CLOCK_UNSCHEDULED is returned.
Wim Taymans's avatar
Wim Taymans committed
56
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
57
 * Periodic callbacks scheduled async will be repeadedly called automatically
Wim Taymans's avatar
Wim Taymans committed
58
 * until it is unscheduled. To schedule a sync periodic callback,
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
59
 * gst_clock_id_wait() should be called repeadedly.
60
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
61 62
 * The async callbacks can happen from any thread, either provided by the core
 * or from a streaming thread. The application should be prepared for this.
Wim Taymans's avatar
Wim Taymans committed
63 64
 *
 * A #GstClockID that has been unscheduled cannot be used again for any wait
Wim Taymans's avatar
Wim Taymans committed
65 66
 * operation, a new #GstClockID should be created and the old unscheduled one
 * should be destroyed wirth gst_clock_id_unref().
Wim Taymans's avatar
Wim Taymans committed
67
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
68 69
 * It is possible to perform a blocking wait on the same #GstClockID from
 * multiple threads. However, registering the same #GstClockID for multiple
Wim Taymans's avatar
Wim Taymans committed
70 71
 * async notifications is not possible, the callback will only be called for
 * the thread registering the entry last.
Wim Taymans's avatar
Wim Taymans committed
72
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
73 74 75 76
 * None of the wait operations unref the #GstClockID, the owner is responsible
 * for unreffing the ids itself. This holds for both periodic and single shot
 * notifications. The reason being that the owner of the #GstClockID has to
 * keep a handle to the #GstClockID to unblock the wait on FLUSHING events or
Wim Taymans's avatar
Wim Taymans committed
77 78
 * state changes and if the entry would be unreffed automatically, the handle 
 * might become invalid without any notification.
Wim Taymans's avatar
Wim Taymans committed
79 80 81 82 83 84
 *
 * These clock operations do not operate on the stream time, so the callbacks
 * will also occur when not in PLAYING state as if the clock just keeps on
 * running. Some clocks however do not progress when the element that provided
 * the clock is not PLAYING.
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
85 86 87 88 89 90 91 92
 * When a clock has the GST_CLOCK_FLAG_CAN_SET_MASTER flag set, it can be
 * slaved to another #GstClock with the gst_clock_set_master(). The clock will
 * then automatically be synchronized to this master clock by repeadedly
 * sampling the master clock and the slave clock and recalibrating the slave
 * clock with gst_clock_set_calibration(). This feature is mostly usefull for
 * plugins that have an internal clock but must operate with another clock
 * selected by the #GstPipeline.  They can track the offset and rate difference
 * of their internal clock relative to the master clock by using the
Wim Taymans's avatar
Wim Taymans committed
93 94 95 96 97 98 99 100
 * gst_clock_get_calibration() function. 
 *
 * The master/slave synchronisation can be tuned with the "timeout", "window-size"
 * and "window-threshold" properties. The "timeout" property defines the interval
 * to sample the master clock and run the calibration functions. 
 * "window-size" defines the number of samples to use when calibrating and
 * "window-threshold" defines the minimum number of samples before the 
 * calibration is performed.
Wim Taymans's avatar
Wim Taymans committed
101
 *
102
 * Last reviewed on 2006-08-11 (0.10.10)
103
 */
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
104

105 106

#include "gst_private.h"
107
#include <time.h>
108

109
#include "gstclock.h"
110
#include "gstinfo.h"
111
#include "gstutils.h"
Wim Taymans's avatar
Wim Taymans committed
112

Wim Taymans's avatar
Wim Taymans committed
113
#ifndef GST_DISABLE_TRACE
Wim Taymans's avatar
Wim Taymans committed
114
/* #define GST_WITH_ALLOC_TRACE */
Wim Taymans's avatar
Wim Taymans committed
115 116 117
#include "gsttrace.h"
static GstAllocTrace *_gst_clock_entry_trace;
#endif
Wim Taymans's avatar
Wim Taymans committed
118

119 120 121 122 123 124 125 126
#if GLIB_CHECK_VERSION (2, 10, 0)
#define ALLOC_ENTRY()     g_slice_new (GstClockEntry)
#define FREE_ENTRY(entry) g_slice_free (GstClockEntry, entry)
#else
#define ALLOC_ENTRY()     g_new (GstClockEntry, 1)
#define FREE_ENTRY(entry) g_free (entry)
#endif

127 128
/* #define DEBUGGING_ENABLED */

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
129 130 131 132
#define DEFAULT_STATS                   FALSE
#define DEFAULT_WINDOW_SIZE             32
#define DEFAULT_WINDOW_THRESHOLD        4
#define DEFAULT_TIMEOUT                 GST_SECOND / 10
133

134 135
enum
{
136 137 138 139 140
  PROP_0,
  PROP_STATS,
  PROP_WINDOW_SIZE,
  PROP_WINDOW_THRESHOLD,
  PROP_TIMEOUT
141 142
};

143 144
static void gst_clock_class_init (GstClockClass * klass);
static void gst_clock_init (GstClock * clock);
145
static void gst_clock_dispose (GObject * object);
Wim Taymans's avatar
Wim Taymans committed
146
static void gst_clock_finalize (GObject * object);
Wim Taymans's avatar
Wim Taymans committed
147

148 149 150 151 152
static void gst_clock_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
static void gst_clock_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);
static void gst_clock_update_stats (GstClock * clock);
153

154

155
static GstObjectClass *parent_class = NULL;
156

157 158
/* static guint gst_clock_signals[LAST_SIGNAL] = { 0 }; */

Wim Taymans's avatar
Wim Taymans committed
159
static GstClockID
160 161
gst_clock_entry_new (GstClock * clock, GstClockTime time,
    GstClockTime interval, GstClockEntryType type)
162 163
{
  GstClockEntry *entry;
164

165
  entry = ALLOC_ENTRY ();
Wim Taymans's avatar
Wim Taymans committed
166
#ifndef GST_DISABLE_TRACE
Wim Taymans's avatar
Wim Taymans committed
167
  gst_alloc_trace_new (_gst_clock_entry_trace, entry);
Wim Taymans's avatar
Wim Taymans committed
168
#endif
169 170
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
      "created entry %p, time %" GST_TIME_FORMAT, entry, GST_TIME_ARGS (time));
171

172
  gst_atomic_int_set (&entry->refcount, 1);
173
  entry->clock = clock;
174
  entry->type = type;
175
  entry->time = time;
176
  entry->interval = interval;
177
  entry->status = GST_CLOCK_BUSY;
178 179
  entry->func = NULL;
  entry->user_data = NULL;
180

181 182
  return (GstClockID) entry;
}
183

184 185
/**
 * gst_clock_id_ref:
Wim Taymans's avatar
Wim Taymans committed
186
 * @id: The #GstClockID to ref
187
 *
Wim Taymans's avatar
Wim Taymans committed
188
 * Increase the refcount of given @id.
189 190 191 192 193 194 195 196 197 198
 *
 * Returns: The same #GstClockID with increased refcount.
 *
 * MT safe.
 */
GstClockID
gst_clock_id_ref (GstClockID id)
{
  g_return_val_if_fail (id != NULL, NULL);

199
  g_atomic_int_inc (&((GstClockEntry *) id)->refcount);
200 201 202 203 204 205 206 207 208 209 210 211 212 213

  return id;
}

static void
_gst_clock_id_free (GstClockID id)
{
  g_return_if_fail (id != NULL);

  GST_CAT_DEBUG (GST_CAT_CLOCK, "freed entry %p", id);

#ifndef GST_DISABLE_TRACE
  gst_alloc_trace_free (_gst_clock_entry_trace, id);
#endif
214
  FREE_ENTRY (id);
215 216 217 218
}

/**
 * gst_clock_id_unref:
Wim Taymans's avatar
Wim Taymans committed
219
 * @id: The #GstClockID to unref
220
 *
Wim Taymans's avatar
Wim Taymans committed
221
 * Unref given @id. When the refcount reaches 0 the
222 223 224 225 226 227 228 229 230 231 232
 * #GstClockID will be freed.
 *
 * MT safe.
 */
void
gst_clock_id_unref (GstClockID id)
{
  gint zero;

  g_return_if_fail (id != NULL);

233
  zero = g_atomic_int_dec_and_test (&((GstClockEntry *) id)->refcount);
234 235 236 237 238 239
  /* if we ended up with the refcount at zero, free the id */
  if (zero) {
    _gst_clock_id_free (id);
  }
}

240 241
/**
 * gst_clock_new_single_shot_id
Wim Taymans's avatar
Wim Taymans committed
242
 * @clock: The #GstClockID to get a single shot notification from
243 244
 * @time: the requested time
 *
Wim Taymans's avatar
Wim Taymans committed
245
 * Get a #GstClockID from @clock to trigger a single shot
246 247
 * notification at the requested time. The single shot id should be
 * unreffed after usage.
248
 *
Wim Taymans's avatar
Wim Taymans committed
249
 * Returns: A #GstClockID that can be used to request the time notification.
250 251
 *
 * MT safe.
252 253
 */
GstClockID
254
gst_clock_new_single_shot_id (GstClock * clock, GstClockTime time)
255
{
256 257
  g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);

258 259
  return gst_clock_entry_new (clock,
      time, GST_CLOCK_TIME_NONE, GST_CLOCK_ENTRY_SINGLE);
260 261 262
}

/**
Wim Taymans's avatar
Wim Taymans committed
263
 * gst_clock_new_periodic_id
Wim Taymans's avatar
Wim Taymans committed
264
 * @clock: The #GstClockID to get a periodic notification id from
265 266 267
 * @start_time: the requested start time
 * @interval: the requested interval
 *
Wim Taymans's avatar
Wim Taymans committed
268
 * Get an ID from @clock to trigger a periodic notification.
269
 * The periodeic notifications will be start at time start_time and
Wim Taymans's avatar
Wim Taymans committed
270
 * will then be fired with the given interval. @id should be unreffed
271
 * after usage.
272
 *
Wim Taymans's avatar
Wim Taymans committed
273
 * Returns: A #GstClockID that can be used to request the time notification.
274 275
 *
 * MT safe.
276 277
 */
GstClockID
278 279
gst_clock_new_periodic_id (GstClock * clock, GstClockTime start_time,
    GstClockTime interval)
280
{
281
  g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);
282
  g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (start_time), NULL);
283 284
  g_return_val_if_fail (interval != 0, NULL);

285 286
  return gst_clock_entry_new (clock,
      start_time, interval, GST_CLOCK_ENTRY_PERIODIC);
287 288
}

289 290
/**
 * gst_clock_id_compare_func
Wim Taymans's avatar
Wim Taymans committed
291 292
 * @id1: A #GstClockID
 * @id2: A #GstClockID to compare with
293
 *
Wim Taymans's avatar
Wim Taymans committed
294
 * Compares the two #GstClockID instances. This function can be used
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
 * as a GCompareFunc when sorting ids.
 *
 * Returns: negative value if a < b; zero if a = b; positive value if a > b
 *
 * MT safe.
 */
gint
gst_clock_id_compare_func (gconstpointer id1, gconstpointer id2)
{
  GstClockEntry *entry1, *entry2;

  entry1 = (GstClockEntry *) id1;
  entry2 = (GstClockEntry *) id2;

  if (GST_CLOCK_ENTRY_TIME (entry1) > GST_CLOCK_ENTRY_TIME (entry2)) {
    return 1;
  }
  if (GST_CLOCK_ENTRY_TIME (entry1) < GST_CLOCK_ENTRY_TIME (entry2)) {
    return -1;
  }
Wim Taymans's avatar
Wim Taymans committed
315
  return 0;
316 317
}

318 319
/**
 * gst_clock_id_get_time
Wim Taymans's avatar
Wim Taymans committed
320
 * @id: The #GstClockID to query
321 322 323
 *
 * Get the time of the clock ID
 *
324 325 326
 * Returns: the time of the given clock id.
 *
 * MT safe.
327 328 329 330 331 332
 */
GstClockTime
gst_clock_id_get_time (GstClockID id)
{
  g_return_val_if_fail (id != NULL, GST_CLOCK_TIME_NONE);

333
  return GST_CLOCK_ENTRY_TIME ((GstClockEntry *) id);
334 335 336 337
}

/**
 * gst_clock_id_wait
Wim Taymans's avatar
Wim Taymans committed
338 339 340 341 342 343 344 345 346 347 348
 * @id: The #GstClockID to wait on
 * @jitter: A pointer that will contain the jitter, can be NULL.
 *
 * Perform a blocking wait on @id. 
 * @id should have been created with gst_clock_new_single_shot_id()
 * or gst_clock_new_periodic_id() and should not have been unscheduled
 * with a call to gst_clock_id_unschedule(). 
 *
 * If the @jitter argument is not NULL and this function returns #GST_CLOCK_OK
 * or #GST_CLOCK_EARLY, it will contain the difference
 * against the clock and the time of @id when this method was
349 350
 * called. 
 * Positive values indicate how late @id was relative to the clock
351
 * (in which case this function will return #GST_CLOCK_EARLY). 
352
 * Negative values indicate how much time was spent waiting on the clock 
353
 * before this function returned.
Wim Taymans's avatar
Wim Taymans committed
354 355 356 357 358
 *
 * Returns: the result of the blocking wait. #GST_CLOCK_EARLY will be returned
 * if the current clock time is past the time of @id, #GST_CLOCK_OK if 
 * @id was scheduled in time. #GST_CLOCK_UNSCHEDULED if @id was 
 * unscheduled with gst_clock_id_unschedule().
359 360
 *
 * MT safe.
361 362
 */
GstClockReturn
363
gst_clock_id_wait (GstClockID id, GstClockTimeDiff * jitter)
364 365
{
  GstClockEntry *entry;
366
  GstClock *clock;
367
  GstClockReturn res;
368
  GstClockTime requested;
Wim Taymans's avatar
Wim Taymans committed
369
  GstClockClass *cclass;
370

371
  g_return_val_if_fail (id != NULL, GST_CLOCK_ERROR);
372

373 374
  entry = (GstClockEntry *) id;
  requested = GST_CLOCK_ENTRY_TIME (entry);
375

376 377
  clock = GST_CLOCK_ENTRY_CLOCK (entry);

Wim Taymans's avatar
Wim Taymans committed
378
  /* can't sync on invalid times */
379 380 381
  if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (requested)))
    goto invalid_time;

Wim Taymans's avatar
Wim Taymans committed
382
  /* a previously unscheduled entry cannot be scheduled again */
383 384
  if (G_UNLIKELY (entry->status == GST_CLOCK_UNSCHEDULED))
    goto unscheduled;
385

Wim Taymans's avatar
Wim Taymans committed
386
  cclass = GST_CLOCK_GET_CLASS (clock);
387

Wim Taymans's avatar
Wim Taymans committed
388 389
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "waiting on clock entry %p", id);

390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
  /* if we have a wait_jitter function, use that */
  if (G_LIKELY (cclass->wait_jitter)) {
    res = cclass->wait_jitter (clock, entry, jitter);
  } else {
    /* check if we have a simple _wait function otherwise. The function without
     * the jitter arg is less optimal as we need to do an additional _get_time()
     * which is not atomic with the _wait() and a typical _wait() function does
     * yet another _get_time() anyway. */
    if (G_UNLIKELY (cclass->wait == NULL))
      goto not_supported;

    if (jitter) {
      GstClockTime now = gst_clock_get_time (clock);

      /* jitter is the diff against the clock when this entry is scheduled. Negative
       * values mean that the entry was in time, a positive value means that the
       * entry was too late. */
      *jitter = GST_CLOCK_DIFF (requested, now);
    }
    res = cclass->wait (clock, entry);
Wim Taymans's avatar
Wim Taymans committed
410 411 412 413 414 415 416
  }

  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
      "done waiting entry %p, res: %d", id, res);

  if (entry->type == GST_CLOCK_ENTRY_PERIODIC) {
    entry->time += entry->interval;
417
  }
Wim Taymans's avatar
Wim Taymans committed
418 419 420 421

  if (clock->stats)
    gst_clock_update_stats (clock);

422
  return res;
423 424 425 426

  /* ERRORS */
invalid_time:
  {
427 428
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "invalid time requested, returning _BADTIME");
429 430 431 432
    return GST_CLOCK_BADTIME;
  }
unscheduled:
  {
433 434
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "entry was unscheduled return _UNSCHEDULED");
435 436
    return GST_CLOCK_UNSCHEDULED;
  }
Wim Taymans's avatar
Wim Taymans committed
437 438 439 440 441
not_supported:
  {
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "clock wait is not supported");
    return GST_CLOCK_UNSUPPORTED;
  }
442 443 444
}

/**
Wim Taymans's avatar
Wim Taymans committed
445 446
 * gst_clock_id_wait_async:
 * @id: a #GstClockID to wait on
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
447
 * @func: The callback function
448 449
 * @user_data: User data passed in the calback
 *
Wim Taymans's avatar
Wim Taymans committed
450 451
 * Register a callback on the given #GstClockID @id with the given
 * function and user_data. When passing a #GstClockID with an invalid
452 453
 * time to this function, the callback will be called immediatly
 * with  a time set to GST_CLOCK_TIME_NONE. The callback will
Wim Taymans's avatar
Wim Taymans committed
454
 * be called when the time of @id has been reached.
455
 *
456
 * Returns: the result of the non blocking wait.
457 458
 *
 * MT safe.
459 460 461
 */
GstClockReturn
gst_clock_id_wait_async (GstClockID id,
462
    GstClockCallback func, gpointer user_data)
463 464 465
{
  GstClockEntry *entry;
  GstClock *clock;
466
  GstClockReturn res;
Wim Taymans's avatar
Wim Taymans committed
467
  GstClockClass *cclass;
468
  GstClockTime requested;
469

470
  g_return_val_if_fail (id != NULL, GST_CLOCK_ERROR);
471
  g_return_val_if_fail (func != NULL, GST_CLOCK_ERROR);
472 473

  entry = (GstClockEntry *) id;
474 475
  requested = GST_CLOCK_ENTRY_TIME (entry);
  clock = GST_CLOCK_ENTRY_CLOCK (entry);
476

Wim Taymans's avatar
Wim Taymans committed
477
  /* can't sync on invalid times */
478 479 480
  if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (requested)))
    goto invalid_time;

Wim Taymans's avatar
Wim Taymans committed
481
  /* a previously unscheduled entry cannot be scheduled again */
482 483
  if (G_UNLIKELY (entry->status == GST_CLOCK_UNSCHEDULED))
    goto unscheduled;
484

Wim Taymans's avatar
Wim Taymans committed
485 486
  cclass = GST_CLOCK_GET_CLASS (clock);

Wim Taymans's avatar
Wim Taymans committed
487 488 489 490 491 492 493
  if (G_UNLIKELY (cclass->wait_async == NULL))
    goto not_supported;

  entry->func = func;
  entry->user_data = user_data;

  res = cclass->wait_async (clock, entry);
Wim Taymans's avatar
Wim Taymans committed
494

495 496
  return res;

497 498 499 500
  /* ERRORS */
invalid_time:
  {
    (func) (clock, GST_CLOCK_TIME_NONE, id, user_data);
501 502
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "invalid time requested, returning _BADTIME");
503 504 505 506
    return GST_CLOCK_BADTIME;
  }
unscheduled:
  {
507 508
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "entry was unscheduled return _UNSCHEDULED");
509 510
    return GST_CLOCK_UNSCHEDULED;
  }
Wim Taymans's avatar
Wim Taymans committed
511 512 513 514 515
not_supported:
  {
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "clock wait is not supported");
    return GST_CLOCK_UNSUPPORTED;
  }
516 517
}

518
/**
Wim Taymans's avatar
Wim Taymans committed
519 520
 * gst_clock_id_unschedule:
 * @id: The id to unschedule
521
 *
Wim Taymans's avatar
Wim Taymans committed
522
 * Cancel an outstanding request with @id. This can either
523
 * be an outstanding async notification or a pending sync notification.
Wim Taymans's avatar
Wim Taymans committed
524 525
 * After this call, @id cannot be used anymore to receive sync or
 * async notifications, you need to create a new #GstClockID.
526 527
 *
 * MT safe.
528 529 530 531 532 533
 */
void
gst_clock_id_unschedule (GstClockID id)
{
  GstClockEntry *entry;
  GstClock *clock;
Wim Taymans's avatar
Wim Taymans committed
534
  GstClockClass *cclass;
535

536 537 538 539
  g_return_if_fail (id != NULL);

  entry = (GstClockEntry *) id;
  clock = entry->clock;
540

Wim Taymans's avatar
Wim Taymans committed
541 542
  cclass = GST_CLOCK_GET_CLASS (clock);

Wim Taymans's avatar
Wim Taymans committed
543
  if (G_LIKELY (cclass->unschedule))
Wim Taymans's avatar
Wim Taymans committed
544
    cclass->unschedule (clock, entry);
545 546
}

547 548 549 550

/**
 * GstClock abstract base class implementation
 */
551 552
GType
gst_clock_get_type (void)
Wim Taymans's avatar
Wim Taymans committed
553
{
554 555
  static GType clock_type = 0;

556
  if (G_UNLIKELY (clock_type == 0)) {
557
    static const GTypeInfo clock_info = {
558
      sizeof (GstClockClass),
559 560 561 562 563
      NULL,
      NULL,
      (GClassInitFunc) gst_clock_class_init,
      NULL,
      NULL,
564
      sizeof (GstClock),
565
      0,
566 567 568
      (GInstanceInitFunc) gst_clock_init,
      NULL
    };
569

570
    clock_type = g_type_register_static (GST_TYPE_OBJECT, "GstClock",
571
        &clock_info, G_TYPE_FLAG_ABSTRACT);
572 573 574
  }
  return clock_type;
}
575

576
static void
577
gst_clock_class_init (GstClockClass * klass)
578 579 580
{
  GObjectClass *gobject_class;
  GstObjectClass *gstobject_class;
581

582 583
  gobject_class = G_OBJECT_CLASS (klass);
  gstobject_class = GST_OBJECT_CLASS (klass);
584

585
  parent_class = g_type_class_peek_parent (klass);
586

Wim Taymans's avatar
Wim Taymans committed
587 588 589
  if (!g_thread_supported ())
    g_thread_init (NULL);

Wim Taymans's avatar
Wim Taymans committed
590
#ifndef GST_DISABLE_TRACE
591 592
  _gst_clock_entry_trace =
      gst_alloc_trace_register (GST_CLOCK_ENTRY_TRACE_NAME);
Wim Taymans's avatar
Wim Taymans committed
593
#endif
594

595
  gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_clock_dispose);
Wim Taymans's avatar
Wim Taymans committed
596
  gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_clock_finalize);
597 598 599
  gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_clock_set_property);
  gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_clock_get_property);

600
  g_object_class_install_property (gobject_class, PROP_STATS,
601 602 603
      g_param_spec_boolean ("stats", "Stats",
          "Enable clock stats (unimplemented)", DEFAULT_STATS,
          G_PARAM_READWRITE));
604
  g_object_class_install_property (gobject_class, PROP_WINDOW_SIZE,
605 606 607
      g_param_spec_int ("window-size", "Window size",
          "The size of the window used to calculate rate and offset", 2, 1024,
          DEFAULT_WINDOW_SIZE, G_PARAM_READWRITE));
608 609
  g_object_class_install_property (gobject_class, PROP_WINDOW_THRESHOLD,
      g_param_spec_int ("window-threshold", "Window threshold",
610 611
          "The threshold to start calculating rate and offset", 2, 1024,
          DEFAULT_WINDOW_THRESHOLD, G_PARAM_READWRITE));
612
  g_object_class_install_property (gobject_class, PROP_TIMEOUT,
613 614 615
      g_param_spec_uint64 ("timeout", "Timeout",
          "The amount of time, in nanoseconds, to sample master and slave clocks",
          0, G_MAXUINT64, DEFAULT_TIMEOUT, G_PARAM_READWRITE));
Wim Taymans's avatar
Wim Taymans committed
616 617
}

618
static void
619
gst_clock_init (GstClock * clock)
Wim Taymans's avatar
Wim Taymans committed
620
{
621 622
  clock->last_time = 0;
  clock->entries = NULL;
623
  clock->entries_changed = g_cond_new ();
624
  clock->stats = FALSE;
625

626 627
  clock->internal_calibration = 0;
  clock->external_calibration = 0;
628 629 630 631
  clock->rate_numerator = 1;
  clock->rate_denominator = 1;

  clock->slave_lock = g_mutex_new ();
632 633
  clock->window_size = DEFAULT_WINDOW_SIZE;
  clock->window_threshold = DEFAULT_WINDOW_THRESHOLD;
Wim Taymans's avatar
Wim Taymans committed
634
  clock->filling = TRUE;
635 636 637
  clock->time_index = 0;
  clock->timeout = DEFAULT_TIMEOUT;
  clock->times = g_new0 (GstClockTime, 4 * clock->window_size);
Wim Taymans's avatar
Wim Taymans committed
638 639
}

640 641 642 643
static void
gst_clock_dispose (GObject * object)
{
  GstClock *clock = GST_CLOCK (object);
644
  GstClock **master_p;
645 646

  GST_OBJECT_LOCK (clock);
647 648
  master_p = &clock->master;
  gst_object_replace ((GstObject **) master_p, NULL);
649 650 651 652 653
  GST_OBJECT_UNLOCK (clock);

  G_OBJECT_CLASS (parent_class)->dispose (object);
}

Wim Taymans's avatar
Wim Taymans committed
654
static void
Wim Taymans's avatar
Wim Taymans committed
655
gst_clock_finalize (GObject * object)
Wim Taymans's avatar
Wim Taymans committed
656 657 658
{
  GstClock *clock = GST_CLOCK (object);

659
  GST_CLOCK_SLAVE_LOCK (clock);
660 661 662 663 664 665 666
  if (clock->clockid) {
    gst_clock_id_unschedule (clock->clockid);
    gst_clock_id_unref (clock->clockid);
    clock->clockid = NULL;
  }
  g_free (clock->times);
  clock->times = NULL;
667
  GST_CLOCK_SLAVE_UNLOCK (clock);
668

669
  g_cond_free (clock->entries_changed);
670 671
  g_mutex_free (clock->slave_lock);

Wim Taymans's avatar
Wim Taymans committed
672
  G_OBJECT_CLASS (parent_class)->finalize (object);
Wim Taymans's avatar
Wim Taymans committed
673 674
}

Wim Taymans's avatar
Wim Taymans committed
675
/**
676
 * gst_clock_set_resolution
677
 * @clock: a #GstClock
678
 * @resolution: The resolution to set
Wim Taymans's avatar
Wim Taymans committed
679
 *
680 681 682 683 684
 * Set the accuracy of the clock. Some clocks have the possibility to operate
 * with different accuracy at the expense of more resource usage. There is
 * normally no need to change the default resolution of a clock. The resolution
 * of a clock can only be changed if the clock has the
 * #GST_CLOCK_FLAG_CAN_SET_RESOLUTION flag set.
685 686
 *
 * Returns: the new resolution of the clock.
Wim Taymans's avatar
Wim Taymans committed
687
 */
688 689
GstClockTime
gst_clock_set_resolution (GstClock * clock, GstClockTime resolution)
Wim Taymans's avatar
Wim Taymans committed
690
{
Wim Taymans's avatar
Wim Taymans committed
691 692
  GstClockClass *cclass;

693 694
  g_return_val_if_fail (GST_IS_CLOCK (clock), 0);
  g_return_val_if_fail (resolution != 0, 0);
695

Wim Taymans's avatar
Wim Taymans committed
696 697 698
  cclass = GST_CLOCK_GET_CLASS (clock);

  if (cclass->change_resolution)
699
    clock->resolution =
700
        cclass->change_resolution (clock, clock->resolution, resolution);
701

702 703
  return clock->resolution;
}
704

705 706
/**
 * gst_clock_get_resolution
707
 * @clock: a #GstClock
708
 *
709 710
 * Get the accuracy of the clock. The accuracy of the clock is the granularity
 * of the values returned by gst_clock_get_time().
711
 *
712
 * Returns: the resolution of the clock in units of #GstClockTime.
713 714
 *
 * MT safe.
715
 */
716
GstClockTime
717
gst_clock_get_resolution (GstClock * clock)
718
{
Wim Taymans's avatar
Wim Taymans committed
719 720
  GstClockClass *cclass;

721
  g_return_val_if_fail (GST_IS_CLOCK (clock), 0);
722

Wim Taymans's avatar
Wim Taymans committed
723 724 725 726
  cclass = GST_CLOCK_GET_CLASS (clock);

  if (cclass->get_resolution)
    return cclass->get_resolution (clock);
727

728
  return 1;
Wim Taymans's avatar
Wim Taymans committed
729 730
}

Wim Taymans's avatar
Wim Taymans committed
731
/**
732 733 734
 * gst_clock_adjust_unlocked
 * @clock: a #GstClock to use
 * @internal: a clock time
Wim Taymans's avatar
Wim Taymans committed
735
 *
736
 * Converts the given @internal clock time to the real time, adjusting for the
737 738
 * rate and reference time set with gst_clock_set_calibration() and making sure
 * that the returned time is increasing. This function should be called with the
739
 * clock's OBJECT_LOCK held and is mainly used by clock subclasses.
Wim Taymans's avatar
Wim Taymans committed
740
 *
741
 * Returns: the converted time of the clock.
742
 *
743
 * MT safe.
744
 */
745 746
GstClockTime
gst_clock_adjust_unlocked (GstClock * clock, GstClockTime internal)
747
{
748
  GstClockTime ret;
749

750 751
  ret = gst_util_uint64_scale (internal - clock->internal_calibration,
      clock->rate_numerator, clock->rate_denominator);
752
  ret += clock->external_calibration;
753 754 755 756 757

  /* make sure the time is increasing */
  clock->last_time = MAX (ret, clock->last_time);

  return clock->last_time;
758 759
}

Wim Taymans's avatar
Wim Taymans committed
760
/**
761
 * gst_clock_get_internal_time
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
762
 * @clock: a #GstClock to query
Wim Taymans's avatar
Wim Taymans committed
763
 *
764 765
 * Gets the current internal time of the given clock. The time is returned
 * unadjusted for the offset and the rate.
766
 *
767
 * Returns: the internal time of the clock. Or GST_CLOCK_TIME_NONE when
768 769 770
 * giving wrong input.
 *
 * MT safe.
Wim Taymans's avatar
Wim Taymans committed
771
 */
772
GstClockTime
773
gst_clock_get_internal_time (GstClock * clock)
774
{
775
  GstClockTime ret;
776
  GstClockClass *cclass;
777

778
  g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);
779

780
  cclass = GST_CLOCK_GET_CLASS (clock);
Wim Taymans's avatar
Wim Taymans committed
781

Wim Taymans's avatar
Wim Taymans committed
782 783 784 785 786
  if (G_UNLIKELY (cclass->get_internal_time == NULL))
    goto not_supported;

  ret = cclass->get_internal_time (clock);

787
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "internal time %" GST_TIME_FORMAT,
788
      GST_TIME_ARGS (ret));
789

790
  return ret;
Wim Taymans's avatar
Wim Taymans committed
791 792 793 794 795 796 797 798

  /* ERRORS */
not_supported:
  {
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "internal time not supported, return 0");
    return G_GINT64_CONSTANT (0);
  }
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
}

/**
 * gst_clock_get_time
 * @clock: a #GstClock to query
 *
 * Gets the current time of the given clock. The time is always
 * monotonically increasing and adjusted according to the current
 * offset and rate.
 *
 * Returns: the time of the clock. Or GST_CLOCK_TIME_NONE when
 * giving wrong input.
 *
 * MT safe.
 */
GstClockTime
gst_clock_get_time (GstClock * clock)
{
  GstClockTime ret;

  g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);

  ret = gst_clock_get_internal_time (clock);

823
  GST_OBJECT_LOCK (clock);
824
  /* this will scale for rate and offset */
825
  ret = gst_clock_adjust_unlocked (clock, ret);
826
  GST_OBJECT_UNLOCK (clock);
827

828
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "adjusted time %" GST_TIME_FORMAT,
829
      GST_TIME_ARGS (ret));
830

831
  return ret;
832 833
}

834 835 836 837 838
/**
 * gst_clock_set_calibration
 * @clock: a #GstClock to calibrate
 * @internal: a reference internal time
 * @external: a reference external time
839 840 841
 * @rate_num: the numerator of the rate of the clock relative to its
 *            internal time 
 * @rate_denom: the denominator of the rate of the clock
842
 *
843 844
 * Adjusts the rate and time of @clock. A rate of 1/1 is the normal speed of
 * the clock. Values bigger than 1/1 make the clock go faster.
845 846 847 848 849
 *
 * @internal and @external are calibration parameters that arrange that
 * gst_clock_get_time() should have been @external at internal time @internal.
 * This internal time should not be in the future; that is, it should be less
 * than the value of gst_clock_get_internal_time() when this function is called.
850 851 852 853 854
 *
 * Subsequent calls to gst_clock_get_time() will return clock times computed as
 * follows:
 *
 * <programlisting>
855
 *   time = (internal_time - @internal) * @rate_num / @rate_denom + @external
856 857
 * </programlisting>
 *
858 859 860
 * This formula is implemented in gst_clock_adjust_unlocked(). Of course, it
 * tries to do the integer arithmetic as precisely as possible.
 *
861 862 863 864 865 866 867
 * Note that gst_clock_get_time() always returns increasing values so when you
 * move the clock backwards, gst_clock_get_time() will report the previous value
 * until the clock catches up.
 *
 * MT safe.
 */
void
868
gst_clock_set_calibration (GstClock * clock, GstClockTime internal, GstClockTime
869
    external, GstClockTime rate_num, GstClockTime rate_denom)
870 871
{
  g_return_if_fail (GST_IS_CLOCK (clock));
872
  g_return_if_fail (rate_num >= 0);
873
  g_return_if_fail (rate_denom > 0);
874
  g_return_if_fail (internal <= gst_clock_get_internal_time (clock));
875

876
  GST_OBJECT_LOCK (clock);
877 878
  clock->internal_calibration = internal;
  clock->external_calibration = external;
879 880
  clock->rate_numerator = rate_num;
  clock->rate_denominator = rate_denom;
881
  GST_OBJECT_UNLOCK (clock);
882 883 884
}

/**
885 886 887 888
 * gst_clock_get_calibration
 * @clock: a #GstClock 
 * @internal: a location to store the internal time
 * @external: a location to store the external time
889 890
 * @rate_num: a location to store the rate numerator
 * @rate_denom: a location to store the rate denominator
891
 *
892 893
 * Gets the internal rate and reference time of @clock. See
 * gst_clock_set_calibration() for more information.
894
 *
895 896
 * @internal, @external, @rate_num, and @rate_denom can be left NULL if the
 * caller is not interested in the values.
897
 *
898 899 900
 * MT safe.
 */
void
901
gst_clock_get_calibration (GstClock * clock, GstClockTime * internal,
902
    GstClockTime * external, GstClockTime * rate_num, GstClockTime * rate_denom)
903 904 905
{
  g_return_if_fail (GST_IS_CLOCK (clock));

906
  GST_OBJECT_LOCK (clock);
907 908 909 910
  if (rate_num)
    *rate_num = clock->rate_numerator;
  if (rate_denom)
    *rate_denom = clock->rate_denominator;
911
  if (external)