gstclock.c 36.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
 * 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
 *
Wim Taymans's avatar
Wim Taymans committed
39
 * The pipeline uses the clock to calculate the stream time. Usually all
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
40 41
 * 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
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
43 44
 * A clock implementation can support periodic and single shot clock
 * notifications both synchronous and asynchronous.
Wim Taymans's avatar
Wim Taymans committed
45 46
 *
 * One first needs to create a #GstClockID for the periodic or single shot
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
47 48
 * notification using gst_clock_new_single_shot_id() or
 * gst_clock_new_periodic_id().
Wim Taymans's avatar
Wim Taymans committed
49 50 51
 *
 * 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
52 53 54
 * 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
55
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
56
 * Periodic callbacks scheduled async will be repeadedly called automatically
Wim Taymans's avatar
Wim Taymans committed
57
 * until it is unscheduled. To schedule a sync periodic callback,
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
58
 * gst_clock_id_wait() should be called repeadedly.
59
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
60 61
 * 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
62 63
 *
 * A #GstClockID that has been unscheduled cannot be used again for any wait
Wim Taymans's avatar
Wim Taymans committed
64 65
 * 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
66
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
67 68
 * 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
69 70
 * 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
71
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
72 73 74 75
 * 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
76 77
 * 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
78 79 80 81 82 83
 *
 * 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
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
Wim Taymans's avatar
Wim Taymans committed
92 93 94 95 96 97 98 99
 * 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
100
 *
Wim Taymans's avatar
Wim Taymans committed
101
 * Last reviewed on 2006-03-09 (0.10.4)
102
 */
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
103

104
#include <time.h>
105 106

#include "gst_private.h"
107

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

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

118 119
/* #define DEBUGGING_ENABLED */

Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
120 121 122 123
#define DEFAULT_STATS                   FALSE
#define DEFAULT_WINDOW_SIZE             32
#define DEFAULT_WINDOW_THRESHOLD        4
#define DEFAULT_TIMEOUT                 GST_SECOND / 10
124

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

134 135
static void gst_clock_class_init (GstClockClass * klass);
static void gst_clock_init (GstClock * clock);
136
static void gst_clock_dispose (GObject * object);
Wim Taymans's avatar
Wim Taymans committed
137
static void gst_clock_finalize (GObject * object);
Wim Taymans's avatar
Wim Taymans committed
138

139 140 141 142 143
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);
144

145

146
static GstObjectClass *parent_class = NULL;
147

148 149
/* static guint gst_clock_signals[LAST_SIGNAL] = { 0 }; */

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

Wim Taymans's avatar
Wim Taymans committed
156 157 158
  /* FIXME, use g_slice, we do this a lot and potentially from
   * different threads. */
  entry = g_new0 (GstClockEntry, 1);
Wim Taymans's avatar
Wim Taymans committed
159
#ifndef GST_DISABLE_TRACE
Wim Taymans's avatar
Wim Taymans committed
160
  gst_alloc_trace_new (_gst_clock_entry_trace, entry);
Wim Taymans's avatar
Wim Taymans committed
161
#endif
162 163
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
      "created entry %p, time %" GST_TIME_FORMAT, entry, GST_TIME_ARGS (time));
164

165
  gst_atomic_int_set (&entry->refcount, 1);
166 167
  entry->clock = clock;
  entry->time = time;
168
  entry->interval = interval;
169
  entry->type = type;
170
  entry->status = GST_CLOCK_BUSY;
171

172 173
  return (GstClockID) entry;
}
174

175 176
/**
 * gst_clock_id_ref:
Wim Taymans's avatar
Wim Taymans committed
177
 * @id: The #GstClockID to ref
178
 *
Wim Taymans's avatar
Wim Taymans committed
179
 * Increase the refcount of given @id.
180 181 182 183 184 185 186 187 188 189
 *
 * Returns: The same #GstClockID with increased refcount.
 *
 * MT safe.
 */
GstClockID
gst_clock_id_ref (GstClockID id)
{
  g_return_val_if_fail (id != NULL, NULL);

190
  g_atomic_int_inc (&((GstClockEntry *) id)->refcount);
191 192 193 194 195 196 197 198 199 200 201 202 203 204

  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
205
  g_free (id);
206 207 208 209
}

/**
 * gst_clock_id_unref:
Wim Taymans's avatar
Wim Taymans committed
210
 * @id: The #GstClockID to unref
211
 *
Wim Taymans's avatar
Wim Taymans committed
212
 * Unref given @id. When the refcount reaches 0 the
213 214 215 216 217 218 219 220 221 222 223
 * #GstClockID will be freed.
 *
 * MT safe.
 */
void
gst_clock_id_unref (GstClockID id)
{
  gint zero;

  g_return_if_fail (id != NULL);

224
  zero = g_atomic_int_dec_and_test (&((GstClockEntry *) id)->refcount);
225 226 227 228 229 230
  /* if we ended up with the refcount at zero, free the id */
  if (zero) {
    _gst_clock_id_free (id);
  }
}

231 232
/**
 * gst_clock_new_single_shot_id
Wim Taymans's avatar
Wim Taymans committed
233
 * @clock: The #GstClockID to get a single shot notification from
234 235
 * @time: the requested time
 *
Wim Taymans's avatar
Wim Taymans committed
236
 * Get a #GstClockID from @clock to trigger a single shot
237 238
 * notification at the requested time. The single shot id should be
 * unreffed after usage.
239
 *
Wim Taymans's avatar
Wim Taymans committed
240
 * Returns: A #GstClockID that can be used to request the time notification.
241 242
 *
 * MT safe.
243 244
 */
GstClockID
245
gst_clock_new_single_shot_id (GstClock * clock, GstClockTime time)
246
{
247 248
  g_return_val_if_fail (GST_IS_CLOCK (clock), NULL);

249 250
  return gst_clock_entry_new (clock,
      time, GST_CLOCK_TIME_NONE, GST_CLOCK_ENTRY_SINGLE);
251 252 253
}

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

276 277
  return gst_clock_entry_new (clock,
      start_time, interval, GST_CLOCK_ENTRY_PERIODIC);
278 279
}

280 281
/**
 * gst_clock_id_compare_func
Wim Taymans's avatar
Wim Taymans committed
282 283
 * @id1: A #GstClockID
 * @id2: A #GstClockID to compare with
284
 *
Wim Taymans's avatar
Wim Taymans committed
285
 * Compares the two #GstClockID instances. This function can be used
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
 * 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
306
  return 0;
307 308
}

309 310
/**
 * gst_clock_id_get_time
Wim Taymans's avatar
Wim Taymans committed
311
 * @id: The #GstClockID to query
312 313 314
 *
 * Get the time of the clock ID
 *
315 316 317
 * Returns: the time of the given clock id.
 *
 * MT safe.
318 319 320 321 322 323
 */
GstClockTime
gst_clock_id_get_time (GstClockID id)
{
  g_return_val_if_fail (id != NULL, GST_CLOCK_TIME_NONE);

324
  return GST_CLOCK_ENTRY_TIME ((GstClockEntry *) id);
325 326 327 328 329
}


/**
 * gst_clock_id_wait
Wim Taymans's avatar
Wim Taymans committed
330 331 332 333 334 335 336 337 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
 * called. Negative values means @id was scheduled too late (and this
 * function will return #GST_CLOCK_EARLY). Positive values indicate how
 * early @id was scheduled. 
 *
 * 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().
349 350
 *
 * MT safe.
351 352
 */
GstClockReturn
353
gst_clock_id_wait (GstClockID id, GstClockTimeDiff * jitter)
354 355
{
  GstClockEntry *entry;
356
  GstClock *clock;
357
  GstClockReturn res;
358
  GstClockTime requested;
Wim Taymans's avatar
Wim Taymans committed
359
  GstClockClass *cclass;
360

361
  g_return_val_if_fail (id != NULL, GST_CLOCK_ERROR);
362

363 364
  entry = (GstClockEntry *) id;
  requested = GST_CLOCK_ENTRY_TIME (entry);
365

366 367
  clock = GST_CLOCK_ENTRY_CLOCK (entry);

Wim Taymans's avatar
Wim Taymans committed
368
  /* can't sync on invalid times */
369 370 371
  if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (requested)))
    goto invalid_time;

Wim Taymans's avatar
Wim Taymans committed
372
  /* a previously unscheduled entry cannot be scheduled again */
373 374
  if (G_UNLIKELY (entry->status == GST_CLOCK_UNSCHEDULED))
    goto unscheduled;
375

Wim Taymans's avatar
Wim Taymans committed
376
  cclass = GST_CLOCK_GET_CLASS (clock);
377

Wim Taymans's avatar
Wim Taymans committed
378 379
  if (G_UNLIKELY (cclass->wait == NULL))
    goto not_supported;
380

Wim Taymans's avatar
Wim Taymans committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "waiting on clock entry %p", id);

  /* jitter is the diff against the clock when this entry is scheduled */
  if (jitter) {
    GstClockTime now = gst_clock_get_time (clock);

    *jitter = GST_CLOCK_DIFF (requested, now);
  }
  res = cclass->wait (clock, entry);

  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;
396
  }
Wim Taymans's avatar
Wim Taymans committed
397 398 399 400

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

401
  return res;
402 403 404 405

  /* ERRORS */
invalid_time:
  {
406 407
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "invalid time requested, returning _BADTIME");
408 409 410 411
    return GST_CLOCK_BADTIME;
  }
unscheduled:
  {
412 413
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "entry was unscheduled return _UNSCHEDULED");
414 415
    return GST_CLOCK_UNSCHEDULED;
  }
Wim Taymans's avatar
Wim Taymans committed
416 417 418 419 420
not_supported:
  {
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "clock wait is not supported");
    return GST_CLOCK_UNSUPPORTED;
  }
421 422 423
}

/**
Wim Taymans's avatar
Wim Taymans committed
424 425
 * gst_clock_id_wait_async:
 * @id: a #GstClockID to wait on
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
426
 * @func: The callback function
427 428
 * @user_data: User data passed in the calback
 *
Wim Taymans's avatar
Wim Taymans committed
429 430
 * Register a callback on the given #GstClockID @id with the given
 * function and user_data. When passing a #GstClockID with an invalid
431 432
 * 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
433
 * be called when the time of @id has been reached.
434
 *
435
 * Returns: the result of the non blocking wait.
436 437
 *
 * MT safe.
438 439 440
 */
GstClockReturn
gst_clock_id_wait_async (GstClockID id,
441
    GstClockCallback func, gpointer user_data)
442 443 444
{
  GstClockEntry *entry;
  GstClock *clock;
445
  GstClockReturn res;
Wim Taymans's avatar
Wim Taymans committed
446
  GstClockClass *cclass;
447
  GstClockTime requested;
448

449
  g_return_val_if_fail (id != NULL, GST_CLOCK_ERROR);
450
  g_return_val_if_fail (func != NULL, GST_CLOCK_ERROR);
451 452

  entry = (GstClockEntry *) id;
453 454
  requested = GST_CLOCK_ENTRY_TIME (entry);
  clock = GST_CLOCK_ENTRY_CLOCK (entry);
455

Wim Taymans's avatar
Wim Taymans committed
456
  /* can't sync on invalid times */
457 458 459
  if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (requested)))
    goto invalid_time;

Wim Taymans's avatar
Wim Taymans committed
460
  /* a previously unscheduled entry cannot be scheduled again */
461 462
  if (G_UNLIKELY (entry->status == GST_CLOCK_UNSCHEDULED))
    goto unscheduled;
463

Wim Taymans's avatar
Wim Taymans committed
464 465
  cclass = GST_CLOCK_GET_CLASS (clock);

Wim Taymans's avatar
Wim Taymans committed
466 467 468 469 470 471 472
  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
473

474 475
  return res;

476 477 478 479
  /* ERRORS */
invalid_time:
  {
    (func) (clock, GST_CLOCK_TIME_NONE, id, user_data);
480 481
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "invalid time requested, returning _BADTIME");
482 483 484 485
    return GST_CLOCK_BADTIME;
  }
unscheduled:
  {
486 487
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "entry was unscheduled return _UNSCHEDULED");
488 489
    return GST_CLOCK_UNSCHEDULED;
  }
Wim Taymans's avatar
Wim Taymans committed
490 491 492 493 494
not_supported:
  {
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "clock wait is not supported");
    return GST_CLOCK_UNSUPPORTED;
  }
495 496
}

497
/**
Wim Taymans's avatar
Wim Taymans committed
498 499
 * gst_clock_id_unschedule:
 * @id: The id to unschedule
500
 *
Wim Taymans's avatar
Wim Taymans committed
501
 * Cancel an outstanding request with @id. This can either
502
 * be an outstanding async notification or a pending sync notification.
Wim Taymans's avatar
Wim Taymans committed
503 504
 * After this call, @id cannot be used anymore to receive sync or
 * async notifications, you need to create a new #GstClockID.
505 506
 *
 * MT safe.
507 508 509 510 511 512
 */
void
gst_clock_id_unschedule (GstClockID id)
{
  GstClockEntry *entry;
  GstClock *clock;
Wim Taymans's avatar
Wim Taymans committed
513
  GstClockClass *cclass;
514

515 516 517 518
  g_return_if_fail (id != NULL);

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

Wim Taymans's avatar
Wim Taymans committed
520 521
  cclass = GST_CLOCK_GET_CLASS (clock);

Wim Taymans's avatar
Wim Taymans committed
522
  if (G_LIKELY (cclass->unschedule))
Wim Taymans's avatar
Wim Taymans committed
523
    cclass->unschedule (clock, entry);
524 525
}

526 527 528 529

/**
 * GstClock abstract base class implementation
 */
530 531
GType
gst_clock_get_type (void)
Wim Taymans's avatar
Wim Taymans committed
532
{
533 534
  static GType clock_type = 0;

535
  if (G_UNLIKELY (clock_type == 0)) {
536
    static const GTypeInfo clock_info = {
537
      sizeof (GstClockClass),
538 539 540 541 542
      NULL,
      NULL,
      (GClassInitFunc) gst_clock_class_init,
      NULL,
      NULL,
543
      sizeof (GstClock),
544
      0,
545 546 547
      (GInstanceInitFunc) gst_clock_init,
      NULL
    };
548

549
    clock_type = g_type_register_static (GST_TYPE_OBJECT, "GstClock",
550
        &clock_info, G_TYPE_FLAG_ABSTRACT);
551 552 553
  }
  return clock_type;
}
554

555
static void
556
gst_clock_class_init (GstClockClass * klass)
557 558 559
{
  GObjectClass *gobject_class;
  GstObjectClass *gstobject_class;
560

561 562
  gobject_class = (GObjectClass *) klass;
  gstobject_class = (GstObjectClass *) klass;
563

564
  parent_class = g_type_class_ref (GST_TYPE_OBJECT);
565

Wim Taymans's avatar
Wim Taymans committed
566 567 568
  if (!g_thread_supported ())
    g_thread_init (NULL);

Wim Taymans's avatar
Wim Taymans committed
569
#ifndef GST_DISABLE_TRACE
570 571
  _gst_clock_entry_trace =
      gst_alloc_trace_register (GST_CLOCK_ENTRY_TRACE_NAME);
Wim Taymans's avatar
Wim Taymans committed
572
#endif
573

574
  gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_clock_dispose);
Wim Taymans's avatar
Wim Taymans committed
575
  gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_clock_finalize);
576 577 578
  gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_clock_set_property);
  gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_clock_get_property);

579
  g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_STATS,
580
      g_param_spec_boolean ("stats", "Stats", "Enable clock stats",
581 582 583 584 585 586 587 588 589 590 591 592 593 594
          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
595 596
}

597
static void
598
gst_clock_init (GstClock * clock)
Wim Taymans's avatar
Wim Taymans committed
599
{
600 601
  clock->last_time = 0;
  clock->entries = NULL;
602
  clock->entries_changed = g_cond_new ();
603
  clock->stats = FALSE;
604

605 606
  clock->internal_calibration = 0;
  clock->external_calibration = 0;
607 608 609 610
  clock->rate_numerator = 1;
  clock->rate_denominator = 1;

  clock->slave_lock = g_mutex_new ();
611 612
  clock->window_size = DEFAULT_WINDOW_SIZE;
  clock->window_threshold = DEFAULT_WINDOW_THRESHOLD;
Wim Taymans's avatar
Wim Taymans committed
613
  clock->filling = TRUE;
614 615 616
  clock->time_index = 0;
  clock->timeout = DEFAULT_TIMEOUT;
  clock->times = g_new0 (GstClockTime, 4 * clock->window_size);
Wim Taymans's avatar
Wim Taymans committed
617 618
}

619 620 621 622 623 624 625 626 627 628 629 630
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
631
static void
Wim Taymans's avatar
Wim Taymans committed
632
gst_clock_finalize (GObject * object)
Wim Taymans's avatar
Wim Taymans committed
633 634 635
{
  GstClock *clock = GST_CLOCK (object);

636
  GST_CLOCK_SLAVE_LOCK (clock);
637 638 639 640 641 642 643
  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;
644
  GST_CLOCK_SLAVE_UNLOCK (clock);
645

646
  g_cond_free (clock->entries_changed);
647 648
  g_mutex_free (clock->slave_lock);

Wim Taymans's avatar
Wim Taymans committed
649
  G_OBJECT_CLASS (parent_class)->finalize (object);
Wim Taymans's avatar
Wim Taymans committed
650 651
}

Wim Taymans's avatar
Wim Taymans committed
652
/**
653
 * gst_clock_set_resolution
654
 * @clock: a #GstClock
655
 * @resolution: The resolution to set
Wim Taymans's avatar
Wim Taymans committed
656
 *
657 658 659
 * Set the accuracy of the clock.
 *
 * Returns: the new resolution of the clock.
Wim Taymans's avatar
Wim Taymans committed
660
 */
661 662
GstClockTime
gst_clock_set_resolution (GstClock * clock, GstClockTime resolution)
Wim Taymans's avatar
Wim Taymans committed
663
{
Wim Taymans's avatar
Wim Taymans committed
664 665
  GstClockClass *cclass;

666 667
  g_return_val_if_fail (GST_IS_CLOCK (clock), 0);
  g_return_val_if_fail (resolution != 0, 0);
668

Wim Taymans's avatar
Wim Taymans committed
669 670 671
  cclass = GST_CLOCK_GET_CLASS (clock);

  if (cclass->change_resolution)
672
    clock->resolution =
673
        cclass->change_resolution (clock, clock->resolution, resolution);
674

675 676
  return clock->resolution;
}
677

678 679
/**
 * gst_clock_get_resolution
680
 * @clock: a #GstClock
681 682 683
 *
 * Get the accuracy of the clock.
 *
684
 * Returns: the resolution of the clock in units of #GstClockTime.
685 686
 *
 * MT safe.
687
 */
688
GstClockTime
689
gst_clock_get_resolution (GstClock * clock)
690
{
Wim Taymans's avatar
Wim Taymans committed
691 692
  GstClockClass *cclass;

693
  g_return_val_if_fail (GST_IS_CLOCK (clock), 0);
694

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

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

700
  return 1;
Wim Taymans's avatar
Wim Taymans committed
701 702
}

Wim Taymans's avatar
Wim Taymans committed
703
/**
704 705 706
 * gst_clock_adjust_unlocked
 * @clock: a #GstClock to use
 * @internal: a clock time
Wim Taymans's avatar
Wim Taymans committed
707
 *
708
 * Converts the given @internal clock time to the real time, adjusting for the
709 710
 * 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
711
 * clock's OBJECT_LOCK held and is mainly used by clock subclasses.
Wim Taymans's avatar
Wim Taymans committed
712
 *
713
 * Returns: the converted time of the clock.
714
 *
715
 * MT safe.
716
 */
717 718
GstClockTime
gst_clock_adjust_unlocked (GstClock * clock, GstClockTime internal)
719
{
720
  GstClockTime ret;
721

722 723
  ret = gst_util_uint64_scale (internal - clock->internal_calibration,
      clock->rate_numerator, clock->rate_denominator);
724
  ret += clock->external_calibration;
725 726 727 728 729

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

  return clock->last_time;
730 731
}

Wim Taymans's avatar
Wim Taymans committed
732
/**
733
 * gst_clock_get_internal_time
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
734
 * @clock: a #GstClock to query
Wim Taymans's avatar
Wim Taymans committed
735
 *
736 737
 * Gets the current internal time of the given clock. The time is returned
 * unadjusted for the offset and the rate.
738
 *
739
 * Returns: the internal time of the clock. Or GST_CLOCK_TIME_NONE when
740 741 742
 * giving wrong input.
 *
 * MT safe.
Wim Taymans's avatar
Wim Taymans committed
743
 */
744
GstClockTime
745
gst_clock_get_internal_time (GstClock * clock)
746
{
747
  GstClockTime ret;
748
  GstClockClass *cclass;
749

750
  g_return_val_if_fail (GST_IS_CLOCK (clock), GST_CLOCK_TIME_NONE);
751

752
  cclass = GST_CLOCK_GET_CLASS (clock);
Wim Taymans's avatar
Wim Taymans committed
753

Wim Taymans's avatar
Wim Taymans committed
754 755 756 757 758
  if (G_UNLIKELY (cclass->get_internal_time == NULL))
    goto not_supported;

  ret = cclass->get_internal_time (clock);

759
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "internal time %" GST_TIME_FORMAT,
760
      GST_TIME_ARGS (ret));
761

762
  return ret;
Wim Taymans's avatar
Wim Taymans committed
763 764 765 766 767 768 769 770

  /* ERRORS */
not_supported:
  {
    GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock,
        "internal time not supported, return 0");
    return G_GINT64_CONSTANT (0);
  }
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
}

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

795
  GST_OBJECT_LOCK (clock);
796
  /* this will scale for rate and offset */
797
  ret = gst_clock_adjust_unlocked (clock, ret);
798
  GST_OBJECT_UNLOCK (clock);
799

800
  GST_CAT_DEBUG_OBJECT (GST_CAT_CLOCK, clock, "adjusted time %" GST_TIME_FORMAT,
801
      GST_TIME_ARGS (ret));
802

803
  return ret;
804 805
}

806 807 808 809 810
/**
 * gst_clock_set_calibration
 * @clock: a #GstClock to calibrate
 * @internal: a reference internal time
 * @external: a reference external time
811 812 813
 * @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
814
 *
815 816
 * 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.
817 818 819 820 821
 *
 * @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.
822 823 824 825 826
 *
 * Subsequent calls to gst_clock_get_time() will return clock times computed as
 * follows:
 *
 * <programlisting>
827
 *   time = (internal_time - @internal) * @rate_num / @rate_denom + @external
828 829
 * </programlisting>
 *
830 831 832
 * This formula is implemented in gst_clock_adjust_unlocked(). Of course, it
 * tries to do the integer arithmetic as precisely as possible.
 *
833 834 835 836 837 838 839
 * 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
840
gst_clock_set_calibration (GstClock * clock, GstClockTime internal, GstClockTime
841
    external, GstClockTime rate_num, GstClockTime rate_denom)
842 843
{
  g_return_if_fail (GST_IS_CLOCK (clock));
844
  g_return_if_fail (rate_num >= 0);
845
  g_return_if_fail (rate_denom > 0);
846
  g_return_if_fail (internal <= gst_clock_get_internal_time (clock));
847

848
  GST_OBJECT_LOCK (clock);
849 850
  clock->internal_calibration = internal;
  clock->external_calibration = external;
851 852
  clock->rate_numerator = rate_num;
  clock->rate_denominator = rate_denom;
853
  GST_OBJECT_UNLOCK (clock);
854 855 856
}

/**
857 858 859 860
 * gst_clock_get_calibration
 * @clock: a #GstClock 
 * @internal: a location to store the internal time
 * @external: a location to store the external time
861 862
 * @rate_num: a location to store the rate numerator
 * @rate_denom: a location to store the rate denominator
863
 *
864 865
 * Gets the internal rate and reference time of @clock. See
 * gst_clock_set_calibration() for more information.
866
 *
867 868
 * @internal, @external, @rate_num, and @rate_denom can be left NULL if the
 * caller is not interested in the values.
869
 *
870 871 872
 * MT safe.
 */
void
873
gst_clock_get_calibration (GstClock * clock, GstClockTime * internal,
874
    GstClockTime * external, GstClockTime * rate_num, GstClockTime * rate_denom)
875 876 877
{
  g_return_if_fail (GST_IS_CLOCK (clock));

878
  GST_OBJECT_LOCK (clock);
879 880 881 882
  if (rate_num)
    *rate_num = clock->rate_numerator;
  if (rate_denom)
    *rate_denom = clock->rate_denominator;
883
  if (external)
884
    *external = clock->external_calibration;
885
  if (internal)
886
    *internal = clock->internal_calibration;
887
  GST_OBJECT_UNLOCK (clock);
888 889
}

890
/* will be called repeadedly to sample the master and slave clock
Wim Taymans's avatar
Wim Taymans committed
891
 * to recalibrate the clock  */
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
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;
}

914 915 916 917 918 919 920 921 922 923 924 925
/**
 * 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().
 *
Wim Taymans's avatar
Wim Taymans committed
926 927 928 929 930 931 932
 * @master can be NULL in which case @clock will not be slaved anymore. It will
 * however keep reporting its time adjusted with the last configured rate 
 * and time offsets.
 *
 * Returns: TRUE if the clock is capable of being slaved to a master clock. 
 * Trying to set a master on a clock without the 
 * GST_CLOCK_FLAG_CAN_SET_MASTER flag will make this function return FALSE.
933
 *
934 935
 * MT safe.
 */
936
gboolean
937 938
gst_clock_set_master (GstClock * clock, GstClock * master)
{
939
  g_return_val_if_fail (GST_IS_CLOCK (clock), FALSE);
940
  g_return_val_if_fail (master != clock, FALSE);
941