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

use std::mem;

use glib::{prelude::*, translate::*};
use gst::LoggableError;
use gst_base::subclass::prelude::*;

use super::prelude::*;
use crate::{ffi, AudioRingBufferSpec, AudioSrc};

pub trait AudioSrcImpl: AudioSrcImplExt + AudioBaseSrcImpl {
    /// close the device
    fn close(&self) -> Result<(), LoggableError> {
        self.parent_close()
    }

    /// the number of frames queued in the device
    fn delay(&self) -> u32 {
        self.parent_delay()
    }

    /// open the device with the specified caps
    fn open(&self) -> Result<(), LoggableError> {
        self.parent_open()
    }

    /// configure device with format
    fn prepare(&self, spec: &mut AudioRingBufferSpec) -> Result<(), LoggableError> {
        AudioSrcImplExt::parent_prepare(self, spec)
    }

    /// undo the configuration
    fn unprepare(&self) -> Result<(), LoggableError> {
        self.parent_unprepare()
    }

    /// Read samples from the device.
    ///
    /// # Returns
    ///
    ///
    /// ## `timestamp`
    /// a `GstClockTime`
    fn read(&self, audio_data: &mut [u8]) -> Result<(u32, Option<gst::ClockTime>), LoggableError> {
        self.parent_read(audio_data)
    }

    /// unblock a read to the device and reset.
    fn reset(&self) {
        self.parent_reset()
    }
}

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

pub trait AudioSrcImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_close(&self) -> Result<(), LoggableError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAudioSrcClass;
            let f = match (*parent_class).close {
                None => return Ok(()),
                Some(f) => f,
            };
            gst::result_from_gboolean!(
                f(self.obj().unsafe_cast_ref::<AudioSrc>().to_glib_none().0),
                gst::CAT_RUST,
                "Failed to close element using the parent function"
            )
        }
    }

    fn parent_delay(&self) -> u32 {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAudioSrcClass;
            let f = match (*parent_class).delay {
                Some(f) => f,
                None => return 0,
            };
            f(self.obj().unsafe_cast_ref::<AudioSrc>().to_glib_none().0)
        }
    }

    fn parent_open(&self) -> Result<(), LoggableError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAudioSrcClass;
            let f = match (*parent_class).open {
                Some(f) => f,
                None => return Ok(()),
            };
            gst::result_from_gboolean!(
                f(self.obj().unsafe_cast_ref::<AudioSrc>().to_glib_none().0),
                gst::CAT_RUST,
                "Failed to open element using the parent function"
            )
        }
    }

    fn parent_prepare(&self, spec: &mut AudioRingBufferSpec) -> Result<(), LoggableError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAudioSrcClass;
            let f = match (*parent_class).prepare {
                Some(f) => f,
                None => return Ok(()),
            };
            gst::result_from_gboolean!(
                f(
                    self.obj().unsafe_cast_ref::<AudioSrc>().to_glib_none().0,
                    &mut spec.0
                ),
                gst::CAT_RUST,
                "Failed to prepare element using the parent function"
            )
        }
    }

    fn parent_unprepare(&self) -> Result<(), LoggableError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAudioSrcClass;
            let f = match (*parent_class).unprepare {
                Some(f) => f,
                None => {
                    return Err(gst::loggable_error!(
                        gst::CAT_RUST,
                        "Unprepare is not implemented!"
                    ))
                }
            };
            gst::result_from_gboolean!(
                f(self.obj().unsafe_cast_ref::<AudioSrc>().to_glib_none().0),
                gst::CAT_RUST,
                "Failed to unprepare element using the parent function"
            )
        }
    }

    fn parent_read(
        &self,
        buffer: &mut [u8],
    ) -> Result<(u32, Option<gst::ClockTime>), LoggableError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAudioSrcClass;
            let f = match (*parent_class).read {
                Some(f) => f,
                None => return Ok((0, gst::ClockTime::NONE)),
            };
            let buffer_ptr = buffer.as_mut_ptr() as *mut _;
            let mut timestamp = mem::MaybeUninit::uninit();
            let ret = f(
                self.obj().unsafe_cast_ref::<AudioSrc>().to_glib_none().0,
                buffer_ptr,
                buffer.len() as u32,
                timestamp.as_mut_ptr(),
            );
            if ret > 0 {
                Ok((ret, from_glib(timestamp.assume_init())))
            } else {
                Err(gst::loggable_error!(
                    gst::CAT_RUST,
                    "Failed to read using the parent function"
                ))
            }
        }
    }

    fn parent_reset(&self) {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstAudioSrcClass;
            if let Some(f) = (*parent_class).reset {
                f(self.obj().unsafe_cast_ref::<AudioSrc>().to_glib_none().0)
            }
        }
    }
}

impl<T: AudioSrcImpl> AudioSrcImplExt for T {}

unsafe impl<T: AudioSrcImpl> IsSubclassable<T> for AudioSrc {
    fn class_init(klass: &mut glib::Class<Self>) {
        Self::parent_class_init::<T>(klass);
        let klass = klass.as_mut();
        klass.close = Some(audiosrc_close::<T>);
        klass.delay = Some(audiosrc_delay::<T>);
        klass.open = Some(audiosrc_open::<T>);
        klass.prepare = Some(audiosrc_prepare::<T>);
        klass.unprepare = Some(audiosrc_unprepare::<T>);
        klass.read = Some(audiosrc_read::<T>);
        klass.reset = Some(audiosrc_reset::<T>);
    }
}

unsafe extern "C" fn audiosrc_close<T: AudioSrcImpl>(
    ptr: *mut ffi::GstAudioSrc,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    gst::panic_to_error!(imp, false, {
        match imp.close() {
            Ok(()) => true,
            Err(err) => {
                err.log_with_imp(imp);
                false
            }
        }
    })
    .into_glib()
}

unsafe extern "C" fn audiosrc_delay<T: AudioSrcImpl>(ptr: *mut ffi::GstAudioSrc) -> u32 {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    gst::panic_to_error!(imp, 0, { imp.delay() })
}

unsafe extern "C" fn audiosrc_open<T: AudioSrcImpl>(
    ptr: *mut ffi::GstAudioSrc,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    gst::panic_to_error!(imp, false, {
        match imp.open() {
            Ok(()) => true,
            Err(err) => {
                err.log_with_imp(imp);
                false
            }
        }
    })
    .into_glib()
}

unsafe extern "C" fn audiosrc_prepare<T: AudioSrcImpl>(
    ptr: *mut ffi::GstAudioSrc,
    spec: *mut ffi::GstAudioRingBufferSpec,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let spec = &mut *(spec as *mut AudioRingBufferSpec);

    gst::panic_to_error!(imp, false, {
        match AudioSrcImpl::prepare(imp, spec) {
            Ok(()) => true,
            Err(err) => {
                err.log_with_imp(imp);
                false
            }
        }
    })
    .into_glib()
}

unsafe extern "C" fn audiosrc_unprepare<T: AudioSrcImpl>(
    ptr: *mut ffi::GstAudioSrc,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    gst::panic_to_error!(imp, false, {
        match imp.unprepare() {
            Ok(()) => true,
            Err(err) => {
                err.log_with_imp(imp);
                false
            }
        }
    })
    .into_glib()
}

unsafe extern "C" fn audiosrc_read<T: AudioSrcImpl>(
    ptr: *mut ffi::GstAudioSrc,
    data: glib::ffi::gpointer,
    length: u32,
    timestamp: *mut gst::ffi::GstClockTime,
) -> u32 {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let data_slice = if length == 0 {
        &mut []
    } else {
        std::slice::from_raw_parts_mut(data as *mut u8, length as usize)
    };

    gst::panic_to_error!(imp, 0, {
        let (res, timestamp_res) = imp.read(data_slice).unwrap_or((0, gst::ClockTime::NONE));
        *timestamp = timestamp_res.into_glib();

        res
    })
}

unsafe extern "C" fn audiosrc_reset<T: AudioSrcImpl>(ptr: *mut ffi::GstAudioSrc) {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    gst::panic_to_error!(imp, (), {
        imp.reset();
    });
}