netclientclock: Implement resolval of hostnames
[platform/upstream/gstreamer.git] / libs / gst / net / gstnetclientclock.c
1 /* GStreamer
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>
7  *
8  * gstnetclientclock.h: clock that synchronizes itself to a time provider over
9  * the network
10  *
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.
15  *
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.
20  *
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.
25  */
26 /**
27  * SECTION:gstnetclientclock
28  * @short_description: Special clock that synchronizes to a remote time
29  *                     provider.
30  * @see_also: #GstClock, #GstNetTimeProvider, #GstPipeline
31  *
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.
35  *
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.
39  *
40  * This clock will poll the time provider and will update its calibration
41  * parameters based on the local and remote observations.
42  *
43  * The "round-trip" property limits the maximum round trip packets can take.
44  *
45  * Various parameters of the clock can be configured with the parent #GstClock
46  * "timeout", "window-size" and "window-threshold" object properties.
47  *
48  * A #GstNetClientClock and #GstNtpClock is typically set on a #GstPipeline with
49  * gst_pipeline_use_clock().
50  *
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.
54  */
55
56 #ifdef HAVE_CONFIG_H
57 #include "config.h"
58 #endif
59
60 #include "gstnettimepacket.h"
61 #include "gstntppacket.h"
62 #include "gstnetclientclock.h"
63
64 #include <gio/gio.h>
65
66 #include <string.h>
67
68 GST_DEBUG_CATEGORY_STATIC (ncc_debug);
69 #define GST_CAT_DEFAULT (ncc_debug)
70
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
79
80 /* Maximum number of clock updates we can skip before updating */
81 #define MAX_SKIPPED_UPDATES 5
82
83 #define MEDIAN_PRE_FILTERING_WINDOW 9
84
85 enum
86 {
87   PROP_0,
88   PROP_ADDRESS,
89   PROP_PORT,
90   PROP_ROUNDTRIP_LIMIT,
91   PROP_MINIMUM_UPDATE_INTERVAL,
92   PROP_BUS,
93   PROP_BASE_TIME,
94   PROP_INTERNAL_CLOCK
95 };
96
97 #define GST_NET_CLIENT_CLOCK_GET_PRIVATE(obj)  \
98   (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_NET_CLIENT_CLOCK, GstNetClientClockPrivate))
99
100 struct _GstNetClientClockPrivate
101 {
102   GstClock *internal_clock;
103
104   GThread *thread;
105
106   GSocket *socket;
107   GSocketAddress *servaddr;
108   GCancellable *cancel;
109   gboolean made_cancel_fd;
110
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;
119
120   GstClockTime base_time;
121
122   gchar *address;
123   gint port;
124
125   GstBus *bus;
126
127   gboolean is_ntp;
128 };
129
130 #define _do_init \
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);
135
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);
142
143 static gboolean gst_net_client_clock_start (GstNetClientClock * self);
144 static void gst_net_client_clock_stop (GstNetClientClock * self);
145
146 static GstClockTime gst_net_client_clock_get_internal_time (GstClock * clock);
147
148 static void
149 gst_net_client_clock_class_init (GstNetClientClockClass * klass)
150 {
151   GObjectClass *gobject_class;
152   GstClockClass *clock_class;
153
154   gobject_class = G_OBJECT_CLASS (klass);
155   clock_class = GST_CLOCK_CLASS (klass);
156
157   g_type_class_add_private (klass, sizeof (GstNetClientClockPrivate));
158
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;
163
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",
167           DEFAULT_ADDRESS,
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,
172           DEFAULT_PORT,
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));
178
179   /**
180    * GstNetClientClock::round-trip-limit:
181    *
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
188    * for the limit.
189    * If the property is set to zero, the limit is disabled.
190    *
191    * Since: 1.4
192    */
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));
198
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));
204
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));
210
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));
215
216   clock_class->get_internal_time = gst_net_client_clock_get_internal_time;
217 }
218
219 static void
220 gst_net_client_clock_init (GstNetClientClock * self)
221 {
222   GstNetClientClockPrivate *priv;
223
224   self->priv = priv = GST_NET_CLIENT_CLOCK_GET_PRIVATE (self);
225
226   GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_CAN_SET_MASTER);
227   GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC);
228
229   priv->internal_clock = g_object_new (GST_TYPE_SYSTEM_CLOCK, NULL);
230
231   priv->port = DEFAULT_PORT;
232   priv->address = g_strdup (DEFAULT_ADDRESS);
233
234   gst_clock_set_timeout (priv->internal_clock, DEFAULT_TIMEOUT);
235
236   priv->thread = NULL;
237
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;
246 }
247
248 static void
249 gst_net_client_clock_finalize (GObject * object)
250 {
251   GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
252
253   if (self->priv->thread) {
254     gst_net_client_clock_stop (self);
255   }
256
257   g_free (self->priv->address);
258   self->priv->address = NULL;
259
260   if (self->priv->servaddr != NULL) {
261     g_object_unref (self->priv->servaddr);
262     self->priv->servaddr = NULL;
263   }
264
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;
269   }
270
271   if (self->priv->bus != NULL) {
272     gst_object_unref (self->priv->bus);
273     self->priv->bus = NULL;
274   }
275
276   if (self->priv->internal_clock != NULL) {
277     gst_object_unref (self->priv->internal_clock);
278     self->priv->internal_clock = NULL;
279   }
280
281   G_OBJECT_CLASS (parent_class)->finalize (object);
282 }
283
284 static void
285 gst_net_client_clock_set_property (GObject * object, guint prop_id,
286     const GValue * value, GParamSpec * pspec)
287 {
288   GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
289
290   switch (prop_id) {
291     case PROP_ADDRESS:
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);
298       break;
299     case PROP_PORT:
300       GST_OBJECT_LOCK (self);
301       self->priv->port = g_value_get_int (value);
302       GST_OBJECT_UNLOCK (self);
303       break;
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);
308       break;
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);
313       break;
314     case PROP_BUS:
315       GST_OBJECT_LOCK (self);
316       if (self->priv->bus)
317         gst_object_unref (self->priv->bus);
318       self->priv->bus = g_value_dup_object (value);
319       GST_OBJECT_UNLOCK (self);
320       break;
321     case PROP_BASE_TIME:
322       self->priv->base_time = g_value_get_uint64 (value);
323       break;
324     default:
325       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
326       break;
327   }
328 }
329
330 static void
331 gst_net_client_clock_get_property (GObject * object, guint prop_id,
332     GValue * value, GParamSpec * pspec)
333 {
334   GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
335
336   switch (prop_id) {
337     case PROP_ADDRESS:
338       GST_OBJECT_LOCK (self);
339       g_value_set_string (value, self->priv->address);
340       GST_OBJECT_UNLOCK (self);
341       break;
342     case PROP_PORT:
343       g_value_set_int (value, self->priv->port);
344       break;
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);
349       break;
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);
354       break;
355     case PROP_BUS:
356       GST_OBJECT_LOCK (self);
357       g_value_set_object (value, self->priv->bus);
358       GST_OBJECT_UNLOCK (self);
359       break;
360     case PROP_BASE_TIME:
361       g_value_set_uint64 (value, self->priv->base_time);
362       break;
363     case PROP_INTERNAL_CLOCK:
364       g_value_set_object (value, self->priv->internal_clock);
365       break;
366     default:
367       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
368       break;
369   }
370 }
371
372 static void
373 gst_net_client_clock_constructed (GObject * object)
374 {
375   GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
376   GstClock *internal_clock = self->priv->internal_clock;
377   GstClockTime internal;
378
379   G_OBJECT_CLASS (parent_class)->constructed (object);
380
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
384    * internal time.
385    */
386
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);
392
393   {
394     GstClockTime now = gst_clock_get_time (internal_clock);
395
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!");
399     }
400   }
401
402   if (!gst_net_client_clock_start (self)) {
403     g_warning ("failed to start clock '%s'", GST_OBJECT_NAME (self));
404   }
405
406   /* all systems go, cap'n */
407 }
408
409 static GstClockTime
410 gst_net_client_clock_get_internal_time (GstClock * clock)
411 {
412   GstNetClientClock *self = GST_NET_CLIENT_CLOCK (clock);
413
414   return gst_clock_get_time (self->priv->internal_clock);
415 }
416
417 static gint
418 compare_clock_time (const GstClockTime * a, const GstClockTime * b)
419 {
420   if (*a < *b)
421     return -1;
422   else if (*a > *b)
423     return 1;
424   return 0;
425 }
426
427 static void
428 gst_net_client_clock_observe_times (GstNetClientClock * self,
429     GstClockTime local_1, GstClockTime remote_1, GstClockTime remote_2,
430     GstClockTime local_2)
431 {
432   GstNetClientClockPrivate *priv = self->priv;
433   GstClock *internal_clock = priv->internal_clock;
434   GstClockTime current_timeout = 0;
435   GstClockTime local_avg, remote_avg;
436   gdouble r_squared;
437   GstClock *clock;
438   GstClockTime rtt, rtt_limit, min_update_interval;
439   GstBus *bus = NULL;
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,
447       orig_rate_den;
448   GstClockTime max_discont;
449   GstClockTime last_rtts[MEDIAN_PRE_FILTERING_WINDOW];
450   GstClockTime median;
451   gint i;
452
453   GST_OBJECT_LOCK (self);
454   rtt_limit = self->priv->roundtrip_limit;
455
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;
462   else
463     min_update_interval = self->priv->minimum_update_interval;
464
465   if (self->priv->bus)
466     bus = gst_object_ref (self->priv->bus);
467   GST_OBJECT_UNLOCK (self);
468
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;
474   }
475
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;
482   }
483
484   /* The round trip time is (assuming symmetric path delays)
485    * delta = (local_2 - local_1) - (remote_2 - remote_1)
486    */
487
488   rtt = GST_CLOCK_DIFF (local_1, local_2) - GST_CLOCK_DIFF (remote_1, remote_2);
489
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;
495   }
496
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;
500
501   if (self->priv->last_rtts_missing) {
502     self->priv->last_rtts_missing--;
503   } else {
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);
508
509     median = last_rtts[MEDIAN_PRE_FILTERING_WINDOW / 2];
510
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
514      * in tests so far.
515      */
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;
521     }
522   }
523
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)
528     priv->rtt_avg = rtt;
529   else if (rtt < priv->rtt_avg) /* Shorter RTTs carry more weight than longer */
530     priv->rtt_avg = (3 * priv->rtt_avg + rtt) / 4;
531   else
532     priv->rtt_avg = (15 * priv->rtt_avg + rtt) / 16;
533
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;
539   }
540
541   /* The difference between the local and remote clock (again assuming
542    * symmetric path delays):
543    *
544    * local_1 + delta / 2 - remote_1 = theta
545    * or
546    * local_2 - delta / 2 - remote_2 = theta
547    *
548    * which gives after some simple algebraic transformations:
549    *
550    *         (remote_1 - local_1) + (remote_2 - local_2)
551    * theta = -------------------------------------------
552    *                              2
553    *
554    *
555    * Thus remote time at local_avg is equal to:
556    *
557    * local_avg + theta =
558    *
559    * local_1 + local_2   (remote_1 - local_1) + (remote_2 - local_2)
560    * ----------------- + -------------------------------------------
561    *         2                                2
562    *
563    * =
564    *
565    * remote_1 + remote_2
566    * ------------------- = remote_avg
567    *          2
568    *
569    * We use this for our clock estimation, i.e. local_avg at remote clock
570    * being the same as remote_avg.
571    */
572
573   local_avg = (local_2 + local_1) / 2;
574   remote_avg = (remote_2 + remote_1) / 2;
575
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);
581
582   clock = GST_CLOCK_CAST (self);
583
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;
591
592   min_guess =
593       gst_clock_adjust_with_calibration (internal_clock, local_1,
594       internal_time, external_time, rate_num, rate_den);
595   time_before =
596       gst_clock_adjust_with_calibration (internal_clock, local_2,
597       internal_time, external_time, rate_num, rate_den);
598
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;
602
603   /* If the remote observation was within a max_discont window around our min/max estimates, we're synched */
604   synched =
605       (GST_CLOCK_DIFF (remote_avg, min_guess) < (GstClockTimeDiff) (max_discont)
606       && GST_CLOCK_DIFF (time_before,
607           remote_avg) < (GstClockTimeDiff) (max_discont));
608
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)) {
612
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));
618
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)
630           external_time = 0;
631         else
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;
636       }
637
638       time_discont += offset;
639     }
640
641     /* Check if the new clock params would have made our observation within range */
642     now_synched =
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))
647         &&
648         (GST_CLOCK_DIFF (gst_clock_adjust_with_calibration
649             (internal_clock, local_2, internal_time, external_time,
650                 rate_num, rate_den),
651             remote_avg) < (GstClockTimeDiff) (max_discont));
652
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;
659       current_timeout =
660           MIN (current_timeout, gst_clock_get_timeout (internal_clock));
661       priv->skipped_updates = 0;
662
663       /* FIXME: When do we consider the clock absolutely not synced anymore? */
664       gst_clock_set_synced (GST_CLOCK (self), TRUE);
665     } else {
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;
671       time_discont = 0;
672       priv->skipped_updates++;
673     }
674   }
675
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);
679
680   if (bus) {
681     GstStructure *s;
682     GstMessage *msg;
683
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);
706   }
707
708   GST_INFO ("next timeout: %" GST_TIME_FORMAT, GST_TIME_ARGS (current_timeout));
709   self->priv->timeout_expiration = gst_util_get_timestamp () + current_timeout;
710
711   if (bus)
712     gst_object_unref (bus);
713   return;
714
715 bogus_observation:
716   if (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);
720   return;
721 }
722
723 static gpointer
724 gst_net_client_clock_thread (gpointer data)
725 {
726   GstNetClientClock *self = data;
727   GstClock *internal_clock = self->priv->internal_clock;
728   GSocket *socket = self->priv->socket;
729   GError *err = NULL;
730
731   GST_INFO_OBJECT (self, "net client clock thread running, socket=%p", socket);
732
733   g_socket_set_blocking (socket, TRUE);
734   g_socket_set_timeout (socket, 0);
735
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;
740
741     if (now >= expiration_time || (expiration_time - now) <= GST_MSECOND) {
742       socket_timeout = 0;
743     } else {
744       socket_timeout = (expiration_time - now) / GST_USECOND;
745     }
746
747     GST_TRACE_OBJECT (self, "timeout: %" G_GINT64_FORMAT "us", socket_timeout);
748
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);
755         break;
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");
759
760         if (self->priv->is_ntp) {
761           GstNtpPacket *packet;
762
763           packet = gst_ntp_packet_new (NULL, NULL);
764
765           packet->transmit_time = gst_clock_get_internal_time (internal_clock);
766
767           GST_DEBUG_OBJECT (self,
768               "sending packet, local time = %" GST_TIME_FORMAT,
769               GST_TIME_ARGS (packet->transmit_time));
770
771           gst_ntp_packet_send (packet, self->priv->socket,
772               self->priv->servaddr, NULL);
773
774           g_free (packet);
775         } else {
776           GstNetTimePacket *packet;
777
778           packet = gst_net_time_packet_new (NULL);
779
780           packet->local_time = gst_clock_get_internal_time (internal_clock);
781
782           GST_DEBUG_OBJECT (self,
783               "sending packet, local time = %" GST_TIME_FORMAT,
784               GST_TIME_ARGS (packet->local_time));
785
786           gst_net_time_packet_send (packet, self->priv->socket,
787               self->priv->servaddr, NULL);
788
789           g_free (packet);
790         }
791
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);
795       } else {
796         GST_DEBUG_OBJECT (self, "socket error: %s", err->message);
797         g_usleep (G_USEC_PER_SEC / 10); /* throttle */
798       }
799       g_clear_error (&err);
800     } else {
801       GstClockTime new_local;
802
803       /* got packet */
804
805       new_local = gst_clock_get_internal_time (internal_clock);
806
807       if (self->priv->is_ntp) {
808         GstNtpPacket *packet;
809
810         packet = gst_ntp_packet_receive (socket, NULL, &err);
811
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));
824
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;
828
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);
832
833           g_free (packet);
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);
838             break;
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");
842
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;
849
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);
855           } else {
856             GST_WARNING_OBJECT (self, "receive error: %s", err->message);
857           }
858           g_clear_error (&err);
859         }
860       } else {
861         GstNetTimePacket *packet;
862
863         packet = gst_net_time_packet_receive (socket, NULL, &err);
864
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));
873
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);
877
878           g_free (packet);
879         } else if (err != NULL) {
880           GST_WARNING_OBJECT (self, "receive error: %s", err->message);
881           g_clear_error (&err);
882         }
883       }
884     }
885   }
886   GST_INFO_OBJECT (self, "shutting down net client clock thread");
887   return NULL;
888 }
889
890 static gboolean
891 gst_net_client_clock_start (GstNetClientClock * self)
892 {
893   GSocketAddress *servaddr;
894   GSocketAddress *myaddr;
895   GSocketAddress *anyaddr;
896   GInetAddress *inetaddr;
897   GSocket *socket;
898   GError *error = NULL;
899   GSocketFamily family;
900   GPollFD dummy_pollfd;
901   GResolver *resolver = NULL;
902   GError *err = NULL;
903
904   g_return_val_if_fail (self->priv->address != NULL, FALSE);
905   g_return_val_if_fail (self->priv->servaddr == NULL, FALSE);
906
907   /* create target address */
908   inetaddr = g_inet_address_new_from_string (self->priv->address);
909   if (inetaddr == NULL) {
910     GList *results;
911
912     resolver = g_resolver_get_default ();
913
914     results =
915         g_resolver_lookup_by_name (resolver, self->priv->address, NULL, &err);
916     if (!results)
917       goto failed_to_resolve;
918
919     inetaddr = G_INET_ADDRESS (g_object_ref (results->data));
920     g_resolver_free_addresses (results);
921     g_object_unref (resolver);
922   }
923
924   family = g_inet_address_get_family (inetaddr);
925
926   servaddr = g_inet_socket_address_new (inetaddr, self->priv->port);
927   g_object_unref (inetaddr);
928
929   g_assert (servaddr != NULL);
930
931   GST_DEBUG_OBJECT (self, "will communicate with %s:%d", self->priv->address,
932       self->priv->port);
933
934   socket = g_socket_new (family, G_SOCKET_TYPE_DATAGRAM,
935       G_SOCKET_PROTOCOL_UDP, &error);
936
937   if (socket == NULL)
938     goto no_socket;
939
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);
946
947   if (error != NULL)
948     goto bind_error;
949
950   /* check address we're bound to, mostly for debugging purposes */
951   myaddr = g_socket_get_local_address (socket, &error);
952
953   if (myaddr == NULL)
954     goto getsockname_error;
955
956   GST_DEBUG_OBJECT (self, "socket opened on UDP port %d",
957       g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (myaddr)));
958
959   g_object_unref (myaddr);
960
961   self->priv->cancel = g_cancellable_new ();
962   self->priv->made_cancel_fd =
963       g_cancellable_make_pollfd (self->priv->cancel, &dummy_pollfd);
964
965   self->priv->socket = socket;
966   self->priv->servaddr = G_SOCKET_ADDRESS (servaddr);
967
968   self->priv->thread = g_thread_try_new ("GstNetClientClock",
969       gst_net_client_clock_thread, self, &error);
970
971   if (error != NULL)
972     goto no_thread;
973
974   return TRUE;
975
976   /* ERRORS */
977 no_socket:
978   {
979     GST_ERROR_OBJECT (self, "socket_new() failed: %s", error->message);
980     g_error_free (error);
981     return FALSE;
982   }
983 bind_error:
984   {
985     GST_ERROR_OBJECT (self, "bind failed: %s", error->message);
986     g_error_free (error);
987     g_object_unref (socket);
988     return FALSE;
989   }
990 getsockname_error:
991   {
992     GST_ERROR_OBJECT (self, "get_local_address() failed: %s", error->message);
993     g_error_free (error);
994     g_object_unref (socket);
995     return FALSE;
996   }
997 failed_to_resolve:
998   {
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);
1003     return FALSE;
1004   }
1005 no_thread:
1006   {
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);
1013     return FALSE;
1014   }
1015 }
1016
1017 static void
1018 gst_net_client_clock_stop (GstNetClientClock * self)
1019 {
1020   if (self->priv->thread == NULL)
1021     return;
1022
1023   GST_INFO_OBJECT (self, "stopping...");
1024   g_cancellable_cancel (self->priv->cancel);
1025
1026   g_thread_join (self->priv->thread);
1027   self->priv->thread = NULL;
1028
1029   if (self->priv->made_cancel_fd)
1030     g_cancellable_release_fd (self->priv->cancel);
1031
1032   g_object_unref (self->priv->cancel);
1033   self->priv->cancel = NULL;
1034
1035   g_object_unref (self->priv->servaddr);
1036   self->priv->servaddr = NULL;
1037
1038   g_object_unref (self->priv->socket);
1039   self->priv->socket = NULL;
1040
1041   GST_INFO_OBJECT (self, "stopped");
1042 }
1043
1044 /**
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
1050  *
1051  * Create a new #GstNetClientClock that will report the time
1052  * provided by the #GstNetTimeProvider on @remote_address and 
1053  * @remote_port.
1054  *
1055  * Returns: a new #GstClock that receives a time from the remote
1056  * clock.
1057  */
1058 GstClock *
1059 gst_net_client_clock_new (const gchar * name, const gchar * remote_address,
1060     gint remote_port, GstClockTime base_time)
1061 {
1062   GstNetClientClock *ret;
1063
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);
1068
1069   ret = g_object_new (GST_TYPE_NET_CLIENT_CLOCK, "address", remote_address,
1070       "port", remote_port, "base-time", base_time, NULL);
1071
1072   return (GstClock *) ret;
1073 }
1074
1075 G_DEFINE_TYPE (GstNtpClock, gst_ntp_clock, GST_TYPE_NET_CLIENT_CLOCK);
1076
1077 static void
1078 gst_ntp_clock_class_init (GstNtpClockClass * klass)
1079 {
1080 }
1081
1082 static void
1083 gst_ntp_clock_init (GstNtpClock * self)
1084 {
1085   GST_NET_CLIENT_CLOCK (self)->priv->is_ntp = TRUE;
1086 }
1087
1088 /**
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
1094  *
1095  * Create a new #GstNtpClock that will report the time provided by
1096  * the NTPv4 server on @remote_address and @remote_port.
1097  *
1098  * Returns: a new #GstClock that receives a time from the remote
1099  * clock.
1100  *
1101  * Since: 1.6
1102  */
1103 GstClock *
1104 gst_ntp_clock_new (const gchar * name, const gchar * remote_address,
1105     gint remote_port, GstClockTime base_time)
1106 {
1107   GstNetClientClock *ret;
1108
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);
1113
1114   ret = g_object_new (GST_TYPE_NTP_CLOCK, "address", remote_address,
1115       "port", remote_port, "base-time", base_time, NULL);
1116
1117   return (GstClock *) ret;
1118 }