2 * Copyright (C) 2015 Sebastian Dröge <sebastian@centricular.com>
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
15 * You should have received a copy of the GNU Library General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
22 * @short_description: Special clock that synchronizes to a remote time
23 * provider via PTP (IEEE1588:2008).
24 * @see_also: #GstClock, #GstNetClientClock, #GstPipeline
26 * GstPtpClock implements a PTP (IEEE1588:2008) ordinary clock in slave-only
27 * mode, that allows a GStreamer pipeline to synchronize to a PTP network
28 * clock in some specific domain.
30 * The PTP subsystem can be initialized with gst_ptp_init(), which then starts
31 * a helper process to do the actual communication via the PTP ports. This is
32 * required as PTP listens on ports < 1024 and thus requires special
33 * privileges. Once this helper process is started, the main process will
34 * synchronize to all PTP domains that are detected on the selected
37 * gst_ptp_clock_new() then allows to create a GstClock that provides the PTP
38 * time from a master clock inside a specific PTP domain. This clock will only
39 * return valid timestamps once the timestamps in the PTP domain are known. To
40 * check this, you can use gst_clock_wait_for_sync(), the GstClock::synced
41 * signal and gst_clock_is_synced().
44 * To gather statistics about the PTP clock synchronization,
45 * gst_ptp_statistics_callback_add() can be used. This gives the application
46 * the possibility to collect all kinds of statistics from the clock
56 #include "gstptpclock.h"
58 #include "gstptp_private.h"
60 #ifdef HAVE_SYS_WAIT_H
66 #include <sys/types.h>
69 #include <gst/base/base.h>
71 GST_DEBUG_CATEGORY_STATIC (ptp_debug);
72 #define GST_CAT_DEFAULT (ptp_debug)
74 /* IEEE 1588 7.7.3.1 */
75 #define PTP_ANNOUNCE_RECEIPT_TIMEOUT 4
77 /* Use a running average for calculating the mean path delay instead
78 * of just using the last measurement. Enabling this helps in unreliable
79 * networks, like wifi, with often changing delays
81 * Undef for following IEEE1588-2008 by the letter
83 #define USE_RUNNING_AVERAGE_DELAY 1
85 /* Filter out any measurements that are above a certain threshold compared to
86 * previous measurements. Enabling this helps filtering out outliers that
87 * happen fairly often in unreliable networks, like wifi.
89 * Undef for following IEEE1588-2008 by the letter
91 #define USE_MEASUREMENT_FILTERING 1
93 /* Select the first clock from which we capture a SYNC message as the master
94 * clock of the domain until we are ready to run the best master clock
95 * algorithm. This allows faster syncing but might mean a change of the master
96 * clock in the beginning. As all clocks in a domain are supposed to use the
97 * same time, this shouldn't be much of a problem.
99 * Undef for following IEEE1588-2008 by the letter
101 #define USE_OPPORTUNISTIC_CLOCK_SELECTION 1
103 /* Only consider SYNC messages for which we are allowed to send a DELAY_REQ
104 * afterwards. This allows better synchronization in networks with varying
105 * delays, as for every other SYNC message we would have to assume that it's
106 * the average of what we saw before. But that might be completely off
108 #define USE_ONLY_SYNC_WITH_DELAY 1
110 /* Filter out delay measurements that are too far away from the median of the
111 * last delay measurements, currently those that are more than 2 times as big.
112 * This increases accuracy a lot on wifi.
114 #define USE_MEDIAN_PRE_FILTERING 1
115 #define MEDIAN_PRE_FILTERING_WINDOW 9
117 /* How many updates should be skipped at maximum when using USE_MEASUREMENT_FILTERING */
118 #define MAX_SKIPPED_UPDATES 5
122 PTP_MESSAGE_TYPE_SYNC = 0x0,
123 PTP_MESSAGE_TYPE_DELAY_REQ = 0x1,
124 PTP_MESSAGE_TYPE_PDELAY_REQ = 0x2,
125 PTP_MESSAGE_TYPE_PDELAY_RESP = 0x3,
126 PTP_MESSAGE_TYPE_FOLLOW_UP = 0x8,
127 PTP_MESSAGE_TYPE_DELAY_RESP = 0x9,
128 PTP_MESSAGE_TYPE_PDELAY_RESP_FOLLOW_UP = 0xA,
129 PTP_MESSAGE_TYPE_ANNOUNCE = 0xB,
130 PTP_MESSAGE_TYPE_SIGNALING = 0xC,
131 PTP_MESSAGE_TYPE_MANAGEMENT = 0xD
136 guint64 seconds_field; /* 48 bits valid */
137 guint32 nanoseconds_field;
140 #define PTP_TIMESTAMP_TO_GST_CLOCK_TIME(ptp) (ptp.seconds_field * GST_SECOND + ptp.nanoseconds_field)
141 #define GST_CLOCK_TIME_TO_PTP_TIMESTAMP_SECONDS(gst) (((GstClockTime) gst) / GST_SECOND)
142 #define GST_CLOCK_TIME_TO_PTP_TIMESTAMP_NANOSECONDS(gst) (((GstClockTime) gst) % GST_SECOND)
146 guint64 clock_identity;
151 compare_clock_identity (const PtpClockIdentity * a, const PtpClockIdentity * b)
153 if (a->clock_identity < b->clock_identity)
155 else if (a->clock_identity > b->clock_identity)
158 if (a->port_number < b->port_number)
160 else if (a->port_number > b->port_number)
169 guint8 clock_accuracy;
170 guint16 offset_scaled_log_variance;
175 guint8 transport_specific;
176 PtpMessageType message_type;
177 /* guint8 reserved; */
179 guint16 message_length;
180 guint8 domain_number;
181 /* guint8 reserved; */
183 gint64 correction_field; /* 48.16 fixed point nanoseconds */
184 /* guint32 reserved; */
185 PtpClockIdentity source_port_identity;
187 guint8 control_field;
188 gint8 log_message_interval;
194 PtpTimestamp origin_timestamp;
195 gint16 current_utc_offset;
196 /* guint8 reserved; */
197 guint8 grandmaster_priority_1;
198 PtpClockQuality grandmaster_clock_quality;
199 guint8 grandmaster_priority_2;
200 guint64 grandmaster_identity;
201 guint16 steps_removed;
207 PtpTimestamp origin_timestamp;
212 PtpTimestamp precise_origin_timestamp;
217 PtpTimestamp origin_timestamp;
222 PtpTimestamp receive_timestamp;
223 PtpClockIdentity requesting_port_identity;
229 static GMutex ptp_lock;
230 static GCond ptp_cond;
231 static gboolean initted = FALSE;
233 static gboolean supported = TRUE;
235 static gboolean supported = FALSE;
237 static GPid ptp_helper_pid;
238 static GThread *ptp_helper_thread;
239 static GMainContext *main_context;
240 static GMainLoop *main_loop;
241 static GIOChannel *stdin_channel, *stdout_channel;
242 static GRand *delay_req_rand;
243 static GstClock *observation_system_clock;
244 static PtpClockIdentity ptp_clock_id = { GST_PTP_CLOCK_ID_NONE, 0 };
248 GstClockTime receive_time;
250 PtpClockIdentity master_clock_identity;
252 guint8 grandmaster_priority_1;
253 PtpClockQuality grandmaster_clock_quality;
254 guint8 grandmaster_priority_2;
255 guint64 grandmaster_identity;
256 guint16 steps_removed;
260 } PtpAnnounceMessage;
264 PtpClockIdentity master_clock_identity;
266 GstClockTime announce_interval; /* last interval we received */
267 GQueue announce_messages;
273 PtpClockIdentity master_clock_identity;
276 GstClockTime sync_recv_time_local; /* t2 */
277 GstClockTime sync_send_time_remote; /* t1, might be -1 if FOLLOW_UP pending */
278 GstClockTime follow_up_recv_time_local;
280 GSource *timeout_source;
281 guint16 delay_req_seqnum;
282 GstClockTime delay_req_send_time_local; /* t3, -1 if we wait for FOLLOW_UP */
283 GstClockTime delay_req_recv_time_remote; /* t4, -1 if we wait */
284 GstClockTime delay_resp_recv_time_local;
286 gint64 correction_field_sync; /* sum of the correction fields of SYNC/FOLLOW_UP */
287 gint64 correction_field_delay; /* sum of the correction fields of DELAY_RESP */
291 ptp_pending_sync_free (PtpPendingSync * sync)
293 if (sync->timeout_source)
294 g_source_destroy (sync->timeout_source);
302 GstClockTime last_ptp_time;
303 GstClockTime last_local_time;
304 gint skipped_updates;
306 /* Used for selecting the master/grandmaster */
307 GList *announce_senders;
309 /* Last selected master clock */
310 gboolean have_master_clock;
311 PtpClockIdentity master_clock_identity;
312 guint64 grandmaster_identity;
314 /* Last SYNC or FOLLOW_UP timestamp we received */
315 GstClockTime last_ptp_sync_time;
316 GstClockTime sync_interval;
318 GstClockTime mean_path_delay;
319 GstClockTime last_delay_req, min_delay_req_interval;
320 guint16 last_delay_req_seqnum;
322 GstClockTime last_path_delays[MEDIAN_PRE_FILTERING_WINDOW];
323 gint last_path_delays_missing;
325 GQueue pending_syncs;
327 GstClock *domain_clock;
330 static GList *domain_data;
331 static GMutex domain_clocks_lock;
332 static GList *domain_clocks;
334 /* Protected by PTP lock */
335 static void emit_ptp_statistics (guint8 domain, const GstStructure * stats);
336 static GHookList domain_stats_hooks;
337 static gint domain_stats_n_hooks;
338 static gboolean domain_stats_hooks_initted = FALSE;
340 /* Converts log2 seconds to GstClockTime */
342 log2_to_clock_time (gint l)
345 return GST_SECOND >> (-l);
347 return GST_SECOND << l;
351 dump_ptp_message (PtpMessage * msg)
353 GST_TRACE ("PTP message:");
354 GST_TRACE ("\ttransport_specific: %u", msg->transport_specific);
355 GST_TRACE ("\tmessage_type: 0x%01x", msg->message_type);
356 GST_TRACE ("\tversion_ptp: %u", msg->version_ptp);
357 GST_TRACE ("\tmessage_length: %u", msg->message_length);
358 GST_TRACE ("\tdomain_number: %u", msg->domain_number);
359 GST_TRACE ("\tflag_field: 0x%04x", msg->flag_field);
360 GST_TRACE ("\tcorrection_field: %" G_GINT64_FORMAT ".%03u",
361 (msg->correction_field / 65536),
362 (guint) ((msg->correction_field & 0xffff) * 1000) / 65536);
363 GST_TRACE ("\tsource_port_identity: 0x%016" G_GINT64_MODIFIER "x %u",
364 msg->source_port_identity.clock_identity,
365 msg->source_port_identity.port_number);
366 GST_TRACE ("\tsequence_id: %u", msg->sequence_id);
367 GST_TRACE ("\tcontrol_field: 0x%02x", msg->control_field);
368 GST_TRACE ("\tmessage_interval: %" GST_TIME_FORMAT,
369 GST_TIME_ARGS (log2_to_clock_time (msg->log_message_interval)));
371 switch (msg->message_type) {
372 case PTP_MESSAGE_TYPE_ANNOUNCE:
373 GST_TRACE ("\tANNOUNCE:");
374 GST_TRACE ("\t\torigin_timestamp: %" G_GUINT64_FORMAT ".%09u",
375 msg->message_specific.announce.origin_timestamp.seconds_field,
376 msg->message_specific.announce.origin_timestamp.nanoseconds_field);
377 GST_TRACE ("\t\tcurrent_utc_offset: %d",
378 msg->message_specific.announce.current_utc_offset);
379 GST_TRACE ("\t\tgrandmaster_priority_1: %u",
380 msg->message_specific.announce.grandmaster_priority_1);
381 GST_TRACE ("\t\tgrandmaster_clock_quality: 0x%02x 0x%02x %u",
382 msg->message_specific.announce.grandmaster_clock_quality.clock_class,
383 msg->message_specific.announce.
384 grandmaster_clock_quality.clock_accuracy,
385 msg->message_specific.announce.
386 grandmaster_clock_quality.offset_scaled_log_variance);
387 GST_TRACE ("\t\tgrandmaster_priority_2: %u",
388 msg->message_specific.announce.grandmaster_priority_2);
389 GST_TRACE ("\t\tgrandmaster_identity: 0x%016" G_GINT64_MODIFIER "x",
390 msg->message_specific.announce.grandmaster_identity);
391 GST_TRACE ("\t\tsteps_removed: %u",
392 msg->message_specific.announce.steps_removed);
393 GST_TRACE ("\t\ttime_source: 0x%02x",
394 msg->message_specific.announce.time_source);
396 case PTP_MESSAGE_TYPE_SYNC:
397 GST_TRACE ("\tSYNC:");
398 GST_TRACE ("\t\torigin_timestamp: %" G_GUINT64_FORMAT ".%09u",
399 msg->message_specific.sync.origin_timestamp.seconds_field,
400 msg->message_specific.sync.origin_timestamp.nanoseconds_field);
402 case PTP_MESSAGE_TYPE_FOLLOW_UP:
403 GST_TRACE ("\tFOLLOW_UP:");
404 GST_TRACE ("\t\tprecise_origin_timestamp: %" G_GUINT64_FORMAT ".%09u",
405 msg->message_specific.follow_up.
406 precise_origin_timestamp.seconds_field,
407 msg->message_specific.follow_up.
408 precise_origin_timestamp.nanoseconds_field);
410 case PTP_MESSAGE_TYPE_DELAY_REQ:
411 GST_TRACE ("\tDELAY_REQ:");
412 GST_TRACE ("\t\torigin_timestamp: %" G_GUINT64_FORMAT ".%09u",
413 msg->message_specific.delay_req.origin_timestamp.seconds_field,
414 msg->message_specific.delay_req.origin_timestamp.nanoseconds_field);
416 case PTP_MESSAGE_TYPE_DELAY_RESP:
417 GST_TRACE ("\tDELAY_RESP:");
418 GST_TRACE ("\t\treceive_timestamp: %" G_GUINT64_FORMAT ".%09u",
419 msg->message_specific.delay_resp.receive_timestamp.seconds_field,
420 msg->message_specific.delay_resp.receive_timestamp.nanoseconds_field);
421 GST_TRACE ("\t\trequesting_port_identity: 0x%016" G_GINT64_MODIFIER
423 msg->message_specific.delay_resp.
424 requesting_port_identity.clock_identity,
425 msg->message_specific.delay_resp.
426 requesting_port_identity.port_number);
434 /* IEEE 1588-2008 5.3.3 */
436 parse_ptp_timestamp (PtpTimestamp * timestamp, GstByteReader * reader)
438 g_return_val_if_fail (gst_byte_reader_get_remaining (reader) >= 10, FALSE);
440 timestamp->seconds_field =
441 (((guint64) gst_byte_reader_get_uint32_be_unchecked (reader)) << 16) |
442 gst_byte_reader_get_uint16_be_unchecked (reader);
443 timestamp->nanoseconds_field =
444 gst_byte_reader_get_uint32_be_unchecked (reader);
446 if (timestamp->nanoseconds_field >= 1000000000)
452 /* IEEE 1588-2008 13.3 */
454 parse_ptp_message_header (PtpMessage * msg, GstByteReader * reader)
458 g_return_val_if_fail (gst_byte_reader_get_remaining (reader) >= 34, FALSE);
460 b = gst_byte_reader_get_uint8_unchecked (reader);
461 msg->transport_specific = b >> 4;
462 msg->message_type = b & 0x0f;
464 b = gst_byte_reader_get_uint8_unchecked (reader);
465 msg->version_ptp = b & 0x0f;
466 if (msg->version_ptp != 2) {
467 GST_WARNING ("Unsupported PTP message version (%u != 2)", msg->version_ptp);
471 msg->message_length = gst_byte_reader_get_uint16_be_unchecked (reader);
472 if (gst_byte_reader_get_remaining (reader) + 4 < msg->message_length) {
473 GST_WARNING ("Not enough data (%u < %u)",
474 gst_byte_reader_get_remaining (reader) + 4, msg->message_length);
478 msg->domain_number = gst_byte_reader_get_uint8_unchecked (reader);
479 gst_byte_reader_skip_unchecked (reader, 1);
481 msg->flag_field = gst_byte_reader_get_uint16_be_unchecked (reader);
482 msg->correction_field = gst_byte_reader_get_uint64_be_unchecked (reader);
483 gst_byte_reader_skip_unchecked (reader, 4);
485 msg->source_port_identity.clock_identity =
486 gst_byte_reader_get_uint64_be_unchecked (reader);
487 msg->source_port_identity.port_number =
488 gst_byte_reader_get_uint16_be_unchecked (reader);
490 msg->sequence_id = gst_byte_reader_get_uint16_be_unchecked (reader);
491 msg->control_field = gst_byte_reader_get_uint8_unchecked (reader);
492 msg->log_message_interval = gst_byte_reader_get_uint8_unchecked (reader);
497 /* IEEE 1588-2008 13.5 */
499 parse_ptp_message_announce (PtpMessage * msg, GstByteReader * reader)
501 g_return_val_if_fail (msg->message_type == PTP_MESSAGE_TYPE_ANNOUNCE, FALSE);
503 if (gst_byte_reader_get_remaining (reader) < 20)
506 if (!parse_ptp_timestamp (&msg->message_specific.announce.origin_timestamp,
510 msg->message_specific.announce.current_utc_offset =
511 gst_byte_reader_get_uint16_be_unchecked (reader);
512 gst_byte_reader_skip_unchecked (reader, 1);
514 msg->message_specific.announce.grandmaster_priority_1 =
515 gst_byte_reader_get_uint8_unchecked (reader);
516 msg->message_specific.announce.grandmaster_clock_quality.clock_class =
517 gst_byte_reader_get_uint8_unchecked (reader);
518 msg->message_specific.announce.grandmaster_clock_quality.clock_accuracy =
519 gst_byte_reader_get_uint8_unchecked (reader);
520 msg->message_specific.announce.
521 grandmaster_clock_quality.offset_scaled_log_variance =
522 gst_byte_reader_get_uint16_be_unchecked (reader);
523 msg->message_specific.announce.grandmaster_priority_2 =
524 gst_byte_reader_get_uint8_unchecked (reader);
525 msg->message_specific.announce.grandmaster_identity =
526 gst_byte_reader_get_uint64_be_unchecked (reader);
527 msg->message_specific.announce.steps_removed =
528 gst_byte_reader_get_uint16_be_unchecked (reader);
529 msg->message_specific.announce.time_source =
530 gst_byte_reader_get_uint8_unchecked (reader);
535 /* IEEE 1588-2008 13.6 */
537 parse_ptp_message_sync (PtpMessage * msg, GstByteReader * reader)
539 g_return_val_if_fail (msg->message_type == PTP_MESSAGE_TYPE_SYNC, FALSE);
541 if (gst_byte_reader_get_remaining (reader) < 10)
544 if (!parse_ptp_timestamp (&msg->message_specific.sync.origin_timestamp,
551 /* IEEE 1588-2008 13.6 */
553 parse_ptp_message_delay_req (PtpMessage * msg, GstByteReader * reader)
555 g_return_val_if_fail (msg->message_type == PTP_MESSAGE_TYPE_DELAY_REQ, FALSE);
557 if (gst_byte_reader_get_remaining (reader) < 10)
560 if (!parse_ptp_timestamp (&msg->message_specific.delay_req.origin_timestamp,
567 /* IEEE 1588-2008 13.7 */
569 parse_ptp_message_follow_up (PtpMessage * msg, GstByteReader * reader)
571 g_return_val_if_fail (msg->message_type == PTP_MESSAGE_TYPE_FOLLOW_UP, FALSE);
573 if (gst_byte_reader_get_remaining (reader) < 10)
576 if (!parse_ptp_timestamp (&msg->message_specific.
577 follow_up.precise_origin_timestamp, reader))
583 /* IEEE 1588-2008 13.8 */
585 parse_ptp_message_delay_resp (PtpMessage * msg, GstByteReader * reader)
587 g_return_val_if_fail (msg->message_type == PTP_MESSAGE_TYPE_DELAY_RESP,
590 if (gst_byte_reader_get_remaining (reader) < 20)
593 if (!parse_ptp_timestamp (&msg->message_specific.delay_resp.receive_timestamp,
597 msg->message_specific.delay_resp.requesting_port_identity.clock_identity =
598 gst_byte_reader_get_uint64_be_unchecked (reader);
599 msg->message_specific.delay_resp.requesting_port_identity.port_number =
600 gst_byte_reader_get_uint16_be_unchecked (reader);
606 parse_ptp_message (PtpMessage * msg, const guint8 * data, gsize size)
608 GstByteReader reader;
609 gboolean ret = FALSE;
611 gst_byte_reader_init (&reader, data, size);
613 if (!parse_ptp_message_header (msg, &reader)) {
614 GST_WARNING ("Failed to parse PTP message header");
618 switch (msg->message_type) {
619 case PTP_MESSAGE_TYPE_SYNC:
620 ret = parse_ptp_message_sync (msg, &reader);
622 case PTP_MESSAGE_TYPE_FOLLOW_UP:
623 ret = parse_ptp_message_follow_up (msg, &reader);
625 case PTP_MESSAGE_TYPE_DELAY_REQ:
626 ret = parse_ptp_message_delay_req (msg, &reader);
628 case PTP_MESSAGE_TYPE_DELAY_RESP:
629 ret = parse_ptp_message_delay_resp (msg, &reader);
631 case PTP_MESSAGE_TYPE_ANNOUNCE:
632 ret = parse_ptp_message_announce (msg, &reader);
643 compare_announce_message (const PtpAnnounceMessage * a,
644 const PtpAnnounceMessage * b)
646 /* IEEE 1588 Figure 27 */
647 if (a->grandmaster_identity == b->grandmaster_identity) {
648 if (a->steps_removed + 1 < b->steps_removed)
650 else if (a->steps_removed > b->steps_removed + 1)
653 /* Error cases are filtered out earlier */
654 if (a->steps_removed < b->steps_removed)
656 else if (a->steps_removed > b->steps_removed)
659 /* Error cases are filtered out earlier */
660 if (a->master_clock_identity.clock_identity <
661 b->master_clock_identity.clock_identity)
663 else if (a->master_clock_identity.clock_identity >
664 b->master_clock_identity.clock_identity)
667 /* Error cases are filtered out earlier */
668 if (a->master_clock_identity.port_number <
669 b->master_clock_identity.port_number)
671 else if (a->master_clock_identity.port_number >
672 b->master_clock_identity.port_number)
675 g_assert_not_reached ();
680 if (a->grandmaster_priority_1 < b->grandmaster_priority_1)
682 else if (a->grandmaster_priority_1 > b->grandmaster_priority_1)
685 if (a->grandmaster_clock_quality.clock_class <
686 b->grandmaster_clock_quality.clock_class)
688 else if (a->grandmaster_clock_quality.clock_class >
689 b->grandmaster_clock_quality.clock_class)
692 if (a->grandmaster_clock_quality.clock_accuracy <
693 b->grandmaster_clock_quality.clock_accuracy)
695 else if (a->grandmaster_clock_quality.clock_accuracy >
696 b->grandmaster_clock_quality.clock_accuracy)
699 if (a->grandmaster_clock_quality.offset_scaled_log_variance <
700 b->grandmaster_clock_quality.offset_scaled_log_variance)
702 else if (a->grandmaster_clock_quality.offset_scaled_log_variance >
703 b->grandmaster_clock_quality.offset_scaled_log_variance)
706 if (a->grandmaster_priority_2 < b->grandmaster_priority_2)
708 else if (a->grandmaster_priority_2 > b->grandmaster_priority_2)
711 if (a->grandmaster_identity < b->grandmaster_identity)
713 else if (a->grandmaster_identity > b->grandmaster_identity)
716 g_assert_not_reached ();
722 select_best_master_clock (PtpDomainData * domain, GstClockTime now)
724 GList *qualified_messages = NULL;
726 PtpAnnounceMessage *best = NULL;
728 /* IEEE 1588 9.3.2.5 */
729 for (l = domain->announce_senders; l; l = l->next) {
730 PtpAnnounceSender *sender = l->data;
731 GstClockTime window = 4 * sender->announce_interval;
734 for (m = sender->announce_messages.head; m; m = m->next) {
735 PtpAnnounceMessage *msg = m->data;
737 if (now - msg->receive_time <= window)
741 /* Only include the newest message of announce senders that had at least 2
742 * announce messages in the last 4 announce intervals. Which also means
743 * that we wait at least 4 announce intervals before we select a master
744 * clock. Until then we just report based on the newest SYNC we received
748 g_list_prepend (qualified_messages,
749 g_queue_peek_tail (&sender->announce_messages));
753 if (!qualified_messages) {
755 ("No qualified announce messages for domain %u, can't select a master clock",
757 domain->have_master_clock = FALSE;
761 for (l = qualified_messages; l; l = l->next) {
762 PtpAnnounceMessage *msg = l->data;
764 if (!best || compare_announce_message (msg, best) < 0)
768 if (domain->have_master_clock
769 && compare_clock_identity (&domain->master_clock_identity,
770 &best->master_clock_identity) == 0) {
771 GST_DEBUG ("Master clock in domain %u did not change", domain->domain);
773 GST_DEBUG ("Selected master clock for domain %u: 0x%016" G_GINT64_MODIFIER
774 "x %u with grandmaster clock 0x%016" G_GINT64_MODIFIER "x",
775 domain->domain, best->master_clock_identity.clock_identity,
776 best->master_clock_identity.port_number, best->grandmaster_identity);
778 domain->have_master_clock = TRUE;
779 domain->grandmaster_identity = best->grandmaster_identity;
781 /* Opportunistic master clock selection likely gave us the same master
782 * clock before, no need to reset all statistics */
783 if (compare_clock_identity (&domain->master_clock_identity,
784 &best->master_clock_identity) != 0) {
785 memcpy (&domain->master_clock_identity, &best->master_clock_identity,
786 sizeof (PtpClockIdentity));
787 domain->mean_path_delay = 0;
788 domain->last_delay_req = 0;
789 domain->last_path_delays_missing = 9;
790 domain->min_delay_req_interval = 0;
791 domain->sync_interval = 0;
792 domain->last_ptp_sync_time = 0;
793 domain->skipped_updates = 0;
794 g_queue_foreach (&domain->pending_syncs, (GFunc) ptp_pending_sync_free,
796 g_queue_clear (&domain->pending_syncs);
799 if (g_atomic_int_get (&domain_stats_n_hooks)) {
800 GstStructure *stats =
801 gst_structure_new (GST_PTP_STATISTICS_BEST_MASTER_CLOCK_SELECTED,
802 "domain", G_TYPE_UINT, domain->domain,
803 "master-clock-id", G_TYPE_UINT64,
804 domain->master_clock_identity.clock_identity,
805 "master-clock-port", G_TYPE_UINT,
806 domain->master_clock_identity.port_number,
807 "grandmaster-clock-id", G_TYPE_UINT64, domain->grandmaster_identity,
809 emit_ptp_statistics (domain->domain, stats);
810 gst_structure_free (stats);
816 handle_announce_message (PtpMessage * msg, GstClockTime receive_time)
819 PtpDomainData *domain = NULL;
820 PtpAnnounceSender *sender = NULL;
821 PtpAnnounceMessage *announce;
823 /* IEEE1588 9.3.2.2 e)
824 * Don't consider messages with the alternate master flag set
826 if ((msg->flag_field & 0x0100))
829 /* IEEE 1588 9.3.2.5 d)
830 * Don't consider announce messages with steps_removed>=255
832 if (msg->message_specific.announce.steps_removed >= 255)
835 for (l = domain_data; l; l = l->next) {
836 PtpDomainData *tmp = l->data;
838 if (tmp->domain == msg->domain_number) {
847 domain = g_new0 (PtpDomainData, 1);
848 domain->domain = msg->domain_number;
849 clock_name = g_strdup_printf ("ptp-clock-%u", domain->domain);
850 domain->domain_clock =
851 g_object_new (GST_TYPE_SYSTEM_CLOCK, "name", clock_name, NULL);
853 g_queue_init (&domain->pending_syncs);
854 domain->last_path_delays_missing = 9;
855 domain_data = g_list_prepend (domain_data, domain);
857 g_mutex_lock (&domain_clocks_lock);
858 domain_clocks = g_list_prepend (domain_clocks, domain);
859 g_mutex_unlock (&domain_clocks_lock);
861 if (g_atomic_int_get (&domain_stats_n_hooks)) {
862 GstStructure *stats =
863 gst_structure_new (GST_PTP_STATISTICS_NEW_DOMAIN_FOUND, "domain",
864 G_TYPE_UINT, domain->domain, "clock", GST_TYPE_CLOCK,
865 domain->domain_clock, NULL);
866 emit_ptp_statistics (domain->domain, stats);
867 gst_structure_free (stats);
871 for (l = domain->announce_senders; l; l = l->next) {
872 PtpAnnounceSender *tmp = l->data;
874 if (compare_clock_identity (&tmp->master_clock_identity,
875 &msg->source_port_identity) == 0) {
882 sender = g_new0 (PtpAnnounceSender, 1);
884 memcpy (&sender->master_clock_identity, &msg->source_port_identity,
885 sizeof (PtpClockIdentity));
886 g_queue_init (&sender->announce_messages);
887 domain->announce_senders =
888 g_list_prepend (domain->announce_senders, sender);
891 for (l = sender->announce_messages.head; l; l = l->next) {
892 PtpAnnounceMessage *tmp = l->data;
894 /* IEEE 1588 9.3.2.5 c)
895 * Don't consider identical messages, i.e. duplicates
897 if (tmp->sequence_id == msg->sequence_id)
901 sender->announce_interval = log2_to_clock_time (msg->log_message_interval);
903 announce = g_new0 (PtpAnnounceMessage, 1);
904 announce->receive_time = receive_time;
905 announce->sequence_id = msg->sequence_id;
906 memcpy (&announce->master_clock_identity, &msg->source_port_identity,
907 sizeof (PtpClockIdentity));
908 announce->grandmaster_identity =
909 msg->message_specific.announce.grandmaster_identity;
910 announce->grandmaster_priority_1 =
911 msg->message_specific.announce.grandmaster_priority_1;
912 announce->grandmaster_clock_quality.clock_class =
913 msg->message_specific.announce.grandmaster_clock_quality.clock_class;
914 announce->grandmaster_clock_quality.clock_accuracy =
915 msg->message_specific.announce.grandmaster_clock_quality.clock_accuracy;
916 announce->grandmaster_clock_quality.offset_scaled_log_variance =
917 msg->message_specific.announce.
918 grandmaster_clock_quality.offset_scaled_log_variance;
919 announce->grandmaster_priority_2 =
920 msg->message_specific.announce.grandmaster_priority_2;
921 announce->steps_removed = msg->message_specific.announce.steps_removed;
922 announce->time_source = msg->message_specific.announce.time_source;
923 g_queue_push_tail (&sender->announce_messages, announce);
925 select_best_master_clock (domain, receive_time);
929 send_delay_req_timeout (PtpPendingSync * sync)
931 StdIOHeader header = { 0, };
932 guint8 delay_req[44];
933 GstByteWriter writer;
938 header.type = TYPE_EVENT;
941 gst_byte_writer_init_with_data (&writer, delay_req, 44, FALSE);
942 gst_byte_writer_put_uint8_unchecked (&writer, PTP_MESSAGE_TYPE_DELAY_REQ);
943 gst_byte_writer_put_uint8_unchecked (&writer, 2);
944 gst_byte_writer_put_uint16_be_unchecked (&writer, 44);
945 gst_byte_writer_put_uint8_unchecked (&writer, sync->domain);
946 gst_byte_writer_put_uint8_unchecked (&writer, 0);
947 gst_byte_writer_put_uint16_be_unchecked (&writer, 0);
948 gst_byte_writer_put_uint64_be_unchecked (&writer, 0);
949 gst_byte_writer_put_uint32_be_unchecked (&writer, 0);
950 gst_byte_writer_put_uint64_be_unchecked (&writer,
951 ptp_clock_id.clock_identity);
952 gst_byte_writer_put_uint16_be_unchecked (&writer, ptp_clock_id.port_number);
953 gst_byte_writer_put_uint16_be_unchecked (&writer, sync->delay_req_seqnum);
954 gst_byte_writer_put_uint8_unchecked (&writer, 0x01);
955 gst_byte_writer_put_uint8_unchecked (&writer, 0x7f);
956 gst_byte_writer_put_uint64_be_unchecked (&writer, 0);
957 gst_byte_writer_put_uint16_be_unchecked (&writer, 0);
960 g_io_channel_write_chars (stdout_channel, (gchar *) & header,
961 sizeof (header), &written, &err);
962 if (status == G_IO_STATUS_ERROR) {
963 g_warning ("Failed to write to stdout: %s", err->message);
964 g_clear_error (&err);
965 return G_SOURCE_REMOVE;
966 } else if (status == G_IO_STATUS_EOF) {
967 g_message ("EOF on stdout");
968 g_main_loop_quit (main_loop);
969 return G_SOURCE_REMOVE;
970 } else if (status != G_IO_STATUS_NORMAL) {
971 g_warning ("Unexpected stdout write status: %d", status);
972 g_main_loop_quit (main_loop);
973 return G_SOURCE_REMOVE;
974 } else if (written != sizeof (header)) {
975 g_warning ("Unexpected write size: %" G_GSIZE_FORMAT, written);
976 g_main_loop_quit (main_loop);
977 return G_SOURCE_REMOVE;
980 sync->delay_req_send_time_local =
981 gst_clock_get_time (observation_system_clock);
984 g_io_channel_write_chars (stdout_channel,
985 (const gchar *) delay_req, 44, &written, &err);
986 if (status == G_IO_STATUS_ERROR) {
987 g_warning ("Failed to write to stdout: %s", err->message);
988 g_clear_error (&err);
989 g_main_loop_quit (main_loop);
990 return G_SOURCE_REMOVE;
991 } else if (status == G_IO_STATUS_EOF) {
992 g_message ("EOF on stdout");
993 g_main_loop_quit (main_loop);
994 return G_SOURCE_REMOVE;
995 } else if (status != G_IO_STATUS_NORMAL) {
996 g_warning ("Unexpected stdout write status: %d", status);
997 g_main_loop_quit (main_loop);
998 return G_SOURCE_REMOVE;
999 } else if (written != 44) {
1000 g_warning ("Unexpected write size: %" G_GSIZE_FORMAT, written);
1001 g_main_loop_quit (main_loop);
1002 return G_SOURCE_REMOVE;
1005 return G_SOURCE_REMOVE;
1009 send_delay_req (PtpDomainData * domain, PtpPendingSync * sync)
1011 GstClockTime now = gst_clock_get_time (observation_system_clock);
1013 GSource *timeout_source;
1015 if (domain->last_delay_req != 0
1016 && domain->last_delay_req + domain->min_delay_req_interval > now)
1019 domain->last_delay_req = now;
1020 sync->delay_req_seqnum = domain->last_delay_req_seqnum++;
1022 /* IEEE 1588 9.5.11.2 */
1023 if (domain->last_delay_req == 0 || domain->min_delay_req_interval == 0)
1027 g_rand_int_range (delay_req_rand, 0,
1028 (domain->min_delay_req_interval * 2) / GST_MSECOND);
1030 sync->timeout_source = timeout_source = g_timeout_source_new (timeout);
1031 g_source_set_priority (timeout_source, G_PRIORITY_DEFAULT);
1032 g_source_set_callback (timeout_source, (GSourceFunc) send_delay_req_timeout,
1034 g_source_attach (timeout_source, main_context);
1039 /* Filtering of outliers for RTT and time calculations inspired
1040 * by the code from gstnetclientclock.c
1043 update_ptp_time (PtpDomainData * domain, PtpPendingSync * sync)
1045 GstClockTime internal_time, external_time, rate_num, rate_den;
1046 GstClockTime corrected_ptp_time, corrected_local_time;
1047 gdouble r_squared = 0.0;
1049 GstClockTimeDiff discont = 0;
1050 GstClockTime estimated_ptp_time = GST_CLOCK_TIME_NONE;
1051 #ifdef USE_MEASUREMENT_FILTERING
1052 GstClockTime orig_internal_time, orig_external_time, orig_rate_num,
1054 GstClockTime new_estimated_ptp_time;
1055 GstClockTime max_discont, estimated_ptp_time_min, estimated_ptp_time_max;
1056 gboolean now_synced;
1059 #ifdef USE_ONLY_SYNC_WITH_DELAY
1060 GstClockTime mean_path_delay;
1062 if (sync->delay_req_send_time_local == GST_CLOCK_TIME_NONE)
1065 /* IEEE 1588 11.3 */
1067 (sync->delay_req_recv_time_remote - sync->sync_send_time_remote +
1068 sync->sync_recv_time_local - sync->delay_req_send_time_local -
1069 (sync->correction_field_sync + sync->correction_field_delay +
1070 32768) / 65536) / 2;
1073 /* IEEE 1588 11.2 */
1074 corrected_ptp_time =
1075 sync->sync_send_time_remote +
1076 (sync->correction_field_sync + 32768) / 65536;
1078 #ifdef USE_ONLY_SYNC_WITH_DELAY
1079 corrected_local_time = sync->sync_recv_time_local - mean_path_delay;
1081 corrected_local_time = sync->sync_recv_time_local - domain->mean_path_delay;
1084 #ifdef USE_MEASUREMENT_FILTERING
1085 /* We check this here and when updating the mean path delay, because
1086 * we can get here without a delay response too */
1087 if (sync->follow_up_recv_time_local != GST_CLOCK_TIME_NONE
1088 && sync->follow_up_recv_time_local >
1089 sync->sync_recv_time_local + 2 * domain->mean_path_delay) {
1090 GST_WARNING ("Sync-follow-up delay for domain %u too big: %" GST_TIME_FORMAT
1091 " > 2 * %" GST_TIME_FORMAT, domain->domain,
1092 GST_TIME_ARGS (sync->follow_up_recv_time_local),
1093 GST_TIME_ARGS (domain->mean_path_delay));
1095 gst_clock_get_calibration (GST_CLOCK_CAST (domain->domain_clock),
1096 &internal_time, &external_time, &rate_num, &rate_den);
1101 /* Set an initial local-remote relation */
1102 if (domain->last_ptp_time == 0)
1103 gst_clock_set_calibration (domain->domain_clock, corrected_local_time,
1104 corrected_ptp_time, 1, 1);
1106 #ifdef USE_MEASUREMENT_FILTERING
1107 /* Check if the corrected PTP time is +/- 3/4 RTT around what we would
1108 * estimate with our present knowledge about the clock
1110 /* Store what the clock produced as 'now' before this update */
1111 gst_clock_get_calibration (GST_CLOCK_CAST (domain->domain_clock),
1112 &orig_internal_time, &orig_external_time, &orig_rate_num, &orig_rate_den);
1113 internal_time = orig_internal_time;
1114 external_time = orig_external_time;
1115 rate_num = orig_rate_num;
1116 rate_den = orig_rate_den;
1118 /* 3/4 RTT window around the estimation */
1119 max_discont = domain->mean_path_delay * 3 / 2;
1121 /* Check if the estimated sync time is inside our window */
1122 estimated_ptp_time_min = corrected_local_time - max_discont;
1123 estimated_ptp_time_min =
1124 gst_clock_adjust_with_calibration (GST_CLOCK_CAST (domain->domain_clock),
1125 estimated_ptp_time_min, internal_time, external_time, rate_num, rate_den);
1126 estimated_ptp_time_max = corrected_local_time + max_discont;
1127 estimated_ptp_time_max =
1128 gst_clock_adjust_with_calibration (GST_CLOCK_CAST (domain->domain_clock),
1129 estimated_ptp_time_max, internal_time, external_time, rate_num, rate_den);
1131 synced = (estimated_ptp_time_min < corrected_ptp_time
1132 && corrected_ptp_time < estimated_ptp_time_max);
1134 GST_DEBUG ("Adding observation for domain %u: %" GST_TIME_FORMAT " - %"
1135 GST_TIME_FORMAT, domain->domain,
1136 GST_TIME_ARGS (corrected_ptp_time), GST_TIME_ARGS (corrected_local_time));
1138 GST_DEBUG ("Synced %d: %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT " < %"
1139 GST_TIME_FORMAT, synced, GST_TIME_ARGS (estimated_ptp_time_min),
1140 GST_TIME_ARGS (corrected_ptp_time),
1141 GST_TIME_ARGS (estimated_ptp_time_max));
1143 if (gst_clock_add_observation_unapplied (domain->domain_clock,
1144 corrected_local_time, corrected_ptp_time, &r_squared,
1145 &internal_time, &external_time, &rate_num, &rate_den)) {
1146 GST_DEBUG ("Regression gave r_squared: %f", r_squared);
1148 /* Old estimated PTP time based on receive time and path delay */
1149 estimated_ptp_time = corrected_local_time;
1150 estimated_ptp_time =
1151 gst_clock_adjust_with_calibration (GST_CLOCK_CAST
1152 (domain->domain_clock), estimated_ptp_time, orig_internal_time,
1153 orig_external_time, orig_rate_num, orig_rate_den);
1155 /* New estimated PTP time based on receive time and path delay */
1156 new_estimated_ptp_time = corrected_local_time;
1157 new_estimated_ptp_time =
1158 gst_clock_adjust_with_calibration (GST_CLOCK_CAST
1159 (domain->domain_clock), new_estimated_ptp_time, internal_time,
1160 external_time, rate_num, rate_den);
1162 discont = GST_CLOCK_DIFF (estimated_ptp_time, new_estimated_ptp_time);
1163 if (synced && ABS (discont) > max_discont) {
1164 GstClockTimeDiff offset;
1165 GST_DEBUG ("Too large a discont %s%" GST_TIME_FORMAT
1166 ", clamping to 1/4 average RTT = %" GST_TIME_FORMAT,
1167 (discont < 0 ? "-" : ""), GST_TIME_ARGS (ABS (discont)),
1168 GST_TIME_ARGS (max_discont));
1169 if (discont > 0) { /* Too large a forward step - add a -ve offset */
1170 offset = max_discont - discont;
1171 if (-offset > external_time)
1174 external_time += offset;
1175 } else { /* Too large a backward step - add a +ve offset */
1176 offset = -(max_discont + discont);
1177 external_time += offset;
1182 GST_DEBUG ("Discont %s%" GST_TIME_FORMAT " (max: %" GST_TIME_FORMAT ")",
1183 (discont < 0 ? "-" : ""), GST_TIME_ARGS (ABS (discont)),
1184 GST_TIME_ARGS (max_discont));
1187 /* Check if the estimated sync time is now (still) inside our window */
1188 estimated_ptp_time_min = corrected_local_time - max_discont;
1189 estimated_ptp_time_min =
1190 gst_clock_adjust_with_calibration (GST_CLOCK_CAST
1191 (domain->domain_clock), estimated_ptp_time_min, internal_time,
1192 external_time, rate_num, rate_den);
1193 estimated_ptp_time_max = corrected_local_time + max_discont;
1194 estimated_ptp_time_max =
1195 gst_clock_adjust_with_calibration (GST_CLOCK_CAST
1196 (domain->domain_clock), estimated_ptp_time_max, internal_time,
1197 external_time, rate_num, rate_den);
1199 now_synced = (estimated_ptp_time_min < corrected_ptp_time
1200 && corrected_ptp_time < estimated_ptp_time_max);
1202 GST_DEBUG ("Now synced %d: %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT " < %"
1203 GST_TIME_FORMAT, now_synced, GST_TIME_ARGS (estimated_ptp_time_min),
1204 GST_TIME_ARGS (corrected_ptp_time),
1205 GST_TIME_ARGS (estimated_ptp_time_max));
1207 if (synced || now_synced || domain->skipped_updates > MAX_SKIPPED_UPDATES) {
1208 gst_clock_set_calibration (GST_CLOCK_CAST (domain->domain_clock),
1209 internal_time, external_time, rate_num, rate_den);
1210 domain->skipped_updates = 0;
1212 domain->last_ptp_time = corrected_ptp_time;
1213 domain->last_local_time = corrected_local_time;
1215 domain->skipped_updates++;
1218 domain->last_ptp_time = corrected_ptp_time;
1219 domain->last_local_time = corrected_local_time;
1223 GST_DEBUG ("Adding observation for domain %u: %" GST_TIME_FORMAT " - %"
1224 GST_TIME_FORMAT, domain->domain,
1225 GST_TIME_ARGS (corrected_ptp_time), GST_TIME_ARGS (corrected_local_time));
1227 gst_clock_get_calibration (GST_CLOCK_CAST (domain->domain_clock),
1228 &internal_time, &external_time, &rate_num, &rate_den);
1230 estimated_ptp_time = corrected_local_time;
1231 estimated_ptp_time =
1232 gst_clock_adjust_with_calibration (GST_CLOCK_CAST
1233 (domain->domain_clock), estimated_ptp_time, internal_time,
1234 external_time, rate_num, rate_den);
1236 gst_clock_add_observation (domain->domain_clock,
1237 corrected_local_time, corrected_ptp_time, &r_squared);
1239 gst_clock_get_calibration (GST_CLOCK_CAST (domain->domain_clock),
1240 &internal_time, &external_time, &rate_num, &rate_den);
1243 domain->last_ptp_time = corrected_ptp_time;
1244 domain->last_local_time = corrected_local_time;
1247 #ifdef USE_MEASUREMENT_FILTERING
1250 if (g_atomic_int_get (&domain_stats_n_hooks)) {
1251 GstStructure *stats = gst_structure_new (GST_PTP_STATISTICS_TIME_UPDATED,
1252 "domain", G_TYPE_UINT, domain->domain,
1253 "mean-path-delay-avg", GST_TYPE_CLOCK_TIME, domain->mean_path_delay,
1254 "local-time", GST_TYPE_CLOCK_TIME, corrected_local_time,
1255 "ptp-time", GST_TYPE_CLOCK_TIME, corrected_ptp_time,
1256 "estimated-ptp-time", GST_TYPE_CLOCK_TIME, estimated_ptp_time,
1257 "discontinuity", G_TYPE_INT64, discont,
1258 "synced", G_TYPE_BOOLEAN, synced,
1259 "r-squared", G_TYPE_DOUBLE, r_squared,
1260 "internal-time", GST_TYPE_CLOCK_TIME, internal_time,
1261 "external-time", GST_TYPE_CLOCK_TIME, external_time,
1262 "rate-num", G_TYPE_UINT64, rate_num,
1263 "rate-den", G_TYPE_UINT64, rate_den,
1264 "rate", G_TYPE_DOUBLE, (gdouble) (rate_num) / rate_den,
1266 emit_ptp_statistics (domain->domain, stats);
1267 gst_structure_free (stats);
1272 #ifdef USE_MEDIAN_PRE_FILTERING
1274 compare_clock_time (const GstClockTime * a, const GstClockTime * b)
1285 update_mean_path_delay (PtpDomainData * domain, PtpPendingSync * sync)
1287 #ifdef USE_MEDIAN_PRE_FILTERING
1288 GstClockTime last_path_delays[MEDIAN_PRE_FILTERING_WINDOW];
1289 GstClockTime median;
1293 GstClockTime mean_path_delay, delay_req_delay = 0;
1296 /* IEEE 1588 11.3 */
1298 (sync->delay_req_recv_time_remote - sync->sync_send_time_remote +
1299 sync->sync_recv_time_local - sync->delay_req_send_time_local -
1300 (sync->correction_field_sync + sync->correction_field_delay +
1301 32768) / 65536) / 2;
1303 #ifdef USE_MEDIAN_PRE_FILTERING
1304 for (i = 1; i < MEDIAN_PRE_FILTERING_WINDOW; i++)
1305 domain->last_path_delays[i - 1] = domain->last_path_delays[i];
1306 domain->last_path_delays[i - 1] = mean_path_delay;
1308 if (domain->last_path_delays_missing) {
1309 domain->last_path_delays_missing--;
1311 memcpy (&last_path_delays, &domain->last_path_delays,
1312 sizeof (last_path_delays));
1313 g_qsort_with_data (&last_path_delays,
1314 MEDIAN_PRE_FILTERING_WINDOW, sizeof (GstClockTime),
1315 (GCompareDataFunc) compare_clock_time, NULL);
1317 median = last_path_delays[MEDIAN_PRE_FILTERING_WINDOW / 2];
1319 /* FIXME: We might want to use something else here, like only allowing
1320 * things in the interquartile range, or also filtering away delays that
1321 * are too small compared to the median. This here worked well enough
1324 if (mean_path_delay > 2 * median) {
1325 GST_WARNING ("Path delay for domain %u too big compared to median: %"
1326 GST_TIME_FORMAT " > 2 * %" GST_TIME_FORMAT, domain->domain,
1327 GST_TIME_ARGS (mean_path_delay), GST_TIME_ARGS (median));
1334 #ifdef USE_RUNNING_AVERAGE_DELAY
1335 /* Track an average round trip time, for a bit of smoothing */
1336 /* Always update before discarding a sample, so genuine changes in
1337 * the network get picked up, eventually */
1338 if (domain->mean_path_delay == 0)
1339 domain->mean_path_delay = mean_path_delay;
1340 else if (mean_path_delay < domain->mean_path_delay) /* Shorter RTTs carry more weight than longer */
1341 domain->mean_path_delay =
1342 (3 * domain->mean_path_delay + mean_path_delay) / 4;
1344 domain->mean_path_delay =
1345 (15 * domain->mean_path_delay + mean_path_delay) / 16;
1347 domain->mean_path_delay = mean_path_delay;
1350 #ifdef USE_MEASUREMENT_FILTERING
1351 if (sync->follow_up_recv_time_local != GST_CLOCK_TIME_NONE &&
1352 domain->mean_path_delay != 0
1353 && sync->follow_up_recv_time_local >
1354 sync->sync_recv_time_local + 2 * domain->mean_path_delay) {
1355 GST_WARNING ("Sync-follow-up delay for domain %u too big: %" GST_TIME_FORMAT
1356 " > 2 * %" GST_TIME_FORMAT, domain->domain,
1357 GST_TIME_ARGS (sync->follow_up_recv_time_local -
1358 sync->sync_recv_time_local),
1359 GST_TIME_ARGS (domain->mean_path_delay));
1364 if (mean_path_delay > 2 * domain->mean_path_delay) {
1365 GST_WARNING ("Mean path delay for domain %u too big: %" GST_TIME_FORMAT
1366 " > 2 * %" GST_TIME_FORMAT, domain->domain,
1367 GST_TIME_ARGS (mean_path_delay),
1368 GST_TIME_ARGS (domain->mean_path_delay));
1375 sync->delay_resp_recv_time_local - sync->delay_req_send_time_local;
1377 #ifdef USE_MEASUREMENT_FILTERING
1378 /* delay_req_delay is a RTT, so 2 times the path delay */
1379 if (delay_req_delay > 4 * domain->mean_path_delay) {
1380 GST_WARNING ("Delay-request-response delay for domain %u too big: %"
1381 GST_TIME_FORMAT " > 4 * %" GST_TIME_FORMAT, domain->domain,
1382 GST_TIME_ARGS (delay_req_delay),
1383 GST_TIME_ARGS (domain->mean_path_delay));
1391 GST_DEBUG ("Got mean path delay for domain %u: %" GST_TIME_FORMAT " (new: %"
1392 GST_TIME_FORMAT ")", domain->domain,
1393 GST_TIME_ARGS (domain->mean_path_delay), GST_TIME_ARGS (mean_path_delay));
1394 GST_DEBUG ("Delay request delay for domain %u: %" GST_TIME_FORMAT,
1395 domain->domain, GST_TIME_ARGS (delay_req_delay));
1397 #ifdef USE_MEASUREMENT_FILTERING
1400 if (g_atomic_int_get (&domain_stats_n_hooks)) {
1401 GstStructure *stats =
1402 gst_structure_new (GST_PTP_STATISTICS_PATH_DELAY_MEASURED,
1403 "domain", G_TYPE_UINT, domain->domain,
1404 "mean-path-delay-avg", GST_TYPE_CLOCK_TIME, domain->mean_path_delay,
1405 "mean-path-delay", GST_TYPE_CLOCK_TIME, mean_path_delay,
1406 "delay-request-delay", GST_TYPE_CLOCK_TIME, delay_req_delay, NULL);
1407 emit_ptp_statistics (domain->domain, stats);
1408 gst_structure_free (stats);
1415 handle_sync_message (PtpMessage * msg, GstClockTime receive_time)
1418 PtpDomainData *domain = NULL;
1419 PtpPendingSync *sync = NULL;
1421 /* Don't consider messages with the alternate master flag set */
1422 if ((msg->flag_field & 0x0100))
1425 for (l = domain_data; l; l = l->next) {
1426 PtpDomainData *tmp = l->data;
1428 if (msg->domain_number == tmp->domain) {
1437 domain = g_new0 (PtpDomainData, 1);
1438 domain->domain = msg->domain_number;
1439 clock_name = g_strdup_printf ("ptp-clock-%u", domain->domain);
1440 domain->domain_clock =
1441 g_object_new (GST_TYPE_SYSTEM_CLOCK, "name", clock_name, NULL);
1442 g_free (clock_name);
1443 g_queue_init (&domain->pending_syncs);
1444 domain->last_path_delays_missing = 9;
1445 domain_data = g_list_prepend (domain_data, domain);
1447 g_mutex_lock (&domain_clocks_lock);
1448 domain_clocks = g_list_prepend (domain_clocks, domain);
1449 g_mutex_unlock (&domain_clocks_lock);
1452 /* If we have a master clock, ignore this message if it's not coming from there */
1453 if (domain->have_master_clock
1454 && compare_clock_identity (&domain->master_clock_identity,
1455 &msg->source_port_identity) != 0)
1458 #ifdef USE_OPPORTUNISTIC_CLOCK_SELECTION
1459 /* Opportunistic selection of master clock */
1460 if (!domain->have_master_clock)
1461 memcpy (&domain->master_clock_identity, &msg->source_port_identity,
1462 sizeof (PtpClockIdentity));
1464 if (!domain->have_master_clock)
1468 domain->sync_interval = log2_to_clock_time (msg->log_message_interval);
1470 /* Check if duplicated */
1471 for (l = domain->pending_syncs.head; l; l = l->next) {
1472 PtpPendingSync *tmp = l->data;
1474 if (tmp->sync_seqnum == msg->sequence_id)
1478 if (msg->message_specific.sync.origin_timestamp.seconds_field >
1479 GST_CLOCK_TIME_NONE / GST_SECOND) {
1480 GST_FIXME ("Unsupported sync message seconds field value: %"
1481 G_GUINT64_FORMAT " > %" G_GUINT64_FORMAT,
1482 msg->message_specific.sync.origin_timestamp.seconds_field,
1483 GST_CLOCK_TIME_NONE / GST_SECOND);
1487 sync = g_new0 (PtpPendingSync, 1);
1488 sync->domain = domain->domain;
1489 sync->sync_seqnum = msg->sequence_id;
1490 sync->sync_recv_time_local = receive_time;
1491 sync->sync_send_time_remote = GST_CLOCK_TIME_NONE;
1492 sync->follow_up_recv_time_local = GST_CLOCK_TIME_NONE;
1493 sync->delay_req_send_time_local = GST_CLOCK_TIME_NONE;
1494 sync->delay_req_recv_time_remote = GST_CLOCK_TIME_NONE;
1495 sync->delay_resp_recv_time_local = GST_CLOCK_TIME_NONE;
1497 /* 0.5 correction factor for division later */
1498 sync->correction_field_sync = msg->correction_field;
1500 if ((msg->flag_field & 0x0200)) {
1501 /* Wait for FOLLOW_UP */
1503 sync->sync_send_time_remote =
1504 PTP_TIMESTAMP_TO_GST_CLOCK_TIME (msg->message_specific.
1505 sync.origin_timestamp);
1507 if (domain->last_ptp_sync_time != 0
1508 && domain->last_ptp_sync_time >= sync->sync_send_time_remote) {
1509 GST_WARNING ("Backwards PTP times in domain %u: %" GST_TIME_FORMAT " >= %"
1510 GST_TIME_FORMAT, domain->domain,
1511 GST_TIME_ARGS (domain->last_ptp_sync_time),
1512 GST_TIME_ARGS (sync->sync_send_time_remote));
1513 ptp_pending_sync_free (sync);
1517 domain->last_ptp_sync_time = sync->sync_send_time_remote;
1519 if (send_delay_req (domain, sync)) {
1520 /* Sent delay request */
1522 update_ptp_time (domain, sync);
1523 ptp_pending_sync_free (sync);
1529 g_queue_push_tail (&domain->pending_syncs, sync);
1533 handle_follow_up_message (PtpMessage * msg, GstClockTime receive_time)
1536 PtpDomainData *domain = NULL;
1537 PtpPendingSync *sync = NULL;
1539 /* Don't consider messages with the alternate master flag set */
1540 if ((msg->flag_field & 0x0100))
1543 for (l = domain_data; l; l = l->next) {
1544 PtpDomainData *tmp = l->data;
1546 if (msg->domain_number == tmp->domain) {
1555 /* If we have a master clock, ignore this message if it's not coming from there */
1556 if (domain->have_master_clock
1557 && compare_clock_identity (&domain->master_clock_identity,
1558 &msg->source_port_identity) != 0)
1561 /* Check if we know about this one */
1562 for (l = domain->pending_syncs.head; l; l = l->next) {
1563 PtpPendingSync *tmp = l->data;
1565 if (tmp->sync_seqnum == msg->sequence_id) {
1574 /* Got a FOLLOW_UP for this already */
1575 if (sync->sync_send_time_remote != GST_CLOCK_TIME_NONE)
1578 if (sync->sync_recv_time_local >= receive_time) {
1579 GST_ERROR ("Got bogus follow up in domain %u: %" GST_TIME_FORMAT " > %"
1580 GST_TIME_FORMAT, domain->domain,
1581 GST_TIME_ARGS (sync->sync_recv_time_local),
1582 GST_TIME_ARGS (receive_time));
1583 g_queue_remove (&domain->pending_syncs, sync);
1584 ptp_pending_sync_free (sync);
1588 sync->correction_field_sync += msg->correction_field;
1589 sync->sync_send_time_remote =
1590 PTP_TIMESTAMP_TO_GST_CLOCK_TIME (msg->message_specific.
1591 follow_up.precise_origin_timestamp);
1592 sync->follow_up_recv_time_local = receive_time;
1594 if (domain->last_ptp_sync_time >= sync->sync_send_time_remote) {
1595 GST_WARNING ("Backwards PTP times in domain %u: %" GST_TIME_FORMAT " >= %"
1596 GST_TIME_FORMAT, domain->domain,
1597 GST_TIME_ARGS (domain->last_ptp_sync_time),
1598 GST_TIME_ARGS (sync->sync_send_time_remote));
1599 g_queue_remove (&domain->pending_syncs, sync);
1600 ptp_pending_sync_free (sync);
1604 domain->last_ptp_sync_time = sync->sync_send_time_remote;
1606 if (send_delay_req (domain, sync)) {
1607 /* Sent delay request */
1609 update_ptp_time (domain, sync);
1610 g_queue_remove (&domain->pending_syncs, sync);
1611 ptp_pending_sync_free (sync);
1617 handle_delay_resp_message (PtpMessage * msg, GstClockTime receive_time)
1620 PtpDomainData *domain = NULL;
1621 PtpPendingSync *sync = NULL;
1623 /* Don't consider messages with the alternate master flag set */
1624 if ((msg->flag_field & 0x0100))
1627 for (l = domain_data; l; l = l->next) {
1628 PtpDomainData *tmp = l->data;
1630 if (msg->domain_number == tmp->domain) {
1639 /* If we have a master clock, ignore this message if it's not coming from there */
1640 if (domain->have_master_clock
1641 && compare_clock_identity (&domain->master_clock_identity,
1642 &msg->source_port_identity) != 0)
1646 if (msg->message_specific.delay_resp.
1647 requesting_port_identity.clock_identity != ptp_clock_id.clock_identity
1648 || msg->message_specific.delay_resp.
1649 requesting_port_identity.port_number != ptp_clock_id.port_number)
1652 domain->min_delay_req_interval =
1653 log2_to_clock_time (msg->log_message_interval);
1655 /* Check if we know about this one */
1656 for (l = domain->pending_syncs.head; l; l = l->next) {
1657 PtpPendingSync *tmp = l->data;
1659 if (tmp->delay_req_seqnum == msg->sequence_id) {
1668 /* Got a DELAY_RESP for this already */
1669 if (sync->delay_req_recv_time_remote != GST_CLOCK_TIME_NONE)
1672 if (sync->delay_req_send_time_local > receive_time) {
1673 GST_ERROR ("Got bogus delay response in domain %u: %" GST_TIME_FORMAT " > %"
1674 GST_TIME_FORMAT, domain->domain,
1675 GST_TIME_ARGS (sync->delay_req_send_time_local),
1676 GST_TIME_ARGS (receive_time));
1677 g_queue_remove (&domain->pending_syncs, sync);
1678 ptp_pending_sync_free (sync);
1682 sync->correction_field_delay = msg->correction_field;
1684 sync->delay_req_recv_time_remote =
1685 PTP_TIMESTAMP_TO_GST_CLOCK_TIME (msg->message_specific.
1686 delay_resp.receive_timestamp);
1687 sync->delay_resp_recv_time_local = receive_time;
1689 if (domain->mean_path_delay != 0
1690 && sync->sync_send_time_remote > sync->delay_req_recv_time_remote) {
1691 GST_WARNING ("Sync send time after delay req receive time for domain %u: %"
1692 GST_TIME_FORMAT " > %" GST_TIME_FORMAT, domain->domain,
1693 GST_TIME_ARGS (sync->sync_send_time_remote),
1694 GST_TIME_ARGS (sync->delay_req_recv_time_remote));
1695 g_queue_remove (&domain->pending_syncs, sync);
1696 ptp_pending_sync_free (sync);
1700 if (update_mean_path_delay (domain, sync))
1701 update_ptp_time (domain, sync);
1702 g_queue_remove (&domain->pending_syncs, sync);
1703 ptp_pending_sync_free (sync);
1707 handle_ptp_message (PtpMessage * msg, GstClockTime receive_time)
1709 /* Ignore our own messages */
1710 if (msg->source_port_identity.clock_identity == ptp_clock_id.clock_identity &&
1711 msg->source_port_identity.port_number == ptp_clock_id.port_number)
1714 switch (msg->message_type) {
1715 case PTP_MESSAGE_TYPE_ANNOUNCE:
1716 handle_announce_message (msg, receive_time);
1718 case PTP_MESSAGE_TYPE_SYNC:
1719 handle_sync_message (msg, receive_time);
1721 case PTP_MESSAGE_TYPE_FOLLOW_UP:
1722 handle_follow_up_message (msg, receive_time);
1724 case PTP_MESSAGE_TYPE_DELAY_RESP:
1725 handle_delay_resp_message (msg, receive_time);
1733 have_stdin_data_cb (GIOChannel * channel, GIOCondition condition,
1742 if ((condition & G_IO_STATUS_EOF)) {
1743 GST_ERROR ("Got EOF on stdin");
1744 g_main_loop_quit (main_loop);
1745 return G_SOURCE_REMOVE;
1749 g_io_channel_read_chars (channel, (gchar *) & header, sizeof (header),
1751 if (status == G_IO_STATUS_ERROR) {
1752 GST_ERROR ("Failed to read from stdin: %s", err->message);
1753 g_clear_error (&err);
1754 g_main_loop_quit (main_loop);
1755 return G_SOURCE_REMOVE;
1756 } else if (status == G_IO_STATUS_EOF) {
1757 GST_ERROR ("Got EOF on stdin");
1758 g_main_loop_quit (main_loop);
1759 return G_SOURCE_REMOVE;
1760 } else if (status != G_IO_STATUS_NORMAL) {
1761 GST_ERROR ("Unexpected stdin read status: %d", status);
1762 g_main_loop_quit (main_loop);
1763 return G_SOURCE_REMOVE;
1764 } else if (read != sizeof (header)) {
1765 GST_ERROR ("Unexpected read size: %" G_GSIZE_FORMAT, read);
1766 g_main_loop_quit (main_loop);
1767 return G_SOURCE_REMOVE;
1768 } else if (header.size > 8192) {
1769 GST_ERROR ("Unexpected size: %u", header.size);
1770 g_main_loop_quit (main_loop);
1771 return G_SOURCE_REMOVE;
1774 status = g_io_channel_read_chars (channel, buffer, header.size, &read, &err);
1775 if (status == G_IO_STATUS_ERROR) {
1776 GST_ERROR ("Failed to read from stdin: %s", err->message);
1777 g_clear_error (&err);
1778 g_main_loop_quit (main_loop);
1779 return G_SOURCE_REMOVE;
1780 } else if (status == G_IO_STATUS_EOF) {
1781 GST_ERROR ("EOF on stdin");
1782 g_main_loop_quit (main_loop);
1783 return G_SOURCE_REMOVE;
1784 } else if (status != G_IO_STATUS_NORMAL) {
1785 GST_ERROR ("Unexpected stdin read status: %d", status);
1786 g_main_loop_quit (main_loop);
1787 return G_SOURCE_REMOVE;
1788 } else if (read != header.size) {
1789 GST_ERROR ("Unexpected read size: %" G_GSIZE_FORMAT, read);
1790 g_main_loop_quit (main_loop);
1791 return G_SOURCE_REMOVE;
1794 switch (header.type) {
1797 GstClockTime receive_time = gst_clock_get_time (observation_system_clock);
1800 if (parse_ptp_message (&msg, (const guint8 *) buffer, header.size)) {
1801 dump_ptp_message (&msg);
1802 handle_ptp_message (&msg, receive_time);
1807 case TYPE_CLOCK_ID:{
1808 if (header.size != 8) {
1809 GST_ERROR ("Unexpected clock id size (%u != 8)", header.size);
1810 g_main_loop_quit (main_loop);
1811 return G_SOURCE_REMOVE;
1813 g_mutex_lock (&ptp_lock);
1814 ptp_clock_id.clock_identity = GST_READ_UINT64_BE (buffer);
1815 ptp_clock_id.port_number = getpid ();
1816 GST_DEBUG ("Got clock id 0x%016" G_GINT64_MODIFIER "x %u",
1817 ptp_clock_id.clock_identity, ptp_clock_id.port_number);
1818 g_cond_signal (&ptp_cond);
1819 g_mutex_unlock (&ptp_lock);
1824 return G_SOURCE_CONTINUE;
1827 /* Cleanup all announce messages and announce message senders
1828 * that are timed out by now, and clean up all pending syncs
1829 * that are missing their FOLLOW_UP or DELAY_RESP */
1831 cleanup_cb (gpointer data)
1833 GstClockTime now = gst_clock_get_time (observation_system_clock);
1836 for (l = domain_data; l; l = l->next) {
1837 PtpDomainData *domain = l->data;
1839 for (n = domain->announce_senders; n;) {
1840 PtpAnnounceSender *sender = n->data;
1841 gboolean timed_out = TRUE;
1843 /* Keep only 5 messages per sender around */
1844 while (g_queue_get_length (&sender->announce_messages) > 5) {
1845 PtpAnnounceMessage *msg = g_queue_pop_head (&sender->announce_messages);
1849 for (m = sender->announce_messages.head; m; m = m->next) {
1850 PtpAnnounceMessage *msg = m->data;
1852 if (msg->receive_time +
1853 sender->announce_interval * PTP_ANNOUNCE_RECEIPT_TIMEOUT > now) {
1860 GST_DEBUG ("Announce sender 0x%016" G_GINT64_MODIFIER "x %u timed out",
1861 sender->master_clock_identity.clock_identity,
1862 sender->master_clock_identity.port_number);
1863 g_queue_foreach (&sender->announce_messages, (GFunc) g_free, NULL);
1864 g_queue_clear (&sender->announce_messages);
1867 if (g_queue_get_length (&sender->announce_messages) == 0) {
1868 GList *tmp = n->next;
1870 if (compare_clock_identity (&sender->master_clock_identity,
1871 &domain->master_clock_identity) == 0)
1872 GST_WARNING ("currently selected master clock timed out");
1874 domain->announce_senders =
1875 g_list_delete_link (domain->announce_senders, n);
1881 select_best_master_clock (domain, now);
1883 /* Clean up any pending syncs */
1884 for (n = domain->pending_syncs.head; n;) {
1885 PtpPendingSync *sync = n->data;
1886 gboolean timed_out = FALSE;
1888 /* Time out pending syncs after 4 sync intervals or 10 seconds,
1889 * and pending delay reqs after 4 delay req intervals or 10 seconds
1891 if (sync->delay_req_send_time_local != GST_CLOCK_TIME_NONE &&
1892 ((domain->min_delay_req_interval != 0
1893 && sync->delay_req_send_time_local +
1894 4 * domain->min_delay_req_interval < now)
1895 || (sync->delay_req_send_time_local + 10 * GST_SECOND < now))) {
1897 } else if ((domain->sync_interval != 0
1898 && sync->sync_recv_time_local + 4 * domain->sync_interval < now)
1899 || (sync->sync_recv_time_local + 10 * GST_SECOND < now)) {
1904 GList *tmp = n->next;
1905 ptp_pending_sync_free (sync);
1906 g_queue_delete_link (&domain->pending_syncs, n);
1914 return G_SOURCE_CONTINUE;
1918 ptp_helper_main (gpointer data)
1920 GSource *cleanup_source;
1922 GST_DEBUG ("Starting PTP helper loop");
1924 /* Check all 5 seconds, if we have to cleanup ANNOUNCE or pending syncs message */
1925 cleanup_source = g_timeout_source_new_seconds (5);
1926 g_source_set_priority (cleanup_source, G_PRIORITY_DEFAULT);
1927 g_source_set_callback (cleanup_source, (GSourceFunc) cleanup_cb, NULL, NULL);
1928 g_source_attach (cleanup_source, main_context);
1929 g_source_unref (cleanup_source);
1931 g_main_loop_run (main_loop);
1932 GST_DEBUG ("Stopped PTP helper loop");
1934 g_mutex_lock (&ptp_lock);
1935 ptp_clock_id.clock_identity = GST_PTP_CLOCK_ID_NONE;
1936 ptp_clock_id.port_number = 0;
1938 g_cond_signal (&ptp_cond);
1939 g_mutex_unlock (&ptp_lock);
1945 * gst_ptp_is_supported:
1947 * Check if PTP clocks are generally supported on this system, and if previous
1948 * initializations did not fail.
1950 * Returns: %TRUE if PTP clocks are generally supported on this system, and
1951 * previous initializations did not fail.
1956 gst_ptp_is_supported (void)
1962 * gst_ptp_is_initialized:
1964 * Check if the GStreamer PTP clock subsystem is initialized.
1966 * Returns: %TRUE if the GStreamer PTP clock subsystem is intialized.
1971 gst_ptp_is_initialized (void)
1978 * @clock_id: PTP clock id of this process' clock or %GST_PTP_CLOCK_ID_NONE
1979 * @interfaces: (transfer none) (array zero-terminated=1) (allow-none): network interfaces to run the clock on
1981 * Initialize the GStreamer PTP subsystem and create a PTP ordinary clock in
1982 * slave-only mode for all domains on the given @interfaces with the
1985 * If @clock_id is %GST_PTP_CLOCK_ID_NONE, a clock id is automatically
1986 * generated from the MAC address of the first network interface.
1989 * This function is automatically called by gst_ptp_clock_new() with default
1990 * parameters if it wasn't called before.
1992 * Returns: %TRUE if the GStreamer PTP clock subsystem could be initialized.
1997 gst_ptp_init (guint64 clock_id, gchar ** interfaces)
2001 gchar **argv = NULL;
2005 GSource *stdin_source;
2007 GST_DEBUG_CATEGORY_INIT (ptp_debug, "ptp", 0, "PTP clock");
2009 g_mutex_lock (&ptp_lock);
2011 GST_ERROR ("PTP not supported");
2017 GST_DEBUG ("PTP already initialized");
2022 if (ptp_helper_pid) {
2023 GST_DEBUG ("PTP currently initializing");
2027 if (!domain_stats_hooks_initted) {
2028 g_hook_list_init (&domain_stats_hooks, sizeof (GHook));
2029 domain_stats_hooks_initted = TRUE;
2033 if (clock_id != GST_PTP_CLOCK_ID_NONE)
2035 if (interfaces != NULL)
2036 argc += 2 * g_strv_length (interfaces);
2038 argv = g_new0 (gchar *, argc + 2);
2041 env = g_getenv ("GST_PTP_HELPER_1_0");
2043 env = g_getenv ("GST_PTP_HELPER");
2044 if (env != NULL && *env != '\0') {
2045 GST_LOG ("Trying GST_PTP_HELPER env var: %s", env);
2046 argv[argc_c++] = g_strdup (env);
2048 argv[argc_c++] = g_strdup (GST_PTP_HELPER_INSTALLED);
2051 if (clock_id != GST_PTP_CLOCK_ID_NONE) {
2052 argv[argc_c++] = g_strdup ("-c");
2053 argv[argc_c++] = g_strdup_printf ("0x%016" G_GINT64_MODIFIER "x", clock_id);
2056 if (interfaces != NULL) {
2057 gchar **ptr = interfaces;
2060 argv[argc_c++] = g_strdup ("-i");
2061 argv[argc_c++] = g_strdup (*ptr);
2066 main_context = g_main_context_new ();
2067 main_loop = g_main_loop_new (main_context, FALSE);
2070 g_thread_try_new ("ptp-helper-thread", ptp_helper_main, NULL, &err);
2071 if (!ptp_helper_thread) {
2072 GST_ERROR ("Failed to start PTP helper thread: %s", err->message);
2073 g_clear_error (&err);
2078 if (!g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL,
2079 &ptp_helper_pid, &fd_w, &fd_r, NULL, &err)) {
2080 GST_ERROR ("Failed to start ptp helper process: %s", err->message);
2081 g_clear_error (&err);
2087 stdin_channel = g_io_channel_unix_new (fd_r);
2088 g_io_channel_set_encoding (stdin_channel, NULL, NULL);
2089 g_io_channel_set_buffered (stdin_channel, FALSE);
2090 g_io_channel_set_close_on_unref (stdin_channel, TRUE);
2092 g_io_create_watch (stdin_channel, G_IO_IN | G_IO_PRI | G_IO_HUP);
2093 g_source_set_priority (stdin_source, G_PRIORITY_DEFAULT);
2094 g_source_set_callback (stdin_source, (GSourceFunc) have_stdin_data_cb, NULL,
2096 g_source_attach (stdin_source, main_context);
2097 g_source_unref (stdin_source);
2099 /* Create stdout channel */
2100 stdout_channel = g_io_channel_unix_new (fd_w);
2101 g_io_channel_set_encoding (stdout_channel, NULL, NULL);
2102 g_io_channel_set_close_on_unref (stdout_channel, TRUE);
2103 g_io_channel_set_buffered (stdout_channel, FALSE);
2105 delay_req_rand = g_rand_new ();
2106 observation_system_clock =
2107 g_object_new (GST_TYPE_SYSTEM_CLOCK, "name", "ptp-observation-clock",
2113 GST_DEBUG ("Waiting for PTP to be initialized");
2115 while (ptp_clock_id.clock_identity == GST_PTP_CLOCK_ID_NONE && initted)
2116 g_cond_wait (&ptp_cond, &ptp_lock);
2120 GST_DEBUG ("Initialized and got clock id 0x%016" G_GINT64_MODIFIER "x %u",
2121 ptp_clock_id.clock_identity, ptp_clock_id.port_number);
2123 GST_ERROR ("Failed to initialize");
2131 if (ptp_helper_pid) {
2133 kill (ptp_helper_pid, SIGKILL);
2134 waitpid (ptp_helper_pid, NULL, 0);
2136 TerminateProcess (ptp_helper_pid, 1);
2137 WaitForSingleObject (ptp_helper_pid, INFINITE);
2139 g_spawn_close_pid (ptp_helper_pid);
2144 g_io_channel_unref (stdin_channel);
2145 stdin_channel = NULL;
2147 g_io_channel_unref (stdout_channel);
2148 stdout_channel = NULL;
2150 if (main_loop && ptp_helper_thread) {
2151 g_main_loop_quit (main_loop);
2152 g_thread_join (ptp_helper_thread);
2154 ptp_helper_thread = NULL;
2156 g_main_loop_unref (main_loop);
2159 g_main_context_unref (main_context);
2160 main_context = NULL;
2163 g_rand_free (delay_req_rand);
2164 delay_req_rand = NULL;
2166 if (observation_system_clock)
2167 gst_object_unref (observation_system_clock);
2168 observation_system_clock = NULL;
2171 g_mutex_unlock (&ptp_lock);
2179 * Deinitialize the GStreamer PTP subsystem and stop the PTP clock. If there
2180 * are any remaining GstPtpClock instances, they won't be further synchronized
2181 * to the PTP network clock.
2186 gst_ptp_deinit (void)
2190 g_mutex_lock (&ptp_lock);
2192 if (ptp_helper_pid) {
2194 kill (ptp_helper_pid, SIGKILL);
2195 waitpid (ptp_helper_pid, NULL, 0);
2197 TerminateProcess (ptp_helper_pid, 1);
2198 WaitForSingleObject (ptp_helper_pid, INFINITE);
2200 g_spawn_close_pid (ptp_helper_pid);
2205 g_io_channel_unref (stdin_channel);
2206 stdin_channel = NULL;
2208 g_io_channel_unref (stdout_channel);
2209 stdout_channel = NULL;
2211 if (main_loop && ptp_helper_thread) {
2212 GThread *tmp = ptp_helper_thread;
2213 ptp_helper_thread = NULL;
2214 g_mutex_unlock (&ptp_lock);
2215 g_main_loop_quit (main_loop);
2216 g_thread_join (tmp);
2217 g_mutex_lock (&ptp_lock);
2220 g_main_loop_unref (main_loop);
2223 g_main_context_unref (main_context);
2224 main_context = NULL;
2227 g_rand_free (delay_req_rand);
2228 delay_req_rand = NULL;
2229 if (observation_system_clock)
2230 gst_object_unref (observation_system_clock);
2231 observation_system_clock = NULL;
2233 for (l = domain_data; l; l = l->next) {
2234 PtpDomainData *domain = l->data;
2236 for (m = domain->announce_senders; m; m = m->next) {
2237 PtpAnnounceSender *sender = m->data;
2239 g_queue_foreach (&sender->announce_messages, (GFunc) g_free, NULL);
2240 g_queue_clear (&sender->announce_messages);
2243 g_list_free (domain->announce_senders);
2245 g_queue_foreach (&domain->pending_syncs, (GFunc) ptp_pending_sync_free,
2247 g_queue_clear (&domain->pending_syncs);
2248 gst_object_unref (domain->domain_clock);
2251 g_list_free (domain_data);
2253 g_list_foreach (domain_clocks, (GFunc) g_free, NULL);
2254 g_list_free (domain_clocks);
2255 domain_clocks = NULL;
2257 ptp_clock_id.clock_identity = GST_PTP_CLOCK_ID_NONE;
2258 ptp_clock_id.port_number = 0;
2262 g_mutex_unlock (&ptp_lock);
2265 #define DEFAULT_DOMAIN 0
2274 #define GST_PTP_CLOCK_GET_PRIVATE(obj) \
2275 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_PTP_CLOCK, GstPtpClockPrivate))
2277 struct _GstPtpClockPrivate
2280 GstClock *domain_clock;
2281 gulong domain_stats_id;
2284 #define gst_ptp_clock_parent_class parent_class
2285 G_DEFINE_TYPE (GstPtpClock, gst_ptp_clock, GST_TYPE_SYSTEM_CLOCK);
2287 static void gst_ptp_clock_set_property (GObject * object, guint prop_id,
2288 const GValue * value, GParamSpec * pspec);
2289 static void gst_ptp_clock_get_property (GObject * object, guint prop_id,
2290 GValue * value, GParamSpec * pspec);
2291 static void gst_ptp_clock_finalize (GObject * object);
2293 static GstClockTime gst_ptp_clock_get_internal_time (GstClock * clock);
2296 gst_ptp_clock_class_init (GstPtpClockClass * klass)
2298 GObjectClass *gobject_class;
2299 GstClockClass *clock_class;
2301 gobject_class = G_OBJECT_CLASS (klass);
2302 clock_class = GST_CLOCK_CLASS (klass);
2304 g_type_class_add_private (klass, sizeof (GstPtpClockPrivate));
2306 gobject_class->finalize = gst_ptp_clock_finalize;
2307 gobject_class->get_property = gst_ptp_clock_get_property;
2308 gobject_class->set_property = gst_ptp_clock_set_property;
2310 g_object_class_install_property (gobject_class, PROP_DOMAIN,
2311 g_param_spec_uint ("domain", "Domain",
2312 "The PTP domain", 0, G_MAXUINT8,
2314 G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
2316 g_object_class_install_property (gobject_class, PROP_INTERNAL_CLOCK,
2317 g_param_spec_object ("internal-clock", "Internal Clock",
2318 "Internal clock", GST_TYPE_CLOCK,
2319 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
2321 clock_class->get_internal_time = gst_ptp_clock_get_internal_time;
2325 gst_ptp_clock_init (GstPtpClock * self)
2327 GstPtpClockPrivate *priv;
2329 self->priv = priv = GST_PTP_CLOCK_GET_PRIVATE (self);
2331 GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_CAN_SET_MASTER);
2332 GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC);
2334 priv->domain = DEFAULT_DOMAIN;
2338 gst_ptp_clock_ensure_domain_clock (GstPtpClock * self)
2340 gboolean got_clock = TRUE;
2342 if (G_UNLIKELY (!self->priv->domain_clock)) {
2343 g_mutex_lock (&domain_clocks_lock);
2344 if (!self->priv->domain_clock) {
2349 for (l = domain_clocks; l; l = l->next) {
2350 PtpDomainData *clock_data = l->data;
2352 if (clock_data->domain == self->priv->domain
2353 && clock_data->last_ptp_time != 0) {
2354 self->priv->domain_clock = clock_data->domain_clock;
2360 g_mutex_unlock (&domain_clocks_lock);
2362 g_object_notify (G_OBJECT (self), "internal-clock");
2363 gst_clock_set_synced (GST_CLOCK (self), TRUE);
2371 gst_ptp_clock_stats_callback (guint8 domain, const GstStructure * stats,
2374 GstPtpClock *self = user_data;
2376 if (domain != self->priv->domain
2377 || !gst_structure_has_name (stats, GST_PTP_STATISTICS_TIME_UPDATED))
2380 /* Let's set our internal clock */
2381 if (!gst_ptp_clock_ensure_domain_clock (self))
2384 self->priv->domain_stats_id = 0;
2390 gst_ptp_clock_set_property (GObject * object, guint prop_id,
2391 const GValue * value, GParamSpec * pspec)
2393 GstPtpClock *self = GST_PTP_CLOCK (object);
2397 self->priv->domain = g_value_get_uint (value);
2398 gst_ptp_clock_ensure_domain_clock (self);
2399 if (!self->priv->domain_clock)
2400 self->priv->domain_stats_id =
2401 gst_ptp_statistics_callback_add (gst_ptp_clock_stats_callback, self,
2405 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2411 gst_ptp_clock_get_property (GObject * object, guint prop_id,
2412 GValue * value, GParamSpec * pspec)
2414 GstPtpClock *self = GST_PTP_CLOCK (object);
2418 g_value_set_uint (value, self->priv->domain);
2420 case PROP_INTERNAL_CLOCK:
2421 gst_ptp_clock_ensure_domain_clock (self);
2422 g_value_set_object (value, self->priv->domain_clock);
2425 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2431 gst_ptp_clock_finalize (GObject * object)
2433 GstPtpClock *self = GST_PTP_CLOCK (object);
2435 if (self->priv->domain_stats_id)
2436 gst_ptp_statistics_callback_remove (self->priv->domain_stats_id);
2438 G_OBJECT_CLASS (gst_ptp_clock_parent_class)->finalize (object);
2442 gst_ptp_clock_get_internal_time (GstClock * clock)
2444 GstPtpClock *self = GST_PTP_CLOCK (clock);
2446 gst_ptp_clock_ensure_domain_clock (self);
2448 if (!self->priv->domain_clock) {
2449 GST_ERROR_OBJECT (self, "Domain %u has no clock yet and is not synced",
2450 self->priv->domain);
2451 return GST_CLOCK_TIME_NONE;
2454 return gst_clock_get_time (self->priv->domain_clock);
2458 * gst_ptp_clock_new:
2459 * @name: Name of the clock
2460 * @domain: PTP domain
2462 * Creates a new PTP clock instance that exports the PTP time of the master
2463 * clock in @domain. This clock can be slaved to other clocks as needed.
2465 * If gst_ptp_init() was not called before, this will call gst_ptp_init() with
2466 * default parameters.
2469 * This clock only returns valid timestamps after it received the first
2470 * times from the PTP master clock on the network. Once this happens the
2471 * GstPtpClock::internal-clock property will become non-NULL. You can
2472 * check this with gst_clock_wait_for_sync(), the GstClock::synced signal and
2473 * gst_clock_is_synced().
2478 gst_ptp_clock_new (const gchar * name, guint domain)
2480 g_return_val_if_fail (name != NULL, NULL);
2481 g_return_val_if_fail (domain <= G_MAXUINT8, NULL);
2483 if (!initted && !gst_ptp_init (GST_PTP_CLOCK_ID_NONE, NULL)) {
2484 GST_ERROR ("Failed to initialize PTP");
2488 return g_object_new (GST_TYPE_PTP_CLOCK, "name", name, "domain", domain,
2495 const GstStructure *stats;
2496 } DomainStatsMarshalData;
2499 domain_stats_marshaller (GHook * hook, DomainStatsMarshalData * data)
2501 GstPtpStatisticsCallback callback = (GstPtpStatisticsCallback) hook->func;
2503 if (!callback (data->domain, data->stats, hook->data))
2504 g_hook_destroy (&domain_stats_hooks, hook->hook_id);
2508 emit_ptp_statistics (guint8 domain, const GstStructure * stats)
2510 DomainStatsMarshalData data = { domain, stats };
2512 g_mutex_lock (&ptp_lock);
2513 g_hook_list_marshal (&domain_stats_hooks, TRUE,
2514 (GHookMarshaller) domain_stats_marshaller, &data);
2515 g_mutex_unlock (&ptp_lock);
2519 * gst_ptp_statistics_callback_add:
2520 * @callback: GstPtpStatisticsCallback to call
2521 * @user_data: Data to pass to the callback
2522 * @destroy_data: GDestroyNotify to destroy the data
2524 * Installs a new statistics callback for gathering PTP statistics. See
2525 * GstPtpStatisticsCallback for a list of statistics that are provided.
2527 * Returns: Id for the callback that can be passed to
2528 * gst_ptp_statistics_callback_remove()
2533 gst_ptp_statistics_callback_add (GstPtpStatisticsCallback callback,
2534 gpointer user_data, GDestroyNotify destroy_data)
2538 g_mutex_lock (&ptp_lock);
2540 if (!domain_stats_hooks_initted) {
2541 g_hook_list_init (&domain_stats_hooks, sizeof (GHook));
2542 domain_stats_hooks_initted = TRUE;
2545 hook = g_hook_alloc (&domain_stats_hooks);
2546 hook->func = callback;
2547 hook->data = user_data;
2548 hook->destroy = destroy_data;
2549 g_hook_prepend (&domain_stats_hooks, hook);
2550 g_atomic_int_add (&domain_stats_n_hooks, 1);
2552 g_mutex_unlock (&ptp_lock);
2554 return hook->hook_id;
2558 * gst_ptp_statistics_callback_remove:
2559 * @id: Callback id to remove
2561 * Removes a PTP statistics callback that was previously added with
2562 * gst_ptp_statistics_callback_add().
2567 gst_ptp_statistics_callback_remove (gulong id)
2569 g_mutex_lock (&ptp_lock);
2570 if (g_hook_destroy (&domain_stats_hooks, id))
2571 g_atomic_int_add (&domain_stats_n_hooks, -1);
2572 g_mutex_unlock (&ptp_lock);