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