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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{
    cmp,
    marker::Unpin,
    pin::Pin,
    ptr,
    sync::{atomic, atomic::AtomicI32},
};

use futures_core::{Future, Stream};
use glib::{
    ffi::{gboolean, gpointer},
    prelude::*,
    translate::*,
};
use libc::c_void;

use crate::{
    ffi, prelude::*, Clock, ClockEntryType, ClockError, ClockFlags, ClockReturn, ClockSuccess,
    ClockTime, ClockTimeDiff,
};

glib::wrapper! {
    #[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
    pub struct ClockId(Shared<c_void>);

    match fn {
        ref => |ptr| ffi::gst_clock_id_ref(ptr),
        unref => |ptr| ffi::gst_clock_id_unref(ptr),
    }
}

impl ClockId {
    #[doc(alias = "get_time")]
    #[doc(alias = "gst_clock_id_get_time")]
    #[doc(alias = "GST_CLOCK_ENTRY_TIME")]
    pub fn time(&self) -> ClockTime {
        unsafe {
            try_from_glib(ffi::gst_clock_id_get_time(self.to_glib_none().0))
                .expect("undefined time")
        }
    }

    #[doc(alias = "gst_clock_id_unschedule")]
    pub fn unschedule(&self) {
        unsafe { ffi::gst_clock_id_unschedule(self.to_glib_none().0) }
    }

    #[doc(alias = "gst_clock_id_wait")]
    pub fn wait(&self) -> (Result<ClockSuccess, ClockError>, ClockTimeDiff) {
        unsafe {
            let mut jitter = 0;
            let res = try_from_glib(ffi::gst_clock_id_wait(self.to_glib_none().0, &mut jitter));
            (res, jitter)
        }
    }

    #[doc(alias = "gst_clock_id_compare_func")]
    pub fn compare_by_time(&self, other: &Self) -> cmp::Ordering {
        unsafe {
            let res = ffi::gst_clock_id_compare_func(self.to_glib_none().0, other.to_glib_none().0);
            res.cmp(&0)
        }
    }

    #[cfg(feature = "v1_16")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
    #[doc(alias = "get_clock")]
    #[doc(alias = "gst_clock_id_get_clock")]
    pub fn clock(&self) -> Option<Clock> {
        unsafe { from_glib_full(ffi::gst_clock_id_get_clock(self.to_glib_none().0)) }
    }

    #[cfg(feature = "v1_16")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v1_16")))]
    #[doc(alias = "gst_clock_id_uses_clock")]
    pub fn uses_clock<P: IsA<Clock>>(&self, clock: &P) -> bool {
        unsafe {
            from_glib(ffi::gst_clock_id_uses_clock(
                self.to_glib_none().0,
                clock.as_ref().as_ptr(),
            ))
        }
    }

    #[doc(alias = "get_type")]
    #[doc(alias = "GST_CLOCK_ENTRY_TYPE")]
    pub fn type_(&self) -> ClockEntryType {
        unsafe {
            let ptr = self.as_ptr() as *mut ffi::GstClockEntry;
            from_glib((*ptr).type_)
        }
    }

    #[doc(alias = "get_status")]
    #[doc(alias = "GST_CLOCK_ENTRY_STATUS")]
    pub fn status(&self) -> &AtomicClockReturn {
        unsafe {
            let ptr = self.as_ptr() as *mut ffi::GstClockEntry;
            &*((&(*ptr).status) as *const i32 as *const AtomicClockReturn)
        }
    }
}

#[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct SingleShotClockId(ClockId);

impl std::ops::Deref for SingleShotClockId {
    type Target = ClockId;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<SingleShotClockId> for ClockId {
    #[inline]
    fn from(id: SingleShotClockId) -> ClockId {
        skip_assert_initialized!();
        id.0
    }
}

impl TryFrom<ClockId> for SingleShotClockId {
    type Error = glib::BoolError;

    #[inline]
    fn try_from(id: ClockId) -> Result<SingleShotClockId, glib::BoolError> {
        skip_assert_initialized!();
        match id.type_() {
            ClockEntryType::Single => Ok(SingleShotClockId(id)),
            _ => Err(glib::bool_error!("Not a single-shot clock id")),
        }
    }
}

impl SingleShotClockId {
    #[doc(alias = "gst_clock_id_compare_func")]
    #[inline]
    pub fn compare_by_time(&self, other: &Self) -> cmp::Ordering {
        self.0.compare_by_time(&other.0)
    }

    #[doc(alias = "gst_clock_id_wait_async")]
    pub fn wait_async<F>(&self, func: F) -> Result<ClockSuccess, ClockError>
    where
        F: FnOnce(&Clock, Option<ClockTime>, &ClockId) + Send + 'static,
    {
        unsafe extern "C" fn trampoline<
            F: FnOnce(&Clock, Option<ClockTime>, &ClockId) + Send + 'static,
        >(
            clock: *mut ffi::GstClock,
            time: ffi::GstClockTime,
            id: gpointer,
            func: gpointer,
        ) -> gboolean {
            let f: &mut Option<F> = &mut *(func as *mut Option<F>);
            let f = f.take().unwrap();

            f(
                &from_glib_borrow(clock),
                from_glib(time),
                &from_glib_borrow(id),
            );

            glib::ffi::GTRUE
        }

        unsafe extern "C" fn destroy_notify<
            F: FnOnce(&Clock, Option<ClockTime>, &ClockId) + Send + 'static,
        >(
            ptr: gpointer,
        ) {
            let _ = Box::<Option<F>>::from_raw(ptr as *mut _);
        }

        let func: Box<Option<F>> = Box::new(Some(func));

        unsafe {
            try_from_glib(ffi::gst_clock_id_wait_async(
                self.to_glib_none().0,
                Some(trampoline::<F>),
                Box::into_raw(func) as gpointer,
                Some(destroy_notify::<F>),
            ))
        }
    }

    #[allow(clippy::type_complexity)]
    pub fn wait_async_future(
        &self,
    ) -> Result<
        Pin<
            Box<
                dyn Future<Output = Result<(Option<ClockTime>, ClockId), ClockError>>
                    + Send
                    + 'static,
            >,
        >,
        ClockError,
    > {
        use futures_channel::oneshot;

        let (sender, receiver) = oneshot::channel();

        self.wait_async(move |_clock, jitter, id| {
            if sender.send((jitter, id.clone())).is_err() {
                // Unschedule any future calls if the receiver end is disconnected
                id.unschedule();
            }
        })?;

        Ok(Box::pin(async move {
            receiver.await.map_err(|_| ClockError::Unscheduled)
        }))
    }
}

#[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct PeriodicClockId(ClockId);

impl std::ops::Deref for PeriodicClockId {
    type Target = ClockId;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<PeriodicClockId> for ClockId {
    #[inline]
    fn from(id: PeriodicClockId) -> ClockId {
        skip_assert_initialized!();
        id.0
    }
}

impl TryFrom<ClockId> for PeriodicClockId {
    type Error = glib::BoolError;

    #[inline]
    fn try_from(id: ClockId) -> Result<PeriodicClockId, glib::BoolError> {
        skip_assert_initialized!();
        match id.type_() {
            ClockEntryType::Periodic => Ok(PeriodicClockId(id)),
            _ => Err(glib::bool_error!("Not a periodic clock id")),
        }
    }
}

impl PeriodicClockId {
    #[doc(alias = "get_interval")]
    #[doc(alias = "GST_CLOCK_ENTRY_INTERVAL")]
    #[inline]
    pub fn interval(&self) -> ClockTime {
        unsafe {
            let ptr = self.as_ptr() as *mut ffi::GstClockEntry;
            try_from_glib((*ptr).interval).expect("undefined interval")
        }
    }

    #[doc(alias = "gst_clock_id_compare_func")]
    #[inline]
    pub fn compare_by_time(&self, other: &Self) -> cmp::Ordering {
        self.0.compare_by_time(&other.0)
    }

    #[doc(alias = "gst_clock_id_wait_async")]
    pub fn wait_async<F>(&self, func: F) -> Result<ClockSuccess, ClockError>
    where
        F: Fn(&Clock, Option<ClockTime>, &ClockId) + Send + 'static,
    {
        unsafe extern "C" fn trampoline<
            F: Fn(&Clock, Option<ClockTime>, &ClockId) + Send + 'static,
        >(
            clock: *mut ffi::GstClock,
            time: ffi::GstClockTime,
            id: gpointer,
            func: gpointer,
        ) -> gboolean {
            let f: &F = &*(func as *const F);
            f(
                &from_glib_borrow(clock),
                from_glib(time),
                &from_glib_borrow(id),
            );
            glib::ffi::GTRUE
        }

        unsafe extern "C" fn destroy_notify<
            F: Fn(&Clock, Option<ClockTime>, &ClockId) + Send + 'static,
        >(
            ptr: gpointer,
        ) {
            let _ = Box::<F>::from_raw(ptr as *mut _);
        }

        let func: Box<F> = Box::new(func);
        unsafe {
            try_from_glib(ffi::gst_clock_id_wait_async(
                self.to_glib_none().0,
                Some(trampoline::<F>),
                Box::into_raw(func) as gpointer,
                Some(destroy_notify::<F>),
            ))
        }
    }

    #[allow(clippy::type_complexity)]
    pub fn wait_async_stream(
        &self,
    ) -> Result<
        Pin<Box<dyn Stream<Item = (Option<ClockTime>, ClockId)> + Unpin + Send + 'static>>,
        ClockError,
    > {
        use futures_channel::mpsc;

        let (sender, receiver) = mpsc::unbounded();

        self.wait_async(move |_clock, jitter, id| {
            if sender.unbounded_send((jitter, id.clone())).is_err() {
                // Unschedule any future calls if the receiver end is disconnected
                id.unschedule();
            }
        })?;

        Ok(Box::pin(receiver))
    }
}

#[repr(transparent)]
#[derive(Debug)]
pub struct AtomicClockReturn(AtomicI32);

impl AtomicClockReturn {
    #[inline]
    pub fn load(&self) -> ClockReturn {
        unsafe { from_glib(self.0.load(atomic::Ordering::SeqCst)) }
    }

    #[inline]
    pub fn store(&self, val: ClockReturn) {
        self.0.store(val.into_glib(), atomic::Ordering::SeqCst)
    }

    #[inline]
    pub fn swap(&self, val: ClockReturn) -> ClockReturn {
        unsafe { from_glib(self.0.swap(val.into_glib(), atomic::Ordering::SeqCst)) }
    }

    #[inline]
    pub fn compare_exchange(
        &self,
        current: ClockReturn,
        new: ClockReturn,
    ) -> Result<ClockReturn, ClockReturn> {
        unsafe {
            self.0
                .compare_exchange(
                    current.into_glib(),
                    new.into_glib(),
                    atomic::Ordering::SeqCst,
                    atomic::Ordering::SeqCst,
                )
                .map(|v| from_glib(v))
                .map_err(|v| from_glib(v))
        }
    }
}

unsafe impl Send for ClockId {}
unsafe impl Sync for ClockId {}

impl Clock {
    #[doc(alias = "gst_clock_adjust_with_calibration")]
    pub fn adjust_with_calibration(
        internal_target: ClockTime,
        cinternal: ClockTime,
        cexternal: ClockTime,
        cnum: u64,
        cdenom: u64,
    ) -> ClockTime {
        skip_assert_initialized!();
        unsafe {
            try_from_glib(ffi::gst_clock_adjust_with_calibration(
                ptr::null_mut(),
                internal_target.into_glib(),
                cinternal.into_glib(),
                cexternal.into_glib(),
                cnum,
                cdenom,
            ))
            .expect("undefined ClockTime")
        }
    }

    #[doc(alias = "gst_clock_unadjust_with_calibration")]
    pub fn unadjust_with_calibration(
        external_target: ClockTime,
        cinternal: ClockTime,
        cexternal: ClockTime,
        cnum: u64,
        cdenom: u64,
    ) -> ClockTime {
        skip_assert_initialized!();
        unsafe {
            try_from_glib(ffi::gst_clock_unadjust_with_calibration(
                ptr::null_mut(),
                external_target.into_glib(),
                cinternal.into_glib(),
                cexternal.into_glib(),
                cnum,
                cdenom,
            ))
            .expect("undefined ClockTime")
        }
    }
}

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

pub trait ClockExtManual: sealed::Sealed + IsA<Clock> + 'static {
    /// Gets an ID from `self` to trigger a periodic notification.
    /// The periodic notifications will start at time `start_time` and
    /// will then be fired with the given `interval`.
    /// ## `start_time`
    /// the requested start time
    /// ## `interval`
    /// the requested interval
    ///
    /// # Returns
    ///
    /// a `GstClockID` that can be used to request the
    ///  time notification.
    #[doc(alias = "gst_clock_new_periodic_id")]
    fn new_periodic_id(&self, start_time: ClockTime, interval: ClockTime) -> PeriodicClockId {
        assert_ne!(interval, ClockTime::ZERO);

        unsafe {
            PeriodicClockId(from_glib_full(ffi::gst_clock_new_periodic_id(
                self.as_ref().to_glib_none().0,
                start_time.into_glib(),
                interval.into_glib(),
            )))
        }
    }

    /// Reinitializes the provided periodic `id` to the provided start time and
    /// interval. Does not modify the reference count.
    /// ## `id`
    /// a `GstClockID`
    /// ## `start_time`
    /// the requested start time
    /// ## `interval`
    /// the requested interval
    ///
    /// # Returns
    ///
    /// [`true`] if the GstClockID could be reinitialized to the provided
    /// `time`, else [`false`].
    #[doc(alias = "gst_clock_periodic_id_reinit")]
    fn periodic_id_reinit(
        &self,
        id: &PeriodicClockId,
        start_time: ClockTime,
        interval: ClockTime,
    ) -> Result<(), glib::BoolError> {
        unsafe {
            let res: bool = from_glib(ffi::gst_clock_periodic_id_reinit(
                self.as_ref().to_glib_none().0,
                id.to_glib_none().0,
                start_time.into_glib(),
                interval.into_glib(),
            ));
            if res {
                Ok(())
            } else {
                Err(glib::bool_error!("Failed to reinit periodic clock id"))
            }
        }
    }

    /// Gets a `GstClockID` from `self` to trigger a single shot
    /// notification at the requested time.
    /// ## `time`
    /// the requested time
    ///
    /// # Returns
    ///
    /// a `GstClockID` that can be used to request the
    ///  time notification.
    #[doc(alias = "gst_clock_new_single_shot_id")]
    fn new_single_shot_id(&self, time: ClockTime) -> SingleShotClockId {
        unsafe {
            SingleShotClockId(from_glib_full(ffi::gst_clock_new_single_shot_id(
                self.as_ref().to_glib_none().0,
                time.into_glib(),
            )))
        }
    }

    /// Reinitializes the provided single shot `id` to the provided time. Does not
    /// modify the reference count.
    /// ## `id`
    /// a `GstClockID`
    /// ## `time`
    /// The requested time.
    ///
    /// # Returns
    ///
    /// [`true`] if the GstClockID could be reinitialized to the provided
    /// `time`, else [`false`].
    #[doc(alias = "gst_clock_single_shot_id_reinit")]
    fn single_shot_id_reinit(
        &self,
        id: &SingleShotClockId,
        time: ClockTime,
    ) -> Result<(), glib::BoolError> {
        unsafe {
            let res: bool = from_glib(ffi::gst_clock_single_shot_id_reinit(
                self.as_ref().to_glib_none().0,
                id.to_glib_none().0,
                time.into_glib(),
            ));
            if res {
                Ok(())
            } else {
                Err(glib::bool_error!("Failed to reinit single shot clock id"))
            }
        }
    }

    fn set_clock_flags(&self, flags: ClockFlags) {
        unsafe {
            let ptr: *mut ffi::GstObject = self.as_ptr() as *mut _;
            let _guard = self.as_ref().object_lock();
            (*ptr).flags |= flags.into_glib();
        }
    }

    fn unset_clock_flags(&self, flags: ClockFlags) {
        unsafe {
            let ptr: *mut ffi::GstObject = self.as_ptr() as *mut _;
            let _guard = self.as_ref().object_lock();
            (*ptr).flags &= !flags.into_glib();
        }
    }

    #[doc(alias = "get_clock_flags")]
    fn clock_flags(&self) -> ClockFlags {
        unsafe {
            let ptr: *mut ffi::GstObject = self.as_ptr() as *mut _;
            let _guard = self.as_ref().object_lock();
            from_glib((*ptr).flags)
        }
    }

    /// 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, u64, u64) {
        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"),
                rate_num.assume_init(),
                rate_denom.assume_init(),
            )
        }
    }

    /// 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
    /// [`ClockExt::time()`][crate::prelude::ClockExt::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 [`ClockExt::internal_time()`][crate::prelude::ClockExt::internal_time()] when this function is called.
    ///
    /// Subsequent calls to [`ClockExt::time()`][crate::prelude::ClockExt::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 [`ClockExt::adjust_unlocked()`][crate::prelude::ClockExt::adjust_unlocked()]. Of course, it
    /// tries to do the integer arithmetic as precisely as possible.
    ///
    /// Note that [`ClockExt::time()`][crate::prelude::ClockExt::time()] always returns increasing values so when you
    /// move the clock backwards, [`ClockExt::time()`][crate::prelude::ClockExt::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: u64,
        rate_denom: u64,
    ) {
        unsafe {
            ffi::gst_clock_set_calibration(
                self.as_ref().to_glib_none().0,
                internal.into_glib(),
                external.into_glib(),
                rate_num,
                rate_denom,
            );
        }
    }
}

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

#[cfg(test)]
mod tests {
    use std::sync::mpsc::channel;

    use super::*;
    use crate::SystemClock;

    #[test]
    fn test_wait() {
        crate::init().unwrap();

        let clock = SystemClock::obtain();
        let now = clock.time().unwrap();
        let id = clock.new_single_shot_id(now + 20 * ClockTime::MSECOND);
        let (res, _) = id.wait();

        assert!(res == Ok(ClockSuccess::Ok) || res == Err(ClockError::Early));
    }

    #[test]
    fn test_wait_async() {
        crate::init().unwrap();

        let (sender, receiver) = channel();

        let clock = SystemClock::obtain();
        let now = clock.time().unwrap();
        let id = clock.new_single_shot_id(now + 20 * ClockTime::MSECOND);
        let res = id.wait_async(move |_, _, _| {
            sender.send(()).unwrap();
        });

        assert!(res == Ok(ClockSuccess::Ok));

        assert_eq!(receiver.recv(), Ok(()));
    }

    #[test]
    fn test_wait_periodic() {
        crate::init().unwrap();

        let clock = SystemClock::obtain();
        let now = clock.time().unwrap();
        let id = clock.new_periodic_id(now + 20 * ClockTime::MSECOND, 20 * ClockTime::MSECOND);

        let (res, _) = id.wait();
        assert!(res == Ok(ClockSuccess::Ok) || res == Err(ClockError::Early));

        let (res, _) = id.wait();
        assert!(res == Ok(ClockSuccess::Ok) || res == Err(ClockError::Early));
    }

    #[test]
    fn test_wait_async_periodic() {
        crate::init().unwrap();

        let (sender, receiver) = channel();

        let clock = SystemClock::obtain();
        let now = clock.time().unwrap();
        let id = clock.new_periodic_id(now + 20 * ClockTime::MSECOND, 20 * ClockTime::MSECOND);
        let res = id.wait_async(move |_, _, _| {
            let _ = sender.send(());
        });

        assert!(res == Ok(ClockSuccess::Ok));

        assert_eq!(receiver.recv(), Ok(()));
        assert_eq!(receiver.recv(), Ok(()));
    }
}