ptpclock: Use #define everywhere instead of G_N_ELEMENTS()
[platform/upstream/gstreamer.git] / libs / gst / net / gstptpclock.c
1 /* GStreamer
2  * Copyright (C) 2015 Sebastian Dröge <sebastian@centricular.com>
3  *
4  *
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.
9  *
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.
14  *
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.
19  */
20 /**
21  * SECTION:gstptpclock
22  * @short_description: Special clock that synchronizes to a remote time
23  *                     provider via PTP (IEEE1588:2008).
24  * @see_also: #GstClock, #GstNetClientClock, #GstPipeline
25  *
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.
29  *
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
35  * interfaces.
36  *
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().
42  *
43  *
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
47  * synchronization.
48  *
49  * Since: 1.6
50  *
51  */
52 #ifdef HAVE_CONFIG_H
53 #include "config.h"
54 #endif
55
56 #include "gstptpclock.h"
57
58 #ifdef HAVE_PTP
59
60 #include "gstptp_private.h"
61
62 #include <sys/wait.h>
63 #include <sys/types.h>
64 #include <unistd.h>
65
66 #include <gst/base/base.h>
67
68 GST_DEBUG_CATEGORY_STATIC (ptp_debug);
69 #define GST_CAT_DEFAULT (ptp_debug)
70
71 /* IEEE 1588 7.7.3.1 */
72 #define PTP_ANNOUNCE_RECEIPT_TIMEOUT 4
73
74 /* Use a running average for calculating the mean path delay instead
75  * of just using the last measurement. Enabling this helps in unreliable
76  * networks, like wifi, with often changing delays
77  *
78  * Undef for following IEEE1588-2008 by the letter
79  */
80 #define USE_RUNNING_AVERAGE_DELAY 1
81
82 /* Filter out any measurements that are above a certain threshold compared to
83  * previous measurements. Enabling this helps filtering out outliers that
84  * happen fairly often in unreliable networks, like wifi.
85  *
86  * Undef for following IEEE1588-2008 by the letter
87  */
88 #define USE_MEASUREMENT_FILTERING 1
89
90 /* Select the first clock from which we capture a SYNC message as the master
91  * clock of the domain until we are ready to run the best master clock
92  * algorithm. This allows faster syncing but might mean a change of the master
93  * clock in the beginning. As all clocks in a domain are supposed to use the
94  * same time, this shouldn't be much of a problem.
95  *
96  * Undef for following IEEE1588-2008 by the letter
97  */
98 #define USE_OPPORTUNISTIC_CLOCK_SELECTION 1
99
100 /* Only consider SYNC messages for which we are allowed to send a DELAY_REQ
101  * afterwards. This allows better synchronization in networks with varying
102  * delays, as for every other SYNC message we would have to assume that it's
103  * the average of what we saw before. But that might be completely off
104  */
105 #define USE_ONLY_SYNC_WITH_DELAY 1
106
107 /* Filter out delay measurements that are too far away from the median of the
108  * last delay measurements, currently those that are more than 2 times as big.
109  * This increases accuracy a lot on wifi.
110  */
111 #define USE_MEDIAN_PRE_FILTERING 1
112 #define MEDIAN_PRE_FILTERING_WINDOW 9
113
114 /* How many updates should be skipped at maximum when using USE_MEASUREMENT_FILTERING */
115 #define MAX_SKIPPED_UPDATES 5
116
117 typedef enum
118 {
119   PTP_MESSAGE_TYPE_SYNC = 0x0,
120   PTP_MESSAGE_TYPE_DELAY_REQ = 0x1,
121   PTP_MESSAGE_TYPE_PDELAY_REQ = 0x2,
122   PTP_MESSAGE_TYPE_PDELAY_RESP = 0x3,
123   PTP_MESSAGE_TYPE_FOLLOW_UP = 0x8,
124   PTP_MESSAGE_TYPE_DELAY_RESP = 0x9,
125   PTP_MESSAGE_TYPE_PDELAY_RESP_FOLLOW_UP = 0xA,
126   PTP_MESSAGE_TYPE_ANNOUNCE = 0xB,
127   PTP_MESSAGE_TYPE_SIGNALING = 0xC,
128   PTP_MESSAGE_TYPE_MANAGEMENT = 0xD
129 } PtpMessageType;
130
131 typedef struct
132 {
133   guint64 seconds_field;        /* 48 bits valid */
134   guint32 nanoseconds_field;
135 } PtpTimestamp;
136
137 #define PTP_TIMESTAMP_TO_GST_CLOCK_TIME(ptp) (ptp.seconds_field * GST_SECOND + ptp.nanoseconds_field)
138 #define GST_CLOCK_TIME_TO_PTP_TIMESTAMP_SECONDS(gst) (((GstClockTime) gst) / GST_SECOND)
139 #define GST_CLOCK_TIME_TO_PTP_TIMESTAMP_NANOSECONDS(gst) (((GstClockTime) gst) % GST_SECOND)
140
141 typedef struct
142 {
143   guint64 clock_identity;
144   guint16 port_number;
145 } PtpClockIdentity;
146
147 static gint
148 compare_clock_identity (const PtpClockIdentity * a, const PtpClockIdentity * b)
149 {
150   if (a->clock_identity < b->clock_identity)
151     return -1;
152   else if (a->clock_identity > b->clock_identity)
153     return 1;
154
155   if (a->port_number < b->port_number)
156     return -1;
157   else if (a->port_number > b->port_number)
158     return 1;
159
160   return 0;
161 }
162
163 typedef struct
164 {
165   guint8 clock_class;
166   guint8 clock_accuracy;
167   guint16 offset_scaled_log_variance;
168 } PtpClockQuality;
169
170 typedef struct
171 {
172   guint8 transport_specific;
173   PtpMessageType message_type;
174   /* guint8 reserved; */
175   guint8 version_ptp;
176   guint16 message_length;
177   guint8 domain_number;
178   /* guint8 reserved; */
179   guint16 flag_field;
180   gint64 correction_field;      /* 48.16 fixed point nanoseconds */
181   /* guint32 reserved; */
182   PtpClockIdentity source_port_identity;
183   guint16 sequence_id;
184   guint8 control_field;
185   gint8 log_message_interval;
186
187   union
188   {
189     struct
190     {
191       PtpTimestamp origin_timestamp;
192       gint16 current_utc_offset;
193       /* guint8 reserved; */
194       guint8 grandmaster_priority_1;
195       PtpClockQuality grandmaster_clock_quality;
196       guint8 grandmaster_priority_2;
197       guint64 grandmaster_identity;
198       guint16 steps_removed;
199       guint8 time_source;
200     } announce;
201
202     struct
203     {
204       PtpTimestamp origin_timestamp;
205     } sync;
206
207     struct
208     {
209       PtpTimestamp precise_origin_timestamp;
210     } follow_up;
211
212     struct
213     {
214       PtpTimestamp origin_timestamp;
215     } delay_req;
216
217     struct
218     {
219       PtpTimestamp receive_timestamp;
220       PtpClockIdentity requesting_port_identity;
221     } delay_resp;
222
223   } message_specific;
224 } PtpMessage;
225
226 static GMutex ptp_lock;
227 static GCond ptp_cond;
228 static gboolean initted = FALSE;
229 static gboolean supported = TRUE;
230 static GPid ptp_helper_pid;
231 static GThread *ptp_helper_thread;
232 static GMainContext *main_context;
233 static GMainLoop *main_loop;
234 static GIOChannel *stdin_channel, *stdout_channel;
235 static GRand *delay_req_rand;
236 static GstClock *observation_system_clock;
237 static PtpClockIdentity ptp_clock_id = { GST_PTP_CLOCK_ID_NONE, 0 };
238
239 typedef struct
240 {
241   GstClockTime receive_time;
242
243   PtpClockIdentity master_clock_identity;
244
245   guint8 grandmaster_priority_1;
246   PtpClockQuality grandmaster_clock_quality;
247   guint8 grandmaster_priority_2;
248   guint64 grandmaster_identity;
249   guint16 steps_removed;
250   guint8 time_source;
251
252   guint16 sequence_id;
253 } PtpAnnounceMessage;
254
255 typedef struct
256 {
257   PtpClockIdentity master_clock_identity;
258
259   GstClockTime announce_interval;       /* last interval we received */
260   GQueue announce_messages;
261 } PtpAnnounceSender;
262
263 typedef struct
264 {
265   guint domain;
266   PtpClockIdentity master_clock_identity;
267
268   guint16 sync_seqnum;
269   GstClockTime sync_recv_time_local;    /* t2 */
270   GstClockTime sync_send_time_remote;   /* t1, might be -1 if FOLLOW_UP pending */
271   GstClockTime follow_up_recv_time_local;
272
273   GSource *timeout_source;
274   guint16 delay_req_seqnum;
275   GstClockTime delay_req_send_time_local;       /* t3, -1 if we wait for FOLLOW_UP */
276   GstClockTime delay_req_recv_time_remote;      /* t4, -1 if we wait */
277   GstClockTime delay_resp_recv_time_local;
278
279   gint64 correction_field_sync; /* sum of the correction fields of SYNC/FOLLOW_UP */
280   gint64 correction_field_delay;        /* sum of the correction fields of DELAY_RESP */
281 } PtpPendingSync;
282
283 static void
284 ptp_pending_sync_free (PtpPendingSync * sync)
285 {
286   if (sync->timeout_source)
287     g_source_destroy (sync->timeout_source);
288   g_free (sync);
289 }
290
291 typedef struct
292 {
293   guint domain;
294
295   GstClockTime last_ptp_time;
296   GstClockTime last_local_time;
297   gint skipped_updates;
298
299   /* Used for selecting the master/grandmaster */
300   GList *announce_senders;
301
302   /* Last selected master clock */
303   gboolean have_master_clock;
304   PtpClockIdentity master_clock_identity;
305   guint64 grandmaster_identity;
306
307   /* Last SYNC or FOLLOW_UP timestamp we received */
308   GstClockTime last_ptp_sync_time;
309   GstClockTime sync_interval;
310
311   GstClockTime mean_path_delay;
312   GstClockTime last_delay_req, min_delay_req_interval;
313   guint16 last_delay_req_seqnum;
314
315   GstClockTime last_path_delays[MEDIAN_PRE_FILTERING_WINDOW];
316   gint last_path_delays_missing;
317
318   GQueue pending_syncs;
319
320   GstClock *domain_clock;
321 } PtpDomainData;
322
323 static GList *domain_data;
324 static GMutex domain_clocks_lock;
325 static GList *domain_clocks;
326
327 /* Protected by PTP lock */
328 static void emit_ptp_statistics (guint8 domain, const GstStructure * stats);
329 static GHookList domain_stats_hooks;
330 static gint domain_stats_n_hooks;
331 static gboolean domain_stats_hooks_initted = FALSE;
332
333 /* Converts log2 seconds to GstClockTime */
334 static GstClockTime
335 log2_to_clock_time (gint l)
336 {
337   if (l < 0)
338     return GST_SECOND >> (-l);
339   else
340     return GST_SECOND << l;
341 }
342
343 static void
344 dump_ptp_message (PtpMessage * msg)
345 {
346   GST_TRACE ("PTP message:");
347   GST_TRACE ("\ttransport_specific: %u", msg->transport_specific);
348   GST_TRACE ("\tmessage_type: 0x%01x", msg->message_type);
349   GST_TRACE ("\tversion_ptp: %u", msg->version_ptp);
350   GST_TRACE ("\tmessage_length: %u", msg->message_length);
351   GST_TRACE ("\tdomain_number: %u", msg->domain_number);
352   GST_TRACE ("\tflag_field: 0x%04x", msg->flag_field);
353   GST_TRACE ("\tcorrection_field: %" G_GINT64_FORMAT ".%03u",
354       (msg->correction_field / 65536),
355       (guint) ((msg->correction_field & 0xffff) * 1000) / 65536);
356   GST_TRACE ("\tsource_port_identity: 0x%016" G_GINT64_MODIFIER "x %u",
357       msg->source_port_identity.clock_identity,
358       msg->source_port_identity.port_number);
359   GST_TRACE ("\tsequence_id: %u", msg->sequence_id);
360   GST_TRACE ("\tcontrol_field: 0x%02x", msg->control_field);
361   GST_TRACE ("\tmessage_interval: %" GST_TIME_FORMAT,
362       GST_TIME_ARGS (log2_to_clock_time (msg->log_message_interval)));
363
364   switch (msg->message_type) {
365     case PTP_MESSAGE_TYPE_ANNOUNCE:
366       GST_TRACE ("\tANNOUNCE:");
367       GST_TRACE ("\t\torigin_timestamp: %" G_GUINT64_FORMAT ".%09u",
368           msg->message_specific.announce.origin_timestamp.seconds_field,
369           msg->message_specific.announce.origin_timestamp.nanoseconds_field);
370       GST_TRACE ("\t\tcurrent_utc_offset: %d",
371           msg->message_specific.announce.current_utc_offset);
372       GST_TRACE ("\t\tgrandmaster_priority_1: %u",
373           msg->message_specific.announce.grandmaster_priority_1);
374       GST_TRACE ("\t\tgrandmaster_clock_quality: 0x%02x 0x%02x %u",
375           msg->message_specific.announce.grandmaster_clock_quality.clock_class,
376           msg->message_specific.announce.
377           grandmaster_clock_quality.clock_accuracy,
378           msg->message_specific.announce.
379           grandmaster_clock_quality.offset_scaled_log_variance);
380       GST_TRACE ("\t\tgrandmaster_priority_2: %u",
381           msg->message_specific.announce.grandmaster_priority_2);
382       GST_TRACE ("\t\tgrandmaster_identity: 0x%016" G_GINT64_MODIFIER "x",
383           msg->message_specific.announce.grandmaster_identity);
384       GST_TRACE ("\t\tsteps_removed: %u",
385           msg->message_specific.announce.steps_removed);
386       GST_TRACE ("\t\ttime_source: 0x%02x",
387           msg->message_specific.announce.time_source);
388       break;
389     case PTP_MESSAGE_TYPE_SYNC:
390       GST_TRACE ("\tSYNC:");
391       GST_TRACE ("\t\torigin_timestamp: %" G_GUINT64_FORMAT ".%09u",
392           msg->message_specific.sync.origin_timestamp.seconds_field,
393           msg->message_specific.sync.origin_timestamp.nanoseconds_field);
394       break;
395     case PTP_MESSAGE_TYPE_FOLLOW_UP:
396       GST_TRACE ("\tFOLLOW_UP:");
397       GST_TRACE ("\t\tprecise_origin_timestamp: %" G_GUINT64_FORMAT ".%09u",
398           msg->message_specific.follow_up.
399           precise_origin_timestamp.seconds_field,
400           msg->message_specific.follow_up.
401           precise_origin_timestamp.nanoseconds_field);
402       break;
403     case PTP_MESSAGE_TYPE_DELAY_REQ:
404       GST_TRACE ("\tDELAY_REQ:");
405       GST_TRACE ("\t\torigin_timestamp: %" G_GUINT64_FORMAT ".%09u",
406           msg->message_specific.delay_req.origin_timestamp.seconds_field,
407           msg->message_specific.delay_req.origin_timestamp.nanoseconds_field);
408       break;
409     case PTP_MESSAGE_TYPE_DELAY_RESP:
410       GST_TRACE ("\tDELAY_RESP:");
411       GST_TRACE ("\t\treceive_timestamp: %" G_GUINT64_FORMAT ".%09u",
412           msg->message_specific.delay_resp.receive_timestamp.seconds_field,
413           msg->message_specific.delay_resp.receive_timestamp.nanoseconds_field);
414       GST_TRACE ("\t\trequesting_port_identity: 0x%016" G_GINT64_MODIFIER
415           "x %u",
416           msg->message_specific.delay_resp.
417           requesting_port_identity.clock_identity,
418           msg->message_specific.delay_resp.
419           requesting_port_identity.port_number);
420       break;
421     default:
422       break;
423   }
424   GST_TRACE (" ");
425 }
426
427 /* IEEE 1588-2008 5.3.3 */
428 static gboolean
429 parse_ptp_timestamp (PtpTimestamp * timestamp, GstByteReader * reader)
430 {
431   g_return_val_if_fail (gst_byte_reader_get_remaining (reader) >= 10, FALSE);
432
433   timestamp->seconds_field =
434       (((guint64) gst_byte_reader_get_uint32_be_unchecked (reader)) << 16) |
435       gst_byte_reader_get_uint16_be_unchecked (reader);
436   timestamp->nanoseconds_field =
437       gst_byte_reader_get_uint32_be_unchecked (reader);
438
439   if (timestamp->nanoseconds_field >= 1000000000)
440     return FALSE;
441
442   return TRUE;
443 }
444
445 /* IEEE 1588-2008 13.3 */
446 static gboolean
447 parse_ptp_message_header (PtpMessage * msg, GstByteReader * reader)
448 {
449   guint8 b;
450
451   g_return_val_if_fail (gst_byte_reader_get_remaining (reader) >= 34, FALSE);
452
453   b = gst_byte_reader_get_uint8_unchecked (reader);
454   msg->transport_specific = b >> 4;
455   msg->message_type = b & 0x0f;
456
457   b = gst_byte_reader_get_uint8_unchecked (reader);
458   msg->version_ptp = b & 0x0f;
459   if (msg->version_ptp != 2) {
460     GST_WARNING ("Unsupported PTP message version (%u != 2)", msg->version_ptp);
461     return FALSE;
462   }
463
464   msg->message_length = gst_byte_reader_get_uint16_be_unchecked (reader);
465   if (gst_byte_reader_get_remaining (reader) + 4 < msg->message_length) {
466     GST_WARNING ("Not enough data (%u < %u)",
467         gst_byte_reader_get_remaining (reader) + 4, msg->message_length);
468     return FALSE;
469   }
470
471   msg->domain_number = gst_byte_reader_get_uint8_unchecked (reader);
472   gst_byte_reader_skip_unchecked (reader, 1);
473
474   msg->flag_field = gst_byte_reader_get_uint16_be_unchecked (reader);
475   msg->correction_field = gst_byte_reader_get_uint64_be_unchecked (reader);
476   gst_byte_reader_skip_unchecked (reader, 4);
477
478   msg->source_port_identity.clock_identity =
479       gst_byte_reader_get_uint64_be_unchecked (reader);
480   msg->source_port_identity.port_number =
481       gst_byte_reader_get_uint16_be_unchecked (reader);
482
483   msg->sequence_id = gst_byte_reader_get_uint16_be_unchecked (reader);
484   msg->control_field = gst_byte_reader_get_uint8_unchecked (reader);
485   msg->log_message_interval = gst_byte_reader_get_uint8_unchecked (reader);
486
487   return TRUE;
488 }
489
490 /* IEEE 1588-2008 13.5 */
491 static gboolean
492 parse_ptp_message_announce (PtpMessage * msg, GstByteReader * reader)
493 {
494   g_return_val_if_fail (msg->message_type == PTP_MESSAGE_TYPE_ANNOUNCE, FALSE);
495
496   if (gst_byte_reader_get_remaining (reader) < 20)
497     return FALSE;
498
499   if (!parse_ptp_timestamp (&msg->message_specific.announce.origin_timestamp,
500           reader))
501     return FALSE;
502
503   msg->message_specific.announce.current_utc_offset =
504       gst_byte_reader_get_uint16_be_unchecked (reader);
505   gst_byte_reader_skip_unchecked (reader, 1);
506
507   msg->message_specific.announce.grandmaster_priority_1 =
508       gst_byte_reader_get_uint8_unchecked (reader);
509   msg->message_specific.announce.grandmaster_clock_quality.clock_class =
510       gst_byte_reader_get_uint8_unchecked (reader);
511   msg->message_specific.announce.grandmaster_clock_quality.clock_accuracy =
512       gst_byte_reader_get_uint8_unchecked (reader);
513   msg->message_specific.announce.
514       grandmaster_clock_quality.offset_scaled_log_variance =
515       gst_byte_reader_get_uint16_be_unchecked (reader);
516   msg->message_specific.announce.grandmaster_priority_2 =
517       gst_byte_reader_get_uint8_unchecked (reader);
518   msg->message_specific.announce.grandmaster_identity =
519       gst_byte_reader_get_uint64_be_unchecked (reader);
520   msg->message_specific.announce.steps_removed =
521       gst_byte_reader_get_uint16_be_unchecked (reader);
522   msg->message_specific.announce.time_source =
523       gst_byte_reader_get_uint8_unchecked (reader);
524
525   return TRUE;
526 }
527
528 /* IEEE 1588-2008 13.6 */
529 static gboolean
530 parse_ptp_message_sync (PtpMessage * msg, GstByteReader * reader)
531 {
532   g_return_val_if_fail (msg->message_type == PTP_MESSAGE_TYPE_SYNC, FALSE);
533
534   if (gst_byte_reader_get_remaining (reader) < 10)
535     return FALSE;
536
537   if (!parse_ptp_timestamp (&msg->message_specific.sync.origin_timestamp,
538           reader))
539     return FALSE;
540
541   return TRUE;
542 }
543
544 /* IEEE 1588-2008 13.6 */
545 static gboolean
546 parse_ptp_message_delay_req (PtpMessage * msg, GstByteReader * reader)
547 {
548   g_return_val_if_fail (msg->message_type == PTP_MESSAGE_TYPE_DELAY_REQ, FALSE);
549
550   if (gst_byte_reader_get_remaining (reader) < 10)
551     return FALSE;
552
553   if (!parse_ptp_timestamp (&msg->message_specific.delay_req.origin_timestamp,
554           reader))
555     return FALSE;
556
557   return TRUE;
558 }
559
560 /* IEEE 1588-2008 13.7 */
561 static gboolean
562 parse_ptp_message_follow_up (PtpMessage * msg, GstByteReader * reader)
563 {
564   g_return_val_if_fail (msg->message_type == PTP_MESSAGE_TYPE_FOLLOW_UP, FALSE);
565
566   if (gst_byte_reader_get_remaining (reader) < 10)
567     return FALSE;
568
569   if (!parse_ptp_timestamp (&msg->message_specific.
570           follow_up.precise_origin_timestamp, reader))
571     return FALSE;
572
573   return TRUE;
574 }
575
576 /* IEEE 1588-2008 13.8 */
577 static gboolean
578 parse_ptp_message_delay_resp (PtpMessage * msg, GstByteReader * reader)
579 {
580   g_return_val_if_fail (msg->message_type == PTP_MESSAGE_TYPE_DELAY_RESP,
581       FALSE);
582
583   if (gst_byte_reader_get_remaining (reader) < 20)
584     return FALSE;
585
586   if (!parse_ptp_timestamp (&msg->message_specific.delay_resp.receive_timestamp,
587           reader))
588     return FALSE;
589
590   msg->message_specific.delay_resp.requesting_port_identity.clock_identity =
591       gst_byte_reader_get_uint64_be_unchecked (reader);
592   msg->message_specific.delay_resp.requesting_port_identity.port_number =
593       gst_byte_reader_get_uint16_be_unchecked (reader);
594
595   return TRUE;
596 }
597
598 static gboolean
599 parse_ptp_message (PtpMessage * msg, const guint8 * data, gsize size)
600 {
601   GstByteReader reader;
602   gboolean ret = FALSE;
603
604   gst_byte_reader_init (&reader, data, size);
605
606   if (!parse_ptp_message_header (msg, &reader)) {
607     GST_WARNING ("Failed to parse PTP message header");
608     return FALSE;
609   }
610
611   switch (msg->message_type) {
612     case PTP_MESSAGE_TYPE_SYNC:
613       ret = parse_ptp_message_sync (msg, &reader);
614       break;
615     case PTP_MESSAGE_TYPE_FOLLOW_UP:
616       ret = parse_ptp_message_follow_up (msg, &reader);
617       break;
618     case PTP_MESSAGE_TYPE_DELAY_REQ:
619       ret = parse_ptp_message_delay_req (msg, &reader);
620       break;
621     case PTP_MESSAGE_TYPE_DELAY_RESP:
622       ret = parse_ptp_message_delay_resp (msg, &reader);
623       break;
624     case PTP_MESSAGE_TYPE_ANNOUNCE:
625       ret = parse_ptp_message_announce (msg, &reader);
626       break;
627     default:
628       /* ignore for now */
629       break;
630   }
631
632   return ret;
633 }
634
635 static gint
636 compare_announce_message (const PtpAnnounceMessage * a,
637     const PtpAnnounceMessage * b)
638 {
639   /* IEEE 1588 Figure 27 */
640   if (a->grandmaster_identity == b->grandmaster_identity) {
641     if (a->steps_removed + 1 < b->steps_removed)
642       return -1;
643     else if (a->steps_removed > b->steps_removed + 1)
644       return 1;
645
646     /* Error cases are filtered out earlier */
647     if (a->steps_removed < b->steps_removed)
648       return -1;
649     else if (a->steps_removed > b->steps_removed)
650       return 1;
651
652     /* Error cases are filtered out earlier */
653     if (a->master_clock_identity.clock_identity <
654         b->master_clock_identity.clock_identity)
655       return -1;
656     else if (a->master_clock_identity.clock_identity >
657         b->master_clock_identity.clock_identity)
658       return 1;
659
660     /* Error cases are filtered out earlier */
661     if (a->master_clock_identity.port_number <
662         b->master_clock_identity.port_number)
663       return -1;
664     else if (a->master_clock_identity.port_number >
665         b->master_clock_identity.port_number)
666       return 1;
667     else
668       g_assert_not_reached ();
669
670     return 0;
671   }
672
673   if (a->grandmaster_priority_1 < b->grandmaster_priority_1)
674     return -1;
675   else if (a->grandmaster_priority_1 > b->grandmaster_priority_1)
676     return 1;
677
678   if (a->grandmaster_clock_quality.clock_class <
679       b->grandmaster_clock_quality.clock_class)
680     return -1;
681   else if (a->grandmaster_clock_quality.clock_class >
682       b->grandmaster_clock_quality.clock_class)
683     return 1;
684
685   if (a->grandmaster_clock_quality.clock_accuracy <
686       b->grandmaster_clock_quality.clock_accuracy)
687     return -1;
688   else if (a->grandmaster_clock_quality.clock_accuracy >
689       b->grandmaster_clock_quality.clock_accuracy)
690     return 1;
691
692   if (a->grandmaster_clock_quality.offset_scaled_log_variance <
693       b->grandmaster_clock_quality.offset_scaled_log_variance)
694     return -1;
695   else if (a->grandmaster_clock_quality.offset_scaled_log_variance >
696       b->grandmaster_clock_quality.offset_scaled_log_variance)
697     return 1;
698
699   if (a->grandmaster_priority_2 < b->grandmaster_priority_2)
700     return -1;
701   else if (a->grandmaster_priority_2 > b->grandmaster_priority_2)
702     return 1;
703
704   if (a->grandmaster_identity < b->grandmaster_identity)
705     return -1;
706   else if (a->grandmaster_identity > b->grandmaster_identity)
707     return 1;
708   else
709     g_assert_not_reached ();
710
711   return 0;
712 }
713
714 static void
715 select_best_master_clock (PtpDomainData * domain, GstClockTime now)
716 {
717   GList *qualified_messages = NULL;
718   GList *l, *m;
719   PtpAnnounceMessage *best = NULL;
720
721   /* IEEE 1588 9.3.2.5 */
722   for (l = domain->announce_senders; l; l = l->next) {
723     PtpAnnounceSender *sender = l->data;
724     GstClockTime window = 4 * sender->announce_interval;
725     gint count = 0;
726
727     for (m = sender->announce_messages.head; m; m = m->next) {
728       PtpAnnounceMessage *msg = m->data;
729
730       if (now - msg->receive_time <= window)
731         count++;
732     }
733
734     /* Only include the newest message of announce senders that had at least 2
735      * announce messages in the last 4 announce intervals. Which also means
736      * that we wait at least 4 announce intervals before we select a master
737      * clock. Until then we just report based on the newest SYNC we received
738      */
739     if (count >= 2) {
740       qualified_messages =
741           g_list_prepend (qualified_messages,
742           g_queue_peek_tail (&sender->announce_messages));
743     }
744   }
745
746   if (!qualified_messages) {
747     GST_DEBUG
748         ("No qualified announce messages for domain %u, can't select a master clock",
749         domain->domain);
750     domain->have_master_clock = FALSE;
751     return;
752   }
753
754   for (l = qualified_messages; l; l = l->next) {
755     PtpAnnounceMessage *msg = l->data;
756
757     if (!best || compare_announce_message (msg, best) < 0)
758       best = msg;
759   }
760
761   if (domain->have_master_clock
762       && compare_clock_identity (&domain->master_clock_identity,
763           &best->master_clock_identity) == 0) {
764     GST_DEBUG ("Master clock in domain %u did not change", domain->domain);
765   } else {
766     GST_DEBUG ("Selected master clock for domain %u: 0x%016" G_GINT64_MODIFIER
767         "x %u with grandmaster clock 0x%016" G_GINT64_MODIFIER "x",
768         domain->domain, best->master_clock_identity.clock_identity,
769         best->master_clock_identity.port_number, best->grandmaster_identity);
770
771     domain->have_master_clock = TRUE;
772     domain->grandmaster_identity = best->grandmaster_identity;
773
774     /* Opportunistic master clock selection likely gave us the same master
775      * clock before, no need to reset all statistics */
776     if (compare_clock_identity (&domain->master_clock_identity,
777             &best->master_clock_identity) != 0) {
778       memcpy (&domain->master_clock_identity, &best->master_clock_identity,
779           sizeof (PtpClockIdentity));
780       domain->mean_path_delay = 0;
781       domain->last_delay_req = 0;
782       domain->last_path_delays_missing = 9;
783       domain->min_delay_req_interval = 0;
784       domain->sync_interval = 0;
785       domain->last_ptp_sync_time = 0;
786       domain->skipped_updates = 0;
787       g_queue_foreach (&domain->pending_syncs, (GFunc) ptp_pending_sync_free,
788           NULL);
789       g_queue_clear (&domain->pending_syncs);
790     }
791
792     if (g_atomic_int_get (&domain_stats_n_hooks)) {
793       GstStructure *stats =
794           gst_structure_new (GST_PTP_STATISTICS_BEST_MASTER_CLOCK_SELECTED,
795           "domain", G_TYPE_UINT, domain->domain,
796           "master-clock-id", G_TYPE_UINT64,
797           domain->master_clock_identity.clock_identity,
798           "master-clock-port", G_TYPE_UINT,
799           domain->master_clock_identity.port_number,
800           "grandmaster-clock-id", G_TYPE_UINT64, domain->grandmaster_identity,
801           NULL);
802       emit_ptp_statistics (domain->domain, stats);
803       gst_structure_free (stats);
804     }
805   }
806 }
807
808 static void
809 handle_announce_message (PtpMessage * msg, GstClockTime receive_time)
810 {
811   GList *l;
812   PtpDomainData *domain = NULL;
813   PtpAnnounceSender *sender = NULL;
814   PtpAnnounceMessage *announce;
815
816   /* IEEE1588 9.3.2.2 e)
817    * Don't consider messages with the alternate master flag set
818    */
819   if ((msg->flag_field & 0x0100))
820     return;
821
822   /* IEEE 1588 9.3.2.5 d)
823    * Don't consider announce messages with steps_removed>=255
824    */
825   if (msg->message_specific.announce.steps_removed >= 255)
826     return;
827
828   for (l = domain_data; l; l = l->next) {
829     PtpDomainData *tmp = l->data;
830
831     if (tmp->domain == msg->domain_number) {
832       domain = tmp;
833       break;
834     }
835   }
836
837   if (!domain) {
838     gchar *clock_name;
839
840     domain = g_new0 (PtpDomainData, 1);
841     domain->domain = msg->domain_number;
842     clock_name = g_strdup_printf ("ptp-clock-%u", domain->domain);
843     domain->domain_clock =
844         g_object_new (GST_TYPE_SYSTEM_CLOCK, "name", clock_name, NULL);
845     g_free (clock_name);
846     g_queue_init (&domain->pending_syncs);
847     domain->last_path_delays_missing = 9;
848     domain_data = g_list_prepend (domain_data, domain);
849
850     g_mutex_lock (&domain_clocks_lock);
851     domain_clocks = g_list_prepend (domain_clocks, domain);
852     g_mutex_unlock (&domain_clocks_lock);
853
854     if (g_atomic_int_get (&domain_stats_n_hooks)) {
855       GstStructure *stats =
856           gst_structure_new (GST_PTP_STATISTICS_NEW_DOMAIN_FOUND, "domain",
857           G_TYPE_UINT, domain->domain, "clock", GST_TYPE_CLOCK,
858           domain->domain_clock, NULL);
859       emit_ptp_statistics (domain->domain, stats);
860       gst_structure_free (stats);
861     }
862   }
863
864   for (l = domain->announce_senders; l; l = l->next) {
865     PtpAnnounceSender *tmp = l->data;
866
867     if (compare_clock_identity (&tmp->master_clock_identity,
868             &msg->source_port_identity) == 0) {
869       sender = tmp;
870       break;
871     }
872   }
873
874   if (!sender) {
875     sender = g_new0 (PtpAnnounceSender, 1);
876
877     memcpy (&sender->master_clock_identity, &msg->source_port_identity,
878         sizeof (PtpClockIdentity));
879     g_queue_init (&sender->announce_messages);
880     domain->announce_senders =
881         g_list_prepend (domain->announce_senders, sender);
882   }
883
884   for (l = sender->announce_messages.head; l; l = l->next) {
885     PtpAnnounceMessage *tmp = l->data;
886
887     /* IEEE 1588 9.3.2.5 c)
888      * Don't consider identical messages, i.e. duplicates
889      */
890     if (tmp->sequence_id == msg->sequence_id)
891       return;
892   }
893
894   sender->announce_interval = log2_to_clock_time (msg->log_message_interval);
895
896   announce = g_new0 (PtpAnnounceMessage, 1);
897   announce->receive_time = receive_time;
898   announce->sequence_id = msg->sequence_id;
899   memcpy (&announce->master_clock_identity, &msg->source_port_identity,
900       sizeof (PtpClockIdentity));
901   announce->grandmaster_identity =
902       msg->message_specific.announce.grandmaster_identity;
903   announce->grandmaster_priority_1 =
904       msg->message_specific.announce.grandmaster_priority_1;
905   announce->grandmaster_clock_quality.clock_class =
906       msg->message_specific.announce.grandmaster_clock_quality.clock_class;
907   announce->grandmaster_clock_quality.clock_accuracy =
908       msg->message_specific.announce.grandmaster_clock_quality.clock_accuracy;
909   announce->grandmaster_clock_quality.offset_scaled_log_variance =
910       msg->message_specific.announce.
911       grandmaster_clock_quality.offset_scaled_log_variance;
912   announce->grandmaster_priority_2 =
913       msg->message_specific.announce.grandmaster_priority_2;
914   announce->steps_removed = msg->message_specific.announce.steps_removed;
915   announce->time_source = msg->message_specific.announce.time_source;
916   g_queue_push_tail (&sender->announce_messages, announce);
917
918   select_best_master_clock (domain, receive_time);
919 }
920
921 static gboolean
922 send_delay_req_timeout (PtpPendingSync * sync)
923 {
924   StdIOHeader header = { 0, };
925   guint8 delay_req[44];
926   GstByteWriter writer;
927   GIOStatus status;
928   gsize written;
929   GError *err = NULL;
930
931   header.type = TYPE_EVENT;
932   header.size = 44;
933
934   gst_byte_writer_init_with_data (&writer, delay_req, 44, FALSE);
935   gst_byte_writer_put_uint8_unchecked (&writer, PTP_MESSAGE_TYPE_DELAY_REQ);
936   gst_byte_writer_put_uint8_unchecked (&writer, 2);
937   gst_byte_writer_put_uint16_be_unchecked (&writer, 44);
938   gst_byte_writer_put_uint8_unchecked (&writer, sync->domain);
939   gst_byte_writer_put_uint8_unchecked (&writer, 0);
940   gst_byte_writer_put_uint16_be_unchecked (&writer, 0);
941   gst_byte_writer_put_uint64_be_unchecked (&writer, 0);
942   gst_byte_writer_put_uint32_be_unchecked (&writer, 0);
943   gst_byte_writer_put_uint64_be_unchecked (&writer,
944       ptp_clock_id.clock_identity);
945   gst_byte_writer_put_uint16_be_unchecked (&writer, ptp_clock_id.port_number);
946   gst_byte_writer_put_uint16_be_unchecked (&writer, sync->delay_req_seqnum);
947   gst_byte_writer_put_uint8_unchecked (&writer, 0x01);
948   gst_byte_writer_put_uint8_unchecked (&writer, 0x7f);
949   gst_byte_writer_put_uint64_be_unchecked (&writer, 0);
950   gst_byte_writer_put_uint16_be_unchecked (&writer, 0);
951
952   status =
953       g_io_channel_write_chars (stdout_channel, (gchar *) & header,
954       sizeof (header), &written, &err);
955   if (status == G_IO_STATUS_ERROR) {
956     g_warning ("Failed to write to stdout: %s", err->message);
957     return G_SOURCE_REMOVE;
958   } else if (status == G_IO_STATUS_EOF) {
959     g_message ("EOF on stdout");
960     g_main_loop_quit (main_loop);
961     return G_SOURCE_REMOVE;
962   } else if (status != G_IO_STATUS_NORMAL) {
963     g_warning ("Unexpected stdout write status: %d", status);
964     g_main_loop_quit (main_loop);
965     return G_SOURCE_REMOVE;
966   } else if (written != sizeof (header)) {
967     g_warning ("Unexpected write size: %" G_GSIZE_FORMAT, written);
968     g_main_loop_quit (main_loop);
969     return G_SOURCE_REMOVE;
970   }
971
972   sync->delay_req_send_time_local =
973       gst_clock_get_time (observation_system_clock);
974
975   status =
976       g_io_channel_write_chars (stdout_channel,
977       (const gchar *) delay_req, 44, &written, &err);
978   if (status == G_IO_STATUS_ERROR) {
979     g_warning ("Failed to write to stdout: %s", err->message);
980     g_main_loop_quit (main_loop);
981     return G_SOURCE_REMOVE;
982   } else if (status == G_IO_STATUS_EOF) {
983     g_message ("EOF on stdout");
984     g_main_loop_quit (main_loop);
985     return G_SOURCE_REMOVE;
986   } else if (status != G_IO_STATUS_NORMAL) {
987     g_warning ("Unexpected stdout write status: %d", status);
988     g_main_loop_quit (main_loop);
989     return G_SOURCE_REMOVE;
990   } else if (written != 44) {
991     g_warning ("Unexpected write size: %" G_GSIZE_FORMAT, written);
992     g_main_loop_quit (main_loop);
993     return G_SOURCE_REMOVE;
994   }
995
996   return G_SOURCE_REMOVE;
997 }
998
999 static gboolean
1000 send_delay_req (PtpDomainData * domain, PtpPendingSync * sync)
1001 {
1002   GstClockTime now = gst_clock_get_time (observation_system_clock);
1003   guint timeout;
1004   GSource *timeout_source;
1005
1006   if (domain->last_delay_req != 0
1007       && domain->last_delay_req + domain->min_delay_req_interval > now)
1008     return FALSE;
1009
1010   domain->last_delay_req = now;
1011   sync->delay_req_seqnum = domain->last_delay_req_seqnum++;
1012
1013   /* IEEE 1588 9.5.11.2 */
1014   if (domain->last_delay_req == 0 || domain->min_delay_req_interval == 0)
1015     timeout = 0;
1016   else
1017     timeout =
1018         g_rand_int_range (delay_req_rand, 0,
1019         (domain->min_delay_req_interval * 2) / GST_MSECOND);
1020
1021   sync->timeout_source = timeout_source = g_timeout_source_new (timeout);
1022   g_source_set_priority (timeout_source, G_PRIORITY_DEFAULT);
1023   g_source_set_callback (timeout_source, (GSourceFunc) send_delay_req_timeout,
1024       sync, NULL);
1025   g_source_attach (timeout_source, main_context);
1026
1027   return TRUE;
1028 }
1029
1030 /* Filtering of outliers for RTT and time calculations inspired
1031  * by the code from gstnetclientclock.c
1032  */
1033 static void
1034 update_ptp_time (PtpDomainData * domain, PtpPendingSync * sync)
1035 {
1036   GstClockTime internal_time, external_time, rate_num, rate_den;
1037   GstClockTime corrected_ptp_time, corrected_local_time;
1038   gdouble r_squared = 0.0;
1039   gboolean synced;
1040   GstClockTimeDiff discont = 0;
1041   GstClockTime estimated_ptp_time = GST_CLOCK_TIME_NONE;
1042 #ifdef USE_MEASUREMENT_FILTERING
1043   GstClockTime orig_internal_time, orig_external_time, orig_rate_num,
1044       orig_rate_den;
1045   GstClockTime new_estimated_ptp_time;
1046   GstClockTime max_discont, estimated_ptp_time_min, estimated_ptp_time_max;
1047   gboolean now_synced;
1048 #endif
1049
1050 #ifdef USE_ONLY_SYNC_WITH_DELAY
1051   if (sync->delay_req_send_time_local == GST_CLOCK_TIME_NONE)
1052     return;
1053 #endif
1054
1055   /* IEEE 1588 11.2 */
1056   corrected_ptp_time =
1057       sync->sync_send_time_remote +
1058       (sync->correction_field_sync + 32768) / 65536;
1059   corrected_local_time = sync->sync_recv_time_local - domain->mean_path_delay;
1060
1061 #ifdef USE_MEASUREMENT_FILTERING
1062   /* We check this here and when updating the mean path delay, because
1063    * we can get here without a delay response too */
1064   if (sync->follow_up_recv_time_local != GST_CLOCK_TIME_NONE
1065       && sync->follow_up_recv_time_local >
1066       sync->sync_recv_time_local + 2 * domain->mean_path_delay) {
1067     GST_WARNING ("Sync-follow-up delay for domain %u too big: %" GST_TIME_FORMAT
1068         " > 2 * %" GST_TIME_FORMAT, domain->domain,
1069         GST_TIME_ARGS (sync->follow_up_recv_time_local),
1070         GST_TIME_ARGS (domain->mean_path_delay));
1071     synced = FALSE;
1072     goto out;
1073   }
1074 #endif
1075
1076   /* Set an initial local-remote relation */
1077   if (domain->last_ptp_time == 0)
1078     gst_clock_set_calibration (domain->domain_clock, corrected_local_time,
1079         corrected_ptp_time, 1, 1);
1080
1081 #ifdef USE_MEASUREMENT_FILTERING
1082   /* Check if the corrected PTP time is +/- 3/4 RTT around what we would
1083    * estimate with our present knowledge about the clock
1084    */
1085   /* Store what the clock produced as 'now' before this update */
1086   gst_clock_get_calibration (GST_CLOCK_CAST (domain->domain_clock),
1087       &orig_internal_time, &orig_external_time, &orig_rate_num, &orig_rate_den);
1088   internal_time = orig_internal_time;
1089   external_time = orig_external_time;
1090   rate_num = orig_rate_num;
1091   rate_den = orig_rate_den;
1092
1093   /* 3/4 RTT window around the estimation */
1094   max_discont = domain->mean_path_delay * 3 / 2;
1095
1096   /* Check if the estimated sync time is inside our window */
1097   estimated_ptp_time_min = corrected_local_time - max_discont;
1098   estimated_ptp_time_min =
1099       gst_clock_adjust_with_calibration (GST_CLOCK_CAST (domain->domain_clock),
1100       estimated_ptp_time_min, internal_time, external_time, rate_num, rate_den);
1101   estimated_ptp_time_max = corrected_local_time + max_discont;
1102   estimated_ptp_time_max =
1103       gst_clock_adjust_with_calibration (GST_CLOCK_CAST (domain->domain_clock),
1104       estimated_ptp_time_max, internal_time, external_time, rate_num, rate_den);
1105
1106   synced = (estimated_ptp_time_min < corrected_ptp_time
1107       && corrected_ptp_time < estimated_ptp_time_max);
1108
1109   GST_DEBUG ("Adding observation for domain %u: %" GST_TIME_FORMAT " - %"
1110       GST_TIME_FORMAT, domain->domain,
1111       GST_TIME_ARGS (corrected_ptp_time), GST_TIME_ARGS (corrected_local_time));
1112
1113   GST_DEBUG ("Synced %d: %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT " < %"
1114       GST_TIME_FORMAT, synced, GST_TIME_ARGS (estimated_ptp_time_min),
1115       GST_TIME_ARGS (corrected_ptp_time),
1116       GST_TIME_ARGS (estimated_ptp_time_max));
1117
1118   if (gst_clock_add_observation_unapplied (domain->domain_clock,
1119           corrected_local_time, corrected_ptp_time, &r_squared,
1120           &internal_time, &external_time, &rate_num, &rate_den)) {
1121     GST_DEBUG ("Regression gave r_squared: %f", r_squared);
1122
1123     /* Old estimated PTP time based on receive time and path delay */
1124     estimated_ptp_time = corrected_local_time;
1125     estimated_ptp_time =
1126         gst_clock_adjust_with_calibration (GST_CLOCK_CAST
1127         (domain->domain_clock), estimated_ptp_time, orig_internal_time,
1128         orig_external_time, orig_rate_num, orig_rate_den);
1129
1130     /* New estimated PTP time based on receive time and path delay */
1131     new_estimated_ptp_time = corrected_local_time;
1132     new_estimated_ptp_time =
1133         gst_clock_adjust_with_calibration (GST_CLOCK_CAST
1134         (domain->domain_clock), new_estimated_ptp_time, internal_time,
1135         external_time, rate_num, rate_den);
1136
1137     discont = GST_CLOCK_DIFF (estimated_ptp_time, new_estimated_ptp_time);
1138     if (synced && ABS (discont) > max_discont) {
1139       GstClockTimeDiff offset;
1140       GST_DEBUG ("Too large a discont %s%" GST_TIME_FORMAT
1141           ", clamping to 1/4 average RTT = %" GST_TIME_FORMAT,
1142           (discont < 0 ? "-" : ""), GST_TIME_ARGS (ABS (discont)),
1143           GST_TIME_ARGS (max_discont));
1144       if (discont > 0) {        /* Too large a forward step - add a -ve offset */
1145         offset = max_discont - discont;
1146         if (-offset > external_time)
1147           external_time = 0;
1148         else
1149           external_time += offset;
1150       } else {                  /* Too large a backward step - add a +ve offset */
1151         offset = -(max_discont + discont);
1152         external_time += offset;
1153       }
1154
1155       discont += offset;
1156     } else {
1157       GST_DEBUG ("Discont %s%" GST_TIME_FORMAT " (max: %" GST_TIME_FORMAT ")",
1158           (discont < 0 ? "-" : ""), GST_TIME_ARGS (ABS (discont)),
1159           GST_TIME_ARGS (max_discont));
1160     }
1161
1162     /* Check if the estimated sync time is now (still) inside our window */
1163     estimated_ptp_time_min = corrected_local_time - max_discont;
1164     estimated_ptp_time_min =
1165         gst_clock_adjust_with_calibration (GST_CLOCK_CAST
1166         (domain->domain_clock), estimated_ptp_time_min, internal_time,
1167         external_time, rate_num, rate_den);
1168     estimated_ptp_time_max = corrected_local_time + max_discont;
1169     estimated_ptp_time_max =
1170         gst_clock_adjust_with_calibration (GST_CLOCK_CAST
1171         (domain->domain_clock), estimated_ptp_time_max, internal_time,
1172         external_time, rate_num, rate_den);
1173
1174     now_synced = (estimated_ptp_time_min < corrected_ptp_time
1175         && corrected_ptp_time < estimated_ptp_time_max);
1176
1177     GST_DEBUG ("Now synced %d: %" GST_TIME_FORMAT " < %" GST_TIME_FORMAT " < %"
1178         GST_TIME_FORMAT, now_synced, GST_TIME_ARGS (estimated_ptp_time_min),
1179         GST_TIME_ARGS (corrected_ptp_time),
1180         GST_TIME_ARGS (estimated_ptp_time_max));
1181
1182     if (synced || now_synced || domain->skipped_updates > MAX_SKIPPED_UPDATES) {
1183       gst_clock_set_calibration (GST_CLOCK_CAST (domain->domain_clock),
1184           internal_time, external_time, rate_num, rate_den);
1185       domain->skipped_updates = 0;
1186
1187       domain->last_ptp_time = corrected_ptp_time;
1188       domain->last_local_time = corrected_local_time;
1189     } else {
1190       domain->skipped_updates++;
1191     }
1192   } else {
1193     domain->last_ptp_time = corrected_ptp_time;
1194     domain->last_local_time = corrected_local_time;
1195   }
1196
1197 #else
1198   GST_DEBUG ("Adding observation for domain %u: %" GST_TIME_FORMAT " - %"
1199       GST_TIME_FORMAT, domain->domain,
1200       GST_TIME_ARGS (corrected_ptp_time), GST_TIME_ARGS (corrected_local_time));
1201
1202   gst_clock_get_calibration (GST_CLOCK_CAST (domain->domain_clock),
1203       &internal_time, &external_time, &rate_num, &rate_den);
1204
1205   estimated_ptp_time = corrected_local_time;
1206   estimated_ptp_time =
1207       gst_clock_adjust_with_calibration (GST_CLOCK_CAST
1208       (domain->domain_clock), estimated_ptp_time, internal_time,
1209       external_time, rate_num, rate_den);
1210
1211   gst_clock_add_observation (domain->domain_clock,
1212       corrected_local_time, corrected_ptp_time, &r_squared);
1213
1214   gst_clock_get_calibration (GST_CLOCK_CAST (domain->domain_clock),
1215       &internal_time, &external_time, &rate_num, &rate_den);
1216
1217   synced = TRUE;
1218   domain->last_ptp_time = corrected_ptp_time;
1219   domain->last_local_time = corrected_local_time;
1220 #endif
1221
1222 #ifdef USE_MEASUREMENT_FILTERING
1223 out:
1224 #endif
1225   if (g_atomic_int_get (&domain_stats_n_hooks)) {
1226     GstStructure *stats = gst_structure_new (GST_PTP_STATISTICS_TIME_UPDATED,
1227         "domain", G_TYPE_UINT, domain->domain,
1228         "mean-path-delay-avg", GST_TYPE_CLOCK_TIME, domain->mean_path_delay,
1229         "local-time", GST_TYPE_CLOCK_TIME, corrected_local_time,
1230         "ptp-time", GST_TYPE_CLOCK_TIME, corrected_ptp_time,
1231         "estimated-ptp-time", GST_TYPE_CLOCK_TIME, estimated_ptp_time,
1232         "discontinuity", G_TYPE_INT64, discont,
1233         "synced", G_TYPE_BOOLEAN, synced,
1234         "r-squared", G_TYPE_DOUBLE, r_squared,
1235         "internal-time", GST_TYPE_CLOCK_TIME, internal_time,
1236         "external-time", GST_TYPE_CLOCK_TIME, external_time,
1237         "rate-num", G_TYPE_UINT64, rate_num,
1238         "rate-den", G_TYPE_UINT64, rate_den,
1239         "rate", G_TYPE_DOUBLE, (gdouble) (rate_num) / rate_den,
1240         NULL);
1241     emit_ptp_statistics (domain->domain, stats);
1242     gst_structure_free (stats);
1243   }
1244
1245 }
1246
1247 #ifdef USE_MEDIAN_PRE_FILTERING
1248 static gint
1249 compare_clock_time (const GstClockTime * a, const GstClockTime * b)
1250 {
1251   if (*a < *b)
1252     return -1;
1253   else if (*a > *b)
1254     return 1;
1255   return 0;
1256 }
1257 #endif
1258
1259 static gboolean
1260 update_mean_path_delay (PtpDomainData * domain, PtpPendingSync * sync)
1261 {
1262 #ifdef USE_MEDIAN_PRE_FILTERING
1263   GstClockTime last_path_delays[MEDIAN_PRE_FILTERING_WINDOW];
1264   GstClockTime median;
1265   gint i;
1266 #endif
1267
1268   GstClockTime mean_path_delay, delay_req_delay = 0;
1269   gboolean ret;
1270
1271   /* IEEE 1588 11.3 */
1272   mean_path_delay =
1273       (sync->delay_req_recv_time_remote - sync->sync_send_time_remote +
1274       sync->sync_recv_time_local - sync->delay_req_send_time_local -
1275       (sync->correction_field_sync + sync->correction_field_delay +
1276           32768) / 65536) / 2;
1277
1278 #ifdef USE_MEDIAN_PRE_FILTERING
1279   for (i = 1; i < MEDIAN_PRE_FILTERING_WINDOW; i++)
1280     domain->last_path_delays[i - 1] = domain->last_path_delays[i];
1281   domain->last_path_delays[i - 1] = mean_path_delay;
1282
1283   if (domain->last_path_delays_missing) {
1284     domain->last_path_delays_missing--;
1285   } else {
1286     memcpy (&last_path_delays, &domain->last_path_delays,
1287         sizeof (last_path_delays));
1288     g_qsort_with_data (&last_path_delays,
1289         MEDIAN_PRE_FILTERING_WINDOW, sizeof (GstClockTime),
1290         (GCompareDataFunc) compare_clock_time, NULL);
1291
1292     median = last_path_delays[MEDIAN_PRE_FILTERING_WINDOW / 2];
1293
1294     /* FIXME: We might want to use something else here, like only allowing
1295      * things in the interquartile range, or also filtering away delays that
1296      * are too small compared to the median. This here worked well enough
1297      * in tests so far.
1298      */
1299     if (mean_path_delay > 2 * median) {
1300       GST_WARNING ("Path delay for domain %u too big compared to median: %"
1301           GST_TIME_FORMAT " > 2 * %" GST_TIME_FORMAT, domain->domain,
1302           GST_TIME_ARGS (mean_path_delay), GST_TIME_ARGS (median));
1303       ret = FALSE;
1304       goto out;
1305     }
1306   }
1307 #endif
1308
1309 #ifdef USE_RUNNING_AVERAGE_DELAY
1310   /* Track an average round trip time, for a bit of smoothing */
1311   /* Always update before discarding a sample, so genuine changes in
1312    * the network get picked up, eventually */
1313   if (domain->mean_path_delay == 0)
1314     domain->mean_path_delay = mean_path_delay;
1315   else if (mean_path_delay < domain->mean_path_delay)   /* Shorter RTTs carry more weight than longer */
1316     domain->mean_path_delay =
1317         (3 * domain->mean_path_delay + mean_path_delay) / 4;
1318   else
1319     domain->mean_path_delay =
1320         (15 * domain->mean_path_delay + mean_path_delay) / 16;
1321 #else
1322   domain->mean_path_delay = mean_path_delay;
1323 #endif
1324
1325 #ifdef USE_MEASUREMENT_FILTERING
1326   if (sync->follow_up_recv_time_local != GST_CLOCK_TIME_NONE &&
1327       domain->mean_path_delay != 0
1328       && sync->follow_up_recv_time_local >
1329       sync->sync_recv_time_local + 2 * domain->mean_path_delay) {
1330     GST_WARNING ("Sync-follow-up delay for domain %u too big: %" GST_TIME_FORMAT
1331         " > 2 * %" GST_TIME_FORMAT, domain->domain,
1332         GST_TIME_ARGS (sync->follow_up_recv_time_local -
1333             sync->sync_recv_time_local),
1334         GST_TIME_ARGS (domain->mean_path_delay));
1335     ret = FALSE;
1336     goto out;
1337   }
1338
1339   if (mean_path_delay > 2 * domain->mean_path_delay) {
1340     GST_WARNING ("Mean path delay for domain %u too big: %" GST_TIME_FORMAT
1341         " > 2 * %" GST_TIME_FORMAT, domain->domain,
1342         GST_TIME_ARGS (mean_path_delay),
1343         GST_TIME_ARGS (domain->mean_path_delay));
1344     ret = FALSE;
1345     goto out;
1346   }
1347 #endif
1348
1349   delay_req_delay =
1350       sync->delay_resp_recv_time_local - sync->delay_req_send_time_local;
1351
1352 #ifdef USE_MEASUREMENT_FILTERING
1353   /* delay_req_delay is a RTT, so 2 times the path delay */
1354   if (delay_req_delay > 4 * domain->mean_path_delay) {
1355     GST_WARNING ("Delay-request-response delay for domain %u too big: %"
1356         GST_TIME_FORMAT " > 4 * %" GST_TIME_FORMAT, domain->domain,
1357         GST_TIME_ARGS (delay_req_delay),
1358         GST_TIME_ARGS (domain->mean_path_delay));
1359     ret = FALSE;
1360     goto out;
1361   }
1362 #endif
1363
1364   ret = TRUE;
1365
1366   GST_DEBUG ("Got mean path delay for domain %u: %" GST_TIME_FORMAT " (new: %"
1367       GST_TIME_FORMAT ")", domain->domain,
1368       GST_TIME_ARGS (domain->mean_path_delay), GST_TIME_ARGS (mean_path_delay));
1369   GST_DEBUG ("Delay request delay for domain %u: %" GST_TIME_FORMAT,
1370       domain->domain, GST_TIME_ARGS (delay_req_delay));
1371
1372 #ifdef USE_MEASUREMENT_FILTERING
1373 out:
1374 #endif
1375   if (g_atomic_int_get (&domain_stats_n_hooks)) {
1376     GstStructure *stats =
1377         gst_structure_new (GST_PTP_STATISTICS_PATH_DELAY_MEASURED,
1378         "domain", G_TYPE_UINT, domain->domain,
1379         "mean-path-delay-avg", GST_TYPE_CLOCK_TIME, domain->mean_path_delay,
1380         "mean-path-delay", GST_TYPE_CLOCK_TIME, mean_path_delay,
1381         "delay-request-delay", GST_TYPE_CLOCK_TIME, delay_req_delay, NULL);
1382     emit_ptp_statistics (domain->domain, stats);
1383     gst_structure_free (stats);
1384   }
1385
1386   return ret;
1387 }
1388
1389 static void
1390 handle_sync_message (PtpMessage * msg, GstClockTime receive_time)
1391 {
1392   GList *l;
1393   PtpDomainData *domain = NULL;
1394   PtpPendingSync *sync = NULL;
1395
1396   /* Don't consider messages with the alternate master flag set */
1397   if ((msg->flag_field & 0x0100))
1398     return;
1399
1400   for (l = domain_data; l; l = l->next) {
1401     PtpDomainData *tmp = l->data;
1402
1403     if (msg->domain_number == tmp->domain) {
1404       domain = tmp;
1405       break;
1406     }
1407   }
1408
1409   if (!domain) {
1410     gchar *clock_name;
1411
1412     domain = g_new0 (PtpDomainData, 1);
1413     domain->domain = msg->domain_number;
1414     clock_name = g_strdup_printf ("ptp-clock-%u", domain->domain);
1415     domain->domain_clock =
1416         g_object_new (GST_TYPE_SYSTEM_CLOCK, "name", clock_name, NULL);
1417     g_free (clock_name);
1418     g_queue_init (&domain->pending_syncs);
1419     domain->last_path_delays_missing = 9;
1420     domain_data = g_list_prepend (domain_data, domain);
1421
1422     g_mutex_lock (&domain_clocks_lock);
1423     domain_clocks = g_list_prepend (domain_clocks, domain);
1424     g_mutex_unlock (&domain_clocks_lock);
1425   }
1426
1427   /* If we have a master clock, ignore this message if it's not coming from there */
1428   if (domain->have_master_clock
1429       && compare_clock_identity (&domain->master_clock_identity,
1430           &msg->source_port_identity) != 0)
1431     return;
1432
1433 #ifdef USE_OPPORTUNISTIC_CLOCK_SELECTION
1434   /* Opportunistic selection of master clock */
1435   if (!domain->have_master_clock)
1436     memcpy (&domain->master_clock_identity, &msg->source_port_identity,
1437         sizeof (PtpClockIdentity));
1438 #else
1439   if (!domain->have_master_clock)
1440     return;
1441 #endif
1442
1443   domain->sync_interval = log2_to_clock_time (msg->log_message_interval);
1444
1445   /* Check if duplicated */
1446   for (l = domain->pending_syncs.head; l; l = l->next) {
1447     PtpPendingSync *tmp = l->data;
1448
1449     if (tmp->sync_seqnum == msg->sequence_id)
1450       return;
1451   }
1452
1453   if (msg->message_specific.sync.origin_timestamp.seconds_field >
1454       GST_CLOCK_TIME_NONE / GST_SECOND) {
1455     GST_FIXME ("Unsupported sync message seconds field value: %"
1456         G_GUINT64_FORMAT " > %" G_GUINT64_FORMAT,
1457         msg->message_specific.sync.origin_timestamp.seconds_field,
1458         GST_CLOCK_TIME_NONE / GST_SECOND);
1459     return;
1460   }
1461
1462   sync = g_new0 (PtpPendingSync, 1);
1463   sync->domain = domain->domain;
1464   sync->sync_seqnum = msg->sequence_id;
1465   sync->sync_recv_time_local = receive_time;
1466   sync->sync_send_time_remote = GST_CLOCK_TIME_NONE;
1467   sync->follow_up_recv_time_local = GST_CLOCK_TIME_NONE;
1468   sync->delay_req_send_time_local = GST_CLOCK_TIME_NONE;
1469   sync->delay_req_recv_time_remote = GST_CLOCK_TIME_NONE;
1470   sync->delay_resp_recv_time_local = GST_CLOCK_TIME_NONE;
1471
1472   /* 0.5 correction factor for division later */
1473   sync->correction_field_sync = msg->correction_field;
1474
1475   if ((msg->flag_field & 0x0200)) {
1476     /* Wait for FOLLOW_UP */
1477   } else {
1478     sync->sync_send_time_remote =
1479         PTP_TIMESTAMP_TO_GST_CLOCK_TIME (msg->message_specific.
1480         sync.origin_timestamp);
1481
1482     if (domain->last_ptp_sync_time != 0
1483         && domain->last_ptp_sync_time >= sync->sync_send_time_remote) {
1484       GST_WARNING ("Backwards PTP times in domain %u: %" GST_TIME_FORMAT " >= %"
1485           GST_TIME_FORMAT, domain->domain,
1486           GST_TIME_ARGS (domain->last_ptp_sync_time),
1487           GST_TIME_ARGS (sync->sync_send_time_remote));
1488       ptp_pending_sync_free (sync);
1489       sync = NULL;
1490       return;
1491     }
1492     domain->last_ptp_sync_time = sync->sync_send_time_remote;
1493
1494     if (send_delay_req (domain, sync)) {
1495       /* Sent delay request */
1496     } else {
1497       update_ptp_time (domain, sync);
1498       ptp_pending_sync_free (sync);
1499       sync = NULL;
1500     }
1501   }
1502
1503   if (sync)
1504     g_queue_push_tail (&domain->pending_syncs, sync);
1505 }
1506
1507 static void
1508 handle_follow_up_message (PtpMessage * msg, GstClockTime receive_time)
1509 {
1510   GList *l;
1511   PtpDomainData *domain = NULL;
1512   PtpPendingSync *sync = NULL;
1513
1514   /* Don't consider messages with the alternate master flag set */
1515   if ((msg->flag_field & 0x0100))
1516     return;
1517
1518   for (l = domain_data; l; l = l->next) {
1519     PtpDomainData *tmp = l->data;
1520
1521     if (msg->domain_number == tmp->domain) {
1522       domain = tmp;
1523       break;
1524     }
1525   }
1526
1527   if (!domain)
1528     return;
1529
1530   /* If we have a master clock, ignore this message if it's not coming from there */
1531   if (domain->have_master_clock
1532       && compare_clock_identity (&domain->master_clock_identity,
1533           &msg->source_port_identity) != 0)
1534     return;
1535
1536   /* Check if we know about this one */
1537   for (l = domain->pending_syncs.head; l; l = l->next) {
1538     PtpPendingSync *tmp = l->data;
1539
1540     if (tmp->sync_seqnum == msg->sequence_id) {
1541       sync = tmp;
1542       break;
1543     }
1544   }
1545
1546   if (!sync)
1547     return;
1548
1549   /* Got a FOLLOW_UP for this already */
1550   if (sync->sync_send_time_remote != GST_CLOCK_TIME_NONE)
1551     return;
1552
1553   if (sync->sync_recv_time_local >= receive_time) {
1554     GST_ERROR ("Got bogus follow up in domain %u: %" GST_TIME_FORMAT " > %"
1555         GST_TIME_FORMAT, domain->domain,
1556         GST_TIME_ARGS (sync->sync_recv_time_local),
1557         GST_TIME_ARGS (receive_time));
1558     g_queue_remove (&domain->pending_syncs, sync);
1559     ptp_pending_sync_free (sync);
1560     return;
1561   }
1562
1563   sync->correction_field_sync += msg->correction_field;
1564   sync->sync_send_time_remote =
1565       PTP_TIMESTAMP_TO_GST_CLOCK_TIME (msg->message_specific.
1566       follow_up.precise_origin_timestamp);
1567   sync->follow_up_recv_time_local = receive_time;
1568
1569   if (domain->last_ptp_sync_time >= sync->sync_send_time_remote) {
1570     GST_WARNING ("Backwards PTP times in domain %u: %" GST_TIME_FORMAT " >= %"
1571         GST_TIME_FORMAT, domain->domain,
1572         GST_TIME_ARGS (domain->last_ptp_sync_time),
1573         GST_TIME_ARGS (sync->sync_send_time_remote));
1574     g_queue_remove (&domain->pending_syncs, sync);
1575     ptp_pending_sync_free (sync);
1576     sync = NULL;
1577     return;
1578   }
1579   domain->last_ptp_sync_time = sync->sync_send_time_remote;
1580
1581   if (send_delay_req (domain, sync)) {
1582     /* Sent delay request */
1583   } else {
1584     update_ptp_time (domain, sync);
1585     g_queue_remove (&domain->pending_syncs, sync);
1586     ptp_pending_sync_free (sync);
1587     sync = NULL;
1588   }
1589 }
1590
1591 static void
1592 handle_delay_resp_message (PtpMessage * msg, GstClockTime receive_time)
1593 {
1594   GList *l;
1595   PtpDomainData *domain = NULL;
1596   PtpPendingSync *sync = NULL;
1597
1598   /* Don't consider messages with the alternate master flag set */
1599   if ((msg->flag_field & 0x0100))
1600     return;
1601
1602   for (l = domain_data; l; l = l->next) {
1603     PtpDomainData *tmp = l->data;
1604
1605     if (msg->domain_number == tmp->domain) {
1606       domain = tmp;
1607       break;
1608     }
1609   }
1610
1611   if (!domain)
1612     return;
1613
1614   /* If we have a master clock, ignore this message if it's not coming from there */
1615   if (domain->have_master_clock
1616       && compare_clock_identity (&domain->master_clock_identity,
1617           &msg->source_port_identity) != 0)
1618     return;
1619
1620   /* Not for us */
1621   if (msg->message_specific.delay_resp.
1622       requesting_port_identity.clock_identity != ptp_clock_id.clock_identity
1623       || msg->message_specific.delay_resp.
1624       requesting_port_identity.port_number != ptp_clock_id.port_number)
1625     return;
1626
1627   domain->min_delay_req_interval =
1628       log2_to_clock_time (msg->log_message_interval);
1629
1630   /* Check if we know about this one */
1631   for (l = domain->pending_syncs.head; l; l = l->next) {
1632     PtpPendingSync *tmp = l->data;
1633
1634     if (tmp->delay_req_seqnum == msg->sequence_id) {
1635       sync = tmp;
1636       break;
1637     }
1638   }
1639
1640   if (!sync)
1641     return;
1642
1643   /* Got a DELAY_RESP for this already */
1644   if (sync->delay_req_recv_time_remote != GST_CLOCK_TIME_NONE)
1645     return;
1646
1647   if (sync->delay_req_send_time_local > receive_time) {
1648     GST_ERROR ("Got bogus delay response in domain %u: %" GST_TIME_FORMAT " > %"
1649         GST_TIME_FORMAT, domain->domain,
1650         GST_TIME_ARGS (sync->delay_req_send_time_local),
1651         GST_TIME_ARGS (receive_time));
1652     g_queue_remove (&domain->pending_syncs, sync);
1653     ptp_pending_sync_free (sync);
1654     return;
1655   }
1656
1657   sync->correction_field_delay = msg->correction_field;
1658
1659   sync->delay_req_recv_time_remote =
1660       PTP_TIMESTAMP_TO_GST_CLOCK_TIME (msg->message_specific.
1661       delay_resp.receive_timestamp);
1662   sync->delay_resp_recv_time_local = receive_time;
1663
1664   if (domain->mean_path_delay != 0
1665       && sync->sync_send_time_remote > sync->delay_req_recv_time_remote) {
1666     GST_WARNING ("Sync send time after delay req receive time for domain %u: %"
1667         GST_TIME_FORMAT " > %" GST_TIME_FORMAT, domain->domain,
1668         GST_TIME_ARGS (sync->sync_send_time_remote),
1669         GST_TIME_ARGS (sync->delay_req_recv_time_remote));
1670     g_queue_remove (&domain->pending_syncs, sync);
1671     ptp_pending_sync_free (sync);
1672     return;
1673   }
1674
1675   if (update_mean_path_delay (domain, sync))
1676     update_ptp_time (domain, sync);
1677   g_queue_remove (&domain->pending_syncs, sync);
1678   ptp_pending_sync_free (sync);
1679 }
1680
1681 static void
1682 handle_ptp_message (PtpMessage * msg, GstClockTime receive_time)
1683 {
1684   /* Ignore our own messages */
1685   if (msg->source_port_identity.clock_identity == ptp_clock_id.clock_identity &&
1686       msg->source_port_identity.port_number == ptp_clock_id.port_number)
1687     return;
1688
1689   switch (msg->message_type) {
1690     case PTP_MESSAGE_TYPE_ANNOUNCE:
1691       handle_announce_message (msg, receive_time);
1692       break;
1693     case PTP_MESSAGE_TYPE_SYNC:
1694       handle_sync_message (msg, receive_time);
1695       break;
1696     case PTP_MESSAGE_TYPE_FOLLOW_UP:
1697       handle_follow_up_message (msg, receive_time);
1698       break;
1699     case PTP_MESSAGE_TYPE_DELAY_RESP:
1700       handle_delay_resp_message (msg, receive_time);
1701       break;
1702     default:
1703       break;
1704   }
1705 }
1706
1707 static gboolean
1708 have_stdin_data_cb (GIOChannel * channel, GIOCondition condition,
1709     gpointer user_data)
1710 {
1711   GIOStatus status;
1712   StdIOHeader header;
1713   gchar buffer[8192];
1714   GError *err = NULL;
1715   gsize read;
1716
1717   if ((condition & G_IO_STATUS_EOF)) {
1718     GST_ERROR ("Got EOF on stdin");
1719     g_main_loop_quit (main_loop);
1720     return G_SOURCE_REMOVE;
1721   }
1722
1723   status =
1724       g_io_channel_read_chars (channel, (gchar *) & header, sizeof (header),
1725       &read, &err);
1726   if (status == G_IO_STATUS_ERROR) {
1727     GST_ERROR ("Failed to read from stdin: %s", err->message);
1728     g_main_loop_quit (main_loop);
1729     return G_SOURCE_REMOVE;
1730   } else if (status == G_IO_STATUS_EOF) {
1731     GST_ERROR ("Got EOF on stdin");
1732     g_main_loop_quit (main_loop);
1733     return G_SOURCE_REMOVE;
1734   } else if (status != G_IO_STATUS_NORMAL) {
1735     GST_ERROR ("Unexpected stdin read status: %d", status);
1736     g_main_loop_quit (main_loop);
1737     return G_SOURCE_REMOVE;
1738   } else if (read != sizeof (header)) {
1739     GST_ERROR ("Unexpected read size: %" G_GSIZE_FORMAT, read);
1740     g_main_loop_quit (main_loop);
1741     return G_SOURCE_REMOVE;
1742   } else if (header.size > 8192) {
1743     GST_ERROR ("Unexpected size: %u", header.size);
1744     g_main_loop_quit (main_loop);
1745     return G_SOURCE_REMOVE;
1746   }
1747
1748   status = g_io_channel_read_chars (channel, buffer, header.size, &read, &err);
1749   if (status == G_IO_STATUS_ERROR) {
1750     GST_ERROR ("Failed to read from stdin: %s", err->message);
1751     g_main_loop_quit (main_loop);
1752     return G_SOURCE_REMOVE;
1753   } else if (status == G_IO_STATUS_EOF) {
1754     GST_ERROR ("EOF on stdin");
1755     g_main_loop_quit (main_loop);
1756     return G_SOURCE_REMOVE;
1757   } else if (status != G_IO_STATUS_NORMAL) {
1758     GST_ERROR ("Unexpected stdin read status: %d", status);
1759     g_main_loop_quit (main_loop);
1760     return G_SOURCE_REMOVE;
1761   } else if (read != header.size) {
1762     GST_ERROR ("Unexpected read size: %" G_GSIZE_FORMAT, read);
1763     g_main_loop_quit (main_loop);
1764     return G_SOURCE_REMOVE;
1765   }
1766
1767   switch (header.type) {
1768     case TYPE_EVENT:
1769     case TYPE_GENERAL:{
1770       GstClockTime receive_time = gst_clock_get_time (observation_system_clock);
1771       PtpMessage msg;
1772
1773       if (parse_ptp_message (&msg, (const guint8 *) buffer, header.size)) {
1774         dump_ptp_message (&msg);
1775         handle_ptp_message (&msg, receive_time);
1776       }
1777       break;
1778     }
1779     default:
1780     case TYPE_CLOCK_ID:{
1781       if (header.size != 8) {
1782         GST_ERROR ("Unexpected clock id size (%u != 8)", header.size);
1783         g_main_loop_quit (main_loop);
1784         return G_SOURCE_REMOVE;
1785       }
1786       g_mutex_lock (&ptp_lock);
1787       ptp_clock_id.clock_identity = GST_READ_UINT64_BE (buffer);
1788       ptp_clock_id.port_number = getpid ();
1789       GST_DEBUG ("Got clock id 0x%016" G_GINT64_MODIFIER "x %u",
1790           ptp_clock_id.clock_identity, ptp_clock_id.port_number);
1791       g_cond_signal (&ptp_cond);
1792       g_mutex_unlock (&ptp_lock);
1793       break;
1794     }
1795   }
1796
1797   return G_SOURCE_CONTINUE;
1798 }
1799
1800 /* Cleanup all announce messages and announce message senders
1801  * that are timed out by now, and clean up all pending syncs
1802  * that are missing their FOLLOW_UP or DELAY_RESP */
1803 static gboolean
1804 cleanup_cb (gpointer data)
1805 {
1806   GstClockTime now = gst_clock_get_time (observation_system_clock);
1807   GList *l, *m, *n;
1808
1809   for (l = domain_data; l; l = l->next) {
1810     PtpDomainData *domain = l->data;
1811
1812     for (n = domain->announce_senders; n;) {
1813       PtpAnnounceSender *sender = n->data;
1814       gboolean timed_out = TRUE;
1815
1816       /* Keep only 5 messages per sender around */
1817       while (g_queue_get_length (&sender->announce_messages) > 5) {
1818         PtpAnnounceMessage *msg = g_queue_pop_head (&sender->announce_messages);
1819         g_free (msg);
1820       }
1821
1822       for (m = sender->announce_messages.head; m; m = m->next) {
1823         PtpAnnounceMessage *msg = m->data;
1824
1825         if (msg->receive_time +
1826             sender->announce_interval * PTP_ANNOUNCE_RECEIPT_TIMEOUT > now) {
1827           timed_out = FALSE;
1828           break;
1829         }
1830       }
1831
1832       if (timed_out) {
1833         GST_DEBUG ("Announce sender 0x%016" G_GINT64_MODIFIER "x %u timed out",
1834             sender->master_clock_identity.clock_identity,
1835             sender->master_clock_identity.port_number);
1836         g_queue_foreach (&sender->announce_messages, (GFunc) g_free, NULL);
1837         g_queue_clear (&sender->announce_messages);
1838       }
1839
1840       if (g_queue_get_length (&sender->announce_messages) == 0) {
1841         GList *tmp = n->next;
1842
1843         if (compare_clock_identity (&sender->master_clock_identity,
1844                 &domain->master_clock_identity) == 0)
1845           GST_WARNING ("currently selected master clock timed out");
1846         g_free (sender);
1847         domain->announce_senders =
1848             g_list_delete_link (domain->announce_senders, n);
1849         n = tmp;
1850       } else {
1851         n = n->next;
1852       }
1853     }
1854     select_best_master_clock (domain, now);
1855
1856     /* Clean up any pending syncs */
1857     for (n = domain->pending_syncs.head; n;) {
1858       PtpPendingSync *sync = n->data;
1859       gboolean timed_out = FALSE;
1860
1861       /* Time out pending syncs after 4 sync intervals or 10 seconds,
1862        * and pending delay reqs after 4 delay req intervals or 10 seconds
1863        */
1864       if (sync->delay_req_send_time_local != GST_CLOCK_TIME_NONE &&
1865           ((domain->min_delay_req_interval != 0
1866                   && sync->delay_req_send_time_local +
1867                   4 * domain->min_delay_req_interval < now)
1868               || (sync->delay_req_send_time_local + 10 * GST_SECOND < now))) {
1869         timed_out = TRUE;
1870       } else if ((domain->sync_interval != 0
1871               && sync->sync_recv_time_local + 4 * domain->sync_interval < now)
1872           || (sync->sync_recv_time_local + 10 * GST_SECOND < now)) {
1873         timed_out = TRUE;
1874       }
1875
1876       if (timed_out) {
1877         GList *tmp = n->next;
1878         ptp_pending_sync_free (sync);
1879         g_queue_delete_link (&domain->pending_syncs, n);
1880         n = tmp;
1881       } else {
1882         n = n->next;
1883       }
1884     }
1885   }
1886
1887   return G_SOURCE_CONTINUE;
1888 }
1889
1890 static gpointer
1891 ptp_helper_main (gpointer data)
1892 {
1893   GSource *cleanup_source;
1894
1895   GST_DEBUG ("Starting PTP helper loop");
1896
1897   /* Check all 5 seconds, if we have to cleanup ANNOUNCE or pending syncs message */
1898   cleanup_source = g_timeout_source_new_seconds (5);
1899   g_source_set_priority (cleanup_source, G_PRIORITY_DEFAULT);
1900   g_source_set_callback (cleanup_source, (GSourceFunc) cleanup_cb, NULL, NULL);
1901   g_source_attach (cleanup_source, main_context);
1902   g_source_unref (cleanup_source);
1903
1904   g_main_loop_run (main_loop);
1905   GST_DEBUG ("Stopped PTP helper loop");
1906
1907   g_mutex_lock (&ptp_lock);
1908   ptp_clock_id.clock_identity = GST_PTP_CLOCK_ID_NONE;
1909   ptp_clock_id.port_number = 0;
1910   initted = FALSE;
1911   g_cond_signal (&ptp_cond);
1912   g_mutex_unlock (&ptp_lock);
1913
1914   return NULL;
1915 }
1916
1917 /**
1918  * gst_ptp_is_supported:
1919  *
1920  * Check if PTP clocks are generally supported on this system, and if previous
1921  * initializations did not fail.
1922  *
1923  * Returns: %TRUE if PTP clocks are generally supported on this system, and
1924  * previous initializations did not fail.
1925  *
1926  * Since: 1.6
1927  */
1928 gboolean
1929 gst_ptp_is_supported (void)
1930 {
1931   return supported;
1932 }
1933
1934 /**
1935  * gst_ptp_is_initialized:
1936  *
1937  * Check if the GStreamer PTP clock subsystem is initialized.
1938  *
1939  * Returns: %TRUE if the GStreamer PTP clock subsystem is intialized.
1940  *
1941  * Since: 1.6
1942  */
1943 gboolean
1944 gst_ptp_is_initialized (void)
1945 {
1946   return initted;
1947 }
1948
1949 /**
1950  * gst_ptp_init:
1951  * @clock_id: PTP clock id of this process' clock or %GST_PTP_CLOCK_ID_NONE
1952  * @interfaces: (transfer none) (array zero-terminated=1): network interfaces to run the clock on
1953  *
1954  * Initialize the GStreamer PTP subsystem and create a PTP ordinary clock in
1955  * slave-only mode for all domains on the given @interfaces with the
1956  * given @clock_id.
1957  *
1958  * If @clock_id is %GST_PTP_CLOCK_ID_NONE, a clock id is automatically
1959  * generated from the MAC address of the first network interface.
1960  *
1961  *
1962  * This function is automatically called by gst_ptp_clock_new() with default
1963  * parameters if it wasn't called before.
1964  *
1965  * Returns: %TRUE if the GStreamer PTP clock subsystem could be initialized.
1966  *
1967  * Since: 1.6
1968  */
1969 gboolean
1970 gst_ptp_init (guint64 clock_id, gchar ** interfaces)
1971 {
1972   gboolean ret;
1973   const gchar *env;
1974   gchar **argv = NULL;
1975   gint argc, argc_c;
1976   gint fd_r, fd_w;
1977   GError *err = NULL;
1978   GSource *stdin_source;
1979
1980   GST_DEBUG_CATEGORY_INIT (ptp_debug, "ptp", 0, "PTP clock");
1981
1982   g_mutex_lock (&ptp_lock);
1983   if (!supported) {
1984     GST_ERROR ("PTP not supported");
1985     ret = FALSE;
1986     goto done;
1987   }
1988
1989   if (initted) {
1990     GST_DEBUG ("PTP already initialized");
1991     ret = TRUE;
1992     goto done;
1993   }
1994
1995   if (ptp_helper_pid) {
1996     GST_DEBUG ("PTP currently initializing");
1997     goto wait;
1998   }
1999
2000   if (!domain_stats_hooks_initted) {
2001     g_hook_list_init (&domain_stats_hooks, sizeof (GHook));
2002     domain_stats_hooks_initted = TRUE;
2003   }
2004
2005   argc = 1;
2006   if (clock_id != GST_PTP_CLOCK_ID_NONE)
2007     argc += 2;
2008   if (interfaces != NULL)
2009     argc += 2 * g_strv_length (interfaces);
2010
2011   argv = g_new0 (gchar *, argc + 2);
2012   argc_c = 0;
2013
2014   env = g_getenv ("GST_PTP_HELPER_1_0");
2015   if (env == NULL)
2016     env = g_getenv ("GST_PTP_HELPER");
2017   if (env != NULL && *env != '\0') {
2018     GST_LOG ("Trying GST_PTP_HELPER env var: %s", env);
2019     argv[argc_c++] = g_strdup (env);
2020   } else {
2021     argv[argc_c++] = g_strdup (GST_PTP_HELPER_INSTALLED);
2022   }
2023
2024   if (clock_id != GST_PTP_CLOCK_ID_NONE) {
2025     argv[argc_c++] = g_strdup ("-c");
2026     argv[argc_c++] = g_strdup_printf ("0x%016" G_GINT64_MODIFIER "x", clock_id);
2027   }
2028
2029   if (interfaces != NULL) {
2030     gchar **ptr = interfaces;
2031
2032     while (*ptr) {
2033       argv[argc_c++] = g_strdup ("-i");
2034       argv[argc_c++] = g_strdup (*ptr);
2035       ptr++;
2036     }
2037   }
2038
2039   main_context = g_main_context_new ();
2040   main_loop = g_main_loop_new (main_context, FALSE);
2041
2042   ptp_helper_thread =
2043       g_thread_try_new ("ptp-helper-thread", ptp_helper_main, NULL, &err);
2044   if (!ptp_helper_thread) {
2045     GST_ERROR ("Failed to start PTP helper thread: %s", err->message);
2046     g_clear_error (&err);
2047     ret = FALSE;
2048     goto done;
2049   }
2050
2051   if (!g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL,
2052           &ptp_helper_pid, &fd_w, &fd_r, NULL, &err)) {
2053     GST_ERROR ("Failed to start ptp helper process: %s", err->message);
2054     g_clear_error (&err);
2055     ret = FALSE;
2056     supported = FALSE;
2057     goto done;
2058   }
2059
2060   stdin_channel = g_io_channel_unix_new (fd_r);
2061   g_io_channel_set_encoding (stdin_channel, NULL, NULL);
2062   g_io_channel_set_buffered (stdin_channel, FALSE);
2063   g_io_channel_set_close_on_unref (stdin_channel, TRUE);
2064   stdin_source =
2065       g_io_create_watch (stdin_channel, G_IO_IN | G_IO_PRI | G_IO_HUP);
2066   g_source_set_priority (stdin_source, G_PRIORITY_DEFAULT);
2067   g_source_set_callback (stdin_source, (GSourceFunc) have_stdin_data_cb, NULL,
2068       NULL);
2069   g_source_attach (stdin_source, main_context);
2070   g_source_unref (stdin_source);
2071
2072   /* Create stdout channel */
2073   stdout_channel = g_io_channel_unix_new (fd_w);
2074   g_io_channel_set_encoding (stdout_channel, NULL, NULL);
2075   g_io_channel_set_close_on_unref (stdout_channel, TRUE);
2076   g_io_channel_set_buffered (stdout_channel, FALSE);
2077
2078   delay_req_rand = g_rand_new ();
2079   observation_system_clock =
2080       g_object_new (GST_TYPE_SYSTEM_CLOCK, "name", "ptp-observation-clock",
2081       NULL);
2082
2083   initted = TRUE;
2084
2085 wait:
2086   GST_DEBUG ("Waiting for PTP to be initialized");
2087
2088   while (ptp_clock_id.clock_identity == GST_PTP_CLOCK_ID_NONE && initted)
2089     g_cond_wait (&ptp_cond, &ptp_lock);
2090
2091   ret = initted;
2092   if (ret) {
2093     GST_DEBUG ("Initialized and got clock id 0x%016" G_GINT64_MODIFIER "x %u",
2094         ptp_clock_id.clock_identity, ptp_clock_id.port_number);
2095   } else {
2096     GST_ERROR ("Failed to initialize");
2097     supported = FALSE;
2098   }
2099
2100 done:
2101   g_strfreev (argv);
2102
2103   if (!ret) {
2104     if (ptp_helper_pid) {
2105       kill (ptp_helper_pid, SIGKILL);
2106       waitpid (ptp_helper_pid, NULL, 0);
2107       g_spawn_close_pid (ptp_helper_pid);
2108     }
2109     ptp_helper_pid = 0;
2110
2111     if (stdin_channel)
2112       g_io_channel_unref (stdin_channel);
2113     stdin_channel = NULL;
2114     if (stdout_channel)
2115       g_io_channel_unref (stdout_channel);
2116     stdout_channel = NULL;
2117
2118     if (main_loop && ptp_helper_thread) {
2119       g_main_loop_quit (main_loop);
2120       g_thread_join (ptp_helper_thread);
2121     }
2122     ptp_helper_thread = NULL;
2123     if (main_loop)
2124       g_main_loop_unref (main_loop);
2125     main_loop = NULL;
2126     if (main_context)
2127       g_main_context_unref (main_context);
2128     main_context = NULL;
2129
2130     if (delay_req_rand)
2131       g_rand_free (delay_req_rand);
2132     delay_req_rand = NULL;
2133
2134     if (observation_system_clock)
2135       gst_object_unref (observation_system_clock);
2136     observation_system_clock = NULL;
2137   }
2138
2139   g_mutex_unlock (&ptp_lock);
2140
2141   return ret;
2142 }
2143
2144 /**
2145  * gst_ptp_deinit:
2146  *
2147  * Deinitialize the GStreamer PTP subsystem and stop the PTP clock. If there
2148  * are any remaining GstPtpClock instances, they won't be further synchronized
2149  * to the PTP network clock.
2150  *
2151  * Since: 1.6
2152  */
2153 void
2154 gst_ptp_deinit (void)
2155 {
2156   GList *l, *m;
2157
2158   g_mutex_lock (&ptp_lock);
2159
2160   if (ptp_helper_pid) {
2161     kill (ptp_helper_pid, SIGKILL);
2162     waitpid (ptp_helper_pid, NULL, 0);
2163     g_spawn_close_pid (ptp_helper_pid);
2164   }
2165   ptp_helper_pid = 0;
2166
2167   if (stdin_channel)
2168     g_io_channel_unref (stdin_channel);
2169   stdin_channel = NULL;
2170   if (stdout_channel)
2171     g_io_channel_unref (stdout_channel);
2172   stdout_channel = NULL;
2173
2174   if (main_loop && ptp_helper_thread) {
2175     GThread *tmp = ptp_helper_thread;
2176     ptp_helper_thread = NULL;
2177     g_mutex_unlock (&ptp_lock);
2178     g_main_loop_quit (main_loop);
2179     g_thread_join (tmp);
2180     g_mutex_lock (&ptp_lock);
2181   }
2182   if (main_loop)
2183     g_main_loop_unref (main_loop);
2184   main_loop = NULL;
2185   if (main_context)
2186     g_main_context_unref (main_context);
2187   main_context = NULL;
2188
2189   if (delay_req_rand)
2190     g_rand_free (delay_req_rand);
2191   delay_req_rand = NULL;
2192   if (observation_system_clock)
2193     gst_object_unref (observation_system_clock);
2194   observation_system_clock = NULL;
2195
2196   for (l = domain_data; l; l = l->next) {
2197     PtpDomainData *domain = l->data;
2198
2199     for (m = domain->announce_senders; m; m = m->next) {
2200       PtpAnnounceSender *sender = m->data;
2201
2202       g_queue_foreach (&sender->announce_messages, (GFunc) g_free, NULL);
2203       g_queue_clear (&sender->announce_messages);
2204       g_free (sender);
2205     }
2206     g_list_free (domain->announce_senders);
2207
2208     g_queue_foreach (&domain->pending_syncs, (GFunc) ptp_pending_sync_free,
2209         NULL);
2210     g_queue_clear (&domain->pending_syncs);
2211     gst_object_unref (domain->domain_clock);
2212     g_free (domain);
2213   }
2214   g_list_free (domain_data);
2215   domain_data = NULL;
2216   g_list_foreach (domain_clocks, (GFunc) g_free, NULL);
2217   g_list_free (domain_clocks);
2218   domain_clocks = NULL;
2219
2220   ptp_clock_id.clock_identity = GST_PTP_CLOCK_ID_NONE;
2221   ptp_clock_id.port_number = 0;
2222
2223   initted = FALSE;
2224
2225   g_mutex_unlock (&ptp_lock);
2226 }
2227
2228 #define DEFAULT_DOMAIN 0
2229
2230 enum
2231 {
2232   PROP_0,
2233   PROP_DOMAIN,
2234   PROP_INTERNAL_CLOCK
2235 };
2236
2237 #define GST_PTP_CLOCK_GET_PRIVATE(obj)  \
2238   (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_PTP_CLOCK, GstPtpClockPrivate))
2239
2240 struct _GstPtpClockPrivate
2241 {
2242   guint domain;
2243   GstClock *domain_clock;
2244   gulong domain_stats_id;
2245 };
2246
2247 #define gst_ptp_clock_parent_class parent_class
2248 G_DEFINE_TYPE (GstPtpClock, gst_ptp_clock, GST_TYPE_SYSTEM_CLOCK);
2249
2250 static void gst_ptp_clock_set_property (GObject * object, guint prop_id,
2251     const GValue * value, GParamSpec * pspec);
2252 static void gst_ptp_clock_get_property (GObject * object, guint prop_id,
2253     GValue * value, GParamSpec * pspec);
2254 static void gst_ptp_clock_finalize (GObject * object);
2255
2256 static GstClockTime gst_ptp_clock_get_internal_time (GstClock * clock);
2257
2258 static void
2259 gst_ptp_clock_class_init (GstPtpClockClass * klass)
2260 {
2261   GObjectClass *gobject_class;
2262   GstClockClass *clock_class;
2263
2264   gobject_class = G_OBJECT_CLASS (klass);
2265   clock_class = GST_CLOCK_CLASS (klass);
2266
2267   g_type_class_add_private (klass, sizeof (GstPtpClockPrivate));
2268
2269   gobject_class->finalize = gst_ptp_clock_finalize;
2270   gobject_class->get_property = gst_ptp_clock_get_property;
2271   gobject_class->set_property = gst_ptp_clock_set_property;
2272
2273   g_object_class_install_property (gobject_class, PROP_DOMAIN,
2274       g_param_spec_uint ("domain", "Domain",
2275           "The PTP domain", 0, G_MAXUINT8,
2276           DEFAULT_DOMAIN,
2277           G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
2278
2279   g_object_class_install_property (gobject_class, PROP_INTERNAL_CLOCK,
2280       g_param_spec_object ("internal-clock", "Internal Clock",
2281           "Internal clock", GST_TYPE_CLOCK,
2282           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
2283
2284   clock_class->get_internal_time = gst_ptp_clock_get_internal_time;
2285 }
2286
2287 static void
2288 gst_ptp_clock_init (GstPtpClock * self)
2289 {
2290   GstPtpClockPrivate *priv;
2291
2292   self->priv = priv = GST_PTP_CLOCK_GET_PRIVATE (self);
2293
2294   GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_CAN_SET_MASTER);
2295   GST_OBJECT_FLAG_SET (self, GST_CLOCK_FLAG_NEEDS_STARTUP_SYNC);
2296
2297   priv->domain = DEFAULT_DOMAIN;
2298 }
2299
2300 static gboolean
2301 gst_ptp_clock_ensure_domain_clock (GstPtpClock * self)
2302 {
2303   gboolean got_clock = TRUE;
2304
2305   if (G_UNLIKELY (!self->priv->domain_clock)) {
2306     g_mutex_lock (&domain_clocks_lock);
2307     if (!self->priv->domain_clock) {
2308       GList *l;
2309
2310       got_clock = FALSE;
2311
2312       for (l = domain_clocks; l; l = l->next) {
2313         PtpDomainData *clock_data = l->data;
2314
2315         if (clock_data->domain == self->priv->domain
2316             && clock_data->last_ptp_time != 0) {
2317           self->priv->domain_clock = clock_data->domain_clock;
2318           got_clock = TRUE;
2319           break;
2320         }
2321       }
2322     }
2323     g_mutex_unlock (&domain_clocks_lock);
2324     if (got_clock) {
2325       g_object_notify (G_OBJECT (self), "internal-clock");
2326       gst_clock_set_synced (GST_CLOCK (self), TRUE);
2327     }
2328   }
2329
2330   return got_clock;
2331 }
2332
2333 static gboolean
2334 gst_ptp_clock_stats_callback (guint8 domain, const GstStructure * stats,
2335     gpointer user_data)
2336 {
2337   GstPtpClock *self = user_data;
2338
2339   if (domain != self->priv->domain
2340       || !gst_structure_has_name (stats, GST_PTP_STATISTICS_TIME_UPDATED))
2341     return TRUE;
2342
2343   /* Let's set our internal clock */
2344   if (!gst_ptp_clock_ensure_domain_clock (self))
2345     return TRUE;
2346
2347   self->priv->domain_stats_id = 0;
2348
2349   return FALSE;
2350 }
2351
2352 static void
2353 gst_ptp_clock_set_property (GObject * object, guint prop_id,
2354     const GValue * value, GParamSpec * pspec)
2355 {
2356   GstPtpClock *self = GST_PTP_CLOCK (object);
2357
2358   switch (prop_id) {
2359     case PROP_DOMAIN:
2360       self->priv->domain = g_value_get_uint (value);
2361       gst_ptp_clock_ensure_domain_clock (self);
2362       if (!self->priv->domain_clock)
2363         self->priv->domain_stats_id =
2364             gst_ptp_statistics_callback_add (gst_ptp_clock_stats_callback, self,
2365             NULL);
2366       break;
2367     default:
2368       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2369       break;
2370   }
2371 }
2372
2373 static void
2374 gst_ptp_clock_get_property (GObject * object, guint prop_id,
2375     GValue * value, GParamSpec * pspec)
2376 {
2377   GstPtpClock *self = GST_PTP_CLOCK (object);
2378
2379   switch (prop_id) {
2380     case PROP_DOMAIN:
2381       g_value_set_uint (value, self->priv->domain);
2382       break;
2383     case PROP_INTERNAL_CLOCK:
2384       gst_ptp_clock_ensure_domain_clock (self);
2385       g_value_set_object (value, self->priv->domain_clock);
2386       break;
2387     default:
2388       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2389       break;
2390   }
2391 }
2392
2393 static void
2394 gst_ptp_clock_finalize (GObject * object)
2395 {
2396   GstPtpClock *self = GST_PTP_CLOCK (object);
2397
2398   if (self->priv->domain_stats_id)
2399     gst_ptp_statistics_callback_remove (self->priv->domain_stats_id);
2400
2401   G_OBJECT_CLASS (gst_ptp_clock_parent_class)->finalize (object);
2402 }
2403
2404 static GstClockTime
2405 gst_ptp_clock_get_internal_time (GstClock * clock)
2406 {
2407   GstPtpClock *self = GST_PTP_CLOCK (clock);
2408
2409   gst_ptp_clock_ensure_domain_clock (self);
2410
2411   if (!self->priv->domain_clock) {
2412     GST_ERROR_OBJECT (self, "Domain %u has no clock yet and is not synced",
2413         self->priv->domain);
2414     return GST_CLOCK_TIME_NONE;
2415   }
2416
2417   return gst_clock_get_time (self->priv->domain_clock);
2418 }
2419
2420 /**
2421  * gst_ptp_clock_new:
2422  * @name: Name of the clock
2423  * @domain: PTP domain
2424  *
2425  * Creates a new PTP clock instance that exports the PTP time of the master
2426  * clock in @domain. This clock can be slaved to other clocks as needed.
2427  *
2428  * If gst_ptp_init() was not called before, this will call gst_ptp_init() with
2429  * default parameters.
2430  *
2431  *
2432  * This clock only returns valid timestamps after it received the first
2433  * times from the PTP master clock on the network. Once this happens the
2434  * GstPtpClock::internal-clock property will become non-NULL. You can
2435  * check this with gst_clock_wait_for_sync(), the GstClock::synced signal and
2436  * gst_clock_is_synced().
2437  *
2438  * Since: 1.6
2439  */
2440 GstClock *
2441 gst_ptp_clock_new (const gchar * name, guint domain)
2442 {
2443   g_return_val_if_fail (name != NULL, NULL);
2444   g_return_val_if_fail (domain <= G_MAXUINT8, NULL);
2445
2446   if (!initted && !gst_ptp_init (GST_PTP_CLOCK_ID_NONE, NULL)) {
2447     GST_ERROR ("Failed to initialize PTP");
2448     return NULL;
2449   }
2450
2451   return g_object_new (GST_TYPE_PTP_CLOCK, "name", name, "domain", domain,
2452       NULL);
2453 }
2454
2455 typedef struct
2456 {
2457   guint8 domain;
2458   const GstStructure *stats;
2459 } DomainStatsMarshalData;
2460
2461 static void
2462 domain_stats_marshaller (GHook * hook, DomainStatsMarshalData * data)
2463 {
2464   GstPtpStatisticsCallback callback = (GstPtpStatisticsCallback) hook->func;
2465
2466   if (!callback (data->domain, data->stats, hook->data))
2467     g_hook_destroy (&domain_stats_hooks, hook->hook_id);
2468 }
2469
2470 static void
2471 emit_ptp_statistics (guint8 domain, const GstStructure * stats)
2472 {
2473   DomainStatsMarshalData data = { domain, stats };
2474
2475   g_mutex_lock (&ptp_lock);
2476   g_hook_list_marshal (&domain_stats_hooks, TRUE,
2477       (GHookMarshaller) domain_stats_marshaller, &data);
2478   g_mutex_unlock (&ptp_lock);
2479 }
2480
2481 /**
2482  * gst_ptp_statistics_callback_add:
2483  * @callback: GstPtpStatisticsCallback to call
2484  * @user_data: Data to pass to the callback
2485  * @destroy_data: GDestroyNotify to destroy the data
2486  *
2487  * Installs a new statistics callback for gathering PTP statistics. See
2488  * GstPtpStatisticsCallback for a list of statistics that are provided.
2489  *
2490  * Returns: Id for the callback that can be passed to
2491  * gst_ptp_statistics_callback_remove()
2492  *
2493  * Since: 1.6
2494  */
2495 gulong
2496 gst_ptp_statistics_callback_add (GstPtpStatisticsCallback callback,
2497     gpointer user_data, GDestroyNotify destroy_data)
2498 {
2499   GHook *hook;
2500
2501   g_mutex_lock (&ptp_lock);
2502
2503   if (!domain_stats_hooks_initted) {
2504     g_hook_list_init (&domain_stats_hooks, sizeof (GHook));
2505     domain_stats_hooks_initted = TRUE;
2506   }
2507
2508   hook = g_hook_alloc (&domain_stats_hooks);
2509   hook->func = callback;
2510   hook->data = user_data;
2511   hook->destroy = destroy_data;
2512   g_hook_prepend (&domain_stats_hooks, hook);
2513   g_atomic_int_add (&domain_stats_n_hooks, 1);
2514
2515   g_mutex_unlock (&ptp_lock);
2516
2517   return hook->hook_id;
2518 }
2519
2520 /**
2521  * gst_ptp_statistics_callback_remove:
2522  * @id: Callback id to remove
2523  *
2524  * Removes a PTP statistics callback that was previously added with
2525  * gst_ptp_statistics_callback_add().
2526  *
2527  * Since: 1.6
2528  */
2529 void
2530 gst_ptp_statistics_callback_remove (gulong id)
2531 {
2532   g_mutex_lock (&ptp_lock);
2533   if (g_hook_destroy (&domain_stats_hooks, id))
2534     g_atomic_int_add (&domain_stats_n_hooks, -1);
2535   g_mutex_unlock (&ptp_lock);
2536 }
2537
2538 #else /* HAVE_PTP */
2539
2540 GType
2541 gst_ptp_clock_get_type (void)
2542 {
2543   return G_TYPE_INVALID;
2544 }
2545
2546 gboolean
2547 gst_ptp_is_supported (void)
2548 {
2549   return FALSE;
2550 }
2551
2552 gboolean
2553 gst_ptp_is_initialized (void)
2554 {
2555   return FALSE;
2556 }
2557
2558 gboolean
2559 gst_ptp_init (guint64 clock_id, gchar ** interfaces)
2560 {
2561   return FALSE;
2562 }
2563
2564 void
2565 gst_ptp_deinit (void)
2566 {
2567 }
2568
2569 GstClock *
2570 gst_ptp_clock_new (const gchar * name, guint domain)
2571 {
2572   return NULL;
2573 }
2574
2575 gulong
2576 gst_ptp_statistics_callback_add (GstPtpStatisticsCallback callback,
2577     gpointer user_data, GDestroyNotify destroy_data)
2578 {
2579   return 0;
2580 }
2581
2582 void
2583 gst_ptp_statistics_callback_remove (gulong id)
2584 {
2585   return;
2586 }
2587
2588 #endif