File: gstclocksync.c

package info (click to toggle)
gstreamer1.0 1.28.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,604 kB
  • sloc: ansic: 203,072; python: 1,985; sh: 566; lex: 188; lisp: 154; java: 81; makefile: 59; cpp: 58; perl: 46
file content (996 lines) | stat: -rw-r--r-- 30,844 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
/*
 * GStreamer
 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
 *                    2000 Wim Taymans <wtay@chello.be>
 *                    2005 Wim Taymans <wim@fluendo.com>
 * Copyright (C) 2020 Jan Schmidt <jan@centricular.com>
 *
 * gstclocksync.c:
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

/**
 * SECTION:element-clocksync
 * @title: clocksync
 *
 * Simple element that passes all buffers and buffer-lists intact, but
 * synchronising them to the clock before passing.
 *
 * Synchronisation to the clock is on by default, but can be turned
 * off by setting the 'sync' property to FALSE
 *
 * <refsect2>
 * <title>Example launch line</title>
 * |[
 * gst-launch -v -m videotestsrc ! clocksync ! fakesink silent=TRUE
 * ]|
 * </refsect2>
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include <gst/gst.h>

#include "gstclocksync.h"
#include "gstcoreelementselements.h"

GST_DEBUG_CATEGORY_STATIC (gst_clock_sync_debug);
#define GST_CAT_DEFAULT gst_clock_sync_debug

/* ClockSync args */
#define DEFAULT_SYNC                    TRUE
#define DEFAULT_TS_OFFSET               0
#define DEFAULT_SYNC_TO_FIRST           FALSE
#define DEFAULT_QOS                     FALSE
#define DEFAULT_RATE                    1.0

enum
{
  PROP_0,
  PROP_SYNC,
  PROP_TS_OFFSET,
  PROP_SYNC_TO_FIRST,
  PROP_QOS,
  PROP_RATE,
  PROP_LAST
};

enum
{
  SIGNAL_RESYNC,
  SIGNAL_LAST
};

static GParamSpec *properties[PROP_LAST];
static gint clocksync_signals[SIGNAL_LAST] = { 0, };

static GstStaticPadTemplate sinktemplate = GST_STATIC_PAD_TEMPLATE ("sink",
    GST_PAD_SINK,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("ANY")
    );

static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("ANY")
    );

#define _do_init \
    GST_DEBUG_CATEGORY_INIT (gst_clock_sync_debug, "clocksync", 0, "clocksync element");
#define gst_clock_sync_parent_class parent_class
G_DEFINE_TYPE_WITH_CODE (GstClockSync, gst_clock_sync, GST_TYPE_ELEMENT,
    _do_init);
GST_ELEMENT_REGISTER_DEFINE (clocksync, "clocksync", GST_RANK_NONE,
    GST_TYPE_CLOCKSYNC);

#define DO_RUNNING_AVG(avg,val,size) (((val) + ((size)-1) * (avg)) / (size))

/* generic running average, this has a neutral window size */
#define UPDATE_RUNNING_AVG(avg,val)   DO_RUNNING_AVG(avg,val,8)

/* the windows for these running averages are experimentally obtained.
 * positive values get averaged more while negative values use a small
 * window so we can react faster to badness. */
#define UPDATE_RUNNING_AVG_P(avg,val) DO_RUNNING_AVG(avg,val,16)
#define UPDATE_RUNNING_AVG_N(avg,val) DO_RUNNING_AVG(avg,val,4)

static void gst_clock_sync_finalize (GObject * object);

static void gst_clock_sync_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec);
static void gst_clock_sync_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec);

static gboolean gst_clock_sync_sink_event (GstPad * pad, GstObject * parent,
    GstEvent * event);
static GstFlowReturn gst_clock_sync_chain (GstPad * pad, GstObject * parent,
    GstBuffer * buf);
static GstFlowReturn gst_clock_sync_chain_list (GstPad * pad,
    GstObject * parent, GstBufferList * buflist);
static gboolean gst_clock_sync_src_query (GstPad * pad, GstObject * parent,
    GstQuery * query);
static gboolean gst_clock_sync_src_event (GstPad * pad, GstObject * parent,
    GstEvent * event);
static GstStateChangeReturn gst_clocksync_change_state (GstElement * element,
    GstStateChange transition);
static GstClock *gst_clocksync_provide_clock (GstElement * element);
static void gst_clock_sync_resync (GstClockSync * self);

static void
gst_clock_sync_class_init (GstClockSyncClass * klass)
{
  GObjectClass *gobject_class;
  GstElementClass *gstelement_class;

  gobject_class = (GObjectClass *) klass;
  gstelement_class = (GstElementClass *) klass;

  gobject_class->set_property = gst_clock_sync_set_property;
  gobject_class->get_property = gst_clock_sync_get_property;
  gobject_class->finalize = gst_clock_sync_finalize;

  properties[PROP_SYNC] =
      g_param_spec_boolean ("sync", "Synchronize",
      "Synchronize to pipeline clock", DEFAULT_SYNC,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
  properties[PROP_TS_OFFSET] =
      g_param_spec_int64 ("ts-offset", "Timestamp offset for synchronisation",
      "Timestamp offset in nanoseconds for synchronisation, negative for earlier sync",
      G_MININT64, G_MAXINT64, DEFAULT_TS_OFFSET,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

  /**
   * GstClockSync:sync-to-first:
   *
   * When enabled, clocksync elemenet will adjust "ts-offset" value
   * automatically by using given timestamp of the first buffer and running
   * time of pipeline, so that clocksync element can output the first buffer
   * immediately without clock waiting.
   *
   * Since: 1.20
   */
  properties[PROP_SYNC_TO_FIRST] =
      g_param_spec_boolean ("sync-to-first",
      "Sync to first",
      "Automatically set ts-offset based on running time of the first "
      "buffer and pipeline's running time "
      "(i.e., ts-offset = \"pipeline running time\" - \"buffer running time\"). "
      "When enabled, clocksync element will update ts-offset on the first "
      "buffer per flush event or READY to PAUSED state change. "
      "This property can be useful in case that buffer timestamp does not "
      "necessarily have to be synchronized with pipeline's running time, "
      "but duration of the buffer through clocksync element needs to be "
      "synchronized with the amount of clock time go. "
      "Note that mixed use of ts-offset and this property would be racy "
      "if clocksync element is running already.",
      DEFAULT_SYNC_TO_FIRST, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

  /**
   * GstClockSync:qos:
   *
   * Generate Quality-of-Service events upstream.
   *
   * Since: 1.22
   */
  properties[PROP_QOS] =
      g_param_spec_boolean ("qos", "Qos",
      "Generate Quality-of-Service events upstream", DEFAULT_QOS,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);

  /**
   * GstClockSync:rate:
   *
   * Factor of buffer output speed
   *
   * Since: 1.28
   */
  properties[PROP_RATE] =
      g_param_spec_double ("rate", "Rate",
      "Factor of buffer output speed",
      0.0, G_MAXDOUBLE, DEFAULT_RATE,
      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | GST_PARAM_MUTABLE_READY);

  g_object_class_install_properties (gobject_class, PROP_LAST, properties);

  /**
   * GstClockSync::resync:
   * @clocksync: the #GstClockSync
   *
   * Request recalculation of the "ts-offset" for the next incoming buffer
   * without changing the state of clocksync.
   *
   * This is useful when "sync-to-first=true" has already established
   * an initial `ts-offset` but running-time of buffer flow is no longer linear
   * (e.g., data flow was temporarily blocked by pad probe). In such cases,
   * a new "ts-offset" may be required so that buffer flow can be throttled
   * correctly again.
   *
   * Since: 1.28
   */
  clocksync_signals[SIGNAL_RESYNC] =
      g_signal_new_class_handler ("resync", G_TYPE_FROM_CLASS (klass),
      (GSignalFlags) (G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION),
      G_CALLBACK (gst_clock_sync_resync), NULL, NULL, NULL, G_TYPE_NONE, 0);

  gstelement_class->change_state =
      GST_DEBUG_FUNCPTR (gst_clocksync_change_state);
  gstelement_class->provide_clock =
      GST_DEBUG_FUNCPTR (gst_clocksync_provide_clock);

  gst_element_class_set_static_metadata (gstelement_class,
      "ClockSync",
      "Generic",
      "Synchronise buffers to the clock", "Jan Schmidt <jan@centricular.com>");

  gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
  gst_element_class_add_static_pad_template (gstelement_class, &sinktemplate);
}

static void
gst_clock_sync_finalize (GObject * object)
{
  GstClockSync *clocksync = GST_CLOCKSYNC (object);

  g_cond_clear (&clocksync->blocked_cond);

  G_OBJECT_CLASS (parent_class)->finalize (object);
}

static void
gst_clock_sync_init (GstClockSync * clocksync)
{
  clocksync->sinkpad = gst_pad_new_from_static_template (&sinktemplate, "sink");
  gst_pad_set_event_function (clocksync->sinkpad,
      GST_DEBUG_FUNCPTR (gst_clock_sync_sink_event));
  gst_pad_set_chain_function (clocksync->sinkpad,
      GST_DEBUG_FUNCPTR (gst_clock_sync_chain));
  gst_pad_set_chain_list_function (clocksync->sinkpad,
      GST_DEBUG_FUNCPTR (gst_clock_sync_chain_list));
  GST_PAD_SET_PROXY_CAPS (clocksync->sinkpad);
  GST_PAD_SET_PROXY_ALLOCATION (clocksync->sinkpad);
  gst_element_add_pad (GST_ELEMENT (clocksync), clocksync->sinkpad);

  clocksync->srcpad = gst_pad_new_from_static_template (&srctemplate, "src");

  gst_pad_set_query_function (clocksync->srcpad, gst_clock_sync_src_query);

  GST_PAD_SET_PROXY_CAPS (clocksync->srcpad);
  GST_PAD_SET_PROXY_ALLOCATION (clocksync->srcpad);
  gst_pad_set_event_function (clocksync->srcpad,
      GST_DEBUG_FUNCPTR (gst_clock_sync_src_event));
  gst_element_add_pad (GST_ELEMENT (clocksync), clocksync->srcpad);

  clocksync->ts_offset = DEFAULT_TS_OFFSET;
  clocksync->sync = DEFAULT_SYNC;
  clocksync->sync_to_first = DEFAULT_SYNC_TO_FIRST;
  clocksync->rate = DEFAULT_RATE;

  g_atomic_int_set (&clocksync->qos_enabled, DEFAULT_QOS);
  g_cond_init (&clocksync->blocked_cond);

  GST_OBJECT_FLAG_SET (clocksync, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
  GST_OBJECT_FLAG_SET (clocksync, GST_ELEMENT_FLAG_REQUIRE_CLOCK);
}

static void
gst_clock_sync_set_property (GObject * object, guint prop_id,
    const GValue * value, GParamSpec * pspec)
{
  GstClockSync *clocksync = GST_CLOCKSYNC (object);
  GstMessage *clock_message = NULL;
  gboolean sync;

  switch (prop_id) {
    case PROP_SYNC:
      clocksync->sync = g_value_get_boolean (value);
      sync = g_value_get_boolean (value);
      GST_OBJECT_LOCK (clocksync);
      if (sync != clocksync->sync) {
        clocksync->sync = sync;
        if (sync) {
          GST_OBJECT_FLAG_SET (clocksync, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
          clock_message =
              gst_message_new_clock_provide (GST_OBJECT_CAST (clocksync),
              gst_system_clock_obtain (), TRUE);
        } else {
          GST_OBJECT_FLAG_UNSET (clocksync, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
          clock_message =
              gst_message_new_clock_lost (GST_OBJECT_CAST (clocksync),
              gst_system_clock_obtain ());
        }
      }
      GST_OBJECT_UNLOCK (clocksync);
      if (clock_message)
        gst_element_post_message (GST_ELEMENT_CAST (clocksync), clock_message);
      break;
    case PROP_TS_OFFSET:
      clocksync->ts_offset = g_value_get_int64 (value);
      break;
    case PROP_SYNC_TO_FIRST:
      clocksync->sync_to_first = g_value_get_boolean (value);
      break;
    case PROP_QOS:
      g_atomic_int_set (&clocksync->qos_enabled, g_value_get_boolean (value));
      break;
    case PROP_RATE:
      clocksync->rate = g_value_get_double (value);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

static void
gst_clock_sync_get_property (GObject * object, guint prop_id,
    GValue * value, GParamSpec * pspec)
{
  GstClockSync *clocksync = GST_CLOCKSYNC (object);

  switch (prop_id) {
    case PROP_SYNC:
      g_value_set_boolean (value, clocksync->sync);
      break;
    case PROP_TS_OFFSET:
      g_value_set_int64 (value, clocksync->ts_offset);
      break;
    case PROP_SYNC_TO_FIRST:
      g_value_set_boolean (value, clocksync->sync_to_first);
      break;
    case PROP_QOS:
      g_value_set_boolean (value, g_atomic_int_get (&clocksync->qos_enabled));
      break;
    case PROP_RATE:
      g_value_set_double (value, clocksync->rate);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
  }
}

/* With STREAM_LOCK
 * reset all qos measuring */
static void
gst_clock_sync_reset_qos (GstClockSync * clocksync)
{
  clocksync->prev_rstart = GST_CLOCK_TIME_NONE;
  clocksync->earliest_in_time = GST_CLOCK_TIME_NONE;
  clocksync->last_left = GST_CLOCK_TIME_NONE;
  clocksync->avg_pt = GST_CLOCK_TIME_NONE;
  clocksync->avg_rate = -1.0;
  clocksync->avg_in_diff = GST_CLOCK_TIME_NONE;

}

static gboolean
gst_clock_sync_send_qos (GstClockSync * clocksync, GstQOSType type,
    gdouble proportion, GstClockTime time, GstClockTimeDiff diff)
{
  GstEvent *event;
  gboolean res;

  /* generate Quality-of-Service event */
  GST_DEBUG_OBJECT (clocksync,
      "qos: type %d, proportion: %lf, diff %" G_GINT64_FORMAT ", timestamp %"
      GST_TIME_FORMAT, type, proportion, diff, GST_TIME_ARGS (time));

  event = gst_event_new_qos (type, proportion, diff, time);

  /* send upstream */
  res = gst_pad_push_event (clocksync->sinkpad, event);

  return res;
}

static gboolean
gst_clock_sync_perform_qos (GstClockSync * clocksync)
{
  GstClockTime start;
  GstClockTimeDiff jitter;
  GstClockTime pt, entered;
  GstClockTime duration;
  gdouble rate;

  start = clocksync->current_rstart;

  /* if Quality-of-Service disabled, do nothing */
  if (!g_atomic_int_get (&clocksync->qos_enabled) ||
      !GST_CLOCK_TIME_IS_VALID (start) || !clocksync->sync) {

    return FALSE;
  }

  jitter = clocksync->current_jitter;

  if (jitter < 0) {
    /* this is the time the buffer entered the clocksync */
    if (start < -jitter)
      entered = 0;
    else
      entered = start + jitter;
  } else {
    /* this is the time the buffer entered the clocksync */
    entered = start + jitter;
  }

  /* Average duration between each buffer timestamps */
  duration = clocksync->avg_in_diff;

  /* if we have the time when the last buffer left us, calculate
   * processing time */
  if (GST_CLOCK_TIME_IS_VALID (clocksync->last_left)) {
    if (entered > clocksync->last_left) {
      pt = entered - clocksync->last_left;
    } else {
      pt = 0;
    }
  } else {
    pt = clocksync->avg_pt;
  }

  GST_DEBUG_OBJECT (clocksync, "start: %" GST_TIME_FORMAT
      ", entered %" GST_TIME_FORMAT ", pt: %" GST_TIME_FORMAT ", duration %"
      GST_TIME_FORMAT ",jitter %" G_GINT64_FORMAT, GST_TIME_ARGS (start),
      GST_TIME_ARGS (entered), GST_TIME_ARGS (pt), GST_TIME_ARGS (duration),
      jitter);

  GST_DEBUG_OBJECT (clocksync,
      "avg_pt: %" GST_TIME_FORMAT ", avg_rate: %g",
      GST_TIME_ARGS (clocksync->avg_pt), clocksync->avg_rate);

  /* collect running averages. for first observations, we copy the
   * values */
  if (!GST_CLOCK_TIME_IS_VALID (clocksync->avg_pt))
    clocksync->avg_pt = pt;
  else
    clocksync->avg_pt = UPDATE_RUNNING_AVG (clocksync->avg_pt, pt);

  if (duration != -1 && duration != 0) {
    rate =
        gst_guint64_to_gdouble (clocksync->avg_pt) /
        gst_guint64_to_gdouble (duration);
  } else {
    rate = 1.0;
  }

  if (GST_CLOCK_TIME_IS_VALID (clocksync->last_left)) {
    if (clocksync->avg_rate < 0.0) {
      clocksync->avg_rate = rate;
    } else {
      if (rate > 1.0)
        clocksync->avg_rate = UPDATE_RUNNING_AVG_N (clocksync->avg_rate, rate);
      else
        clocksync->avg_rate = UPDATE_RUNNING_AVG_P (clocksync->avg_rate, rate);
    }
  }

  GST_DEBUG_OBJECT (clocksync,
      "updated: avg_pt: %" GST_TIME_FORMAT
      ", avg_rate: %g", GST_TIME_ARGS (clocksync->avg_pt), clocksync->avg_rate);

  if (clocksync->avg_rate >= 0.0) {
    GstQOSType type;
    GstClockTimeDiff diff;

    /* if we have a valid rate, start sending QoS messages */
    if (clocksync->current_jitter < 0) {
      /* make sure we never go below 0 when adding the jitter to the
       * timestamp. */
      if (clocksync->current_rstart < -clocksync->current_jitter)
        clocksync->current_jitter = -clocksync->current_rstart;
    }

    diff = clocksync->current_jitter;
    if (diff <= 0)
      type = GST_QOS_TYPE_OVERFLOW;
    else
      type = GST_QOS_TYPE_UNDERFLOW;

    gst_clock_sync_send_qos (clocksync, type, clocksync->avg_rate,
        clocksync->current_rstart, diff);
  }

  return TRUE;
}

static GstFlowReturn
gst_clocksync_do_sync (GstClockSync * clocksync, GstClockTime running_time)
{
  GstFlowReturn ret = GST_FLOW_OK;
  GstClock *clock;

  clocksync->current_rstart = GST_CLOCK_TIME_NONE;

  if (!clocksync->sync)
    return GST_FLOW_OK;

  if (running_time == GST_CLOCK_TIME_NONE)
    return GST_FLOW_OK;         /* Can't sync on an invalid time either way */

  if (clocksync->segment.format != GST_FORMAT_TIME)
    return GST_FLOW_OK;

  GST_OBJECT_LOCK (clocksync);

  if (clocksync->flushing) {
    GST_OBJECT_UNLOCK (clocksync);
    return GST_FLOW_FLUSHING;
  }

  while (clocksync->blocked && !clocksync->flushing)
    g_cond_wait (&clocksync->blocked_cond, GST_OBJECT_GET_LOCK (clocksync));

  if (clocksync->flushing) {
    GST_OBJECT_UNLOCK (clocksync);
    return GST_FLOW_FLUSHING;
  }

  if ((clock = GST_ELEMENT (clocksync)->clock)) {
    GstClockReturn cret;
    GstClockTime timestamp;
    GstClockTimeDiff ts_offset = clocksync->ts_offset;
    GstClockTimeDiff jitter;

    timestamp = running_time + GST_ELEMENT (clocksync)->base_time +
        clocksync->upstream_latency;

    GST_DEBUG_OBJECT (clocksync,
        "running time: %" GST_TIME_FORMAT " base time: %" GST_TIME_FORMAT
        " upstream latency: %" GST_TIME_FORMAT, GST_TIME_ARGS (running_time),
        GST_TIME_ARGS (GST_ELEMENT (clocksync)->base_time),
        GST_TIME_ARGS (clocksync->upstream_latency));

    GST_DEBUG_OBJECT (clocksync,
        "Waiting for clock time %" GST_TIME_FORMAT " ts offset: %"
        GST_STIME_FORMAT, GST_TIME_ARGS (timestamp),
        GST_STIME_ARGS (ts_offset));

    if (ts_offset < 0) {
      ts_offset = -ts_offset;
      if (ts_offset < timestamp)
        timestamp -= ts_offset;
      else
        timestamp = 0;
    } else {
      timestamp += ts_offset;
    }

    GST_DEBUG_OBJECT (clocksync, "Offset clock time %" GST_TIME_FORMAT,
        GST_TIME_ARGS (timestamp));

    /* save id if we need to unlock */
    clocksync->clock_id = gst_clock_new_single_shot_id (clock, timestamp);
    GST_OBJECT_UNLOCK (clocksync);

    cret = gst_clock_id_wait (clocksync->clock_id, &jitter);

    GST_DEBUG_OBJECT (clocksync, "Clock returned %d, jitter %" GST_STIME_FORMAT,
        cret, GST_STIME_ARGS (jitter));

    GST_OBJECT_LOCK (clocksync);
    if (clocksync->clock_id) {
      gst_clock_id_unref (clocksync->clock_id);
      clocksync->clock_id = NULL;
    }
    if (cret == GST_CLOCK_UNSCHEDULED || clocksync->flushing)
      ret = GST_FLOW_FLUSHING;

    clocksync->current_jitter = jitter;
  }

  clocksync->current_rstart = running_time;
  /* calculate inter frame spacing */
  if (G_UNLIKELY (GST_CLOCK_TIME_IS_VALID (clocksync->prev_rstart) &&
          clocksync->prev_rstart < running_time)) {
    GstClockTime in_diff;

    in_diff = running_time - clocksync->prev_rstart;

    if (clocksync->avg_in_diff == -1)
      clocksync->avg_in_diff = in_diff;
    else
      clocksync->avg_in_diff =
          UPDATE_RUNNING_AVG (clocksync->avg_in_diff, in_diff);

    GST_LOG_OBJECT (clocksync, "avg frame diff %" GST_TIME_FORMAT,
        GST_TIME_ARGS (clocksync->avg_in_diff));
  }
  clocksync->prev_rstart = running_time;

  GST_OBJECT_UNLOCK (clocksync);

  return ret;
}

static gboolean
gst_clock_sync_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
{
  GstClockSync *clocksync = GST_CLOCKSYNC (parent);
  gboolean ret;

  GST_LOG_OBJECT (clocksync, "Received %s event: %" GST_PTR_FORMAT,
      GST_EVENT_TYPE_NAME (event), event);

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_SEGMENT:
      /* store the event for synching */
      gst_event_copy_segment (event, &clocksync->segment);

      if (clocksync->rate > 0.0)
        clocksync->segment.rate *= clocksync->rate;

      gst_clock_sync_reset_qos (clocksync);
      break;
    case GST_EVENT_GAP:
    {
      GstClockTime start, dur;

      if (clocksync->segment.format != GST_FORMAT_TIME)
        break;

      gst_event_parse_gap (event, &start, &dur);
      if (GST_CLOCK_TIME_IS_VALID (start)) {
        start = gst_segment_to_running_time (&clocksync->segment,
            GST_FORMAT_TIME, start);

        gst_clocksync_do_sync (clocksync, start);
      }
      break;
    }
    case GST_EVENT_FLUSH_START:
      GST_OBJECT_LOCK (clocksync);
      clocksync->flushing = TRUE;
      g_cond_signal (&clocksync->blocked_cond);
      if (clocksync->clock_id) {
        GST_DEBUG_OBJECT (clocksync, "unlock clock wait");
        gst_clock_id_unschedule (clocksync->clock_id);
      }
      GST_OBJECT_UNLOCK (clocksync);
      break;
    case GST_EVENT_FLUSH_STOP:
      GST_OBJECT_LOCK (clocksync);
      clocksync->flushing = FALSE;
      gst_segment_init (&clocksync->segment, GST_FORMAT_UNDEFINED);
      GST_OBJECT_UNLOCK (clocksync);
      gst_clock_sync_reset_qos (clocksync);
      g_atomic_int_set (&clocksync->is_first, TRUE);
      break;
    default:
      break;
  }

  /* Always handle all events as normal: */
  ret = gst_pad_event_default (pad, parent, event);
  return ret;
}

static gboolean
gst_clock_sync_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
{
  GstClockSync *clocksync = GST_CLOCKSYNC (parent);

  GST_LOG_OBJECT (clocksync, "Received %s event: %" GST_PTR_FORMAT,
      GST_EVENT_TYPE_NAME (event), event);

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_QOS:
      if (g_atomic_int_get (&clocksync->qos_enabled)) {
        GST_LOG_OBJECT (clocksync,
            "Dropping downstream QoS event as we are responsible for handling QoS");
        gst_event_unref (event);
        return TRUE;
      }
      break;
    default:
      break;
  }

  /* Always handle all events as normal: */
  return gst_pad_event_default (pad, parent, event);
}

static void
gst_clock_sync_update_ts_offset (GstClockSync * clocksync,
    GstClockTime runtimestamp)
{
  GstClock *clock;
  GstClockTimeDiff ts_offset = 0;
  GstClockTime running_time;
  gboolean is_first;

  is_first = g_atomic_int_get (&clocksync->is_first);

  if (!clocksync->sync_to_first || !is_first || !clocksync->sync)
    return;

  GST_OBJECT_LOCK (clocksync);
  clock = GST_ELEMENT_CLOCK (clocksync);
  if (!clock) {
    GST_DEBUG_OBJECT (clocksync, "We have no clock");
    GST_OBJECT_UNLOCK (clocksync);
    return;
  }

  running_time = gst_clock_get_time (clock) -
      GST_ELEMENT_CAST (clocksync)->base_time;
  ts_offset = GST_CLOCK_DIFF (runtimestamp, running_time);
  GST_OBJECT_UNLOCK (clocksync);

  GST_DEBUG_OBJECT (clocksync, "Running time %" GST_TIME_FORMAT
      ", running time stamp %" GST_TIME_FORMAT ", calculated ts-offset %"
      GST_STIME_FORMAT, GST_TIME_ARGS (running_time),
      GST_TIME_ARGS (runtimestamp), GST_STIME_ARGS (ts_offset));

  g_atomic_int_set (&clocksync->is_first, FALSE);
  if (ts_offset != clocksync->ts_offset) {
    clocksync->ts_offset = ts_offset;
    g_object_notify_by_pspec (G_OBJECT (clocksync), properties[PROP_TS_OFFSET]);
  }
}

static GstFlowReturn
gst_clock_sync_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
{
  gboolean performed_qos = FALSE;
  GstClockSync *clocksync = GST_CLOCKSYNC (parent);
  GstFlowReturn ret = GST_FLOW_OK;

  GST_LOG_OBJECT (clocksync, "Handling buffer %" GST_PTR_FORMAT, buf);

  if (clocksync->segment.format == GST_FORMAT_TIME) {
    GstClockTime runtimestamp = 0;
    GstClockTime rundts, runpts;

    if (clocksync->segment.rate > 0.0) {
      rundts = gst_segment_to_running_time (&clocksync->segment,
          GST_FORMAT_TIME, GST_BUFFER_DTS (buf));
      runpts = gst_segment_to_running_time (&clocksync->segment,
          GST_FORMAT_TIME, GST_BUFFER_PTS (buf));
    } else {
      runpts = gst_segment_to_running_time (&clocksync->segment,
          GST_FORMAT_TIME, GST_CLOCK_TIME_IS_VALID (buf->duration)
          && GST_CLOCK_TIME_IS_VALID (buf->pts) ? buf->pts +
          buf->duration : buf->pts);
      rundts = gst_segment_to_running_time (&clocksync->segment,
          GST_FORMAT_TIME, GST_CLOCK_TIME_IS_VALID (buf->duration)
          && GST_CLOCK_TIME_IS_VALID (buf->dts) ? buf->dts +
          buf->duration : buf->dts);
    }

    if (GST_CLOCK_TIME_IS_VALID (rundts))
      runtimestamp = rundts;
    else if (GST_CLOCK_TIME_IS_VALID (runpts))
      runtimestamp = runpts;

    gst_clock_sync_update_ts_offset (clocksync, runtimestamp);

    ret = gst_clocksync_do_sync (clocksync, runtimestamp);
    if (ret != GST_FLOW_OK) {
      GST_LOG_OBJECT (clocksync,
          "Interrupted while waiting on the clock. Dropping buffer.");
      gst_buffer_unref (buf);
      return ret;
    }

    performed_qos = gst_clock_sync_perform_qos (clocksync);
  }

  /* Forward the buffer */
  ret = gst_pad_push (clocksync->srcpad, buf);

  if (performed_qos)
    clocksync->last_left =
        gst_element_get_current_running_time (GST_ELEMENT (parent));

  return ret;
}

static GstFlowReturn
gst_clock_sync_chain_list (GstPad * pad, GstObject * parent,
    GstBufferList * buffer_list)
{
  gboolean performed_qos = FALSE;
  GstClockSync *clocksync = GST_CLOCKSYNC (parent);
  GstFlowReturn ret = GST_FLOW_OK;
  GstBuffer *buf;

  GST_LOG_OBJECT (clocksync, "Handling buffer list %" GST_PTR_FORMAT,
      buffer_list);

  if (gst_buffer_list_length (buffer_list) == 0)
    goto done;

  buf = gst_buffer_list_get (buffer_list, 0);

  if (clocksync->segment.format == GST_FORMAT_TIME) {
    GstClockTime runtimestamp = 0;
    GstClockTime rundts, runpts;

    rundts = gst_segment_to_running_time (&clocksync->segment,
        GST_FORMAT_TIME, GST_BUFFER_DTS (buf));
    runpts = gst_segment_to_running_time (&clocksync->segment,
        GST_FORMAT_TIME, GST_BUFFER_PTS (buf));

    if (GST_CLOCK_TIME_IS_VALID (rundts))
      runtimestamp = rundts;
    else if (GST_CLOCK_TIME_IS_VALID (runpts))
      runtimestamp = runpts;

    gst_clock_sync_update_ts_offset (clocksync, runtimestamp);

    ret = gst_clocksync_do_sync (clocksync, runtimestamp);
    if (ret != GST_FLOW_OK) {
      gst_buffer_list_unref (buffer_list);
      return ret;
    }

    performed_qos = gst_clock_sync_perform_qos (clocksync);
  }

  /* Forward the buffer list */
done:
  ret = gst_pad_push_list (clocksync->srcpad, buffer_list);

  if (performed_qos)
    clocksync->last_left =
        gst_element_get_current_running_time (GST_ELEMENT (parent));

  return ret;
}

static gboolean
gst_clock_sync_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
{
  GstClockSync *clocksync = GST_CLOCKSYNC (parent);
  gboolean res;

  res = gst_pad_query_default (pad, parent, query);

  switch (GST_QUERY_TYPE (query)) {
    case GST_QUERY_LATENCY:{
      gboolean live = FALSE;
      GstClockTime min = 0, max = 0;

      if (res) {
        gst_query_parse_latency (query, &live, &min, &max);

        if (clocksync->sync && max < min) {
          GST_ELEMENT_WARNING (parent, CORE, CLOCK, (NULL),
              ("Impossible to configure latency upstream of clocksync sync=true:"
                  " max %" GST_TIME_FORMAT " < min %"
                  GST_TIME_FORMAT ". Add queues or other buffering elements.",
                  GST_TIME_ARGS (max), GST_TIME_ARGS (min)));
        }
      }

      /* Ignore the upstream latency if it is not live */
      GST_OBJECT_LOCK (clocksync);
      if (live)
        clocksync->upstream_latency = min;
      else {
        clocksync->upstream_latency = 0;
        /* if upstream is non-live source, then there is no
         * limit on the maximum latency */
        max = -1;
      }

      GST_OBJECT_UNLOCK (clocksync);

      GST_DEBUG_OBJECT (clocksync,
          "Configured upstream latency = %" GST_TIME_FORMAT,
          GST_TIME_ARGS (clocksync->upstream_latency));

      gst_query_set_latency (query, live ||
          (clocksync->sync && clocksync->rate == 1.0), min, max);
      break;
    }
    default:
      break;
  }

  return res;
}

static GstStateChangeReturn
gst_clocksync_change_state (GstElement * element, GstStateChange transition)
{
  GstClockSync *clocksync = GST_CLOCKSYNC (element);
  GstStateChangeReturn ret;
  gboolean no_preroll = FALSE;

  switch (transition) {
    case GST_STATE_CHANGE_NULL_TO_READY:
      break;
    case GST_STATE_CHANGE_READY_TO_PAUSED:
      GST_OBJECT_LOCK (clocksync);
      clocksync->flushing = FALSE;
      clocksync->blocked = TRUE;
      GST_OBJECT_UNLOCK (clocksync);
      if (clocksync->sync)
        no_preroll = TRUE;
      g_atomic_int_set (&clocksync->is_first, TRUE);
      break;
    case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
      GST_OBJECT_LOCK (clocksync);
      clocksync->blocked = FALSE;
      g_cond_signal (&clocksync->blocked_cond);
      GST_OBJECT_UNLOCK (clocksync);
      break;
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      GST_OBJECT_LOCK (clocksync);
      clocksync->flushing = TRUE;
      if (clocksync->clock_id) {
        GST_DEBUG_OBJECT (clocksync, "unlock clock wait");
        gst_clock_id_unschedule (clocksync->clock_id);
      }
      clocksync->blocked = FALSE;
      g_cond_signal (&clocksync->blocked_cond);
      GST_OBJECT_UNLOCK (clocksync);
      break;
    default:
      break;
  }

  ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);

  switch (transition) {
    case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
      GST_OBJECT_LOCK (clocksync);
      clocksync->upstream_latency = 0;
      clocksync->blocked = TRUE;
      GST_OBJECT_UNLOCK (clocksync);
      if (clocksync->sync)
        no_preroll = TRUE;
      gst_clock_sync_reset_qos (clocksync);
      break;
    case GST_STATE_CHANGE_PAUSED_TO_READY:
      break;
    case GST_STATE_CHANGE_READY_TO_NULL:
      break;
    default:
      break;
  }

  if (no_preroll && ret == GST_STATE_CHANGE_SUCCESS)
    ret = GST_STATE_CHANGE_NO_PREROLL;

  return ret;
}

/* FIXME: GStreamer 2.0 */
static GstClock *
gst_clocksync_provide_clock (GstElement * element)
{
  GstClockSync *clocksync = GST_CLOCKSYNC (element);

  if (!clocksync->sync)
    return NULL;

  return gst_system_clock_obtain ();
}

static void
gst_clock_sync_resync (GstClockSync * self)
{
  GST_DEBUG_OBJECT (self, "Enable resync");

  g_atomic_int_set (&self->is_first, TRUE);
}