gstclock.c 33.1 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 27 28
/**
 * SECTION:gstclock
 * @short_description: Abstract class for global clocks
 * @see_also: #GstSystemClock
 *
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 34 35 36 37 38 39 40 41
 * The #GstClock returns a monotonically increasing time with the method
 * gst_clock_get_time(). Its accuracy and base time depends on the specific clock
 * implementation but time is always expessed in nanoseconds. Since the
 * baseline of the clock is undefined, the clock time returned is not
 * meaningfull in itself, what matters are the deltas between two clock
 * times.
 *
 * The pipeline uses the clock to calculate the stream time.
 * Usually all renderers synchronize to the global clock using the buffer timestamps,
42
 * the newsegment events and the element's base time.
Wim Taymans's avatar
Wim Taymans committed
43
 *
Stefan Kost's avatar
Stefan Kost committed
44
 * The time of the clock in itself is not very useful for an application.
Wim Taymans's avatar
Wim Taymans committed
45 46 47 48 49 50 51 52 53 54 55 56 57
 *
 * A clock implementation can support periodic and single shot clock notifications 
 * both synchronous and asynchronous.
 *
 * One first needs to create a #GstClockID for the periodic or single shot
 * notification using gst_clock_new_single_shot_id() or gst_clock_new_periodic_id().
 *
 * 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
 * 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.
 *
58 59 60 61
 * Periodic callbacks scheduled async will be repeadedly called automatically until
 * it is unscheduled. To schedule an async periodic callback, gst_clock_id_wait() 
 * should be called repeadedly.
 *
Wim Taymans's avatar
Wim Taymans committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
 * 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.
 *
 * A #GstClockID that has been unscheduled cannot be used again for any wait
 * operation.
 *
 * It is possible to perform a blocking wait on the same #GstClockID from multiple
 * threads. However, registering the same #GstClockID for multiple async notifications is
 * not possible, the callback will only be called once.
 *
 * 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 state changes and if we unref it automatically, the handle might be
 * invalid.
 *
 * 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.
 *
Wim Taymans's avatar
Wim Taymans committed
84 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 gst_clock_get_calibration() function.
 *
Wim Taymans's avatar
Wim Taymans committed
93
 * Last reviewed on 2005-10-28 (0.9.4)
94
 */
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
95

96
#include <time.h>
97 98

#include "gst_private.h"
99

100
#include "gstclock.h"
101
#include "gstinfo.h"
102
#include "gstutils.h"
Wim Taymans's avatar
Wim Taymans committed
103

Wim Taymans's avatar
Wim Taymans committed
104
#ifndef GST_DISABLE_TRACE
Wim Taymans's avatar
Wim Taymans committed
105
/* #define GST_WITH_ALLOC_TRACE */
Wim Taymans's avatar
Wim Taymans committed
106 107 108
#include "gsttrace.h"
static GstAllocTrace *_gst_clock_entry_trace;
#endif
Wim Taymans's avatar
Wim Taymans committed
109

110 111 112 113 114 115 116 117 118 119 120 121
/* #define DEBUGGING_ENABLED */

#ifdef DEBUGGING_ENABLED
#define DEBUG(x, args...) g_print (x "\n", ##args)
#else
#define DEBUG(x, args...)       /* nop */
#endif

#define DEFAULT_STATS			FALSE
#define DEFAULT_WINDOW_SIZE		32
#define DEFAULT_WINDOW_THRESHOLD	4
#define DEFAULT_TIMEOUT         	GST_SECOND / 10
122

123 124
enum
{
125 126 127 128 129
  PROP_0,
  PROP_STATS,
  PROP_WINDOW_SIZE,
  PROP_WINDOW_THRESHOLD,
  PROP_TIMEOUT
130 131
};

132 133
static void gst_clock_class_init (GstClockClass * klass);
static void gst_clock_init (GstClock * clock);
Wim Taymans's avatar
Wim Taymans committed
134
static void gst_clock_finalize (GObject * object);
Wim Taymans's avatar
Wim Taymans committed
135

136 137 138 139 140
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);
141

142

143
static GstObjectClass *parent_class = NULL;
144

145 146
/* static guint gst_clock_signals[LAST_SIGNAL] = { 0 }; */

Wim Taymans's avatar
Wim Taymans committed
147
static GstClockID
148 149
gst_clock_entry_new (GstClock * clock, GstClockTime time,
    GstClockTime interval, GstClockEntryType type)
150 151
{
  GstClockEntry *entry;
152

153
  entry = g_malloc0 (sizeof (GstClockEntry));
Wim Taymans's avatar
Wim Taymans committed
154
#ifndef GST_DISABLE_TRACE
Wim Taymans's avatar
Wim Taymans committed
155
  gst_alloc_trace_new (_gst_clock_entry_trace, entry);
Wim Taymans's avatar
Wim Taymans committed
156
#endif
157 158
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
      "created entry %p, time %" GST_TIME_FORMAT, entry, GST_TIME_ARGS (time));
159

160
  gst_atomic_int_set (&entry->refcount, 1);
161 162
  entry->clock = clock;
  entry->time = time;
163
  entry->interval = interval;
164
  entry->type = type;
165
  entry->status = GST_CLOCK_BUSY;
166

167 168
  return (GstClockID) entry;
}
169

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
/**
 * gst_clock_id_ref:
 * @id: The clockid to ref
 *
 * Increase the refcount of the given clockid.
 *
 * Returns: The same #GstClockID with increased refcount.
 *
 * MT safe.
 */
GstClockID
gst_clock_id_ref (GstClockID id)
{
  g_return_val_if_fail (id != NULL, NULL);

185
  g_atomic_int_inc (&((GstClockEntry *) id)->refcount);
186 187 188 189 190 191 192 193 194 195 196 197 198 199

  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
200
  g_free (id);
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
}

/**
 * gst_clock_id_unref:
 * @id: The clockid to unref
 *
 * Unref the given clockid. When the refcount reaches 0 the
 * #GstClockID will be freed.
 *
 * MT safe.
 */
void
gst_clock_id_unref (GstClockID id)
{
  gint zero;

  g_return_if_fail (id != NULL);

219
  zero = g_atomic_int_dec_and_test (&((GstClockEntry *) id)->refcount);
220 221 222 223 224 225
  /* if we ended up with the refcount at zero, free the id */
  if (zero) {
    _gst_clock_id_free (id);
  }
}

226 227 228 229 230
/**
 * gst_clock_new_single_shot_id
 * @clock: The clockid to get a single shot notification from
 * @time: the requested time
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
231
 * Get an ID from the given clock to trigger a single shot
232 233
 * notification at the requested time. The single shot id should be
 * unreffed after usage.
234 235
 *
 * Returns: An id that can be used to request the time notification.
236 237
 *
 * MT safe.
238 239
 */
GstClockID
240
gst_clock_new_single_shot_id (GstClock * clock, GstClockTime time)
241
{
242 243
  g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);

244 245
  return gst_clock_entry_new (clock,
      time, GST_CLOCK_TIME_NONE, GST_CLOCK_ENTRY_SINGLE);
246 247 248
}

/**
Wim Taymans's avatar
Wim Taymans committed
249
 * gst_clock_new_periodic_id
250 251 252 253 254 255
 * @clock: The clockid to get a periodic notification id from
 * @start_time: the requested start time
 * @interval: the requested interval
 *
 * Get an ID from the given clock to trigger a periodic notification.
 * The periodeic notifications will be start at time start_time and
256 257
 * will then be fired with the given interval. The id should be unreffed
 * after usage.
258 259
 *
 * Returns: An id that can be used to request the time notification.
260 261
 *
 * MT safe.
262 263
 */
GstClockID
264 265
gst_clock_new_periodic_id (GstClock * clock, GstClockTime start_time,
    GstClockTime interval)
266
{
267
  g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);
268
  g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (start_time), NULL);
269 270
  g_return_val_if_fail (interval != 0, NULL);

271 272
  return gst_clock_entry_new (clock,
      start_time, interval, GST_CLOCK_ENTRY_PERIODIC);
273 274
}

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
/**
 * gst_clock_id_compare_func
 * @id1: A clockid
 * @id2: A clockid to compare with
 *
 * Compares the two GstClockID instances. This function can be used
 * 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;
  }

  return entry1 - entry2;
}

305 306 307 308 309 310
/**
 * gst_clock_id_get_time
 * @id: The clockid to query
 *
 * Get the time of the clock ID
 *
311 312 313
 * Returns: the time of the given clock id.
 *
 * MT safe.
314 315 316 317 318 319
 */
GstClockTime
gst_clock_id_get_time (GstClockID id)
{
  g_return_val_if_fail (id != NULL, GST_CLOCK_TIME_NONE);

320
  return GST_CLOCK_ENTRY_TIME ((GstClockEntry *) id);
321 322 323 324 325 326 327 328 329
}


/**
 * gst_clock_id_wait
 * @id: The clockid to wait on
 * @jitter: A pointer that will contain the jitter
 *
 * Perform a blocking wait on the given ID. The jitter arg can be
330
 * NULL.
331 332
 *
 * Returns: the result of the blocking wait.
333 334
 *
 * MT safe.
335 336
 */
GstClockReturn
337
gst_clock_id_wait (GstClockID id, GstClockTimeDiff * jitter)
338 339
{
  GstClockEntry *entry;
340
  GstClock *clock;
341
  GstClockReturn res;
342
  GstClockTime requested;
Wim Taymans's avatar
Wim Taymans committed
343
  GstClockClass *cclass;
344

345
  g_return_val_if_fail (id != NULL, GST_CLOCK_ERROR);
346

347 348
  entry = (GstClockEntry *) id;
  requested = GST_CLOCK_ENTRY_TIME (entry);
349

350 351
  clock = GST_CLOCK_ENTRY_CLOCK (entry);

352 353 354 355 356
  if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (requested)))
    goto invalid_time;

  if (G_UNLIKELY (entry->status == GST_CLOCK_UNSCHEDULED))
    goto unscheduled;
357

Wim Taymans's avatar
Wim Taymans committed
358
  cclass = GST_CLOCK_GET_CLASS (clock);
359

360
  if (G_LIKELY (cclass->wait)) {
361

362 363
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "waiting on clock entry %p",
        id);
364
    res = cclass->wait (clock, entry);
365
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "done waiting entry %p", id);
366

367
    if (jitter) {
368 369
      GstClockTime now = gst_clock_get_time (clock);

370 371
      *jitter = now - requested;
    }
372 373 374
    if (entry->type == GST_CLOCK_ENTRY_PERIODIC) {
      entry->time += entry->interval;
    }
375 376 377 378

    if (clock->stats) {
      gst_clock_update_stats (clock);
    }
379 380
  } else {
    res = GST_CLOCK_UNSUPPORTED;
381 382
  }
  return res;
383 384 385 386

  /* ERRORS */
invalid_time:
  {
387 388
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "invalid time requested, returning _BADTIME");
389 390 391 392
    return GST_CLOCK_BADTIME;
  }
unscheduled:
  {
393 394
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "entry was unscheduled return _UNSCHEDULED");
395 396
    return GST_CLOCK_UNSCHEDULED;
  }
397 398 399
}

/**
Wim Taymans's avatar
Wim Taymans committed
400 401
 * gst_clock_id_wait_async:
 * @id: a #GstClockID to wait on
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
402
 * @func: The callback function
403 404
 * @user_data: User data passed in the calback
 *
Wim Taymans's avatar
Wim Taymans committed
405
 * Register a callback on the given clockid with the given
406 407 408 409
 * function and user_data. When passing an id with an invalid
 * time to this function, the callback will be called immediatly
 * with  a time set to GST_CLOCK_TIME_NONE. The callback will
 * be called when the time of the id has been reached.
410
 *
411
 * Returns: the result of the non blocking wait.
412 413
 *
 * MT safe.
414 415 416
 */
GstClockReturn
gst_clock_id_wait_async (GstClockID id,
417
    GstClockCallback func, gpointer user_data)
418 419 420
{
  GstClockEntry *entry;
  GstClock *clock;
421
  GstClockReturn res;
Wim Taymans's avatar
Wim Taymans committed
422
  GstClockClass *cclass;
423
  GstClockTime requested;
424

425
  g_return_val_if_fail (id != NULL, GST_CLOCK_ERROR);
426
  g_return_val_if_fail (func != NULL, GST_CLOCK_ERROR);
427 428

  entry = (GstClockEntry *) id;
429 430
  requested = GST_CLOCK_ENTRY_TIME (entry);
  clock = GST_CLOCK_ENTRY_CLOCK (entry);
431

432 433 434 435 436
  if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (requested)))
    goto invalid_time;

  if (G_UNLIKELY (entry->status == GST_CLOCK_UNSCHEDULED))
    goto unscheduled;
437

Wim Taymans's avatar
Wim Taymans committed
438 439 440 441 442 443 444
  cclass = GST_CLOCK_GET_CLASS (clock);

  if (cclass->wait_async) {
    entry->func = func;
    entry->user_data = user_data;

    res = cclass->wait_async (clock, entry);
445 446
  } else {
    res = GST_CLOCK_UNSUPPORTED;
447 448 449
  }
  return res;

450 451 452 453
  /* ERRORS */
invalid_time:
  {
    (func) (clock, GST_CLOCK_TIME_NONE, id, user_data);
454 455
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "invalid time requested, returning _BADTIME");
456 457 458 459
    return GST_CLOCK_BADTIME;
  }
unscheduled:
  {
460 461
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "entry was unscheduled return _UNSCHEDULED");
462 463
    return GST_CLOCK_UNSCHEDULED;
  }
464 465
}

466
/**
Wim Taymans's avatar
Wim Taymans committed
467 468
 * gst_clock_id_unschedule:
 * @id: The id to unschedule
469
 *
470 471 472 473 474 475
 * Cancel an outstanding request with the given ID. This can either
 * be an outstanding async notification or a pending sync notification.
 * After this call, the @id cannot be used anymore to receive sync or
 * async notifications, you need to create a new GstClockID.
 *
 * MT safe.
476 477 478 479 480 481
 */
void
gst_clock_id_unschedule (GstClockID id)
{
  GstClockEntry *entry;
  GstClock *clock;
Wim Taymans's avatar
Wim Taymans committed
482
  GstClockClass *cclass;
483

484 485 486 487
  g_return_if_fail (id != NULL);

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

Wim Taymans's avatar
Wim Taymans committed
489 490 491 492
  cclass = GST_CLOCK_GET_CLASS (clock);

  if (cclass->unschedule)
    cclass->unschedule (clock, entry);
493 494
}

495 496 497 498

/**
 * GstClock abstract base class implementation
 */
499 500
GType
gst_clock_get_type (void)
Wim Taymans's avatar
Wim Taymans committed
501
{
502 503 504 505
  static GType clock_type = 0;

  if (!clock_type) {
    static const GTypeInfo clock_info = {
506
      sizeof (GstClockClass),
507 508 509 510 511
      NULL,
      NULL,
      (GClassInitFunc) gst_clock_class_init,
      NULL,
      NULL,
512
      sizeof (GstClock),
513
      0,
514 515 516
      (GInstanceInitFunc) gst_clock_init,
      NULL
    };
517

518
    clock_type = g_type_register_static (GST_TYPE_OBJECT, "GstClock",
519
        &clock_info, G_TYPE_FLAG_ABSTRACT);
520 521 522
  }
  return clock_type;
}
523

524
static void
525
gst_clock_class_init (GstClockClass * klass)
526 527 528
{
  GObjectClass *gobject_class;
  GstObjectClass *gstobject_class;
529

530 531
  gobject_class = (GObjectClass *) klass;
  gstobject_class = (GstObjectClass *) klass;
532

533
  parent_class = g_type_class_ref (GST_TYPE_OBJECT);
534

Wim Taymans's avatar
Wim Taymans committed
535 536 537
  if (!g_thread_supported ())
    g_thread_init (NULL);

Wim Taymans's avatar
Wim Taymans committed
538
#ifndef GST_DISABLE_TRACE
539 540
  _gst_clock_entry_trace =
      gst_alloc_trace_register (GST_CLOCK_ENTRY_TRACE_NAME);
Wim Taymans's avatar
Wim Taymans committed
541
#endif
542

Wim Taymans's avatar
Wim Taymans committed
543
  gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_clock_finalize);
544 545 546
  gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_clock_set_property);
  gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_clock_get_property);

547
  g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_STATS,
548
      g_param_spec_boolean ("stats", "Stats", "Enable clock stats",
549 550 551 552 553 554 555 556 557 558 559 560 561 562
          DEFAULT_STATS, G_PARAM_READWRITE));
  g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_WINDOW_SIZE,
      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));
  g_object_class_install_property (G_OBJECT_CLASS (klass),
      PROP_WINDOW_THRESHOLD, g_param_spec_int ("window-threshold",
          "Window threshold",
          "The threshold to start calculating rate and offset", 2, 1024,
          DEFAULT_WINDOW_THRESHOLD, G_PARAM_READWRITE));
  g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_TIMEOUT,
      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
563 564
}

565
static void
566
gst_clock_init (GstClock * clock)
Wim Taymans's avatar
Wim Taymans committed
567
{
568 569
  clock->last_time = 0;
  clock->entries = NULL;
570
  clock->entries_changed = g_cond_new ();
571
  clock->stats = FALSE;
572

573 574
  clock->internal_calibration = 0;
  clock->external_calibration = 0;
575 576 577 578
  clock->rate_numerator = 1;
  clock->rate_denominator = 1;

  clock->slave_lock = g_mutex_new ();
579 580 581 582 583 584
  clock->filling = TRUE;
  clock->window_size = DEFAULT_WINDOW_SIZE;
  clock->window_threshold = DEFAULT_WINDOW_THRESHOLD;
  clock->time_index = 0;
  clock->timeout = DEFAULT_TIMEOUT;
  clock->times = g_new0 (GstClockTime, 4 * clock->window_size);
Wim Taymans's avatar
Wim Taymans committed
585 586
}

Wim Taymans's avatar
Wim Taymans committed
587
static void
Wim Taymans's avatar
Wim Taymans committed
588
gst_clock_finalize (GObject * object)
Wim Taymans's avatar
Wim Taymans committed
589 590 591
{
  GstClock *clock = GST_CLOCK (object);

592
  GST_CLOCK_SLAVE_LOCK (clock);
593 594 595 596 597 598 599
  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;
600
  GST_CLOCK_SLAVE_UNLOCK (clock);
601

602
  g_cond_free (clock->entries_changed);
603 604
  g_mutex_free (clock->slave_lock);

Wim Taymans's avatar
Wim Taymans committed
605
  G_OBJECT_CLASS (parent_class)->finalize (object);
Wim Taymans's avatar
Wim Taymans committed
606 607
}

Wim Taymans's avatar
Wim Taymans committed
608
/**
609
 * gst_clock_set_resolution
610
 * @clock: a #GstClock
611
 * @resolution: The resolution to set
Wim Taymans's avatar
Wim Taymans committed
612
 *
613 614 615
 * Set the accuracy of the clock.
 *
 * Returns: the new resolution of the clock.
Wim Taymans's avatar
Wim Taymans committed
616
 */
617 618
GstClockTime
gst_clock_set_resolution (GstClock * clock, GstClockTime resolution)
Wim Taymans's avatar
Wim Taymans committed
619
{
Wim Taymans's avatar
Wim Taymans committed
620 621
  GstClockClass *cclass;

622 623
  g_return_val_if_fail (GST_IS_CLOCK (clock), 0);
  g_return_val_if_fail (resolution != 0, 0);
624

Wim Taymans's avatar
Wim Taymans committed
625 626 627
  cclass = GST_CLOCK_GET_CLASS (clock);

  if (cclass->change_resolution)
628
    clock->resolution =
629
        cclass->change_resolution (clock, clock->resolution, resolution);
630

631 632
  return clock->resolution;
}
633

634 635
/**
 * gst_clock_get_resolution
636
 * @clock: a #GstClock
637 638 639
 *
 * Get the accuracy of the clock.
 *
640
 * Returns: the resolution of the clock in units of #GstClockTime.
641 642
 *
 * MT safe.
643
 */
644
GstClockTime
645
gst_clock_get_resolution (GstClock * clock)
646
{
Wim Taymans's avatar
Wim Taymans committed
647 648
  GstClockClass *cclass;

649
  g_return_val_if_fail (GST_IS_CLOCK (clock), 0);
650

Wim Taymans's avatar
Wim Taymans committed
651 652 653 654
  cclass = GST_CLOCK_GET_CLASS (clock);

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

656
  return 1;
Wim Taymans's avatar
Wim Taymans committed
657 658
}

Wim Taymans's avatar
Wim Taymans committed
659
/**
660 661 662
 * gst_clock_adjust_unlocked
 * @clock: a #GstClock to use
 * @internal: a clock time
Wim Taymans's avatar
Wim Taymans committed
663
 *
664
 * Converts the given @internal clock time to the real time, adjusting for the
665 666
 * 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
667
 * clock's OBJECT_LOCK held and is mainly used by clock subclasses.
Wim Taymans's avatar
Wim Taymans committed
668
 *
669
 * Returns: the converted time of the clock.
670
 *
671
 * MT safe.
672
 */
673 674
GstClockTime
gst_clock_adjust_unlocked (GstClock * clock, GstClockTime internal)
675
{
676
  GstClockTime ret;
677

678 679
  ret = gst_util_uint64_scale (internal - clock->internal_calibration,
      clock->rate_numerator, clock->rate_denominator);
680
  ret += clock->external_calibration;
681 682 683 684 685

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

  return clock->last_time;
686 687
}

Wim Taymans's avatar
Wim Taymans committed
688
/**
689
 * gst_clock_get_internal_time
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
690
 * @clock: a #GstClock to query
Wim Taymans's avatar
Wim Taymans committed
691
 *
692 693
 * Gets the current internal time of the given clock. The time is returned
 * unadjusted for the offset and the rate.
694
 *
695
 * Returns: the internal time of the clock. Or GST_CLOCK_TIME_NONE when
696 697 698
 * giving wrong input.
 *
 * MT safe.
Wim Taymans's avatar
Wim Taymans committed
699
 */
700
GstClockTime
701
gst_clock_get_internal_time (GstClock * clock)
702
{
703
  GstClockTime ret;
704
  GstClockClass *cclass;
705

706
  g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);
707

708
  cclass = GST_CLOCK_GET_CLASS (clock);
Wim Taymans's avatar
Wim Taymans committed
709

710
  if (cclass->get_internal_time) {
711
    ret = cclass->get_internal_time (clock);
712
  } else {
713
    ret = G_GINT64_CONSTANT (0);
714
  }
715
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "internal time %" GST_TIME_FORMAT,
716
      GST_TIME_ARGS (ret));
717

718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
  return ret;
}

/**
 * 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);

743
  GST_OBJECT_LOCK (clock);
744
  /* this will scale for rate and offset */
745
  ret = gst_clock_adjust_unlocked (clock, ret);
746
  GST_OBJECT_UNLOCK (clock);
747

748
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "adjusted time %" GST_TIME_FORMAT,
749
      GST_TIME_ARGS (ret));
750

751
  return ret;
752 753
}

754 755 756 757 758
/**
 * gst_clock_set_calibration
 * @clock: a #GstClock to calibrate
 * @internal: a reference internal time
 * @external: a reference external time
759 760 761
 * @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
762
 *
763 764
 * 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.
765 766 767 768 769
 *
 * @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.
770 771 772 773 774
 *
 * Subsequent calls to gst_clock_get_time() will return clock times computed as
 * follows:
 *
 * <programlisting>
775
 *   time = (internal_time - @internal) * @rate_num / @rate_denom + @external
776 777
 * </programlisting>
 *
778 779 780
 * This formula is implemented in gst_clock_adjust_unlocked(). Of course, it
 * tries to do the integer arithmetic as precisely as possible.
 *
781 782 783 784 785 786 787
 * 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
788
gst_clock_set_calibration (GstClock * clock, GstClockTime internal, GstClockTime
789
    external, GstClockTime rate_num, GstClockTime rate_denom)
790 791
{
  g_return_if_fail (GST_IS_CLOCK (clock));
792 793
  g_return_if_fail (rate_num > 0);
  g_return_if_fail (rate_denom > 0);
794
  g_return_if_fail (internal <= gst_clock_get_internal_time (clock));
795

796
  GST_OBJECT_LOCK (clock);
797 798
  clock->internal_calibration = internal;
  clock->external_calibration = external;
799 800
  clock->rate_numerator = rate_num;
  clock->rate_denominator = rate_denom;
801
  GST_OBJECT_UNLOCK (clock);
802 803 804
}

/**
805 806 807 808
 * gst_clock_get_calibration
 * @clock: a #GstClock 
 * @internal: a location to store the internal time
 * @external: a location to store the external time
809 810
 * @rate_num: a location to store the rate numerator
 * @rate_denom: a location to store the rate denominator
811
 *
812 813
 * Gets the internal rate and reference time of @clock. See
 * gst_clock_set_calibration() for more information.
814
 *
815 816
 * @internal, @external, @rate_num, and @rate_denom can be left NULL if the
 * caller is not interested in the values.
817
 *
818 819 820
 * MT safe.
 */
void
821
gst_clock_get_calibration (GstClock * clock, GstClockTime * internal,
822
    GstClockTime * external, GstClockTime * rate_num, GstClockTime * rate_denom)
823 824 825
{
  g_return_if_fail (GST_IS_CLOCK (clock));

826
  GST_OBJECT_LOCK (clock);
827 828 829 830
  if (rate_num)
    *rate_num = clock->rate_numerator;
  if (rate_denom)
    *rate_denom = clock->rate_denominator;
831
  if (external)
832
    *external = clock->external_calibration;
833
  if (internal)
834
    *internal = clock->internal_calibration;
835
  GST_OBJECT_UNLOCK (clock);
836 837
}

838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
/* will be called repeadedly to sample the master and slave clock
 * to recalibrate the clock */
static gboolean
gst_clock_slave_callback (GstClock * master, GstClockTime time,
    GstClockID id, GstClock * clock)
{
  GstClockTime stime, mtime;
  gdouble r_squared;

  stime = gst_clock_get_internal_time (clock);
  mtime = gst_clock_get_time (master);

  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
      "master %" GST_TIME_FORMAT ", slave %" GST_TIME_FORMAT,
      GST_TIME_ARGS (mtime), GST_TIME_ARGS (stime));

  gst_clock_add_observation (clock, stime, mtime, &r_squared);

  /* FIXME, we can use the r_squared value to adjust the timeout
   * value of the clockid */

  return TRUE;
}

862 863 864 865 866 867 868 869 870 871 872 873
/**
 * gst_clock_set_master
 * @clock: a #GstClock 
 * @master: a master #GstClock 
 *
 * Set @master as the master clock for @clock. @clock will be automatically
 * calibrated so that gst_clock_get_time() reports the same time as the
 * master clock.  
 * 
 * A clock provider that slaves its clock to a master can get the current
 * calibration values with gst_clock_get_calibration().
 *
874 875
 * Returns: TRUE if the clock is capable of being slaved to a master clock.
 *
876 877
 * MT safe.
 */
878
gboolean
879 880
gst_clock_set_master (GstClock * clock, GstClock * master)
{
881 882
  g_return_val_if_fail (GST_IS_CLOCK (clock), FALSE);

883
  GST_OBJECT_LOCK (clock);
884 885 886 887 888
  /* we always allow setting the master to NULL */
  if (master && !GST_OBJECT_FLAG_IS_SET (clock, GST_CLOCK_FLAG_CAN_SET_MASTER))
    goto not_supported;

  GST_DEBUG_OBJECT (clock, "slaving to master clock %p", master);
889
  gst_object_replace ((GstObject **) & clock->master, (GstObject *) master);
890 891 892
  GST_OBJECT_UNLOCK (clock);

  GST_CLOCK_SLAVE_LOCK (clock);
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
  if (clock->clockid) {
    gst_clock_id_unschedule (clock->clockid);
    gst_clock_id_unref (clock->clockid);
    clock->clockid = NULL;
  }
  if (master) {
    clock->filling = TRUE;
    clock->time_index = 0;
    /* use the master periodic id to schedule sampling and
     * clock calibration. */
    clock->clockid = gst_clock_new_periodic_id (master,
        gst_clock_get_time (master), clock->timeout);
    gst_clock_id_wait_async (clock->clockid,
        (GstClockCallback) gst_clock_slave_callback, clock);
  }
908
  GST_CLOCK_SLAVE_UNLOCK (clock);
909 910 911 912 913 914

  return TRUE;

not_supported:
  {
    GST_DEBUG_OBJECT (clock, "cannot be slaved to a master clock");
915
    GST_OBJECT_UNLOCK (clock);
916 917
    return FALSE;
  }
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
}

/**
 * gst_clock_get_master
 * @clock: a #GstClock 
 *
 * Get the master clock that @clock is slaved to or NULL when the clock is
 * not slaved to any master clock.
 *
 * Returns: a master #GstClock or NULL when this clock is not slaved to a master
 * clock. Unref after usage.
 *
 * MT safe.
 */
GstClock *
gst_clock_get_master (GstClock * clock)
{
  GstClock *result = NULL;

937 938
  g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);

939 940 941 942 943 944 945 946
  GST_OBJECT_LOCK (clock);
  if (clock->master)
    result = gst_object_ref (clock->master);
  GST_OBJECT_UNLOCK (clock);

  return result;
}

947 948 949
/* http://mathworld.wolfram.com/LeastSquaresFitting.html
 * with SLAVE_LOCK
 */
950
static gboolean
951 952 953
do_linear_regression (GstClock * clock, GstClockTime * m_num,
    GstClockTime * m_denom, GstClockTime * b, GstClockTime * xbase,
    gdouble * r_squared)
954 955 956 957 958 959 960 961 962 963 964
{
  GstClockTime *newx, *newy;
  GstClockTime xmin, ymin, xbar, ybar, xbar4, ybar4;
  GstClockTimeDiff sxx, sxy, syy;
  GstClockTime *x, *y;
  gint i, j;
  guint n;

  xbar = ybar = sxx = syy = sxy = 0;

  x = clock->times;
965 966
  y = clock->times + 2;
  n = clock->filling ? clock->time_index : clock->window_size;
967 968 969

#ifdef DEBUGGING_ENABLED
  DEBUG ("doing regression on:");
970 971
  for (i = j = 0; i < n; i++, j += 4)
    DEBUG ("  %" G_GUINT64_FORMAT "  %" G_GUINT64_FORMAT, x[j], y[j]);
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
#endif

  xmin = ymin = G_MAXUINT64;
  for (i = j = 0; i < n; i++, j += 4) {
    xmin = MIN (xmin, x[j]);
    ymin = MIN (ymin, y[j]);
  }

  DEBUG ("min x: %" G_GUINT64_FORMAT, xmin);
  DEBUG ("min y: %" G_GUINT64_FORMAT, ymin);

  newx = clock->times + 1;
  newy = clock->times + 3;

  /* strip off unnecessary bits of precision */
  for (i = j = 0; i < n; i++, j += 4) {
    newx[j] = x[j] - xmin;
    newy[j