gstclock.c 33.6 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
 * The #GstClock returns a monotonically increasing time with the method
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
34 35
 * gst_clock_get_time(). Its accuracy and base time depends on the specific
 * clock implementation but time is always expessed 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
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
39 40 41
 * The pipeline uses the clock to calculate the stream time.  Usually all
 * renderers synchronize to the global clock using the buffer timestamps, the
 * newsegment events and the element's base time.
Wim Taymans's avatar
Wim Taymans committed
42
 *
Stefan Kost's avatar
Stefan Kost committed
43
 * The time of the clock in itself is not very useful for an application.
Wim Taymans's avatar
Wim Taymans committed
44
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
45 46
 * A clock implementation can support periodic and single shot clock
 * notifications both synchronous and asynchronous.
Wim Taymans's avatar
Wim Taymans committed
47 48
 *
 * One first needs to create a #GstClockID for the periodic or single shot
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
49 50
 * notification using gst_clock_new_single_shot_id() or
 * gst_clock_new_periodic_id().
Wim Taymans's avatar
Wim Taymans committed
51 52 53
 *
 * 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
54 55 56
 * 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
57
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
58 59 60
 * 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.
61
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
62 63
 * 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
64 65 66 67
 *
 * A #GstClockID that has been unscheduled cannot be used again for any wait
 * operation.
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
68 69 70
 * 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.
Wim Taymans's avatar
Wim Taymans committed
71
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
72 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
 * state changes and if we unref it automatically, the handle might be invalid.
Wim Taymans's avatar
Wim Taymans committed
77 78 79 80 81 82
 *
 * 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
83 84 85 86 87 88 89 90 91
 * 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
92
 *
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
/* #define DEBUGGING_ENABLED */

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
112 113 114 115
#define DEFAULT_STATS                   FALSE
#define DEFAULT_WINDOW_SIZE             32
#define DEFAULT_WINDOW_THRESHOLD        4
#define DEFAULT_TIMEOUT                 GST_SECOND / 10
116

117 118
enum
{
119 120 121 122 123
  PROP_0,
  PROP_STATS,
  PROP_WINDOW_SIZE,
  PROP_WINDOW_THRESHOLD,
  PROP_TIMEOUT
124 125
};

126 127
static void gst_clock_class_init (GstClockClass * klass);
static void gst_clock_init (GstClock * clock);
128
static void gst_clock_dispose (GObject * object);
Wim Taymans's avatar
Wim Taymans committed
129
static void gst_clock_finalize (GObject * object);
Wim Taymans's avatar
Wim Taymans committed
130

131 132 133 134 135
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);
136

137

138
static GstObjectClass *parent_class = NULL;
139

140 141
/* static guint gst_clock_signals[LAST_SIGNAL] = { 0 }; */

Wim Taymans's avatar
Wim Taymans committed
142
static GstClockID
143 144
gst_clock_entry_new (GstClock * clock, GstClockTime time,
    GstClockTime interval, GstClockEntryType type)
145 146
{
  GstClockEntry *entry;
147

148
  entry = g_malloc0 (sizeof (GstClockEntry));
Wim Taymans's avatar
Wim Taymans committed
149
#ifndef GST_DISABLE_TRACE
Wim Taymans's avatar
Wim Taymans committed
150
  gst_alloc_trace_new (_gst_clock_entry_trace, entry);
Wim Taymans's avatar
Wim Taymans committed
151
#endif
152 153
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
      "created entry %p, time %" GST_TIME_FORMAT, entry, GST_TIME_ARGS (time));
154

155
  gst_atomic_int_set (&entry->refcount, 1);
156 157
  entry->clock = clock;
  entry->time = time;
158
  entry->interval = interval;
159
  entry->type = type;
160
  entry->status = GST_CLOCK_BUSY;
161

162 163
  return (GstClockID) entry;
}
164

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
/**
 * 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);

180
  g_atomic_int_inc (&((GstClockEntry *) id)->refcount);
181 182 183 184 185 186 187 188 189 190 191 192 193 194

  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
195
  g_free (id);
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
}

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

214
  zero = g_atomic_int_dec_and_test (&((GstClockEntry *) id)->refcount);
215 216 217 218 219 220
  /* if we ended up with the refcount at zero, free the id */
  if (zero) {
    _gst_clock_id_free (id);
  }
}

221 222 223 224 225
/**
 * 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
226
 * Get an ID from the given clock to trigger a single shot
227 228
 * notification at the requested time. The single shot id should be
 * unreffed after usage.
229 230
 *
 * Returns: An id that can be used to request the time notification.
231 232
 *
 * MT safe.
233 234
 */
GstClockID
235
gst_clock_new_single_shot_id (GstClock * clock, GstClockTime time)
236
{
237 238
  g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);

239 240
  return gst_clock_entry_new (clock,
      time, GST_CLOCK_TIME_NONE, GST_CLOCK_ENTRY_SINGLE);
241 242 243
}

/**
Wim Taymans's avatar
Wim Taymans committed
244
 * gst_clock_new_periodic_id
245 246 247 248 249 250
 * @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
251 252
 * will then be fired with the given interval. The id should be unreffed
 * after usage.
253 254
 *
 * Returns: An id that can be used to request the time notification.
255 256
 *
 * MT safe.
257 258
 */
GstClockID
259 260
gst_clock_new_periodic_id (GstClock * clock, GstClockTime start_time,
    GstClockTime interval)
261
{
262
  g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);
263
  g_return_val_if_fail (GST_CLOCK_TIME_IS_VALID (start_time), NULL);
264 265
  g_return_val_if_fail (interval != 0, NULL);

266 267
  return gst_clock_entry_new (clock,
      start_time, interval, GST_CLOCK_ENTRY_PERIODIC);
268 269
}

270 271 272 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
/**
 * 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;
}

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

315
  return GST_CLOCK_ENTRY_TIME ((GstClockEntry *) id);
316 317 318 319 320 321 322 323 324
}


/**
 * 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
325
 * NULL.
326 327
 *
 * Returns: the result of the blocking wait.
328 329
 *
 * MT safe.
330 331
 */
GstClockReturn
332
gst_clock_id_wait (GstClockID id, GstClockTimeDiff * jitter)
333 334
{
  GstClockEntry *entry;
335
  GstClock *clock;
336
  GstClockReturn res;
337
  GstClockTime requested;
Wim Taymans's avatar
Wim Taymans committed
338
  GstClockClass *cclass;
339

340
  g_return_val_if_fail (id != NULL, GST_CLOCK_ERROR);
341

342 343
  entry = (GstClockEntry *) id;
  requested = GST_CLOCK_ENTRY_TIME (entry);
344

345 346
  clock = GST_CLOCK_ENTRY_CLOCK (entry);

347 348 349 350 351
  if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (requested)))
    goto invalid_time;

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

Wim Taymans's avatar
Wim Taymans committed
353
  cclass = GST_CLOCK_GET_CLASS (clock);
354

355
  if (G_LIKELY (cclass->wait)) {
356

357 358
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "waiting on clock entry %p",
        id);
359
    res = cclass->wait (clock, entry);
360 361
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "done waiting entry %p, res: %d", id, res);
362

363
    if (jitter) {
364 365
      GstClockTime now = gst_clock_get_time (clock);

366 367
      *jitter = now - requested;
    }
368 369 370
    if (entry->type == GST_CLOCK_ENTRY_PERIODIC) {
      entry->time += entry->interval;
    }
371 372 373 374

    if (clock->stats) {
      gst_clock_update_stats (clock);
    }
375 376
  } else {
    res = GST_CLOCK_UNSUPPORTED;
377 378
  }
  return res;
379 380 381 382

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

/**
Wim Taymans's avatar
Wim Taymans committed
396 397
 * gst_clock_id_wait_async:
 * @id: a #GstClockID to wait on
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
398
 * @func: The callback function
399 400
 * @user_data: User data passed in the calback
 *
Wim Taymans's avatar
Wim Taymans committed
401
 * Register a callback on the given clockid with the given
402 403 404 405
 * 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.
406
 *
407
 * Returns: the result of the non blocking wait.
408 409
 *
 * MT safe.
410 411 412
 */
GstClockReturn
gst_clock_id_wait_async (GstClockID id,
413
    GstClockCallback func, gpointer user_data)
414 415 416
{
  GstClockEntry *entry;
  GstClock *clock;
417
  GstClockReturn res;
Wim Taymans's avatar
Wim Taymans committed
418
  GstClockClass *cclass;
419
  GstClockTime requested;
420

421
  g_return_val_if_fail (id != NULL, GST_CLOCK_ERROR);
422
  g_return_val_if_fail (func != NULL, GST_CLOCK_ERROR);
423 424

  entry = (GstClockEntry *) id;
425 426
  requested = GST_CLOCK_ENTRY_TIME (entry);
  clock = GST_CLOCK_ENTRY_CLOCK (entry);
427

428 429 430 431 432
  if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (requested)))
    goto invalid_time;

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

Wim Taymans's avatar
Wim Taymans committed
434 435 436 437 438 439 440
  cclass = GST_CLOCK_GET_CLASS (clock);

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

    res = cclass->wait_async (clock, entry);
441 442
  } else {
    res = GST_CLOCK_UNSUPPORTED;
443 444 445
  }
  return res;

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

462
/**
Wim Taymans's avatar
Wim Taymans committed
463 464
 * gst_clock_id_unschedule:
 * @id: The id to unschedule
465
 *
466 467 468 469 470 471
 * 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.
472 473 474 475 476 477
 */
void
gst_clock_id_unschedule (GstClockID id)
{
  GstClockEntry *entry;
  GstClock *clock;
Wim Taymans's avatar
Wim Taymans committed
478
  GstClockClass *cclass;
479

480 481 482 483
  g_return_if_fail (id != NULL);

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

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

  if (cclass->unschedule)
    cclass->unschedule (clock, entry);
489 490
}

491 492 493 494

/**
 * GstClock abstract base class implementation
 */
495 496
GType
gst_clock_get_type (void)
Wim Taymans's avatar
Wim Taymans committed
497
{
498 499
  static GType clock_type = 0;

500
  if (G_UNLIKELY (clock_type == 0)) {
501
    static const GTypeInfo clock_info = {
502
      sizeof (GstClockClass),
503 504 505 506 507
      NULL,
      NULL,
      (GClassInitFunc) gst_clock_class_init,
      NULL,
      NULL,
508
      sizeof (GstClock),
509
      0,
510 511 512
      (GInstanceInitFunc) gst_clock_init,
      NULL
    };
513

514
    clock_type = g_type_register_static (GST_TYPE_OBJECT, "GstClock",
515
        &clock_info, G_TYPE_FLAG_ABSTRACT);
516 517 518
  }
  return clock_type;
}
519

520
static void
521
gst_clock_class_init (GstClockClass * klass)
522 523 524
{
  GObjectClass *gobject_class;
  GstObjectClass *gstobject_class;
525

526 527
  gobject_class = (GObjectClass *) klass;
  gstobject_class = (GstObjectClass *) klass;
528

529
  parent_class = g_type_class_ref (GST_TYPE_OBJECT);
530

Wim Taymans's avatar
Wim Taymans committed
531 532 533
  if (!g_thread_supported ())
    g_thread_init (NULL);

Wim Taymans's avatar
Wim Taymans committed
534
#ifndef GST_DISABLE_TRACE
535 536
  _gst_clock_entry_trace =
      gst_alloc_trace_register (GST_CLOCK_ENTRY_TRACE_NAME);
Wim Taymans's avatar
Wim Taymans committed
537
#endif
538

539
  gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_clock_dispose);
Wim Taymans's avatar
Wim Taymans committed
540
  gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_clock_finalize);
541 542 543
  gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_clock_set_property);
  gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_clock_get_property);

544
  g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_STATS,
545
      g_param_spec_boolean ("stats", "Stats", "Enable clock stats",
546 547 548 549 550 551 552 553 554 555 556 557 558 559
          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
560 561
}

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

570 571
  clock->internal_calibration = 0;
  clock->external_calibration = 0;
572 573 574 575
  clock->rate_numerator = 1;
  clock->rate_denominator = 1;

  clock->slave_lock = g_mutex_new ();
576 577 578 579 580 581
  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
582 583
}

584 585 586 587 588 589 590 591 592 593 594 595
static void
gst_clock_dispose (GObject * object)
{
  GstClock *clock = GST_CLOCK (object);

  GST_OBJECT_LOCK (clock);
  gst_object_replace ((GstObject **) & clock->master, NULL);
  GST_OBJECT_UNLOCK (clock);

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

Wim Taymans's avatar
Wim Taymans committed
596
static void
Wim Taymans's avatar
Wim Taymans committed
597
gst_clock_finalize (GObject * object)
Wim Taymans's avatar
Wim Taymans committed
598 599 600
{
  GstClock *clock = GST_CLOCK (object);

601
  GST_CLOCK_SLAVE_LOCK (clock);
602 603 604 605 606 607 608
  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;
609
  GST_CLOCK_SLAVE_UNLOCK (clock);
610

611
  g_cond_free (clock->entries_changed);
612 613
  g_mutex_free (clock->slave_lock);

Wim Taymans's avatar
Wim Taymans committed
614
  G_OBJECT_CLASS (parent_class)->finalize (object);
Wim Taymans's avatar
Wim Taymans committed
615 616
}

Wim Taymans's avatar
Wim Taymans committed
617
/**
618
 * gst_clock_set_resolution
619
 * @clock: a #GstClock
620
 * @resolution: The resolution to set
Wim Taymans's avatar
Wim Taymans committed
621
 *
622 623 624
 * Set the accuracy of the clock.
 *
 * Returns: the new resolution of the clock.
Wim Taymans's avatar
Wim Taymans committed
625
 */
626 627
GstClockTime
gst_clock_set_resolution (GstClock * clock, GstClockTime resolution)
Wim Taymans's avatar
Wim Taymans committed
628
{
Wim Taymans's avatar
Wim Taymans committed
629 630
  GstClockClass *cclass;

631 632
  g_return_val_if_fail (GST_IS_CLOCK (clock), 0);
  g_return_val_if_fail (resolution != 0, 0);
633

Wim Taymans's avatar
Wim Taymans committed
634 635 636
  cclass = GST_CLOCK_GET_CLASS (clock);

  if (cclass->change_resolution)
637
    clock->resolution =
638
        cclass->change_resolution (clock, clock->resolution, resolution);
639

640 641
  return clock->resolution;
}
642

643 644
/**
 * gst_clock_get_resolution
645
 * @clock: a #GstClock
646 647 648
 *
 * Get the accuracy of the clock.
 *
649
 * Returns: the resolution of the clock in units of #GstClockTime.
650 651
 *
 * MT safe.
652
 */
653
GstClockTime
654
gst_clock_get_resolution (GstClock * clock)
655
{
Wim Taymans's avatar
Wim Taymans committed
656 657
  GstClockClass *cclass;

658
  g_return_val_if_fail (GST_IS_CLOCK (clock), 0);
659

Wim Taymans's avatar
Wim Taymans committed
660 661 662 663
  cclass = GST_CLOCK_GET_CLASS (clock);

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

665
  return 1;
Wim Taymans's avatar
Wim Taymans committed
666 667
}

Wim Taymans's avatar
Wim Taymans committed
668
/**
669 670 671
 * gst_clock_adjust_unlocked
 * @clock: a #GstClock to use
 * @internal: a clock time
Wim Taymans's avatar
Wim Taymans committed
672
 *
673
 * Converts the given @internal clock time to the real time, adjusting for the
674 675
 * 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
676
 * clock's OBJECT_LOCK held and is mainly used by clock subclasses.
Wim Taymans's avatar
Wim Taymans committed
677
 *
678
 * Returns: the converted time of the clock.
679
 *
680
 * MT safe.
681
 */
682 683
GstClockTime
gst_clock_adjust_unlocked (GstClock * clock, GstClockTime internal)
684
{
685
  GstClockTime ret;
686

687 688
  ret = gst_util_uint64_scale (internal - clock->internal_calibration,
      clock->rate_numerator, clock->rate_denominator);
689
  ret += clock->external_calibration;
690 691 692 693 694

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

  return clock->last_time;
695 696
}

Wim Taymans's avatar
Wim Taymans committed
697
/**
698
 * gst_clock_get_internal_time
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
699
 * @clock: a #GstClock to query
Wim Taymans's avatar
Wim Taymans committed
700
 *
701 702
 * Gets the current internal time of the given clock. The time is returned
 * unadjusted for the offset and the rate.
703
 *
704
 * Returns: the internal time of the clock. Or GST_CLOCK_TIME_NONE when
705 706 707
 * giving wrong input.
 *
 * MT safe.
Wim Taymans's avatar
Wim Taymans committed
708
 */
709
GstClockTime
710
gst_clock_get_internal_time (GstClock * clock)
711
{
712
  GstClockTime ret;
713
  GstClockClass *cclass;
714

715
  g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);
716

717
  cclass = GST_CLOCK_GET_CLASS (clock);
Wim Taymans's avatar
Wim Taymans committed
718

719
  if (cclass->get_internal_time) {
720
    ret = cclass->get_internal_time (clock);
721
  } else {
722
    ret = G_GINT64_CONSTANT (0);
723
  }
724
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "internal time %" GST_TIME_FORMAT,
725
      GST_TIME_ARGS (ret));
726

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
  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);

752
  GST_OBJECT_LOCK (clock);
753
  /* this will scale for rate and offset */
754
  ret = gst_clock_adjust_unlocked (clock, ret);
755
  GST_OBJECT_UNLOCK (clock);
756

757
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "adjusted time %" GST_TIME_FORMAT,
758
      GST_TIME_ARGS (ret));
759

760
  return ret;
761 762
}

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

805
  GST_OBJECT_LOCK (clock);
806 807
  clock->internal_calibration = internal;
  clock->external_calibration = external;
808 809
  clock->rate_numerator = rate_num;
  clock->rate_denominator = rate_denom;
810
  GST_OBJECT_UNLOCK (clock);
811 812 813
}

/**
814 815 816 817
 * gst_clock_get_calibration
 * @clock: a #GstClock 
 * @internal: a location to store the internal time
 * @external: a location to store the external time
818 819
 * @rate_num: a location to store the rate numerator
 * @rate_denom: a location to store the rate denominator
820
 *
821 822
 * Gets the internal rate and reference time of @clock. See
 * gst_clock_set_calibration() for more information.
823
 *
824 825
 * @internal, @external, @rate_num, and @rate_denom can be left NULL if the
 * caller is not interested in the values.
826
 *
827 828 829
 * MT safe.
 */
void
830
gst_clock_get_calibration (GstClock * clock, GstClockTime * internal,
831
    GstClockTime * external, GstClockTime * rate_num, GstClockTime * rate_denom)
832 833 834
{
  g_return_if_fail (GST_IS_CLOCK (clock));

835
  GST_OBJECT_LOCK (clock);
836 837 838 839
  if (rate_num)
    *rate_num = clock->rate_numerator;
  if (rate_denom)
    *rate_denom = clock->rate_denominator;
840
  if (external)
841
    *external = clock->external_calibration;
842
  if (internal)
843
    *internal = clock->internal_calibration;
844
  GST_OBJECT_UNLOCK (clock);
845 846
}

847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
/* 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;
}

871 872 873 874 875 876 877 878 879 880 881 882
/**
 * 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().
 *
883 884
 * Returns: TRUE if the clock is capable of being slaved to a master clock.
 *
885 886
 * MT safe.
 */
887
gboolean
888 889
gst_clock_set_master (GstClock * clock, GstClock * master)
{
890
  g_return_val_if_fail (GST_IS_CLOCK (clock), FALSE);
891
  g_return_val_if_fail (master != clock, FALSE);
892

893
  GST_OBJECT_LOCK (clock);
894 895 896 897 898
  /* 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);
899
  gst_object_replace ((GstObject **) & clock->master, (GstObject *) master);
900 901 902
  GST_OBJECT_UNLOCK (clock);

  GST_CLOCK_SLAVE_LOCK (clock);
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
  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);
  }
918
  GST_CLOCK_SLAVE_UNLOCK (clock);
919 920 921 922 923 924

  return TRUE;

not_supported:
  {
    GST_DEBUG_OBJECT (clock, "cannot be slaved to a master clock");
925
    GST_OBJECT_UNLOCK (clock);
926 927
    return FALSE;
  }
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
}

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

947 948
  g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);

949 950 951 952 953 954 955 956
  GST_OBJECT_LOCK (clock);
  if (clock->master)
    result = gst_object_ref (clock->master);
  GST_OBJECT_UNLOCK (clock);

  return result;
}

957 958 959
/* http://mathworld.wolfram.com/LeastSquaresFitting.html
 * with SLAVE_LOCK
 */
960
static gboolean
961 962 963
do_linear_regression (GstClock * clock, GstClockTime * m_num,
    GstClockTime * m_denom, GstClockTime * b, GstClockTime * xbase,
    gdouble * r_squared)
964 965 966 967 968 969 970 971 972 973 974
{
  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;
975 976
  y = clock->times + 2;
  n = clock->filling ? clock->time_index : clock->window_size;
977 978

#ifdef DEBUGGING_ENABLED
979
  GST_DEBUG ("doing regression on:");
980
  for (i = j = 0; i < n; i++, j += 4)
981
    GST_DEBUG ("  %" G_GUINT64_FORMAT "  %" G_GUINT64_FORMAT, x[j], y[j]);
982 983 984 985 986 987 988 989
#endif

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

990 991 992