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