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
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// from gst-gir-files (https://gitlab.freedesktop.org/gstreamer/gir-files-rs.git)
// DO NOT EDIT

use crate::{ClockTime, Object};
use glib::{
    prelude::*,
    signal::{connect_raw, SignalHandlerId},
    translate::*,
};
use std::boxed::Box as Box_;

glib::wrapper! {
    /// GStreamer uses a global clock to synchronize the plugins in a pipeline.
    /// Different clock implementations are possible by implementing this abstract
    /// base class or, more conveniently, by subclassing [`SystemClock`][crate::SystemClock].
    ///
    /// The [`Clock`][crate::Clock] returns a monotonically increasing time with the method
    /// [`ClockExt::time()`][crate::prelude::ClockExt::time()]. Its accuracy and base time depend on the specific
    /// clock implementation but time is always expressed in nanoseconds. Since the
    /// baseline of the clock is undefined, the clock time returned is not
    /// meaningful in itself, what matters are the deltas between two clock times.
    /// The time returned by a clock is called the absolute time.
    ///
    /// The pipeline uses the clock to calculate the running time. Usually all
    /// renderers synchronize to the global clock using the buffer timestamps, the
    /// [`EventType::Segment`][crate::EventType::Segment] events and the element's base time, see [`Pipeline`][crate::Pipeline].
    ///
    /// A clock implementation can support periodic and single shot clock
    /// notifications both synchronous and asynchronous.
    ///
    /// One first needs to create a `GstClockID` for the periodic or single shot
    /// notification using [`ClockExtManual::new_single_shot_id()`][crate::prelude::ClockExtManual::new_single_shot_id()] or
    /// [`ClockExtManual::new_periodic_id()`][crate::prelude::ClockExtManual::new_periodic_id()].
    ///
    /// To perform a blocking wait for the specific time of the `GstClockID` use
    /// `gst_clock_id_wait()`. To receive a callback when the specific time is reached
    /// in the clock use `gst_clock_id_wait_async()`. Both these calls can be
    /// interrupted with the `gst_clock_id_unschedule()` call. If the blocking wait is
    /// unscheduled a return value of [`ClockReturn::Unscheduled`][crate::ClockReturn::Unscheduled] is returned.
    ///
    /// Periodic callbacks scheduled async will be repeatedly called automatically
    /// until they are unscheduled. To schedule a sync periodic callback,
    /// `gst_clock_id_wait()` should be called repeatedly.
    ///
    /// The async callbacks can happen from any thread, either provided by the core
    /// or from a streaming thread. The application should be prepared for this.
    ///
    /// A `GstClockID` that has been unscheduled cannot be used again for any wait
    /// operation, a new `GstClockID` should be created and the old unscheduled one
    /// should be destroyed with `gst_clock_id_unref()`.
    ///
    /// It is possible to perform a blocking wait on the same `GstClockID` from
    /// multiple threads. However, registering the same `GstClockID` for multiple
    /// async notifications is not possible, the callback will only be called for
    /// the thread registering the entry last.
    ///
    /// None of the wait operations unref the `GstClockID`, the owner is responsible
    /// for unreffing the ids itself. This holds for both periodic and single shot
    /// notifications. The reason being that the owner of the `GstClockID` has to
    /// keep a handle to the `GstClockID` to unblock the wait on FLUSHING events or
    /// state changes and if the entry would be unreffed automatically, the handle
    /// might become invalid without any notification.
    ///
    /// These clock operations do not operate on the running time, so the callbacks
    /// will also occur when not in PLAYING state as if the clock just keeps on
    /// running. Some clocks however do not progress when the element that provided
    /// the clock is not PLAYING.
    ///
    /// When a clock has the [`ClockFlags::CAN_SET_MASTER`][crate::ClockFlags::CAN_SET_MASTER] flag set, it can be
    /// slaved to another [`Clock`][crate::Clock] with [`ClockExt::set_master()`][crate::prelude::ClockExt::set_master()]. The clock will
    /// then automatically be synchronized to this master clock by repeatedly
    /// sampling the master clock and the slave clock and recalibrating the slave
    /// clock with [`ClockExt::set_calibration()`][crate::prelude::ClockExt::set_calibration()]. This feature is mostly useful for
    /// plugins that have an internal clock but must operate with another clock
    /// selected by the [`Pipeline`][crate::Pipeline]. They can track the offset and rate difference
    /// of their internal clock relative to the master clock by using the
    /// [`ClockExt::calibration()`][crate::prelude::ClockExt::calibration()] function.
    ///
    /// The master/slave synchronisation can be tuned with the [`timeout`][struct@crate::Clock#timeout],
    /// [`window-size`][struct@crate::Clock#window-size] and [`window-threshold`][struct@crate::Clock#window-threshold] properties.
    /// The [`timeout`][struct@crate::Clock#timeout] property defines the interval to sample the master
    /// clock and run the calibration functions. [`window-size`][struct@crate::Clock#window-size] defines the
    /// number of samples to use when calibrating and [`window-threshold`][struct@crate::Clock#window-threshold]
    /// defines the minimum number of samples before the calibration is performed.
    ///
    /// This is an Abstract Base Class, you cannot instantiate it.
    ///
    /// ## Properties
    ///
    ///
    /// #### `timeout`
    ///  Readable | Writeable
    ///
    ///
    /// #### `window-size`
    ///  Readable | Writeable
    ///
    ///
    /// #### `window-threshold`
    ///  Readable | Writeable
    /// <details><summary><h4>Object</h4></summary>
    ///
    ///
    /// #### `name`
    ///  Readable | Writeable | Construct
    ///
    ///
    /// #### `parent`
    ///  The parent of the object. Please note, that when changing the 'parent'
    /// property, we don't emit [`notify`][struct@crate::glib::Object#notify] and [`deep-notify`][struct@crate::Object#deep-notify]
    /// signals due to locking issues. In some cases one can use
    /// [`element-added`][struct@crate::Bin#element-added] or [`element-removed`][struct@crate::Bin#element-removed] signals on the parent to
    /// achieve a similar effect.
    ///
    /// Readable | Writeable
    /// </details>
    ///
    /// ## Signals
    ///
    ///
    /// #### `synced`
    ///  Signaled on clocks with [`ClockFlags::NEEDS_STARTUP_SYNC`][crate::ClockFlags::NEEDS_STARTUP_SYNC] set once
    /// the clock is synchronized, or when it completely lost synchronization.
    /// This signal will not be emitted on clocks without the flag.
    ///
    /// This signal will be emitted from an arbitrary thread, most likely not
    /// the application's main thread.
    ///
    ///
    /// <details><summary><h4>Object</h4></summary>
    ///
    ///
    /// #### `deep-notify`
    ///  The deep notify signal is used to be notified of property changes. It is
    /// typically attached to the toplevel bin to receive notifications from all
    /// the elements contained in that bin.
    ///
    /// Detailed
    /// </details>
    ///
    /// # Implements
    ///
    /// [`ClockExt`][trait@crate::prelude::ClockExt], [`GstObjectExt`][trait@crate::prelude::GstObjectExt], [`trait@glib::ObjectExt`], [`ClockExtManual`][trait@crate::prelude::ClockExtManual]
    #[doc(alias = "GstClock")]
    pub struct Clock(Object<ffi::GstClock, ffi::GstClockClass>) @extends Object;

    match fn {
        type_ => || ffi::gst_clock_get_type(),
    }
}

impl Clock {
    pub const NONE: Option<&'static Clock> = None;

    //#[doc(alias = "gst_clock_id_compare_func")]
    //pub fn id_compare_func(id1: /*Unimplemented*/Option<Basic: Pointer>, id2: /*Unimplemented*/Option<Basic: Pointer>) -> i32 {
    //    unsafe { TODO: call ffi:gst_clock_id_compare_func() }
    //}

    //#[cfg(feature = "v1_16")]
    //#[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
    //#[doc(alias = "gst_clock_id_get_clock")]
    //pub fn id_get_clock(id: /*Unimplemented*/ClockID) -> Option<Clock> {
    //    unsafe { TODO: call ffi:gst_clock_id_get_clock() }
    //}

    //#[doc(alias = "gst_clock_id_get_time")]
    //pub fn id_get_time(id: /*Unimplemented*/ClockID) -> Option<ClockTime> {
    //    unsafe { TODO: call ffi:gst_clock_id_get_time() }
    //}

    //#[doc(alias = "gst_clock_id_ref")]
    //pub fn id_ref(id: /*Unimplemented*/ClockID) -> /*Unimplemented*/ClockID {
    //    unsafe { TODO: call ffi:gst_clock_id_ref() }
    //}

    //#[doc(alias = "gst_clock_id_unref")]
    //pub fn id_unref(id: /*Unimplemented*/ClockID) {
    //    unsafe { TODO: call ffi:gst_clock_id_unref() }
    //}

    //#[doc(alias = "gst_clock_id_unschedule")]
    //pub fn id_unschedule(id: /*Unimplemented*/ClockID) {
    //    unsafe { TODO: call ffi:gst_clock_id_unschedule() }
    //}

    //#[cfg(feature = "v1_16")]
    //#[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
    //#[doc(alias = "gst_clock_id_uses_clock")]
    //pub fn id_uses_clock(id: /*Unimplemented*/ClockID, clock: &impl IsA<Clock>) -> bool {
    //    unsafe { TODO: call ffi:gst_clock_id_uses_clock() }
    //}

    //#[doc(alias = "gst_clock_id_wait")]
    //pub fn id_wait(id: /*Unimplemented*/ClockID) -> (Result<ClockSuccess, ClockError>, ClockTimeDiff) {
    //    unsafe { TODO: call ffi:gst_clock_id_wait() }
    //}

    //#[doc(alias = "gst_clock_id_wait_async")]
    //pub fn id_wait_async(id: /*Unimplemented*/ClockID, func: /*Unimplemented*/Fn(&Clock, impl Into<Option<ClockTime>>, /*Unimplemented*/ClockID) -> bool, user_data: /*Unimplemented*/Option<Basic: Pointer>) -> Result<ClockSuccess, ClockError> {
    //    unsafe { TODO: call ffi:gst_clock_id_wait_async() }
    //}
}

unsafe impl Send for Clock {}
unsafe impl Sync for Clock {}

mod sealed {
    pub trait Sealed {}
    impl<T: super::IsA<super::Clock>> Sealed for T {}
}

/// Trait containing all [`struct@Clock`] methods.
///
/// # Implementors
///
/// [`Clock`][struct@crate::Clock], [`SystemClock`][struct@crate::SystemClock]
pub trait ClockExt: IsA<Clock> + sealed::Sealed + 'static {
    /// The time `master` of the master clock and the time `slave` of the slave
    /// clock are added to the list of observations. If enough observations
    /// are available, a linear regression algorithm is run on the
    /// observations and `self` is recalibrated.
    ///
    /// If this functions returns [`true`], `r_squared` will contain the
    /// correlation coefficient of the interpolation. A value of 1.0
    /// means a perfect regression was performed. This value can
    /// be used to control the sampling frequency of the master and slave
    /// clocks.
    /// ## `slave`
    /// a time on the slave
    /// ## `master`
    /// a time on the master
    ///
    /// # Returns
    ///
    /// [`true`] if enough observations were added to run the
    /// regression algorithm.
    ///
    /// ## `r_squared`
    /// a pointer to hold the result
    #[doc(alias = "gst_clock_add_observation")]
    fn add_observation(&self, slave: ClockTime, master: ClockTime) -> Option<f64> {
        unsafe {
            let mut r_squared = std::mem::MaybeUninit::uninit();
            let ret = from_glib(ffi::gst_clock_add_observation(
                self.as_ref().to_glib_none().0,
                slave.into_glib(),
                master.into_glib(),
                r_squared.as_mut_ptr(),
            ));
            if ret {
                Some(r_squared.assume_init())
            } else {
                None
            }
        }
    }

    /// Add a clock observation to the internal slaving algorithm the same as
    /// [`add_observation()`][Self::add_observation()], and return the result of the master clock
    /// estimation, without updating the internal calibration.
    ///
    /// The caller can then take the results and call [`set_calibration()`][Self::set_calibration()]
    /// with the values, or some modified version of them.
    /// ## `slave`
    /// a time on the slave
    /// ## `master`
    /// a time on the master
    ///
    /// # Returns
    ///
    /// [`true`] if enough observations were added to run the
    /// regression algorithm.
    ///
    /// ## `r_squared`
    /// a pointer to hold the result
    ///
    /// ## `internal`
    /// a location to store the internal time
    ///
    /// ## `external`
    /// a location to store the external time
    ///
    /// ## `rate_num`
    /// a location to store the rate numerator
    ///
    /// ## `rate_denom`
    /// a location to store the rate denominator
    #[doc(alias = "gst_clock_add_observation_unapplied")]
    fn add_observation_unapplied(
        &self,
        slave: ClockTime,
        master: ClockTime,
    ) -> Option<(f64, ClockTime, ClockTime, ClockTime, ClockTime)> {
        unsafe {
            let mut r_squared = std::mem::MaybeUninit::uninit();
            let mut internal = std::mem::MaybeUninit::uninit();
            let mut external = std::mem::MaybeUninit::uninit();
            let mut rate_num = std::mem::MaybeUninit::uninit();
            let mut rate_denom = std::mem::MaybeUninit::uninit();
            let ret = from_glib(ffi::gst_clock_add_observation_unapplied(
                self.as_ref().to_glib_none().0,
                slave.into_glib(),
                master.into_glib(),
                r_squared.as_mut_ptr(),
                internal.as_mut_ptr(),
                external.as_mut_ptr(),
                rate_num.as_mut_ptr(),
                rate_denom.as_mut_ptr(),
            ));
            if ret {
                Some((
                    r_squared.assume_init(),
                    try_from_glib(internal.assume_init()).expect("mandatory glib value is None"),
                    try_from_glib(external.assume_init()).expect("mandatory glib value is None"),
                    try_from_glib(rate_num.assume_init()).expect("mandatory glib value is None"),
                    try_from_glib(rate_denom.assume_init()).expect("mandatory glib value is None"),
                ))
            } else {
                None
            }
        }
    }

    /// Converts the given `internal` clock time to the external time, adjusting for the
    /// rate and reference time set with [`set_calibration()`][Self::set_calibration()] and making sure
    /// that the returned time is increasing. This function should be called with the
    /// clock's OBJECT_LOCK held and is mainly used by clock subclasses.
    ///
    /// This function is the reverse of [`unadjust_unlocked()`][Self::unadjust_unlocked()].
    /// ## `internal`
    /// a clock time
    ///
    /// # Returns
    ///
    /// the converted time of the clock.
    #[doc(alias = "gst_clock_adjust_unlocked")]
    fn adjust_unlocked(&self, internal: ClockTime) -> Option<ClockTime> {
        unsafe {
            from_glib(ffi::gst_clock_adjust_unlocked(
                self.as_ref().to_glib_none().0,
                internal.into_glib(),
            ))
        }
    }

    /// Gets the internal rate and reference time of `self`. See
    /// [`set_calibration()`][Self::set_calibration()] for more information.
    ///
    /// `internal`, `external`, `rate_num`, and `rate_denom` can be left [`None`] if the
    /// caller is not interested in the values.
    ///
    /// # Returns
    ///
    ///
    /// ## `internal`
    /// a location to store the internal time
    ///
    /// ## `external`
    /// a location to store the external time
    ///
    /// ## `rate_num`
    /// a location to store the rate numerator
    ///
    /// ## `rate_denom`
    /// a location to store the rate denominator
    #[doc(alias = "gst_clock_get_calibration")]
    #[doc(alias = "get_calibration")]
    fn calibration(&self) -> (ClockTime, ClockTime, ClockTime, ClockTime) {
        unsafe {
            let mut internal = std::mem::MaybeUninit::uninit();
            let mut external = std::mem::MaybeUninit::uninit();
            let mut rate_num = std::mem::MaybeUninit::uninit();
            let mut rate_denom = std::mem::MaybeUninit::uninit();
            ffi::gst_clock_get_calibration(
                self.as_ref().to_glib_none().0,
                internal.as_mut_ptr(),
                external.as_mut_ptr(),
                rate_num.as_mut_ptr(),
                rate_denom.as_mut_ptr(),
            );
            (
                try_from_glib(internal.assume_init()).expect("mandatory glib value is None"),
                try_from_glib(external.assume_init()).expect("mandatory glib value is None"),
                try_from_glib(rate_num.assume_init()).expect("mandatory glib value is None"),
                try_from_glib(rate_denom.assume_init()).expect("mandatory glib value is None"),
            )
        }
    }

    /// Gets the current internal time of the given clock. The time is returned
    /// unadjusted for the offset and the rate.
    ///
    /// # Returns
    ///
    /// the internal time of the clock. Or `GST_CLOCK_TIME_NONE` when
    /// given invalid input.
    #[doc(alias = "gst_clock_get_internal_time")]
    #[doc(alias = "get_internal_time")]
    fn internal_time(&self) -> ClockTime {
        unsafe {
            try_from_glib(ffi::gst_clock_get_internal_time(
                self.as_ref().to_glib_none().0,
            ))
            .expect("mandatory glib value is None")
        }
    }

    /// Gets the master clock that `self` is slaved to or [`None`] when the clock is
    /// not slaved to any master clock.
    ///
    /// # Returns
    ///
    /// a master [`Clock`][crate::Clock] or [`None`]
    ///  when this clock is not slaved to a master clock.
    #[doc(alias = "gst_clock_get_master")]
    #[doc(alias = "get_master")]
    #[must_use]
    fn master(&self) -> Option<Clock> {
        unsafe { from_glib_full(ffi::gst_clock_get_master(self.as_ref().to_glib_none().0)) }
    }

    /// Gets the accuracy of the clock. The accuracy of the clock is the granularity
    /// of the values returned by [`time()`][Self::time()].
    ///
    /// # Returns
    ///
    /// the resolution of the clock in units of `GstClockTime`.
    #[doc(alias = "gst_clock_get_resolution")]
    #[doc(alias = "get_resolution")]
    fn resolution(&self) -> ClockTime {
        unsafe {
            try_from_glib(ffi::gst_clock_get_resolution(
                self.as_ref().to_glib_none().0,
            ))
            .expect("mandatory glib value is None")
        }
    }

    /// Gets the current time of the given clock. The time is always
    /// monotonically increasing and adjusted according to the current
    /// offset and rate.
    ///
    /// # Returns
    ///
    /// the time of the clock. Or `GST_CLOCK_TIME_NONE` when
    /// given invalid input.
    #[doc(alias = "gst_clock_get_time")]
    #[doc(alias = "get_time")]
    fn time(&self) -> Option<ClockTime> {
        unsafe { from_glib(ffi::gst_clock_get_time(self.as_ref().to_glib_none().0)) }
    }

    /// Gets the amount of time that master and slave clocks are sampled.
    ///
    /// # Returns
    ///
    /// the interval between samples.
    #[doc(alias = "gst_clock_get_timeout")]
    #[doc(alias = "get_timeout")]
    fn timeout(&self) -> Option<ClockTime> {
        unsafe { from_glib(ffi::gst_clock_get_timeout(self.as_ref().to_glib_none().0)) }
    }

    /// Checks if the clock is currently synced, by looking at whether
    /// [`ClockFlags::NEEDS_STARTUP_SYNC`][crate::ClockFlags::NEEDS_STARTUP_SYNC] is set.
    ///
    /// # Returns
    ///
    /// [`true`] if the clock is currently synced
    #[doc(alias = "gst_clock_is_synced")]
    fn is_synced(&self) -> bool {
        unsafe { from_glib(ffi::gst_clock_is_synced(self.as_ref().to_glib_none().0)) }
    }

    /// Adjusts the rate and time of `self`. A rate of 1/1 is the normal speed of
    /// the clock. Values bigger than 1/1 make the clock go faster.
    ///
    /// `internal` and `external` are calibration parameters that arrange that
    /// [`time()`][Self::time()] should have been `external` at internal time `internal`.
    /// This internal time should not be in the future; that is, it should be less
    /// than the value of [`internal_time()`][Self::internal_time()] when this function is called.
    ///
    /// Subsequent calls to [`time()`][Self::time()] will return clock times computed as
    /// follows:
    ///
    /// **⚠️ The following code is in  C ⚠️**
    ///
    /// ``` C
    ///   time = (internal_time - internal) * rate_num / rate_denom + external
    /// ```
    ///
    /// This formula is implemented in [`adjust_unlocked()`][Self::adjust_unlocked()]. Of course, it
    /// tries to do the integer arithmetic as precisely as possible.
    ///
    /// Note that [`time()`][Self::time()] always returns increasing values so when you
    /// move the clock backwards, [`time()`][Self::time()] will report the previous value
    /// until the clock catches up.
    /// ## `internal`
    /// a reference internal time
    /// ## `external`
    /// a reference external time
    /// ## `rate_num`
    /// the numerator of the rate of the clock relative to its
    ///  internal time
    /// ## `rate_denom`
    /// the denominator of the rate of the clock
    #[doc(alias = "gst_clock_set_calibration")]
    fn set_calibration(
        &self,
        internal: ClockTime,
        external: ClockTime,
        rate_num: ClockTime,
        rate_denom: ClockTime,
    ) {
        unsafe {
            ffi::gst_clock_set_calibration(
                self.as_ref().to_glib_none().0,
                internal.into_glib(),
                external.into_glib(),
                rate_num.into_glib(),
                rate_denom.into_glib(),
            );
        }
    }

    /// Sets `master` as the master clock for `self`. `self` will be automatically
    /// calibrated so that [`time()`][Self::time()] reports the same time as the
    /// master clock.
    ///
    /// A clock provider that slaves its clock to a master can get the current
    /// calibration values with [`calibration()`][Self::calibration()].
    ///
    /// `master` can be [`None`] in which case `self` will not be slaved anymore. It will
    /// however keep reporting its time adjusted with the last configured rate
    /// and time offsets.
    /// ## `master`
    /// a master [`Clock`][crate::Clock]
    ///
    /// # Returns
    ///
    /// [`true`] if the clock is capable of being slaved to a master clock.
    /// Trying to set a master on a clock without the
    /// [`ClockFlags::CAN_SET_MASTER`][crate::ClockFlags::CAN_SET_MASTER] flag will make this function return [`false`].
    #[doc(alias = "gst_clock_set_master")]
    fn set_master(&self, master: Option<&impl IsA<Clock>>) -> Result<(), glib::error::BoolError> {
        unsafe {
            glib::result_from_gboolean!(
                ffi::gst_clock_set_master(
                    self.as_ref().to_glib_none().0,
                    master.map(|p| p.as_ref()).to_glib_none().0
                ),
                "Failed to set master clock"
            )
        }
    }

    /// Sets the accuracy of the clock. Some clocks have the possibility to operate
    /// with different accuracy at the expense of more resource usage. There is
    /// normally no need to change the default resolution of a clock. The resolution
    /// of a clock can only be changed if the clock has the
    /// [`ClockFlags::CAN_SET_RESOLUTION`][crate::ClockFlags::CAN_SET_RESOLUTION] flag set.
    /// ## `resolution`
    /// The resolution to set
    ///
    /// # Returns
    ///
    /// the new resolution of the clock.
    #[doc(alias = "gst_clock_set_resolution")]
    fn set_resolution(&self, resolution: ClockTime) -> ClockTime {
        unsafe {
            try_from_glib(ffi::gst_clock_set_resolution(
                self.as_ref().to_glib_none().0,
                resolution.into_glib(),
            ))
            .expect("mandatory glib value is None")
        }
    }

    /// Sets `self` to synced and emits the [`synced`][struct@crate::Clock#synced] signal, and wakes up any
    /// thread waiting in [`wait_for_sync()`][Self::wait_for_sync()].
    ///
    /// This function must only be called if [`ClockFlags::NEEDS_STARTUP_SYNC`][crate::ClockFlags::NEEDS_STARTUP_SYNC]
    /// is set on the clock, and is intended to be called by subclasses only.
    /// ## `synced`
    /// if the clock is synced
    #[doc(alias = "gst_clock_set_synced")]
    fn set_synced(&self, synced: bool) {
        unsafe {
            ffi::gst_clock_set_synced(self.as_ref().to_glib_none().0, synced.into_glib());
        }
    }

    /// Sets the amount of time, in nanoseconds, to sample master and slave
    /// clocks
    /// ## `timeout`
    /// a timeout
    #[doc(alias = "gst_clock_set_timeout")]
    fn set_timeout(&self, timeout: impl Into<Option<ClockTime>>) {
        unsafe {
            ffi::gst_clock_set_timeout(self.as_ref().to_glib_none().0, timeout.into().into_glib());
        }
    }

    /// Converts the given `external` clock time to the internal time of `self`,
    /// using the rate and reference time set with [`set_calibration()`][Self::set_calibration()].
    /// This function should be called with the clock's OBJECT_LOCK held and
    /// is mainly used by clock subclasses.
    ///
    /// This function is the reverse of [`adjust_unlocked()`][Self::adjust_unlocked()].
    /// ## `external`
    /// an external clock time
    ///
    /// # Returns
    ///
    /// the internal time of the clock corresponding to `external`.
    #[doc(alias = "gst_clock_unadjust_unlocked")]
    fn unadjust_unlocked(&self, external: ClockTime) -> Option<ClockTime> {
        unsafe {
            from_glib(ffi::gst_clock_unadjust_unlocked(
                self.as_ref().to_glib_none().0,
                external.into_glib(),
            ))
        }
    }

    /// Waits until `self` is synced for reporting the current time. If `timeout`
    /// is `GST_CLOCK_TIME_NONE` it will wait forever, otherwise it will time out
    /// after `timeout` nanoseconds.
    ///
    /// For asynchronous waiting, the [`synced`][struct@crate::Clock#synced] signal can be used.
    ///
    /// This returns immediately with [`true`] if [`ClockFlags::NEEDS_STARTUP_SYNC`][crate::ClockFlags::NEEDS_STARTUP_SYNC]
    /// is not set on the clock, or if the clock is already synced.
    /// ## `timeout`
    /// timeout for waiting or `GST_CLOCK_TIME_NONE`
    ///
    /// # Returns
    ///
    /// [`true`] if waiting was successful, or [`false`] on timeout
    #[doc(alias = "gst_clock_wait_for_sync")]
    fn wait_for_sync(
        &self,
        timeout: impl Into<Option<ClockTime>>,
    ) -> Result<(), glib::error::BoolError> {
        unsafe {
            glib::result_from_gboolean!(
                ffi::gst_clock_wait_for_sync(
                    self.as_ref().to_glib_none().0,
                    timeout.into().into_glib()
                ),
                "Timed out waiting for sync"
            )
        }
    }

    #[doc(alias = "window-size")]
    fn window_size(&self) -> i32 {
        ObjectExt::property(self.as_ref(), "window-size")
    }

    #[doc(alias = "window-size")]
    fn set_window_size(&self, window_size: i32) {
        ObjectExt::set_property(self.as_ref(), "window-size", window_size)
    }

    #[doc(alias = "window-threshold")]
    fn window_threshold(&self) -> i32 {
        ObjectExt::property(self.as_ref(), "window-threshold")
    }

    #[doc(alias = "window-threshold")]
    fn set_window_threshold(&self, window_threshold: i32) {
        ObjectExt::set_property(self.as_ref(), "window-threshold", window_threshold)
    }

    /// Signaled on clocks with [`ClockFlags::NEEDS_STARTUP_SYNC`][crate::ClockFlags::NEEDS_STARTUP_SYNC] set once
    /// the clock is synchronized, or when it completely lost synchronization.
    /// This signal will not be emitted on clocks without the flag.
    ///
    /// This signal will be emitted from an arbitrary thread, most likely not
    /// the application's main thread.
    /// ## `synced`
    /// if the clock is synced now
    #[doc(alias = "synced")]
    fn connect_synced<F: Fn(&Self, bool) + Send + Sync + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn synced_trampoline<
            P: IsA<Clock>,
            F: Fn(&P, bool) + Send + Sync + 'static,
        >(
            this: *mut ffi::GstClock,
            synced: glib::ffi::gboolean,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(
                Clock::from_glib_borrow(this).unsafe_cast_ref(),
                from_glib(synced),
            )
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"synced\0".as_ptr() as *const _,
                Some(std::mem::transmute::<_, unsafe extern "C" fn()>(
                    synced_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "timeout")]
    fn connect_timeout_notify<F: Fn(&Self) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_timeout_trampoline<
            P: IsA<Clock>,
            F: Fn(&P) + Send + Sync + 'static,
        >(
            this: *mut ffi::GstClock,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Clock::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::timeout\0".as_ptr() as *const _,
                Some(std::mem::transmute::<_, unsafe extern "C" fn()>(
                    notify_timeout_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "window-size")]
    fn connect_window_size_notify<F: Fn(&Self) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_window_size_trampoline<
            P: IsA<Clock>,
            F: Fn(&P) + Send + Sync + 'static,
        >(
            this: *mut ffi::GstClock,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Clock::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::window-size\0".as_ptr() as *const _,
                Some(std::mem::transmute::<_, unsafe extern "C" fn()>(
                    notify_window_size_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[doc(alias = "window-threshold")]
    fn connect_window_threshold_notify<F: Fn(&Self) + Send + Sync + 'static>(
        &self,
        f: F,
    ) -> SignalHandlerId {
        unsafe extern "C" fn notify_window_threshold_trampoline<
            P: IsA<Clock>,
            F: Fn(&P) + Send + Sync + 'static,
        >(
            this: *mut ffi::GstClock,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(Clock::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::window-threshold\0".as_ptr() as *const _,
                Some(std::mem::transmute::<_, unsafe extern "C" fn()>(
                    notify_window_threshold_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl<O: IsA<Clock>> ClockExt for O {}