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

use glib::{prelude::*, subclass::prelude::*, translate::*};

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

pub trait ClockImpl: ClockImplExt + GstObjectImpl + Send + Sync {
    /// Change the resolution of the clock. Not all values might
    /// be acceptable.
    /// ## `old_resolution`
    /// the previous resolution
    /// ## `new_resolution`
    /// the new resolution
    ///
    /// # Returns
    ///
    /// the new resolution
    fn change_resolution(&self, old_resolution: ClockTime, new_resolution: ClockTime) -> ClockTime {
        self.parent_change_resolution(old_resolution, new_resolution)
    }

    /// Gets the accuracy of the clock. The accuracy of the clock is the granularity
    /// of the values returned by [`ClockExt::time()`][crate::prelude::ClockExt::time()].
    ///
    /// # Returns
    ///
    /// the resolution of the clock in units of `GstClockTime`.
    fn resolution(&self) -> ClockTime {
        self.parent_resolution()
    }

    /// 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.
    fn internal_time(&self) -> ClockTime {
        self.parent_internal_time()
    }

    /// Perform a blocking wait on the given `GstClockEntry` and return
    /// the jitter.
    /// ## `entry`
    /// the entry to wait on
    ///
    /// # Returns
    ///
    /// the result of the blocking wait. [`ClockReturn::Early`][crate::ClockReturn::Early] will be returned
    /// if the current clock time is past the time of `id`, [`ClockReturn::Ok`][crate::ClockReturn::Ok] if
    /// `id` was scheduled in time. [`ClockReturn::Unscheduled`][crate::ClockReturn::Unscheduled] if `id` was
    /// unscheduled with `gst_clock_id_unschedule()`.
    ///
    /// ## `jitter`
    /// a pointer that will contain the jitter
    fn wait(&self, id: &ClockId) -> (Result<ClockSuccess, ClockError>, ClockTimeDiff) {
        self.parent_wait(id)
    }

    /// Perform an asynchronous wait on the given `GstClockEntry`.
    /// ## `entry`
    /// the entry to wait on
    ///
    /// # Returns
    ///
    /// the result of the non blocking wait.
    fn wait_async(&self, id: &ClockId) -> Result<ClockSuccess, ClockError> {
        self.parent_wait_async(id)
    }

    /// Unblock a blocking or async wait operation.
    /// ## `entry`
    /// the entry to unschedule
    fn unschedule(&self, id: &ClockId) {
        self.parent_unschedule(id)
    }
}

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

pub trait ClockImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_change_resolution(
        &self,
        old_resolution: ClockTime,
        new_resolution: ClockTime,
    ) -> ClockTime;

    fn parent_resolution(&self) -> ClockTime {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstClockClass;

            try_from_glib(
                (*parent_class)
                    .get_resolution
                    .map(|f| f(self.obj().unsafe_cast_ref::<Clock>().to_glib_none().0))
                    .unwrap_or(1),
            )
            .expect("undefined resolution")
        }
    }

    fn parent_internal_time(&self) -> ClockTime {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstClockClass;

            try_from_glib(
                (*parent_class)
                    .get_internal_time
                    .map(|f| f(self.obj().unsafe_cast_ref::<Clock>().to_glib_none().0))
                    .unwrap_or(0),
            )
            .expect("undefined internal_time")
        }
    }

    fn parent_wait(&self, id: &ClockId) -> (Result<ClockSuccess, ClockError>, ClockTimeDiff) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstClockClass;
            let mut jitter = 0;

            (
                try_from_glib(
                    (*parent_class)
                        .wait
                        .map(|f| {
                            f(
                                self.obj().unsafe_cast_ref::<Clock>().to_glib_none().0,
                                id.as_ptr() as *mut ffi::GstClockEntry,
                                &mut jitter,
                            )
                        })
                        .unwrap_or(ffi::GST_CLOCK_UNSUPPORTED),
                ),
                jitter,
            )
        }
    }

    fn parent_wait_async(&self, id: &ClockId) -> Result<ClockSuccess, ClockError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstClockClass;
            try_from_glib(
                (*parent_class)
                    .wait_async
                    .map(|f| {
                        f(
                            self.obj().unsafe_cast_ref::<Clock>().to_glib_none().0,
                            id.as_ptr() as *mut ffi::GstClockEntry,
                        )
                    })
                    .unwrap_or(ffi::GST_CLOCK_UNSUPPORTED),
            )
        }
    }

    fn parent_unschedule(&self, id: &ClockId) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstClockClass;
            if let Some(func) = (*parent_class).unschedule {
                func(
                    self.obj().unsafe_cast_ref::<Clock>().to_glib_none().0,
                    id.as_ptr() as *mut ffi::GstClockEntry,
                );
            }
        }
    }

    fn wake_id(&self, id: &ClockId) {
        let clock = self.obj();
        let clock = unsafe { clock.unsafe_cast_ref::<Clock>() };

        cfg_if::cfg_if! {
            if #[cfg(feature = "v1_16")] {
                assert!(id.uses_clock(clock));
            } else {
                unsafe {
                    let ptr = id.as_ptr() as *mut ffi::GstClockEntry;
                    assert_eq!((*ptr).clock, clock.to_glib_none().0);
                }
            }
        }

        unsafe {
            let ptr = id.as_ptr() as *mut ffi::GstClockEntry;
            if let Some(func) = (*ptr).func {
                func(
                    clock.to_glib_none().0,
                    (*ptr).time,
                    ptr as ffi::GstClockID,
                    (*ptr).user_data,
                );
            }
            if (*ptr).type_ == ffi::GST_CLOCK_ENTRY_PERIODIC {
                (*ptr).time += (*ptr).interval;
            }
        }
    }
}

impl<T: ClockImpl> ClockImplExt for T {
    fn parent_change_resolution(
        &self,
        old_resolution: ClockTime,
        new_resolution: ClockTime,
    ) -> ClockTime {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstClockClass;

            if let Some(func) = (*parent_class).change_resolution {
                try_from_glib(func(
                    self.obj().unsafe_cast_ref::<Clock>().to_glib_none().0,
                    old_resolution.into_glib(),
                    new_resolution.into_glib(),
                ))
                .expect("undefined resolution")
            } else {
                self.resolution()
            }
        }
    }
}

unsafe impl<T: ClockImpl> IsSubclassable<T> for Clock {
    fn class_init(klass: &mut glib::Class<Self>) {
        Self::parent_class_init::<T>(klass);
        let klass = klass.as_mut();
        klass.change_resolution = Some(clock_change_resolution::<T>);
        klass.get_resolution = Some(clock_get_resolution::<T>);
        klass.get_internal_time = Some(clock_get_internal_time::<T>);
        klass.wait = Some(clock_wait::<T>);
        klass.wait_async = Some(clock_wait_async::<T>);
        klass.unschedule = Some(clock_unschedule::<T>);
    }
}

unsafe extern "C" fn clock_change_resolution<T: ClockImpl>(
    ptr: *mut ffi::GstClock,
    old_resolution: ffi::GstClockTime,
    new_resolution: ffi::GstClockTime,
) -> ffi::GstClockTime {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let old_resolution = match from_glib(old_resolution) {
        Some(old_resolution) => old_resolution,
        None => return ffi::GST_CLOCK_TIME_NONE,
    };
    let new_resolution = match from_glib(new_resolution) {
        Some(new_resolution) => new_resolution,
        None => return ffi::GST_CLOCK_TIME_NONE,
    };

    imp.change_resolution(old_resolution, new_resolution)
        .into_glib()
}

unsafe extern "C" fn clock_get_resolution<T: ClockImpl>(
    ptr: *mut ffi::GstClock,
) -> ffi::GstClockTime {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.resolution().into_glib()
}

unsafe extern "C" fn clock_get_internal_time<T: ClockImpl>(
    ptr: *mut ffi::GstClock,
) -> ffi::GstClockTime {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.internal_time().into_glib()
}

unsafe extern "C" fn clock_wait<T: ClockImpl>(
    ptr: *mut ffi::GstClock,
    id: *mut ffi::GstClockEntry,
    jitter: *mut ffi::GstClockTimeDiff,
) -> ffi::GstClockReturn {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let (res, j) = imp.wait(&from_glib_borrow(id as ffi::GstClockID));
    if !jitter.is_null() {
        *jitter = j;
    }

    ClockReturn::from(res).into_glib()
}

unsafe extern "C" fn clock_wait_async<T: ClockImpl>(
    ptr: *mut ffi::GstClock,
    id: *mut ffi::GstClockEntry,
) -> ffi::GstClockReturn {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    ClockReturn::from(imp.wait_async(&from_glib_borrow(id as ffi::GstClockID))).into_glib()
}

unsafe extern "C" fn clock_unschedule<T: ClockImpl>(
    ptr: *mut ffi::GstClock,
    id: *mut ffi::GstClockEntry,
) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    imp.unschedule(&from_glib_borrow(id as ffi::GstClockID));
}