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  * @title: GstNetClientClock
29  * @short_description: Special clock that synchronizes to a remote time
30  *                     provider.
31  * @see_also: #GstClock, #GstNetTimeProvider, #GstPipeline
32  *
33  * #GstNetClientClock implements a custom #GstClock that synchronizes its time
34  * to a remote time provider such as #GstNetTimeProvider. #GstNtpClock
35  * implements a #GstClock that synchronizes its time to a remote NTPv4 server.
36  *
37  * A new clock is created with gst_net_client_clock_new() or
38  * gst_ntp_clock_new(), which takes the address and port of the remote time
39  * provider along with a name and an initial time.
40  *
41  * This clock will poll the time provider and will update its calibration
42  * parameters based on the local and remote observations.
43  *
44  * The "round-trip" property limits the maximum round trip packets can take.
45  *
46  * Various parameters of the clock can be configured with the parent #GstClock
47  * "timeout", "window-size" and "window-threshold" object properties.
48  *
49  * A #GstNetClientClock and #GstNtpClock is typically set on a #GstPipeline with
50  * gst_pipeline_use_clock().
51  *
52  * If you set a #GstBus on the clock via the "bus" object property, it will
53  * send @GST_MESSAGE_ELEMENT messages with an attached #GstStructure containing
54  * statistics about clock accuracy and network traffic.
55  */
56 
57 #ifdef HAVE_CONFIG_H
58 #include "config.h"
59 #endif
60 
61 #include "gstnettimepacket.h"
62 #include "gstntppacket.h"
63 #include "gstnetclientclock.h"
64 #include "gstnetutils.h"
65 
66 #include <gio/gio.h>
67 
68 #include <string.h>
69 
70 GST_DEBUG_CATEGORY_STATIC (ncc_debug);
71 #define GST_CAT_DEFAULT (ncc_debug)
72 
73 typedef struct
74 {
75   GstClock *clock;              /* GstNetClientInternalClock */
76 
77   GList *clocks;                /* GstNetClientClocks */
78 
79   GstClockID remove_id;
80 } ClockCache;
81 
82 G_LOCK_DEFINE_STATIC (clocks_lock);
83 static GList *clocks = NULL;
84 
85 #define GST_TYPE_NET_CLIENT_INTERNAL_CLOCK \
86   (gst_net_client_internal_clock_get_type())
87 #define GST_NET_CLIENT_INTERNAL_CLOCK(obj) \
88   (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_NET_CLIENT_INTERNAL_CLOCK,GstNetClientInternalClock))
89 #define GST_NET_CLIENT_INTERNAL_CLOCK_CLASS(klass) \
90   (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_NET_CLIENT_INTERNAL_CLOCK,GstNetClientInternalClockClass))
91 #define GST_IS_NET_CLIENT_INTERNAL_CLOCK(obj) \
92   (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_NET_CLIENT_INTERNAL_CLOCK))
93 #define GST_IS_NET_CLIENT_INTERNAL_CLOCK_CLASS(klass) \
94   (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_NET_CLIENT_INTERNAL_CLOCK))
95 
96 typedef struct _GstNetClientInternalClock GstNetClientInternalClock;
97 typedef struct _GstNetClientInternalClockClass GstNetClientInternalClockClass;
98 
99 G_GNUC_INTERNAL GType gst_net_client_internal_clock_get_type (void);
100 
101 #define DEFAULT_ADDRESS         "127.0.0.1"
102 #define DEFAULT_PORT            5637
103 #define DEFAULT_TIMEOUT         GST_SECOND
104 #define DEFAULT_ROUNDTRIP_LIMIT GST_SECOND
105 /* Minimum timeout will be immediately (ie, as fast as one RTT), but no
106  * more often than 1/20th second (arbitrarily, to spread observations a little) */
107 #define DEFAULT_MINIMUM_UPDATE_INTERVAL (GST_SECOND / 20)
108 #define DEFAULT_BASE_TIME       0
109 #define DEFAULT_QOS_DSCP        -1
110 
111 /* Maximum number of clock updates we can skip before updating */
112 #define MAX_SKIPPED_UPDATES 5
113 
114 #define MEDIAN_PRE_FILTERING_WINDOW 9
115 
116 enum
117 {
118   PROP_0,
119   PROP_ADDRESS,
120   PROP_PORT,
121   PROP_ROUNDTRIP_LIMIT,
122   PROP_MINIMUM_UPDATE_INTERVAL,
123   PROP_BUS,
124   PROP_BASE_TIME,
125   PROP_INTERNAL_CLOCK,
126   PROP_IS_NTP,
127   PROP_QOS_DSCP
128 };
129 
130 struct _GstNetClientInternalClock
131 {
132   GstSystemClock clock;
133 
134   GThread *thread;
135 
136   GSocket *socket;
137   GSocketAddress *servaddr;
138   GCancellable *cancel;
139   gboolean made_cancel_fd;
140 
141   GstClockTime timeout_expiration;
142   GstClockTime roundtrip_limit;
143   GstClockTime rtt_avg;
144   GstClockTime minimum_update_interval;
145   GstClockTime last_remote_poll_interval;
146   guint skipped_updates;
147   GstClockTime last_rtts[MEDIAN_PRE_FILTERING_WINDOW];
148   gint last_rtts_missing;
149 
150   gchar *address;
151   gint port;
152   gboolean is_ntp;
153   gint qos_dscp;
154 
155   /* Protected by OBJECT_LOCK */
156   GList *busses;
157 };
158 
159 struct _GstNetClientInternalClockClass
160 {
161   GstSystemClockClass parent_class;
162 };
163 
164 #define _do_init \
165   GST_DEBUG_CATEGORY_INIT (ncc_debug, "netclock", 0, "Network client clock");
166 
167 G_DEFINE_TYPE_WITH_CODE (GstNetClientInternalClock,
168     gst_net_client_internal_clock, GST_TYPE_SYSTEM_CLOCK, _do_init);
169 
170 static void gst_net_client_internal_clock_finalize (GObject * object);
171 static void gst_net_client_internal_clock_set_property (GObject * object,
172     guint prop_id, const GValue * value, GParamSpec * pspec);
173 static void gst_net_client_internal_clock_get_property (GObject * object,
174     guint prop_id, GValue * value, GParamSpec * pspec);
175 static void gst_net_client_internal_clock_constructed (GObject * object);
176 
177 static gboolean gst_net_client_internal_clock_start (GstNetClientInternalClock *
178     self);
179 static void gst_net_client_internal_clock_stop (GstNetClientInternalClock *
180     self);
181 
182 static void
gst_net_client_internal_clock_class_init(GstNetClientInternalClockClass * klass)183 gst_net_client_internal_clock_class_init (GstNetClientInternalClockClass *
184     klass)
185 {
186   GObjectClass *gobject_class;
187 
188   gobject_class = G_OBJECT_CLASS (klass);
189 
190   gobject_class->finalize = gst_net_client_internal_clock_finalize;
191   gobject_class->get_property = gst_net_client_internal_clock_get_property;
192   gobject_class->set_property = gst_net_client_internal_clock_set_property;
193   gobject_class->constructed = gst_net_client_internal_clock_constructed;
194 
195   g_object_class_install_property (gobject_class, PROP_ADDRESS,
196       g_param_spec_string ("address", "address",
197           "The IP address of the machine providing a time server",
198           DEFAULT_ADDRESS,
199           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
200   g_object_class_install_property (gobject_class, PROP_PORT,
201       g_param_spec_int ("port", "port",
202           "The port on which the remote server is listening", 0, G_MAXUINT16,
203           DEFAULT_PORT,
204           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
205   g_object_class_install_property (gobject_class, PROP_IS_NTP,
206       g_param_spec_boolean ("is-ntp", "Is NTP",
207           "The clock is using the NTPv4 protocol", FALSE,
208           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
209 }
210 
211 static void
gst_net_client_internal_clock_init(GstNetClientInternalClock * self)212 gst_net_client_internal_clock_init (GstNetClientInternalClock * self)
213 {
214   GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC);
215 
216   self->port = DEFAULT_PORT;
217   self->address = g_strdup (DEFAULT_ADDRESS);
218   self->is_ntp = FALSE;
219   self->qos_dscp = DEFAULT_QOS_DSCP;
220 
221   gst_clock_set_timeout (GST_CLOCK (self), DEFAULT_TIMEOUT);
222 
223   self->thread = NULL;
224 
225   self->servaddr = NULL;
226   self->rtt_avg = GST_CLOCK_TIME_NONE;
227   self->roundtrip_limit = DEFAULT_ROUNDTRIP_LIMIT;
228   self->minimum_update_interval = DEFAULT_MINIMUM_UPDATE_INTERVAL;
229   self->last_remote_poll_interval = GST_CLOCK_TIME_NONE;
230   self->skipped_updates = 0;
231   self->last_rtts_missing = MEDIAN_PRE_FILTERING_WINDOW;
232 }
233 
234 static void
gst_net_client_internal_clock_finalize(GObject * object)235 gst_net_client_internal_clock_finalize (GObject * object)
236 {
237   GstNetClientInternalClock *self = GST_NET_CLIENT_INTERNAL_CLOCK (object);
238 
239   if (self->thread) {
240     gst_net_client_internal_clock_stop (self);
241   }
242 
243   g_free (self->address);
244   self->address = NULL;
245 
246   if (self->servaddr != NULL) {
247     g_object_unref (self->servaddr);
248     self->servaddr = NULL;
249   }
250 
251   if (self->socket != NULL) {
252     if (!g_socket_close (self->socket, NULL))
253       GST_ERROR_OBJECT (self, "Failed to close socket");
254     g_object_unref (self->socket);
255     self->socket = NULL;
256   }
257 
258   g_warn_if_fail (self->busses == NULL);
259 
260   G_OBJECT_CLASS (gst_net_client_internal_clock_parent_class)->finalize
261       (object);
262 }
263 
264 static void
gst_net_client_internal_clock_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)265 gst_net_client_internal_clock_set_property (GObject * object, guint prop_id,
266     const GValue * value, GParamSpec * pspec)
267 {
268   GstNetClientInternalClock *self = GST_NET_CLIENT_INTERNAL_CLOCK (object);
269 
270   switch (prop_id) {
271     case PROP_ADDRESS:
272       GST_OBJECT_LOCK (self);
273       g_free (self->address);
274       self->address = g_value_dup_string (value);
275       if (self->address == NULL)
276         self->address = g_strdup (DEFAULT_ADDRESS);
277       GST_OBJECT_UNLOCK (self);
278       break;
279     case PROP_PORT:
280       GST_OBJECT_LOCK (self);
281       self->port = g_value_get_int (value);
282       GST_OBJECT_UNLOCK (self);
283       break;
284     case PROP_IS_NTP:
285       GST_OBJECT_LOCK (self);
286       self->is_ntp = g_value_get_boolean (value);
287       GST_OBJECT_UNLOCK (self);
288       break;
289     default:
290       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
291       break;
292   }
293 }
294 
295 static void
gst_net_client_internal_clock_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)296 gst_net_client_internal_clock_get_property (GObject * object, guint prop_id,
297     GValue * value, GParamSpec * pspec)
298 {
299   GstNetClientInternalClock *self = GST_NET_CLIENT_INTERNAL_CLOCK (object);
300 
301   switch (prop_id) {
302     case PROP_ADDRESS:
303       GST_OBJECT_LOCK (self);
304       g_value_set_string (value, self->address);
305       GST_OBJECT_UNLOCK (self);
306       break;
307     case PROP_PORT:
308       g_value_set_int (value, self->port);
309       break;
310     case PROP_IS_NTP:
311       g_value_set_boolean (value, self->is_ntp);
312       break;
313     default:
314       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
315       break;
316   }
317 }
318 
319 static void
gst_net_client_internal_clock_constructed(GObject * object)320 gst_net_client_internal_clock_constructed (GObject * object)
321 {
322   GstNetClientInternalClock *self = GST_NET_CLIENT_INTERNAL_CLOCK (object);
323 
324   G_OBJECT_CLASS (gst_net_client_internal_clock_parent_class)->constructed
325       (object);
326 
327   if (!gst_net_client_internal_clock_start (self)) {
328     g_warning ("failed to start clock '%s'", GST_OBJECT_NAME (self));
329   }
330 
331   /* all systems go, cap'n */
332 }
333 
334 static gint
compare_clock_time(const GstClockTime * a,const GstClockTime * b)335 compare_clock_time (const GstClockTime * a, const GstClockTime * b)
336 {
337   if (*a < *b)
338     return -1;
339   else if (*a > *b)
340     return 1;
341   return 0;
342 }
343 
344 static void
gst_net_client_internal_clock_observe_times(GstNetClientInternalClock * self,GstClockTime local_1,GstClockTime remote_1,GstClockTime remote_2,GstClockTime local_2)345 gst_net_client_internal_clock_observe_times (GstNetClientInternalClock * self,
346     GstClockTime local_1, GstClockTime remote_1, GstClockTime remote_2,
347     GstClockTime local_2)
348 {
349   GstClockTime current_timeout = 0;
350   GstClockTime local_avg, remote_avg;
351   gdouble r_squared;
352   GstClock *clock;
353   GstClockTime rtt, rtt_limit, min_update_interval;
354   /* Use for discont tracking */
355   GstClockTime time_before = 0;
356   GstClockTime min_guess = 0;
357   GstClockTimeDiff time_discont = 0;
358   gboolean synched, now_synched;
359   GstClockTime internal_time, external_time, rate_num, rate_den;
360   GstClockTime orig_internal_time, orig_external_time, orig_rate_num,
361       orig_rate_den;
362   GstClockTime max_discont;
363   GstClockTime last_rtts[MEDIAN_PRE_FILTERING_WINDOW];
364   GstClockTime median;
365   gint i;
366 
367   GST_OBJECT_LOCK (self);
368   rtt_limit = self->roundtrip_limit;
369 
370   GST_LOG_OBJECT (self,
371       "local1 %" G_GUINT64_FORMAT " remote1 %" G_GUINT64_FORMAT " remote2 %"
372       G_GUINT64_FORMAT " local2 %" G_GUINT64_FORMAT, local_1, remote_1,
373       remote_2, local_2);
374 
375   /* If the server told us a poll interval and it's bigger than the
376    * one configured via the property, use the server's */
377   if (self->last_remote_poll_interval != GST_CLOCK_TIME_NONE &&
378       self->last_remote_poll_interval > self->minimum_update_interval)
379     min_update_interval = self->last_remote_poll_interval;
380   else
381     min_update_interval = self->minimum_update_interval;
382   GST_OBJECT_UNLOCK (self);
383 
384   if (local_2 < local_1) {
385     GST_LOG_OBJECT (self, "Dropping observation: receive time %" GST_TIME_FORMAT
386         " < send time %" GST_TIME_FORMAT, GST_TIME_ARGS (local_1),
387         GST_TIME_ARGS (local_2));
388     goto bogus_observation;
389   }
390 
391   if (remote_2 < remote_1) {
392     GST_LOG_OBJECT (self,
393         "Dropping observation: remote receive time %" GST_TIME_FORMAT
394         " < send time %" GST_TIME_FORMAT, GST_TIME_ARGS (remote_1),
395         GST_TIME_ARGS (remote_2));
396     goto bogus_observation;
397   }
398 
399   /* The round trip time is (assuming symmetric path delays)
400    * delta = (local_2 - local_1) - (remote_2 - remote_1)
401    */
402 
403   rtt = GST_CLOCK_DIFF (local_1, local_2) - GST_CLOCK_DIFF (remote_1, remote_2);
404 
405   if ((rtt_limit > 0) && (rtt > rtt_limit)) {
406     GST_LOG_OBJECT (self,
407         "Dropping observation: RTT %" GST_TIME_FORMAT " > limit %"
408         GST_TIME_FORMAT, GST_TIME_ARGS (rtt), GST_TIME_ARGS (rtt_limit));
409     goto bogus_observation;
410   }
411 
412   for (i = 1; i < MEDIAN_PRE_FILTERING_WINDOW; i++)
413     self->last_rtts[i - 1] = self->last_rtts[i];
414   self->last_rtts[i - 1] = rtt;
415 
416   if (self->last_rtts_missing) {
417     self->last_rtts_missing--;
418   } else {
419     memcpy (&last_rtts, &self->last_rtts, sizeof (last_rtts));
420     g_qsort_with_data (&last_rtts,
421         MEDIAN_PRE_FILTERING_WINDOW, sizeof (GstClockTime),
422         (GCompareDataFunc) compare_clock_time, NULL);
423 
424     median = last_rtts[MEDIAN_PRE_FILTERING_WINDOW / 2];
425 
426     /* FIXME: We might want to use something else here, like only allowing
427      * things in the interquartile range, or also filtering away delays that
428      * are too small compared to the median. This here worked well enough
429      * in tests so far.
430      */
431     if (rtt > 2 * median) {
432       GST_LOG_OBJECT (self,
433           "Dropping observation, long RTT %" GST_TIME_FORMAT " > 2 * median %"
434           GST_TIME_FORMAT, GST_TIME_ARGS (rtt), GST_TIME_ARGS (median));
435       goto bogus_observation;
436     }
437   }
438 
439   /* Track an average round trip time, for a bit of smoothing */
440   /* Always update before discarding a sample, so genuine changes in
441    * the network get picked up, eventually */
442   if (self->rtt_avg == GST_CLOCK_TIME_NONE)
443     self->rtt_avg = rtt;
444   else if (rtt < self->rtt_avg) /* Shorter RTTs carry more weight than longer */
445     self->rtt_avg = (3 * self->rtt_avg + rtt) / 4;
446   else
447     self->rtt_avg = (15 * self->rtt_avg + rtt) / 16;
448 
449   if (rtt > 2 * self->rtt_avg) {
450     GST_LOG_OBJECT (self,
451         "Dropping observation, long RTT %" GST_TIME_FORMAT " > 2 * avg %"
452         GST_TIME_FORMAT, GST_TIME_ARGS (rtt), GST_TIME_ARGS (self->rtt_avg));
453     goto bogus_observation;
454   }
455 
456   /* The difference between the local and remote clock (again assuming
457    * symmetric path delays):
458    *
459    * local_1 + delta / 2 - remote_1 = theta
460    * or
461    * local_2 - delta / 2 - remote_2 = theta
462    *
463    * which gives after some simple algebraic transformations:
464    *
465    *         (remote_1 - local_1) + (remote_2 - local_2)
466    * theta = -------------------------------------------
467    *                              2
468    *
469    *
470    * Thus remote time at local_avg is equal to:
471    *
472    * local_avg + theta =
473    *
474    * local_1 + local_2   (remote_1 - local_1) + (remote_2 - local_2)
475    * ----------------- + -------------------------------------------
476    *         2                                2
477    *
478    * =
479    *
480    * remote_1 + remote_2
481    * ------------------- = remote_avg
482    *          2
483    *
484    * We use this for our clock estimation, i.e. local_avg at remote clock
485    * being the same as remote_avg.
486    */
487 
488   local_avg = (local_2 + local_1) / 2;
489   remote_avg = (remote_2 + remote_1) / 2;
490 
491   GST_LOG_OBJECT (self,
492       "remoteavg %" G_GUINT64_FORMAT " localavg %" G_GUINT64_FORMAT,
493       remote_avg, local_avg);
494 
495   clock = GST_CLOCK_CAST (self);
496 
497   /* Store what the clock produced as 'now' before this update */
498   gst_clock_get_calibration (GST_CLOCK_CAST (self), &orig_internal_time,
499       &orig_external_time, &orig_rate_num, &orig_rate_den);
500   internal_time = orig_internal_time;
501   external_time = orig_external_time;
502   rate_num = orig_rate_num;
503   rate_den = orig_rate_den;
504 
505   min_guess =
506       gst_clock_adjust_with_calibration (GST_CLOCK_CAST (self), local_1,
507       internal_time, external_time, rate_num, rate_den);
508   time_before =
509       gst_clock_adjust_with_calibration (GST_CLOCK_CAST (self), local_2,
510       internal_time, external_time, rate_num, rate_den);
511 
512   /* Maximum discontinuity, when we're synched with the master. Could make this a property,
513    * but this value seems to work fine */
514   max_discont = self->rtt_avg / 4;
515 
516   /* If the remote observation was within a max_discont window around our min/max estimates, we're synched */
517   synched =
518       (GST_CLOCK_DIFF (remote_avg, min_guess) < (GstClockTimeDiff) (max_discont)
519       && GST_CLOCK_DIFF (time_before,
520           remote_avg) < (GstClockTimeDiff) (max_discont));
521 
522   if (gst_clock_add_observation_unapplied (GST_CLOCK_CAST (self),
523           local_avg, remote_avg, &r_squared, &internal_time, &external_time,
524           &rate_num, &rate_den)) {
525 
526     /* Now compare the difference (discont) in the clock
527      * after this observation */
528     time_discont = GST_CLOCK_DIFF (time_before,
529         gst_clock_adjust_with_calibration (GST_CLOCK_CAST (self), local_2,
530             internal_time, external_time, rate_num, rate_den));
531 
532     /* If we were in sync with the remote clock, clamp the allowed
533      * discontinuity to within quarter of one RTT. In sync means our send/receive estimates
534      * of remote time correctly windowed the actual remote time observation */
535     if (synched && ABS (time_discont) > max_discont) {
536       GstClockTimeDiff offset;
537       GST_DEBUG_OBJECT (clock,
538           "Too large a discont, clamping to 1/4 average RTT = %"
539           GST_TIME_FORMAT, GST_TIME_ARGS (max_discont));
540       if (time_discont > 0) {   /* Too large a forward step - add a -ve offset */
541         offset = max_discont - time_discont;
542         if (-offset > external_time)
543           external_time = 0;
544         else
545           external_time += offset;
546       } else {                  /* Too large a backward step - add a +ve offset */
547         offset = -(max_discont + time_discont);
548         external_time += offset;
549       }
550 
551       time_discont += offset;
552     }
553 
554     /* Check if the new clock params would have made our observation within range */
555     now_synched =
556         (GST_CLOCK_DIFF (remote_avg,
557             gst_clock_adjust_with_calibration (GST_CLOCK_CAST (self),
558                 local_1, internal_time, external_time, rate_num,
559                 rate_den)) < (GstClockTimeDiff) (max_discont))
560         &&
561         (GST_CLOCK_DIFF (gst_clock_adjust_with_calibration
562             (GST_CLOCK_CAST (self), local_2, internal_time, external_time,
563                 rate_num, rate_den),
564             remote_avg) < (GstClockTimeDiff) (max_discont));
565 
566     /* Only update the clock if we had synch or just gained it */
567     if (synched || now_synched || self->skipped_updates > MAX_SKIPPED_UPDATES) {
568       gst_clock_set_calibration (GST_CLOCK_CAST (self), internal_time,
569           external_time, rate_num, rate_den);
570       /* ghetto formula - shorter timeout for bad correlations */
571       current_timeout = (1e-3 / (1 - MIN (r_squared, 0.99999))) * GST_SECOND;
572       current_timeout =
573           MIN (current_timeout, gst_clock_get_timeout (GST_CLOCK_CAST (self)));
574       self->skipped_updates = 0;
575 
576       /* FIXME: When do we consider the clock absolutely not synced anymore? */
577       gst_clock_set_synced (GST_CLOCK (self), TRUE);
578     } else {
579       /* Restore original calibration vars for the report, we're not changing the clock */
580       internal_time = orig_internal_time;
581       external_time = orig_external_time;
582       rate_num = orig_rate_num;
583       rate_den = orig_rate_den;
584       time_discont = 0;
585       self->skipped_updates++;
586     }
587   }
588 
589   /* Limit the polling to at most one per minimum_update_interval */
590   if (rtt < min_update_interval)
591     current_timeout = MAX (min_update_interval - rtt, current_timeout);
592 
593   GST_OBJECT_LOCK (self);
594   if (self->busses) {
595     GstStructure *s;
596     GstMessage *msg;
597     GList *l;
598 
599     /* Output a stats message, whether we updated the clock or not */
600     s = gst_structure_new ("gst-netclock-statistics",
601         "synchronised", G_TYPE_BOOLEAN, synched,
602         "rtt", G_TYPE_UINT64, rtt,
603         "rtt-average", G_TYPE_UINT64, self->rtt_avg,
604         "local", G_TYPE_UINT64, local_avg,
605         "remote", G_TYPE_UINT64, remote_avg,
606         "discontinuity", G_TYPE_INT64, time_discont,
607         "remote-min-estimate", G_TYPE_UINT64, min_guess,
608         "remote-max-estimate", G_TYPE_UINT64, time_before,
609         "remote-min-error", G_TYPE_INT64, GST_CLOCK_DIFF (remote_avg,
610             min_guess), "remote-max-error", G_TYPE_INT64,
611         GST_CLOCK_DIFF (remote_avg, time_before), "request-send", G_TYPE_UINT64,
612         local_1, "request-receive", G_TYPE_UINT64, local_2, "r-squared",
613         G_TYPE_DOUBLE, r_squared, "timeout", G_TYPE_UINT64, current_timeout,
614         "internal-time", G_TYPE_UINT64, internal_time, "external-time",
615         G_TYPE_UINT64, external_time, "rate-num", G_TYPE_UINT64, rate_num,
616         "rate-den", G_TYPE_UINT64, rate_den, "rate", G_TYPE_DOUBLE,
617         (gdouble) (rate_num) / rate_den, "local-clock-offset", G_TYPE_INT64,
618         GST_CLOCK_DIFF (internal_time, external_time), NULL);
619     msg = gst_message_new_element (GST_OBJECT (self), s);
620 
621     for (l = self->busses; l; l = l->next)
622       gst_bus_post (l->data, gst_message_ref (msg));
623     gst_message_unref (msg);
624   }
625   GST_OBJECT_UNLOCK (self);
626 
627   GST_INFO ("next timeout: %" GST_TIME_FORMAT, GST_TIME_ARGS (current_timeout));
628   self->timeout_expiration = gst_util_get_timestamp () + current_timeout;
629 
630   return;
631 
632 bogus_observation:
633   /* Schedule a new packet again soon */
634   self->timeout_expiration = gst_util_get_timestamp () + (GST_SECOND / 4);
635   return;
636 }
637 
638 static gpointer
gst_net_client_internal_clock_thread(gpointer data)639 gst_net_client_internal_clock_thread (gpointer data)
640 {
641   GstNetClientInternalClock *self = data;
642   GSocket *socket = self->socket;
643   GError *err = NULL;
644   gint cur_qos_dscp = DEFAULT_QOS_DSCP;
645 
646   GST_INFO_OBJECT (self, "net client clock thread running, socket=%p", socket);
647 
648   g_socket_set_blocking (socket, TRUE);
649   g_socket_set_timeout (socket, 0);
650 
651   while (!g_cancellable_is_cancelled (self->cancel)) {
652     GstClockTime expiration_time = self->timeout_expiration;
653     GstClockTime now = gst_util_get_timestamp ();
654     gint64 socket_timeout;
655 
656     if (now >= expiration_time || (expiration_time - now) <= GST_MSECOND) {
657       socket_timeout = 0;
658     } else {
659       socket_timeout = (expiration_time - now) / GST_USECOND;
660     }
661 
662     GST_TRACE_OBJECT (self, "timeout: %" G_GINT64_FORMAT "us", socket_timeout);
663 
664     if (!g_socket_condition_timed_wait (socket, G_IO_IN, socket_timeout,
665             self->cancel, &err)) {
666       /* cancelled, timeout or error */
667       if (err->code == G_IO_ERROR_CANCELLED) {
668         GST_INFO_OBJECT (self, "cancelled");
669         g_clear_error (&err);
670         break;
671       } else if (err->code == G_IO_ERROR_TIMED_OUT) {
672         gint new_qos_dscp;
673 
674         /* timed out, let's send another packet */
675         GST_DEBUG_OBJECT (self, "timed out");
676 
677         /* before next sending check if need to change QoS */
678         new_qos_dscp = self->qos_dscp;
679         if (cur_qos_dscp != new_qos_dscp &&
680             gst_net_utils_set_socket_dscp (socket, new_qos_dscp)) {
681           GST_DEBUG_OBJECT (self, "changed QoS DSCP to: %d", new_qos_dscp);
682           cur_qos_dscp = new_qos_dscp;
683         }
684 
685         if (self->is_ntp) {
686           GstNtpPacket *packet;
687 
688           packet = gst_ntp_packet_new (NULL, NULL);
689 
690           packet->transmit_time =
691               gst_clock_get_internal_time (GST_CLOCK_CAST (self));
692 
693           GST_DEBUG_OBJECT (self,
694               "sending packet, local time = %" GST_TIME_FORMAT,
695               GST_TIME_ARGS (packet->transmit_time));
696 
697           gst_ntp_packet_send (packet, self->socket, self->servaddr, NULL);
698 
699           g_free (packet);
700         } else {
701           GstNetTimePacket *packet;
702 
703           packet = gst_net_time_packet_new (NULL);
704 
705           packet->local_time =
706               gst_clock_get_internal_time (GST_CLOCK_CAST (self));
707 
708           GST_DEBUG_OBJECT (self,
709               "sending packet, local time = %" GST_TIME_FORMAT,
710               GST_TIME_ARGS (packet->local_time));
711 
712           gst_net_time_packet_send (packet, self->socket, self->servaddr, NULL);
713 
714           g_free (packet);
715         }
716 
717         /* reset timeout (but are expecting a response sooner anyway) */
718         self->timeout_expiration =
719             gst_util_get_timestamp () +
720             gst_clock_get_timeout (GST_CLOCK_CAST (self));
721       } else {
722         GST_DEBUG_OBJECT (self, "socket error: %s", err->message);
723         g_usleep (G_USEC_PER_SEC / 10); /* throttle */
724       }
725       g_clear_error (&err);
726     } else {
727       GstClockTime new_local;
728 
729       /* got packet */
730 
731       new_local = gst_clock_get_internal_time (GST_CLOCK_CAST (self));
732 
733       if (self->is_ntp) {
734         GstNtpPacket *packet;
735 
736         packet = gst_ntp_packet_receive (socket, NULL, &err);
737 
738         if (packet != NULL) {
739           GST_LOG_OBJECT (self, "got packet back");
740           GST_LOG_OBJECT (self, "local_1 = %" GST_TIME_FORMAT,
741               GST_TIME_ARGS (packet->origin_time));
742           GST_LOG_OBJECT (self, "remote_1 = %" GST_TIME_FORMAT,
743               GST_TIME_ARGS (packet->receive_time));
744           GST_LOG_OBJECT (self, "remote_2 = %" GST_TIME_FORMAT,
745               GST_TIME_ARGS (packet->transmit_time));
746           GST_LOG_OBJECT (self, "local_2 = %" GST_TIME_FORMAT,
747               GST_TIME_ARGS (new_local));
748           GST_LOG_OBJECT (self, "poll_interval = %" GST_TIME_FORMAT,
749               GST_TIME_ARGS (packet->poll_interval));
750 
751           /* Remember the last poll interval we ever got from the server */
752           if (packet->poll_interval != GST_CLOCK_TIME_NONE)
753             self->last_remote_poll_interval = packet->poll_interval;
754 
755           /* observe_times will reset the timeout */
756           gst_net_client_internal_clock_observe_times (self,
757               packet->origin_time, packet->receive_time, packet->transmit_time,
758               new_local);
759 
760           g_free (packet);
761         } else if (err != NULL) {
762           if (g_error_matches (err, GST_NTP_ERROR, GST_NTP_ERROR_WRONG_VERSION)
763               || g_error_matches (err, GST_NTP_ERROR, GST_NTP_ERROR_KOD_DENY)) {
764             GST_ERROR_OBJECT (self, "fatal receive error: %s", err->message);
765             g_clear_error (&err);
766             break;
767           } else if (g_error_matches (err, GST_NTP_ERROR,
768                   GST_NTP_ERROR_KOD_RATE)) {
769             GST_WARNING_OBJECT (self, "need to limit rate");
770 
771             /* If the server did not tell us a poll interval before, double
772              * our minimum poll interval. Otherwise we assume that the server
773              * already told us something sensible and that this error here
774              * was just a spurious error */
775             if (self->last_remote_poll_interval == GST_CLOCK_TIME_NONE)
776               self->minimum_update_interval *= 2;
777 
778             /* And wait a bit before we send the next packet instead of
779              * sending it immediately */
780             self->timeout_expiration =
781                 gst_util_get_timestamp () +
782                 gst_clock_get_timeout (GST_CLOCK_CAST (self));
783           } else {
784             GST_WARNING_OBJECT (self, "receive error: %s", err->message);
785           }
786           g_clear_error (&err);
787         }
788       } else {
789         GstNetTimePacket *packet;
790 
791         packet = gst_net_time_packet_receive (socket, NULL, &err);
792 
793         if (packet != NULL) {
794           GST_LOG_OBJECT (self, "got packet back");
795           GST_LOG_OBJECT (self, "local_1 = %" GST_TIME_FORMAT,
796               GST_TIME_ARGS (packet->local_time));
797           GST_LOG_OBJECT (self, "remote = %" GST_TIME_FORMAT,
798               GST_TIME_ARGS (packet->remote_time));
799           GST_LOG_OBJECT (self, "local_2 = %" GST_TIME_FORMAT,
800               GST_TIME_ARGS (new_local));
801 
802           /* observe_times will reset the timeout */
803           gst_net_client_internal_clock_observe_times (self, packet->local_time,
804               packet->remote_time, packet->remote_time, new_local);
805 
806           g_free (packet);
807         } else if (err != NULL) {
808           GST_WARNING_OBJECT (self, "receive error: %s", err->message);
809           g_clear_error (&err);
810         }
811       }
812     }
813   }
814   GST_INFO_OBJECT (self, "shutting down net client clock thread");
815   return NULL;
816 }
817 
818 static gboolean
gst_net_client_internal_clock_start(GstNetClientInternalClock * self)819 gst_net_client_internal_clock_start (GstNetClientInternalClock * self)
820 {
821   GSocketAddress *servaddr;
822   GSocketAddress *myaddr;
823   GSocketAddress *anyaddr;
824   GInetAddress *inetaddr;
825   GSocket *socket;
826   GError *error = NULL;
827   GSocketFamily family;
828   GPollFD dummy_pollfd;
829   GResolver *resolver = NULL;
830   GError *err = NULL;
831 
832   g_return_val_if_fail (self->address != NULL, FALSE);
833   g_return_val_if_fail (self->servaddr == NULL, FALSE);
834 
835   /* create target address */
836   inetaddr = g_inet_address_new_from_string (self->address);
837   if (inetaddr == NULL) {
838     GList *results;
839 
840     resolver = g_resolver_get_default ();
841 
842     results = g_resolver_lookup_by_name (resolver, self->address, NULL, &err);
843     if (!results)
844       goto failed_to_resolve;
845 
846     inetaddr = G_INET_ADDRESS (g_object_ref (results->data));
847     g_resolver_free_addresses (results);
848     g_object_unref (resolver);
849   }
850 
851   family = g_inet_address_get_family (inetaddr);
852 
853   servaddr = g_inet_socket_address_new (inetaddr, self->port);
854   g_object_unref (inetaddr);
855 
856   g_assert (servaddr != NULL);
857 
858   GST_DEBUG_OBJECT (self, "will communicate with %s:%d", self->address,
859       self->port);
860 
861   socket = g_socket_new (family, G_SOCKET_TYPE_DATAGRAM,
862       G_SOCKET_PROTOCOL_UDP, &error);
863 
864   if (socket == NULL)
865     goto no_socket;
866 
867   GST_DEBUG_OBJECT (self, "binding socket");
868   inetaddr = g_inet_address_new_any (family);
869   anyaddr = g_inet_socket_address_new (inetaddr, 0);
870   g_socket_bind (socket, anyaddr, TRUE, &error);
871   g_object_unref (anyaddr);
872   g_object_unref (inetaddr);
873 
874   if (error != NULL)
875     goto bind_error;
876 
877   /* check address we're bound to, mostly for debugging purposes */
878   myaddr = g_socket_get_local_address (socket, &error);
879 
880   if (myaddr == NULL)
881     goto getsockname_error;
882 
883   GST_DEBUG_OBJECT (self, "socket opened on UDP port %d",
884       g_inet_socket_address_get_port (G_INET_SOCKET_ADDRESS (myaddr)));
885 
886   g_object_unref (myaddr);
887 
888   self->cancel = g_cancellable_new ();
889   self->made_cancel_fd =
890       g_cancellable_make_pollfd (self->cancel, &dummy_pollfd);
891 
892   self->socket = socket;
893   self->servaddr = G_SOCKET_ADDRESS (servaddr);
894 
895   self->thread = g_thread_try_new ("GstNetClientInternalClock",
896       gst_net_client_internal_clock_thread, self, &error);
897 
898   if (error != NULL)
899     goto no_thread;
900 
901   return TRUE;
902 
903   /* ERRORS */
904 no_socket:
905   {
906     GST_ERROR_OBJECT (self, "socket_new() failed: %s", error->message);
907     g_error_free (error);
908     return FALSE;
909   }
910 bind_error:
911   {
912     GST_ERROR_OBJECT (self, "bind failed: %s", error->message);
913     g_error_free (error);
914     g_object_unref (socket);
915     return FALSE;
916   }
917 getsockname_error:
918   {
919     GST_ERROR_OBJECT (self, "get_local_address() failed: %s", error->message);
920     g_error_free (error);
921     g_object_unref (socket);
922     return FALSE;
923   }
924 failed_to_resolve:
925   {
926     GST_ERROR_OBJECT (self, "resolving '%s' failed: %s",
927         self->address, err->message);
928     g_clear_error (&err);
929     g_object_unref (resolver);
930     return FALSE;
931   }
932 no_thread:
933   {
934     GST_ERROR_OBJECT (self, "could not create thread: %s", error->message);
935     g_object_unref (self->servaddr);
936     self->servaddr = NULL;
937     g_object_unref (self->socket);
938     self->socket = NULL;
939     g_error_free (error);
940     return FALSE;
941   }
942 }
943 
944 static void
gst_net_client_internal_clock_stop(GstNetClientInternalClock * self)945 gst_net_client_internal_clock_stop (GstNetClientInternalClock * self)
946 {
947   if (self->thread == NULL)
948     return;
949 
950   GST_INFO_OBJECT (self, "stopping...");
951   g_cancellable_cancel (self->cancel);
952 
953   g_thread_join (self->thread);
954   self->thread = NULL;
955 
956   if (self->made_cancel_fd)
957     g_cancellable_release_fd (self->cancel);
958 
959   g_object_unref (self->cancel);
960   self->cancel = NULL;
961 
962   g_object_unref (self->servaddr);
963   self->servaddr = NULL;
964 
965   g_object_unref (self->socket);
966   self->socket = NULL;
967 
968   GST_INFO_OBJECT (self, "stopped");
969 }
970 
971 struct _GstNetClientClockPrivate
972 {
973   GstClock *internal_clock;
974 
975   GstClockTime roundtrip_limit;
976   GstClockTime minimum_update_interval;
977 
978   GstClockTime base_time, internal_base_time;
979 
980   gchar *address;
981   gint port;
982   gint qos_dscp;
983 
984   GstBus *bus;
985 
986   gboolean is_ntp;
987 
988   gulong synced_id;
989 };
990 
991 G_DEFINE_TYPE_WITH_PRIVATE (GstNetClientClock, gst_net_client_clock,
992     GST_TYPE_SYSTEM_CLOCK);
993 
994 static void gst_net_client_clock_finalize (GObject * object);
995 static void gst_net_client_clock_set_property (GObject * object, guint prop_id,
996     const GValue * value, GParamSpec * pspec);
997 static void gst_net_client_clock_get_property (GObject * object, guint prop_id,
998     GValue * value, GParamSpec * pspec);
999 static void gst_net_client_clock_constructed (GObject * object);
1000 
1001 static GstClockTime gst_net_client_clock_get_internal_time (GstClock * clock);
1002 
1003 static void
gst_net_client_clock_class_init(GstNetClientClockClass * klass)1004 gst_net_client_clock_class_init (GstNetClientClockClass * klass)
1005 {
1006   GObjectClass *gobject_class;
1007   GstClockClass *clock_class;
1008 
1009   gobject_class = G_OBJECT_CLASS (klass);
1010   clock_class = GST_CLOCK_CLASS (klass);
1011 
1012   gobject_class->finalize = gst_net_client_clock_finalize;
1013   gobject_class->get_property = gst_net_client_clock_get_property;
1014   gobject_class->set_property = gst_net_client_clock_set_property;
1015   gobject_class->constructed = gst_net_client_clock_constructed;
1016 
1017   g_object_class_install_property (gobject_class, PROP_ADDRESS,
1018       g_param_spec_string ("address", "address",
1019           "The IP address of the machine providing a time server",
1020           DEFAULT_ADDRESS,
1021           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
1022   g_object_class_install_property (gobject_class, PROP_PORT,
1023       g_param_spec_int ("port", "port",
1024           "The port on which the remote server is listening", 0, G_MAXUINT16,
1025           DEFAULT_PORT,
1026           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
1027   g_object_class_install_property (gobject_class, PROP_BUS,
1028       g_param_spec_object ("bus", "bus",
1029           "A GstBus on which to send clock status information", GST_TYPE_BUS,
1030           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1031 
1032   /**
1033    * GstNetClientInternalClock::round-trip-limit:
1034    *
1035    * Maximum allowed round-trip for packets. If this property is set to a nonzero
1036    * value, all packets with a round-trip interval larger than this limit will be
1037    * ignored. This is useful for networks with severe and fluctuating transport
1038    * delays. Filtering out these packets increases stability of the synchronization.
1039    * On the other hand, the lower the limit, the higher the amount of filtered
1040    * packets. Empirical tests are typically necessary to estimate a good value
1041    * for the limit.
1042    * If the property is set to zero, the limit is disabled.
1043    *
1044    * Since: 1.4
1045    */
1046   g_object_class_install_property (gobject_class, PROP_ROUNDTRIP_LIMIT,
1047       g_param_spec_uint64 ("round-trip-limit", "round-trip limit",
1048           "Maximum tolerable round-trip interval for packets, in nanoseconds "
1049           "(0 = no limit)", 0, G_MAXUINT64, DEFAULT_ROUNDTRIP_LIMIT,
1050           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1051 
1052   g_object_class_install_property (gobject_class, PROP_MINIMUM_UPDATE_INTERVAL,
1053       g_param_spec_uint64 ("minimum-update-interval", "minimum update interval",
1054           "Minimum polling interval for packets, in nanoseconds"
1055           "(0 = no limit)", 0, G_MAXUINT64, DEFAULT_MINIMUM_UPDATE_INTERVAL,
1056           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1057 
1058   g_object_class_install_property (gobject_class, PROP_BASE_TIME,
1059       g_param_spec_uint64 ("base-time", "Base Time",
1060           "Initial time that is reported before synchronization", 0,
1061           G_MAXUINT64, DEFAULT_BASE_TIME,
1062           G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
1063 
1064   g_object_class_install_property (gobject_class, PROP_INTERNAL_CLOCK,
1065       g_param_spec_object ("internal-clock", "Internal Clock",
1066           "Internal clock that directly slaved to the remote clock",
1067           GST_TYPE_CLOCK, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1068 
1069   g_object_class_install_property (gobject_class, PROP_QOS_DSCP,
1070       g_param_spec_int ("qos-dscp", "QoS diff srv code point",
1071           "Quality of Service, differentiated services code point (-1 default)",
1072           -1, 63, DEFAULT_QOS_DSCP,
1073           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1074 
1075   clock_class->get_internal_time = gst_net_client_clock_get_internal_time;
1076 }
1077 
1078 static void
gst_net_client_clock_init(GstNetClientClock * self)1079 gst_net_client_clock_init (GstNetClientClock * self)
1080 {
1081   GstNetClientClockPrivate *priv;
1082   GstClock *clock;
1083 
1084   self->priv = priv = gst_net_client_clock_get_instance_private (self);
1085 
1086   GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_CAN_SET_MASTER);
1087   GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC);
1088 
1089   priv->port = DEFAULT_PORT;
1090   priv->address = g_strdup (DEFAULT_ADDRESS);
1091   priv->qos_dscp = DEFAULT_QOS_DSCP;
1092 
1093   priv->roundtrip_limit = DEFAULT_ROUNDTRIP_LIMIT;
1094   priv->minimum_update_interval = DEFAULT_MINIMUM_UPDATE_INTERVAL;
1095 
1096   clock = gst_system_clock_obtain ();
1097   priv->base_time = DEFAULT_BASE_TIME;
1098   priv->internal_base_time = gst_clock_get_time (clock);
1099   gst_object_unref (clock);
1100 }
1101 
1102 /* Must be called with clocks_lock */
1103 static void
update_clock_cache(ClockCache * cache)1104 update_clock_cache (ClockCache * cache)
1105 {
1106   GstClockTime roundtrip_limit = 0, minimum_update_interval = 0;
1107   GList *l, *busses = NULL;
1108   gint qos_dscp = DEFAULT_QOS_DSCP;
1109 
1110   GST_OBJECT_LOCK (cache->clock);
1111   g_list_free_full (GST_NET_CLIENT_INTERNAL_CLOCK (cache->clock)->busses,
1112       (GDestroyNotify) gst_object_unref);
1113 
1114   for (l = cache->clocks; l; l = l->next) {
1115     GstNetClientClock *clock = l->data;
1116 
1117     if (clock->priv->bus)
1118       busses = g_list_prepend (busses, gst_object_ref (clock->priv->bus));
1119 
1120     if (roundtrip_limit == 0)
1121       roundtrip_limit = clock->priv->roundtrip_limit;
1122     else
1123       roundtrip_limit = MAX (roundtrip_limit, clock->priv->roundtrip_limit);
1124 
1125     if (minimum_update_interval == 0)
1126       minimum_update_interval = clock->priv->minimum_update_interval;
1127     else
1128       minimum_update_interval =
1129           MIN (minimum_update_interval, clock->priv->minimum_update_interval);
1130 
1131     qos_dscp = MAX (qos_dscp, clock->priv->qos_dscp);
1132   }
1133   GST_NET_CLIENT_INTERNAL_CLOCK (cache->clock)->busses = busses;
1134   GST_NET_CLIENT_INTERNAL_CLOCK (cache->clock)->roundtrip_limit =
1135       roundtrip_limit;
1136   GST_NET_CLIENT_INTERNAL_CLOCK (cache->clock)->minimum_update_interval =
1137       minimum_update_interval;
1138   GST_NET_CLIENT_INTERNAL_CLOCK (cache->clock)->qos_dscp = qos_dscp;
1139 
1140   GST_OBJECT_UNLOCK (cache->clock);
1141 }
1142 
1143 static gboolean
remove_clock_cache(GstClock * clock,GstClockTime time,GstClockID id,gpointer user_data)1144 remove_clock_cache (GstClock * clock, GstClockTime time, GstClockID id,
1145     gpointer user_data)
1146 {
1147   ClockCache *cache = user_data;
1148 
1149   G_LOCK (clocks_lock);
1150   if (!cache->clocks) {
1151     gst_clock_id_unref (cache->remove_id);
1152     gst_object_unref (cache->clock);
1153     clocks = g_list_remove (clocks, cache);
1154     g_free (cache);
1155   }
1156   G_UNLOCK (clocks_lock);
1157 
1158   return TRUE;
1159 }
1160 
1161 static void
gst_net_client_clock_finalize(GObject * object)1162 gst_net_client_clock_finalize (GObject * object)
1163 {
1164   GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
1165   GList *l;
1166 
1167   if (self->priv->synced_id)
1168     g_signal_handler_disconnect (self->priv->internal_clock,
1169         self->priv->synced_id);
1170   self->priv->synced_id = 0;
1171 
1172   G_LOCK (clocks_lock);
1173   for (l = clocks; l; l = l->next) {
1174     ClockCache *cache = l->data;
1175 
1176     if (cache->clock == self->priv->internal_clock) {
1177       cache->clocks = g_list_remove (cache->clocks, self);
1178 
1179       if (cache->clocks) {
1180         update_clock_cache (cache);
1181       } else {
1182         GstClock *sysclock = gst_system_clock_obtain ();
1183         GstClockTime time = gst_clock_get_time (sysclock) + 60 * GST_SECOND;
1184 
1185         cache->remove_id = gst_clock_new_single_shot_id (sysclock, time);
1186         gst_clock_id_wait_async (cache->remove_id, remove_clock_cache, cache,
1187             NULL);
1188         gst_object_unref (sysclock);
1189       }
1190       break;
1191     }
1192   }
1193   G_UNLOCK (clocks_lock);
1194 
1195   g_free (self->priv->address);
1196   self->priv->address = NULL;
1197 
1198   if (self->priv->bus != NULL) {
1199     gst_object_unref (self->priv->bus);
1200     self->priv->bus = NULL;
1201   }
1202 
1203   G_OBJECT_CLASS (gst_net_client_clock_parent_class)->finalize (object);
1204 }
1205 
1206 static void
gst_net_client_clock_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)1207 gst_net_client_clock_set_property (GObject * object, guint prop_id,
1208     const GValue * value, GParamSpec * pspec)
1209 {
1210   GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
1211   gboolean update = FALSE;
1212 
1213   switch (prop_id) {
1214     case PROP_ADDRESS:
1215       GST_OBJECT_LOCK (self);
1216       g_free (self->priv->address);
1217       self->priv->address = g_value_dup_string (value);
1218       if (self->priv->address == NULL)
1219         self->priv->address = g_strdup (DEFAULT_ADDRESS);
1220       GST_OBJECT_UNLOCK (self);
1221       break;
1222     case PROP_PORT:
1223       GST_OBJECT_LOCK (self);
1224       self->priv->port = g_value_get_int (value);
1225       GST_OBJECT_UNLOCK (self);
1226       break;
1227     case PROP_ROUNDTRIP_LIMIT:
1228       GST_OBJECT_LOCK (self);
1229       self->priv->roundtrip_limit = g_value_get_uint64 (value);
1230       GST_OBJECT_UNLOCK (self);
1231       update = TRUE;
1232       break;
1233     case PROP_MINIMUM_UPDATE_INTERVAL:
1234       GST_OBJECT_LOCK (self);
1235       self->priv->minimum_update_interval = g_value_get_uint64 (value);
1236       GST_OBJECT_UNLOCK (self);
1237       update = TRUE;
1238       break;
1239     case PROP_BUS:
1240       GST_OBJECT_LOCK (self);
1241       if (self->priv->bus)
1242         gst_object_unref (self->priv->bus);
1243       self->priv->bus = g_value_dup_object (value);
1244       GST_OBJECT_UNLOCK (self);
1245       update = TRUE;
1246       break;
1247     case PROP_BASE_TIME:{
1248       GstClock *clock;
1249 
1250       self->priv->base_time = g_value_get_uint64 (value);
1251       clock = gst_system_clock_obtain ();
1252       self->priv->internal_base_time = gst_clock_get_time (clock);
1253       gst_object_unref (clock);
1254       break;
1255     }
1256     case PROP_QOS_DSCP:
1257       GST_OBJECT_LOCK (self);
1258       self->priv->qos_dscp = g_value_get_int (value);
1259       GST_OBJECT_UNLOCK (self);
1260       update = TRUE;
1261       break;
1262     default:
1263       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1264       break;
1265   }
1266 
1267   if (update && self->priv->internal_clock) {
1268     GList *l;
1269 
1270     G_LOCK (clocks_lock);
1271     for (l = clocks; l; l = l->next) {
1272       ClockCache *cache = l->data;
1273 
1274       if (cache->clock == self->priv->internal_clock) {
1275         update_clock_cache (cache);
1276       }
1277     }
1278     G_UNLOCK (clocks_lock);
1279   }
1280 }
1281 
1282 static void
gst_net_client_clock_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)1283 gst_net_client_clock_get_property (GObject * object, guint prop_id,
1284     GValue * value, GParamSpec * pspec)
1285 {
1286   GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
1287 
1288   switch (prop_id) {
1289     case PROP_ADDRESS:
1290       GST_OBJECT_LOCK (self);
1291       g_value_set_string (value, self->priv->address);
1292       GST_OBJECT_UNLOCK (self);
1293       break;
1294     case PROP_PORT:
1295       g_value_set_int (value, self->priv->port);
1296       break;
1297     case PROP_ROUNDTRIP_LIMIT:
1298       GST_OBJECT_LOCK (self);
1299       g_value_set_uint64 (value, self->priv->roundtrip_limit);
1300       GST_OBJECT_UNLOCK (self);
1301       break;
1302     case PROP_MINIMUM_UPDATE_INTERVAL:
1303       GST_OBJECT_LOCK (self);
1304       g_value_set_uint64 (value, self->priv->minimum_update_interval);
1305       GST_OBJECT_UNLOCK (self);
1306       break;
1307     case PROP_BUS:
1308       GST_OBJECT_LOCK (self);
1309       g_value_set_object (value, self->priv->bus);
1310       GST_OBJECT_UNLOCK (self);
1311       break;
1312     case PROP_BASE_TIME:
1313       g_value_set_uint64 (value, self->priv->base_time);
1314       break;
1315     case PROP_INTERNAL_CLOCK:
1316       g_value_set_object (value, self->priv->internal_clock);
1317       break;
1318     case PROP_QOS_DSCP:
1319       GST_OBJECT_LOCK (self);
1320       g_value_set_int (value, self->priv->qos_dscp);
1321       GST_OBJECT_UNLOCK (self);
1322       break;
1323     default:
1324       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1325       break;
1326   }
1327 }
1328 
1329 static void
gst_net_client_clock_synced_cb(GstClock * internal_clock,gboolean synced,GstClock * self)1330 gst_net_client_clock_synced_cb (GstClock * internal_clock, gboolean synced,
1331     GstClock * self)
1332 {
1333   gst_clock_set_synced (self, synced);
1334 }
1335 
1336 static void
gst_net_client_clock_constructed(GObject * object)1337 gst_net_client_clock_constructed (GObject * object)
1338 {
1339   GstNetClientClock *self = GST_NET_CLIENT_CLOCK (object);
1340   GstClock *internal_clock;
1341   GList *l;
1342   ClockCache *cache = NULL;
1343 
1344   G_OBJECT_CLASS (gst_net_client_clock_parent_class)->constructed (object);
1345 
1346   G_LOCK (clocks_lock);
1347   for (l = clocks; l; l = l->next) {
1348     ClockCache *tmp = l->data;
1349     GstNetClientInternalClock *internal_clock =
1350         GST_NET_CLIENT_INTERNAL_CLOCK (tmp->clock);
1351 
1352     if (strcmp (internal_clock->address, self->priv->address) == 0 &&
1353         internal_clock->port == self->priv->port) {
1354       cache = tmp;
1355 
1356       if (cache->remove_id) {
1357         gst_clock_id_unschedule (cache->remove_id);
1358         cache->remove_id = NULL;
1359       }
1360       break;
1361     }
1362   }
1363 
1364   if (!cache) {
1365     cache = g_new0 (ClockCache, 1);
1366 
1367     cache->clock =
1368         g_object_new (GST_TYPE_NET_CLIENT_INTERNAL_CLOCK, "address",
1369         self->priv->address, "port", self->priv->port, "is-ntp",
1370         self->priv->is_ntp, NULL);
1371     gst_object_ref_sink (cache->clock);
1372     clocks = g_list_prepend (clocks, cache);
1373 
1374     /* Not actually leaked but is cached for a while before being disposed,
1375      * see gst_net_client_clock_finalize, so pretend it is to not confuse
1376      * tests. */
1377     GST_OBJECT_FLAG_SET (cache->clock, GST_OBJECT_FLAG_MAY_BE_LEAKED);
1378   }
1379 
1380   cache->clocks = g_list_prepend (cache->clocks, self);
1381 
1382   GST_OBJECT_LOCK (cache->clock);
1383   if (gst_clock_is_synced (cache->clock))
1384     gst_clock_set_synced (GST_CLOCK (self), TRUE);
1385   self->priv->synced_id =
1386       g_signal_connect (cache->clock, "synced",
1387       G_CALLBACK (gst_net_client_clock_synced_cb), self);
1388   GST_OBJECT_UNLOCK (cache->clock);
1389 
1390   G_UNLOCK (clocks_lock);
1391 
1392   self->priv->internal_clock = internal_clock = cache->clock;
1393 
1394   /* all systems go, cap'n */
1395 }
1396 
1397 static GstClockTime
gst_net_client_clock_get_internal_time(GstClock * clock)1398 gst_net_client_clock_get_internal_time (GstClock * clock)
1399 {
1400   GstNetClientClock *self = GST_NET_CLIENT_CLOCK (clock);
1401 
1402   if (!gst_clock_is_synced (self->priv->internal_clock)) {
1403     GstClockTime now = gst_clock_get_internal_time (self->priv->internal_clock);
1404     return gst_clock_adjust_with_calibration (self->priv->internal_clock, now,
1405         self->priv->internal_base_time, self->priv->base_time, 1, 1);
1406   }
1407 
1408   return gst_clock_get_time (self->priv->internal_clock);
1409 }
1410 
1411 /**
1412  * gst_net_client_clock_new:
1413  * @name: a name for the clock
1414  * @remote_address: the address or hostname of the remote clock provider
1415  * @remote_port: the port of the remote clock provider
1416  * @base_time: initial time of the clock
1417  *
1418  * Create a new #GstNetClientInternalClock that will report the time
1419  * provided by the #GstNetTimeProvider on @remote_address and
1420  * @remote_port.
1421  *
1422  * Returns: (transfer full): a new #GstClock that receives a time from the remote
1423  * clock.
1424  */
1425 GstClock *
gst_net_client_clock_new(const gchar * name,const gchar * remote_address,gint remote_port,GstClockTime base_time)1426 gst_net_client_clock_new (const gchar * name, const gchar * remote_address,
1427     gint remote_port, GstClockTime base_time)
1428 {
1429   GstClock *ret;
1430 
1431   g_return_val_if_fail (remote_address != NULL, NULL);
1432   g_return_val_if_fail (remote_port > 0, NULL);
1433   g_return_val_if_fail (remote_port <= G_MAXUINT16, NULL);
1434   g_return_val_if_fail (base_time != GST_CLOCK_TIME_NONE, NULL);
1435 
1436   ret =
1437       g_object_new (GST_TYPE_NET_CLIENT_CLOCK, "name", name, "address",
1438       remote_address, "port", remote_port, "base-time", base_time, NULL);
1439 
1440   /* Clear floating flag */
1441   gst_object_ref_sink (ret);
1442 
1443   return ret;
1444 }
1445 
1446 G_DEFINE_TYPE (GstNtpClock, gst_ntp_clock, GST_TYPE_NET_CLIENT_CLOCK);
1447 
1448 static void
gst_ntp_clock_class_init(GstNtpClockClass * klass)1449 gst_ntp_clock_class_init (GstNtpClockClass * klass)
1450 {
1451 }
1452 
1453 static void
gst_ntp_clock_init(GstNtpClock * self)1454 gst_ntp_clock_init (GstNtpClock * self)
1455 {
1456   GST_NET_CLIENT_CLOCK (self)->priv->is_ntp = TRUE;
1457 }
1458 
1459 /**
1460  * gst_ntp_clock_new:
1461  * @name: a name for the clock
1462  * @remote_address: the address or hostname of the remote clock provider
1463  * @remote_port: the port of the remote clock provider
1464  * @base_time: initial time of the clock
1465  *
1466  * Create a new #GstNtpClock that will report the time provided by
1467  * the NTPv4 server on @remote_address and @remote_port.
1468  *
1469  * Returns: (transfer full): a new #GstClock that receives a time from the remote
1470  * clock.
1471  *
1472  * Since: 1.6
1473  */
1474 GstClock *
gst_ntp_clock_new(const gchar * name,const gchar * remote_address,gint remote_port,GstClockTime base_time)1475 gst_ntp_clock_new (const gchar * name, const gchar * remote_address,
1476     gint remote_port, GstClockTime base_time)
1477 {
1478   GstClock *ret;
1479 
1480   g_return_val_if_fail (remote_address != NULL, NULL);
1481   g_return_val_if_fail (remote_port > 0, NULL);
1482   g_return_val_if_fail (remote_port <= G_MAXUINT16, NULL);
1483   g_return_val_if_fail (base_time != GST_CLOCK_TIME_NONE, NULL);
1484 
1485   ret =
1486       g_object_new (GST_TYPE_NTP_CLOCK, "name", name, "address", remote_address,
1487       "port", remote_port, "base-time", base_time, NULL);
1488 
1489   gst_object_ref_sink (ret);
1490 
1491   return ret;
1492 }
1493