2 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3 * 2005 Wim Taymans <wim@fluendo.com>
4 * 2005 Andy Wingo <wingo@pobox.com>
5 * Copyright (C) 2012 Collabora Ltd. <tim.muller@collabora.co.uk>
6 * Copyright (C) 2015 Sebastian Dröge <sebastian@centricular.com>
8 * gstnetclientclock.h: clock that synchronizes itself to a time provider over
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public
22 * License along with this library; if not, write to the
23 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
27 * SECTION:gstnetclientclock
28 * @short_description: Special clock that synchronizes to a remote time
30 * @see_also: #GstClock, #GstNetTimeProvider, #GstPipeline
32 * #GstNetClientClock implements a custom #GstClock that synchronizes its time
33 * to a remote time provider such as #GstNetTimeProvider. #GstNtpClock
34 * implements a #GstClock that synchronizes its time to a remote NTPv4 server.
36 * A new clock is created with gst_net_client_clock_new() or
37 * gst_ntp_clock_new(), which takes the address and port of the remote time
38 * provider along with a name and an initial time.
40 * This clock will poll the time provider and will update its calibration
41 * parameters based on the local and remote observations.
43 * The "round-trip" property limits the maximum round trip packets can take.
45 * Various parameters of the clock can be configured with the parent #GstClock
46 * "timeout", "window-size" and "window-threshold" object properties.
48 * A #GstNetClientClock and #GstNtpClock is typically set on a #GstPipeline with
49 * gst_pipeline_use_clock().
51 * If you set a #GstBus on the clock via the "bus" object property, it will
52 * send @GST_MESSAGE_ELEMENT messages with an attached #GstStructure containing
53 * statistics about clock accuracy and network traffic.
60 #include "gstnettimepacket.h"
61 #include "gstntppacket.h"
62 #include "gstnetclientclock.h"
68 GST_DEBUG_CATEGORY_STATIC (ncc_debug);
69 #define GST_CAT_DEFAULT (ncc_debug)
71 #define DEFAULT_ADDRESS "127.0.0.1"
72 #define DEFAULT_PORT 5637
73 #define DEFAULT_TIMEOUT GST_SECOND
74 #define DEFAULT_ROUNDTRIP_LIMIT GST_SECOND
75 /* Minimum timeout will be immediately (ie, as fast as one RTT), but no
76 * more often than 1/20th second (arbitrarily, to spread observations a little) */
77 #define DEFAULT_MINIMUM_UPDATE_INTERVAL (GST_SECOND / 20)
78 #define DEFAULT_BASE_TIME 0
80 /* Maximum number of clock updates we can skip before updating */
81 #define MAX_SKIPPED_UPDATES 5
83 #define MEDIAN_PRE_FILTERING_WINDOW 9
91 PROP_MINIMUM_UPDATE_INTERVAL,
97 #define GST_NET_CLIENT_CLOCK_GET_PRIVATE(obj) \
98 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_NET_CLIENT_CLOCK, GstNetClientClockPrivate))
100 struct _GstNetClientClockPrivate
102 GstClock *internal_clock;
107 GSocketAddress *servaddr;
108 GCancellable *cancel;
109 gboolean made_cancel_fd;
111 GstClockTime timeout_expiration;
112 GstClockTime roundtrip_limit;
113 GstClockTime rtt_avg;
114 GstClockTime minimum_update_interval;
115 GstClockTime last_remote_poll_interval;
116 guint skipped_updates;
117 GstClockTime last_rtts[MEDIAN_PRE_FILTERING_WINDOW];
118 gint last_rtts_missing;
120 GstClockTime base_time;
131 GST_DEBUG_CATEGORY_INIT (ncc_debug, "netclock", 0, "Network client clock");
132 #define gst_net_client_clock_parent_class parent_class
133 G_DEFINE_TYPE_WITH_CODE (GstNetClientClock, gst_net_client_clock,
134 GST_TYPE_SYSTEM_CLOCK, _do_init);
136 static void gst_net_client_clock_finalize (GObject * object);
137 static void gst_net_client_clock_set_property (GObject * object, guint prop_id,
138 const GValue * value, GParamSpec * pspec);
139 static void gst_net_client_clock_get_property (GObject * object, guint prop_id,
140 GValue * value, GParamSpec * pspec);
141 static void gst_net_client_clock_constructed (GObject * object);
143 static gboolean gst_net_client_clock_start (GstNetClientClock * self);
144 static void gst_net_client_clock_stop (GstNetClientClock * self);
146 static GstClockTime gst_net_client_clock_get_internal_time (GstClock * clock);
149 gst_net_client_clock_class_init (GstNetClientClockClass * klass)
151 GObjectClass *gobject_class;
152 GstClockClass *clock_class;
154 gobject_class = G_OBJECT_CLASS (klass);
155 clock_class = GST_CLOCK_CLASS (klass);
157 g_type_class_add_private (klass, sizeof (GstNetClientClockPrivate));
159 gobject_class->finalize = gst_net_client_clock_finalize;
160 gobject_class->get_property = gst_net_client_clock_get_property;
161 gobject_class->set_property = gst_net_client_clock_set_property;
162 gobject_class->constructed = gst_net_client_clock_constructed;
164 g_object_class_install_property (gobject_class, PROP_ADDRESS,
165 g_param_spec_string ("address", "address",
166 "The IP address of the machine providing a time server",
168 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
169 g_object_class_install_property (gobject_class, PROP_PORT,
170 g_param_spec_int ("port", "port",
171 "The port on which the remote server is listening", 0, G_MAXUINT16,
173 G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
174 g_object_class_install_property (gobject_class, PROP_BUS,
175 g_param_spec_object ("bus", "bus",
176 "A GstBus on which to send clock status information", GST_TYPE_BUS,
177 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
180 * GstNetClientClock::round-trip-limit:
182 * Maximum allowed round-trip for packets. If this property is set to a nonzero
183 * value, all packets with a round-trip interval larger than this limit will be
184 * ignored. This is useful for networks with severe and fluctuating transport
185 * delays. Filtering out these packets increases stability of the synchronization.
186 * On the other hand, the lower the limit, the higher the amount of filtered
187 * packets. Empirical tests are typically necessary to estimate a good value
189 * If the property is set to zero, the limit is disabled.
193 g_object_class_install_property (gobject_class, PROP_ROUNDTRIP_LIMIT,
194 g_param_spec_uint64 ("round-trip-limit", "round-trip limit",
195 "Maximum tolerable round-trip interval for packets, in nanoseconds "
196 "(0 = no limit)", 0, G_MAXUINT64, DEFAULT_ROUNDTRIP_LIMIT,
197 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
199 g_object_class_install_property (gobject_class, PROP_MINIMUM_UPDATE_INTERVAL,
200 g_param_spec_uint64 ("minimum-update-interval", "minimum update interval",
201 "Minimum polling interval for packets, in nanoseconds"
202 "(0 = no limit)", 0, G_MAXUINT64, DEFAULT_MINIMUM_UPDATE_INTERVAL,
203 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
205 g_object_class_install_property (gobject_class, PROP_BASE_TIME,
206 g_param_spec_uint64 ("base-time", "Base Time",
207 "Initial time that is reported before synchronization", 0,
208 G_MAXUINT64, DEFAULT_BASE_TIME,
209 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
211 g_object_class_install_property (gobject_class, PROP_INTERNAL_CLOCK,
212 g_param_spec_object ("internal-clock", "Internal Clock",
213 "Internal clock that directly slaved to the remote clock",
214 GST_TYPE_CLOCK, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
216 clock_class->get_internal_time = gst_net_client_clock_get_internal_time;
220 gst_net_client_clock_init (GstNetClientClock * self)
222 GstNetClientClockPrivate *priv;
224 self->priv = priv = GST_NET_CLIENT_CLOCK_GET_PRIVATE (self);
226 GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_CAN_SET_MASTER);
227 GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC);
229 priv->internal_clock = g_object_new (GST_TYPE_SYSTEM_CLOCK, NULL);
231 priv->port = DEFAULT_PORT;
232 priv->address = g_strdup (DEFAULT_ADDRESS);
234 gst_clock_set_timeout (priv->internal_clock, DEFAULT_TIMEOUT);
238 priv->servaddr = NULL;
239 priv->rtt_avg = GST_CLOCK_TIME_NONE;
240 priv->roundtrip_limit = DEFAULT_ROUNDTRIP_LIMIT;
241 priv->minimum_update_interval = DEFAULT_MINIMUM_UPDATE_INTERVAL;
242 priv->last_remote_poll_interval = GST_CLOCK_TIME_NONE;
243 priv->skipped_updates = 0;
244 priv->last_rtts_missing = MEDIAN_PRE_FILTERING_WINDOW;
245 priv->base_time = DEFAULT_BASE_TIME;
249 gst_net_client_clock_finalize (GObject * object)
251 GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
253 if (self->priv->thread) {
254 gst_net_client_clock_stop (self);
257 g_free (self->priv->address);
258 self->priv->address = NULL;
260 if (self->priv->servaddr != NULL) {
261 g_object_unref (self->priv->servaddr);
262 self->priv->servaddr = NULL;
265 if (self->priv->socket != NULL) {
266 g_socket_close (self->priv->socket, NULL);
267 g_object_unref (self->priv->socket);
268 self->priv->socket = NULL;
271 if (self->priv->bus != NULL) {
272 gst_object_unref (self->priv->bus);
273 self->priv->bus = NULL;
276 if (self->priv->internal_clock != NULL) {
277 gst_object_unref (self->priv->internal_clock);
278 self->priv->internal_clock = NULL;
281 G_OBJECT_CLASS (parent_class)->finalize (object);
285 gst_net_client_clock_set_property (GObject * object, guint prop_id,
286 const GValue * value, GParamSpec * pspec)
288 GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
292 GST_OBJECT_LOCK (self);
293 g_free (self->priv->address);
294 self->priv->address = g_value_dup_string (value);
295 if (self->priv->address == NULL)
296 self->priv->address = g_strdup (DEFAULT_ADDRESS);
297 GST_OBJECT_UNLOCK (self);
300 GST_OBJECT_LOCK (self);
301 self->priv->port = g_value_get_int (value);
302 GST_OBJECT_UNLOCK (self);
304 case PROP_ROUNDTRIP_LIMIT:
305 GST_OBJECT_LOCK (self);
306 self->priv->roundtrip_limit = g_value_get_uint64 (value);
307 GST_OBJECT_UNLOCK (self);
309 case PROP_MINIMUM_UPDATE_INTERVAL:
310 GST_OBJECT_LOCK (self);
311 self->priv->minimum_update_interval = g_value_get_uint64 (value);
312 GST_OBJECT_UNLOCK (self);
315 GST_OBJECT_LOCK (self);
317 gst_object_unref (self->priv->bus);
318 self->priv->bus = g_value_dup_object (value);
319 GST_OBJECT_UNLOCK (self);
322 self->priv->base_time = g_value_get_uint64 (value);
325 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
331 gst_net_client_clock_get_property (GObject * object, guint prop_id,
332 GValue * value, GParamSpec * pspec)
334 GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
338 GST_OBJECT_LOCK (self);
339 g_value_set_string (value, self->priv->address);
340 GST_OBJECT_UNLOCK (self);
343 g_value_set_int (value, self->priv->port);
345 case PROP_ROUNDTRIP_LIMIT:
346 GST_OBJECT_LOCK (self);
347 g_value_set_uint64 (value, self->priv->roundtrip_limit);
348 GST_OBJECT_UNLOCK (self);
350 case PROP_MINIMUM_UPDATE_INTERVAL:
351 GST_OBJECT_LOCK (self);
352 g_value_set_uint64 (value, self->priv->minimum_update_interval);
353 GST_OBJECT_UNLOCK (self);
356 GST_OBJECT_LOCK (self);
357 g_value_set_object (value, self->priv->bus);
358 GST_OBJECT_UNLOCK (self);
361 g_value_set_uint64 (value, self->priv->base_time);
363 case PROP_INTERNAL_CLOCK:
364 g_value_set_object (value, self->priv->internal_clock);
367 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
373 gst_net_client_clock_constructed (GObject * object)
375 GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
376 GstClock *internal_clock = self->priv->internal_clock;
377 GstClockTime internal;
379 G_OBJECT_CLASS (parent_class)->constructed (object);
381 /* gst_clock_get_time() values are guaranteed to be increasing. because no one
382 * has called get_time on this clock yet we are free to adjust to any value
383 * without worrying about worrying about MAX() issues with the clock's
387 /* update our internal time so get_time() give something around base_time.
388 assume that the rate is 1 in the beginning. */
389 internal = gst_clock_get_internal_time (internal_clock);
390 gst_clock_set_calibration (internal_clock, internal,
391 self->priv->base_time, 1, 1);
394 GstClockTime now = gst_clock_get_time (internal_clock);
396 if (GST_CLOCK_DIFF (now, self->priv->base_time) > 0 ||
397 GST_CLOCK_DIFF (now, self->priv->base_time + GST_SECOND) < 0) {
398 g_warning ("unable to set the base time, expect sync problems!");
402 if (!gst_net_client_clock_start (self)) {
403 g_warning ("failed to start clock '%s'", GST_OBJECT_NAME (self));
406 /* all systems go, cap'n */
410 gst_net_client_clock_get_internal_time (GstClock * clock)
412 GstNetClientClock *self = GST_NET_CLIENT_CLOCK (clock);
414 return gst_clock_get_time (self->priv->internal_clock);
418 compare_clock_time (const GstClockTime * a, const GstClockTime * b)
428 gst_net_client_clock_observe_times (GstNetClientClock * self,
429 GstClockTime local_1, GstClockTime remote_1, GstClockTime remote_2,
430 GstClockTime local_2)
432 GstNetClientClockPrivate *priv = self->priv;
433 GstClock *internal_clock = priv->internal_clock;
434 GstClockTime current_timeout = 0;
435 GstClockTime local_avg, remote_avg;
438 GstClockTime rtt, rtt_limit, min_update_interval;
440 /* Use for discont tracking */
441 GstClockTime time_before = 0;
442 GstClockTime min_guess = 0;
443 GstClockTimeDiff time_discont = 0;
444 gboolean synched, now_synched;
445 GstClockTime internal_time, external_time, rate_num, rate_den;
446 GstClockTime orig_internal_time, orig_external_time, orig_rate_num,
448 GstClockTime max_discont;
449 GstClockTime last_rtts[MEDIAN_PRE_FILTERING_WINDOW];
453 GST_OBJECT_LOCK (self);
454 rtt_limit = self->priv->roundtrip_limit;
456 /* If the server told us a poll interval and it's bigger than the
457 * one configured via the property, use the server's */
458 if (self->priv->last_remote_poll_interval != GST_CLOCK_TIME_NONE &&
459 self->priv->last_remote_poll_interval >
460 self->priv->minimum_update_interval)
461 min_update_interval = self->priv->last_remote_poll_interval;
463 min_update_interval = self->priv->minimum_update_interval;
466 bus = gst_object_ref (self->priv->bus);
467 GST_OBJECT_UNLOCK (self);
469 if (local_2 < local_1) {
470 GST_LOG_OBJECT (self, "Dropping observation: receive time %" GST_TIME_FORMAT
471 " < send time %" GST_TIME_FORMAT, GST_TIME_ARGS (local_1),
472 GST_TIME_ARGS (local_2));
473 goto bogus_observation;
476 if (remote_2 < remote_1) {
477 GST_LOG_OBJECT (self,
478 "Dropping observation: remote receive time %" GST_TIME_FORMAT
479 " < send time %" GST_TIME_FORMAT, GST_TIME_ARGS (remote_1),
480 GST_TIME_ARGS (remote_2));
481 goto bogus_observation;
484 /* The round trip time is (assuming symmetric path delays)
485 * delta = (local_2 - local_1) - (remote_2 - remote_1)
488 rtt = GST_CLOCK_DIFF (local_1, local_2) - GST_CLOCK_DIFF (remote_1, remote_2);
490 if ((rtt_limit > 0) && (rtt > rtt_limit)) {
491 GST_LOG_OBJECT (self,
492 "Dropping observation: RTT %" GST_TIME_FORMAT " > limit %"
493 GST_TIME_FORMAT, GST_TIME_ARGS (rtt), GST_TIME_ARGS (rtt_limit));
494 goto bogus_observation;
497 for (i = 1; i < MEDIAN_PRE_FILTERING_WINDOW; i++)
498 self->priv->last_rtts[i - 1] = self->priv->last_rtts[i];
499 self->priv->last_rtts[i - 1] = rtt;
501 if (self->priv->last_rtts_missing) {
502 self->priv->last_rtts_missing--;
504 memcpy (&last_rtts, &self->priv->last_rtts, sizeof (last_rtts));
505 g_qsort_with_data (&last_rtts,
506 MEDIAN_PRE_FILTERING_WINDOW, sizeof (GstClockTime),
507 (GCompareDataFunc) compare_clock_time, NULL);
509 median = last_rtts[MEDIAN_PRE_FILTERING_WINDOW / 2];
511 /* FIXME: We might want to use something else here, like only allowing
512 * things in the interquartile range, or also filtering away delays that
513 * are too small compared to the median. This here worked well enough
516 if (rtt > 2 * median) {
517 GST_LOG_OBJECT (self,
518 "Dropping observation, long RTT %" GST_TIME_FORMAT " > 2 * median %"
519 GST_TIME_FORMAT, GST_TIME_ARGS (rtt), GST_TIME_ARGS (median));
520 goto bogus_observation;
524 /* Track an average round trip time, for a bit of smoothing */
525 /* Always update before discarding a sample, so genuine changes in
526 * the network get picked up, eventually */
527 if (priv->rtt_avg == GST_CLOCK_TIME_NONE)
529 else if (rtt < priv->rtt_avg) /* Shorter RTTs carry more weight than longer */
530 priv->rtt_avg = (3 * priv->rtt_avg + rtt) / 4;
532 priv->rtt_avg = (15 * priv->rtt_avg + rtt) / 16;
534 if (rtt > 2 * priv->rtt_avg) {
535 GST_LOG_OBJECT (self,
536 "Dropping observation, long RTT %" GST_TIME_FORMAT " > 2 * avg %"
537 GST_TIME_FORMAT, GST_TIME_ARGS (rtt), GST_TIME_ARGS (priv->rtt_avg));
538 goto bogus_observation;
541 /* The difference between the local and remote clock (again assuming
542 * symmetric path delays):
544 * local_1 + delta / 2 - remote_1 = theta
546 * local_2 - delta / 2 - remote_2 = theta
548 * which gives after some simple algebraic transformations:
550 * (remote_1 - local_1) + (remote_2 - local_2)
551 * theta = -------------------------------------------
555 * Thus remote time at local_avg is equal to:
557 * local_avg + theta =
559 * local_1 + local_2 (remote_1 - local_1) + (remote_2 - local_2)
560 * ----------------- + -------------------------------------------
565 * remote_1 + remote_2
566 * ------------------- = remote_avg
569 * We use this for our clock estimation, i.e. local_avg at remote clock
570 * being the same as remote_avg.
573 local_avg = (local_2 + local_1) / 2;
574 remote_avg = (remote_2 + remote_1) / 2;
576 GST_LOG_OBJECT (self,
577 "local1 %" G_GUINT64_FORMAT " remote1 %" G_GUINT64_FORMAT " remote2 %"
578 G_GUINT64_FORMAT " remoteavg %" G_GUINT64_FORMAT " localavg %"
579 G_GUINT64_FORMAT " local2 %" G_GUINT64_FORMAT, local_1, remote_1,
580 remote_2, remote_avg, local_avg, local_2);
582 clock = GST_CLOCK_CAST (self);
584 /* Store what the clock produced as 'now' before this update */
585 gst_clock_get_calibration (internal_clock, &orig_internal_time,
586 &orig_external_time, &orig_rate_num, &orig_rate_den);
587 internal_time = orig_internal_time;
588 external_time = orig_external_time;
589 rate_num = orig_rate_num;
590 rate_den = orig_rate_den;
593 gst_clock_adjust_with_calibration (internal_clock, local_1,
594 internal_time, external_time, rate_num, rate_den);
596 gst_clock_adjust_with_calibration (internal_clock, local_2,
597 internal_time, external_time, rate_num, rate_den);
599 /* Maximum discontinuity, when we're synched with the master. Could make this a property,
600 * but this value seems to work fine */
601 max_discont = priv->rtt_avg / 4;
603 /* If the remote observation was within a max_discont window around our min/max estimates, we're synched */
605 (GST_CLOCK_DIFF (remote_avg, min_guess) < (GstClockTimeDiff) (max_discont)
606 && GST_CLOCK_DIFF (time_before,
607 remote_avg) < (GstClockTimeDiff) (max_discont));
609 if (gst_clock_add_observation_unapplied (internal_clock,
610 local_avg, remote_avg, &r_squared, &internal_time, &external_time,
611 &rate_num, &rate_den)) {
613 /* Now compare the difference (discont) in the clock
614 * after this observation */
615 time_discont = GST_CLOCK_DIFF (time_before,
616 gst_clock_adjust_with_calibration (internal_clock, local_2,
617 internal_time, external_time, rate_num, rate_den));
619 /* If we were in sync with the remote clock, clamp the allowed
620 * discontinuity to within quarter of one RTT. In sync means our send/receive estimates
621 * of remote time correctly windowed the actual remote time observation */
622 if (synched && ABS (time_discont) > max_discont) {
623 GstClockTimeDiff offset;
624 GST_DEBUG_OBJECT (clock,
625 "Too large a discont, clamping to 1/4 average RTT = %"
626 GST_TIME_FORMAT, GST_TIME_ARGS (max_discont));
627 if (time_discont > 0) { /* Too large a forward step - add a -ve offset */
628 offset = max_discont - time_discont;
629 if (-offset > external_time)
632 external_time += offset;
633 } else { /* Too large a backward step - add a +ve offset */
634 offset = -(max_discont + time_discont);
635 external_time += offset;
638 time_discont += offset;
641 /* Check if the new clock params would have made our observation within range */
643 (GST_CLOCK_DIFF (remote_avg,
644 gst_clock_adjust_with_calibration (internal_clock,
645 local_1, internal_time, external_time, rate_num,
646 rate_den)) < (GstClockTimeDiff) (max_discont))
648 (GST_CLOCK_DIFF (gst_clock_adjust_with_calibration
649 (internal_clock, local_2, internal_time, external_time,
651 remote_avg) < (GstClockTimeDiff) (max_discont));
653 /* Only update the clock if we had synch or just gained it */
654 if (synched || now_synched || priv->skipped_updates > MAX_SKIPPED_UPDATES) {
655 gst_clock_set_calibration (internal_clock, internal_time,
656 external_time, rate_num, rate_den);
657 /* ghetto formula - shorter timeout for bad correlations */
658 current_timeout = (1e-3 / (1 - MIN (r_squared, 0.99999))) * GST_SECOND;
660 MIN (current_timeout, gst_clock_get_timeout (internal_clock));
661 priv->skipped_updates = 0;
663 /* FIXME: When do we consider the clock absolutely not synced anymore? */
664 gst_clock_set_synced (GST_CLOCK (self), TRUE);
666 /* Restore original calibration vars for the report, we're not changing the clock */
667 internal_time = orig_internal_time;
668 external_time = orig_external_time;
669 rate_num = orig_rate_num;
670 rate_den = orig_rate_den;
672 priv->skipped_updates++;
676 /* Limit the polling to at most one per minimum_update_interval */
677 if (rtt < min_update_interval)
678 current_timeout = MAX (min_update_interval - rtt, current_timeout);
684 /* Output a stats message, whether we updated the clock or not */
685 s = gst_structure_new ("gst-netclock-statistics",
686 "synchronised", G_TYPE_BOOLEAN, synched,
687 "rtt", G_TYPE_UINT64, rtt,
688 "rtt-average", G_TYPE_UINT64, priv->rtt_avg,
689 "local", G_TYPE_UINT64, local_avg,
690 "remote", G_TYPE_UINT64, remote_avg,
691 "discontinuity", G_TYPE_INT64, time_discont,
692 "remote-min-estimate", G_TYPE_UINT64, min_guess,
693 "remote-max-estimate", G_TYPE_UINT64, time_before,
694 "remote-min-error", G_TYPE_INT64, GST_CLOCK_DIFF (remote_avg,
695 min_guess), "remote-max-error", G_TYPE_INT64,
696 GST_CLOCK_DIFF (remote_avg, time_before), "request-send", G_TYPE_UINT64,
697 local_1, "request-receive", G_TYPE_UINT64, local_2, "r-squared",
698 G_TYPE_DOUBLE, r_squared, "timeout", G_TYPE_UINT64, current_timeout,
699 "internal-time", G_TYPE_UINT64, internal_time, "external-time",
700 G_TYPE_UINT64, external_time, "rate-num", G_TYPE_UINT64, rate_num,
701 "rate-den", G_TYPE_UINT64, rate_den, "rate", G_TYPE_DOUBLE,
702 (gdouble) (rate_num) / rate_den, "local-clock-offset", G_TYPE_INT64,
703 GST_CLOCK_DIFF (internal_time, external_time), NULL);
704 msg = gst_message_new_element (GST_OBJECT (self), s);
705 gst_bus_post (bus, msg);
708 GST_INFO ("next timeout: %" GST_TIME_FORMAT, GST_TIME_ARGS (current_timeout));
709 self->priv->timeout_expiration = gst_util_get_timestamp () + current_timeout;
712 gst_object_unref (bus);
717 gst_object_unref (bus);
718 /* Schedule a new packet again soon */
719 self->priv->timeout_expiration = gst_util_get_timestamp () + (GST_SECOND / 4);
724 gst_net_client_clock_thread (gpointer data)
726 GstNetClientClock *self = data;
727 GstClock *internal_clock = self->priv->internal_clock;
728 GSocket *socket = self->priv->socket;
731 GST_INFO_OBJECT (self, "net client clock thread running, socket=%p", socket);
733 g_socket_set_blocking (socket, TRUE);
734 g_socket_set_timeout (socket, 0);
736 while (!g_cancellable_is_cancelled (self->priv->cancel)) {
737 GstClockTime expiration_time = self->priv->timeout_expiration;
738 GstClockTime now = gst_util_get_timestamp ();
739 gint64 socket_timeout;
741 if (now >= expiration_time || (expiration_time - now) <= GST_MSECOND) {
744 socket_timeout = (expiration_time - now) / GST_USECOND;
747 GST_TRACE_OBJECT (self, "timeout: %" G_GINT64_FORMAT "us", socket_timeout);
749 if (!g_socket_condition_timed_wait (socket, G_IO_IN, socket_timeout,
750 self->priv->cancel, &err)) {
751 /* cancelled, timeout or error */
752 if (err->code == G_IO_ERROR_CANCELLED) {
753 GST_INFO_OBJECT (self, "cancelled");
754 g_clear_error (&err);
756 } else if (err->code == G_IO_ERROR_TIMED_OUT) {
757 /* timed out, let's send another packet */
758 GST_DEBUG_OBJECT (self, "timed out");
760 if (self->priv->is_ntp) {
761 GstNtpPacket *packet;
763 packet = gst_ntp_packet_new (NULL, NULL);
765 packet->transmit_time = gst_clock_get_internal_time (internal_clock);
767 GST_DEBUG_OBJECT (self,
768 "sending packet, local time = %" GST_TIME_FORMAT,
769 GST_TIME_ARGS (packet->transmit_time));
771 gst_ntp_packet_send (packet, self->priv->socket,
772 self->priv->servaddr, NULL);
776 GstNetTimePacket *packet;
778 packet = gst_net_time_packet_new (NULL);
780 packet->local_time = gst_clock_get_internal_time (internal_clock);
782 GST_DEBUG_OBJECT (self,
783 "sending packet, local time = %" GST_TIME_FORMAT,
784 GST_TIME_ARGS (packet->local_time));
786 gst_net_time_packet_send (packet, self->priv->socket,
787 self->priv->servaddr, NULL);
792 /* reset timeout (but are expecting a response sooner anyway) */
793 self->priv->timeout_expiration =
794 gst_util_get_timestamp () + gst_clock_get_timeout (internal_clock);
796 GST_DEBUG_OBJECT (self, "socket error: %s", err->message);
797 g_usleep (G_USEC_PER_SEC / 10); /* throttle */
799 g_clear_error (&err);
801 GstClockTime new_local;
805 new_local = gst_clock_get_internal_time (internal_clock);
807 if (self->priv->is_ntp) {
808 GstNtpPacket *packet;
810 packet = gst_ntp_packet_receive (socket, NULL, &err);
812 if (packet != NULL) {
813 GST_LOG_OBJECT (self, "got packet back");
814 GST_LOG_OBJECT (self, "local_1 = %" GST_TIME_FORMAT,
815 GST_TIME_ARGS (packet->origin_time));
816 GST_LOG_OBJECT (self, "remote_1 = %" GST_TIME_FORMAT,
817 GST_TIME_ARGS (packet->receive_time));
818 GST_LOG_OBJECT (self, "remote_2 = %" GST_TIME_FORMAT,
819 GST_TIME_ARGS (packet->transmit_time));
820 GST_LOG_OBJECT (self, "local_2 = %" GST_TIME_FORMAT,
821 GST_TIME_ARGS (new_local));
822 GST_LOG_OBJECT (self, "poll_interval = %" GST_TIME_FORMAT,
823 GST_TIME_ARGS (packet->poll_interval));
825 /* Remember the last poll interval we ever got from the server */
826 if (packet->poll_interval != GST_CLOCK_TIME_NONE)
827 self->priv->last_remote_poll_interval = packet->poll_interval;
829 /* observe_times will reset the timeout */
830 gst_net_client_clock_observe_times (self, packet->origin_time,
831 packet->receive_time, packet->transmit_time, new_local);
834 } else if (err != NULL) {
835 if (g_error_matches (err, GST_NTP_ERROR, GST_NTP_ERROR_WRONG_VERSION)
836 || g_error_matches (err, GST_NTP_ERROR, GST_NTP_ERROR_KOD_DENY)) {
837 GST_ERROR_OBJECT (self, "fatal receive error: %s", err->message);
839 } else if (g_error_matches (err, GST_NTP_ERROR,
840 GST_NTP_ERROR_KOD_RATE)) {
841 GST_WARNING_OBJECT (self, "need to limit rate");
843 /* If the server did not tell us a poll interval before, double
844 * our minimum poll interval. Otherwise we assume that the server
845 * already told us something sensible and that this error here
846 * was just a spurious error */
847 if (self->priv->last_remote_poll_interval == GST_CLOCK_TIME_NONE)
848 self->priv->minimum_update_interval *= 2;
850 /* And wait a bit before we send the next packet instead of
851 * sending it immediately */
852 self->priv->timeout_expiration =
853 gst_util_get_timestamp () +
854 gst_clock_get_timeout (internal_clock);
856 GST_WARNING_OBJECT (self, "receive error: %s", err->message);
858 g_clear_error (&err);
861 GstNetTimePacket *packet;
863 packet = gst_net_time_packet_receive (socket, NULL, &err);
865 if (packet != NULL) {
866 GST_LOG_OBJECT (self, "got packet back");
867 GST_LOG_OBJECT (self, "local_1 = %" GST_TIME_FORMAT,
868 GST_TIME_ARGS (packet->local_time));
869 GST_LOG_OBJECT (self, "remote = %" GST_TIME_FORMAT,
870 GST_TIME_ARGS (packet->remote_time));
871 GST_LOG_OBJECT (self, "local_2 = %" GST_TIME_FORMAT,
872 GST_TIME_ARGS (new_local));
874 /* observe_times will reset the timeout */
875 gst_net_client_clock_observe_times (self, packet->local_time,
876 packet->remote_time, packet->remote_time, new_local);
879 } else if (err != NULL) {
880 GST_WARNING_OBJECT (self, "receive error: %s", err->message);
881 g_clear_error (&err);
886 GST_INFO_OBJECT (self, "shutting down net client clock thread");
891 gst_net_client_clock_start (GstNetClientClock * self)
893 GSocketAddress *servaddr;
894 GSocketAddress *myaddr;
895 GSocketAddress *anyaddr;
896 GInetAddress *inetaddr;
898 GError *error = NULL;
899 GSocketFamily family;
900 GPollFD dummy_pollfd;
901 GResolver *resolver = NULL;
904 g_return_val_if_fail (self->priv->address != NULL, FALSE);
905 g_return_val_if_fail (self->priv->servaddr == NULL, FALSE);
907 /* create target address */
908 inetaddr = g_inet_address_new_from_string (self->priv->address);
909 if (inetaddr == NULL) {
912 resolver = g_resolver_get_default ();
915 g_resolver_lookup_by_name (resolver, self->priv->address, NULL, &err);
917 goto failed_to_resolve;
919 inetaddr = G_INET_ADDRESS (g_object_ref (results->data));
920 g_resolver_free_addresses (results);
921 g_object_unref (resolver);
924 family = g_inet_address_get_family (inetaddr);
926 servaddr = g_inet_socket_address_new (inetaddr, self->priv->port);
927 g_object_unref (inetaddr);
929 g_assert (servaddr != NULL);
931 GST_DEBUG_OBJECT (self, "will communicate with %s:%d", self->priv->address,
934 socket = g_socket_new (family, G_SOCKET_TYPE_DATAGRAM,
935 G_SOCKET_PROTOCOL_UDP, &error);
940 GST_DEBUG_OBJECT (self, "binding socket");
941 inetaddr = g_inet_address_new_any (family);
942 anyaddr = g_inet_socket_address_new (inetaddr, 0);
943 g_socket_bind (socket, anyaddr, TRUE, &error);
944 g_object_unref (anyaddr);
945 g_object_unref (inetaddr);
950 /* check address we're bound to, mostly for debugging purposes */
951 myaddr = g_socket_get_local_address (socket, &error);
954 goto getsockname_error;
956 GST_DEBUG_OBJECT (self, "socket opened on UDP port %d",
957 g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (myaddr)));
959 g_object_unref (myaddr);
961 self->priv->cancel = g_cancellable_new ();
962 self->priv->made_cancel_fd =
963 g_cancellable_make_pollfd (self->priv->cancel, &dummy_pollfd);
965 self->priv->socket = socket;
966 self->priv->servaddr = G_SOCKET_ADDRESS (servaddr);
968 self->priv->thread = g_thread_try_new ("GstNetClientClock",
969 gst_net_client_clock_thread, self, &error);
979 GST_ERROR_OBJECT (self, "socket_new() failed: %s", error->message);
980 g_error_free (error);
985 GST_ERROR_OBJECT (self, "bind failed: %s", error->message);
986 g_error_free (error);
987 g_object_unref (socket);
992 GST_ERROR_OBJECT (self, "get_local_address() failed: %s", error->message);
993 g_error_free (error);
994 g_object_unref (socket);
999 GST_ERROR_OBJECT (self, "resolving '%s' failed: %s",
1000 self->priv->address, err->message);
1001 g_clear_error (&err);
1002 g_object_unref (resolver);
1007 GST_ERROR_OBJECT (self, "could not create thread: %s", error->message);
1008 g_object_unref (self->priv->servaddr);
1009 self->priv->servaddr = NULL;
1010 g_object_unref (self->priv->socket);
1011 self->priv->socket = NULL;
1012 g_error_free (error);
1018 gst_net_client_clock_stop (GstNetClientClock * self)
1020 if (self->priv->thread == NULL)
1023 GST_INFO_OBJECT (self, "stopping...");
1024 g_cancellable_cancel (self->priv->cancel);
1026 g_thread_join (self->priv->thread);
1027 self->priv->thread = NULL;
1029 if (self->priv->made_cancel_fd)
1030 g_cancellable_release_fd (self->priv->cancel);
1032 g_object_unref (self->priv->cancel);
1033 self->priv->cancel = NULL;
1035 g_object_unref (self->priv->servaddr);
1036 self->priv->servaddr = NULL;
1038 g_object_unref (self->priv->socket);
1039 self->priv->socket = NULL;
1041 GST_INFO_OBJECT (self, "stopped");
1045 * gst_net_client_clock_new:
1046 * @name: a name for the clock
1047 * @remote_address: the address or hostname of the remote clock provider
1048 * @remote_port: the port of the remote clock provider
1049 * @base_time: initial time of the clock
1051 * Create a new #GstNetClientClock that will report the time
1052 * provided by the #GstNetTimeProvider on @remote_address and
1055 * Returns: a new #GstClock that receives a time from the remote
1059 gst_net_client_clock_new (const gchar * name, const gchar * remote_address,
1060 gint remote_port, GstClockTime base_time)
1062 GstNetClientClock *ret;
1064 g_return_val_if_fail (remote_address != NULL, NULL);
1065 g_return_val_if_fail (remote_port > 0, NULL);
1066 g_return_val_if_fail (remote_port <= G_MAXUINT16, NULL);
1067 g_return_val_if_fail (base_time != GST_CLOCK_TIME_NONE, NULL);
1069 ret = g_object_new (GST_TYPE_NET_CLIENT_CLOCK, "address", remote_address,
1070 "port", remote_port, "base-time", base_time, NULL);
1072 return (GstClock *) ret;
1075 G_DEFINE_TYPE (GstNtpClock, gst_ntp_clock, GST_TYPE_NET_CLIENT_CLOCK);
1078 gst_ntp_clock_class_init (GstNtpClockClass * klass)
1083 gst_ntp_clock_init (GstNtpClock * self)
1085 GST_NET_CLIENT_CLOCK (self)->priv->is_ntp = TRUE;
1089 * gst_ntp_clock_new:
1090 * @name: a name for the clock
1091 * @remote_address: the address or hostname of the remote clock provider
1092 * @remote_port: the port of the remote clock provider
1093 * @base_time: initial time of the clock
1095 * Create a new #GstNtpClock that will report the time provided by
1096 * the NTPv4 server on @remote_address and @remote_port.
1098 * Returns: a new #GstClock that receives a time from the remote
1104 gst_ntp_clock_new (const gchar * name, const gchar * remote_address,
1105 gint remote_port, GstClockTime base_time)
1107 GstNetClientClock *ret;
1109 g_return_val_if_fail (remote_address != NULL, NULL);
1110 g_return_val_if_fail (remote_port > 0, NULL);
1111 g_return_val_if_fail (remote_port <= G_MAXUINT16, NULL);
1112 g_return_val_if_fail (base_time != GST_CLOCK_TIME_NONE, NULL);
1114 ret = g_object_new (GST_TYPE_NTP_CLOCK, "address", remote_address,
1115 "port", remote_port, "base-time", base_time, NULL);
1117 return (GstClock *) ret;