Debian Codegraph @

libs/gst/net/gstnetclientclock.c

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