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

use std::mem;

use glib::translate::*;
use gst::subclass::prelude::*;

use crate::{ffi, prelude::*, BaseParse, BaseParseFrame};

pub trait BaseParseImpl: BaseParseImplExt + ElementImpl {
    /// Optional.
    ///  Called when the element starts processing.
    ///  Allows opening external resources.
    fn start(&self) -> Result<(), gst::ErrorMessage> {
        self.parent_start()
    }

    /// Optional.
    ///  Called when the element stops processing.
    ///  Allows closing external resources.
    fn stop(&self) -> Result<(), gst::ErrorMessage> {
        self.parent_stop()
    }

    /// Optional.
    ///  Allows the subclass to be notified of the actual caps set.
    fn set_sink_caps(&self, caps: &gst::Caps) -> Result<(), gst::LoggableError> {
        self.parent_set_sink_caps(caps)
    }

    /// Parses the input data into valid frames as defined by subclass
    /// which should be passed to [`BaseParseExtManual::finish_frame()`][crate::prelude::BaseParseExtManual::finish_frame()].
    /// The frame's input buffer is guaranteed writable,
    /// whereas the input frame ownership is held by caller
    /// (so subclass should make a copy if it needs to hang on).
    /// Input buffer (data) is provided by baseclass with as much
    /// metadata set as possible by baseclass according to upstream
    /// information and/or subclass settings,
    /// though subclass may still set buffer timestamp and duration
    /// if desired.
    ///
    /// # Returns
    ///
    fn handle_frame(
        &self,
        frame: BaseParseFrame,
    ) -> Result<(gst::FlowSuccess, u32), gst::FlowError> {
        self.parent_handle_frame(frame)
    }

    /// Optional.
    ///  Convert between formats.
    fn convert(
        &self,
        src_val: impl gst::format::FormattedValue,
        dest_format: gst::Format,
    ) -> Option<gst::GenericFormattedValue> {
        self.parent_convert(src_val, dest_format)
    }
}

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

pub trait BaseParseImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_start(&self) -> Result<(), gst::ErrorMessage> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBaseParseClass;
            (*parent_class)
                .start
                .map(|f| {
                    if from_glib(f(self
                        .obj()
                        .unsafe_cast_ref::<BaseParse>()
                        .to_glib_none()
                        .0))
                    {
                        Ok(())
                    } else {
                        Err(gst::error_msg!(
                            gst::CoreError::StateChange,
                            ["Parent function `start` failed"]
                        ))
                    }
                })
                .unwrap_or(Ok(()))
        }
    }

    fn parent_stop(&self) -> Result<(), gst::ErrorMessage> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBaseParseClass;
            (*parent_class)
                .stop
                .map(|f| {
                    if from_glib(f(self
                        .obj()
                        .unsafe_cast_ref::<BaseParse>()
                        .to_glib_none()
                        .0))
                    {
                        Ok(())
                    } else {
                        Err(gst::error_msg!(
                            gst::CoreError::StateChange,
                            ["Parent function `stop` failed"]
                        ))
                    }
                })
                .unwrap_or(Ok(()))
        }
    }

    fn parent_set_sink_caps(&self, caps: &gst::Caps) -> Result<(), gst::LoggableError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBaseParseClass;
            (*parent_class)
                .set_sink_caps
                .map(|f| {
                    gst::result_from_gboolean!(
                        f(
                            self.obj().unsafe_cast_ref::<BaseParse>().to_glib_none().0,
                            caps.to_glib_none().0,
                        ),
                        gst::CAT_RUST,
                        "Parent function `set_sink_caps` failed",
                    )
                })
                .unwrap_or(Ok(()))
        }
    }

    fn parent_handle_frame(
        &self,
        frame: BaseParseFrame,
    ) -> Result<(gst::FlowSuccess, u32), gst::FlowError> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBaseParseClass;
            let mut skipsize = 0;
            (*parent_class)
                .handle_frame
                .map(|f| {
                    let res = try_from_glib(f(
                        self.obj().unsafe_cast_ref::<BaseParse>().to_glib_none().0,
                        frame.to_glib_none().0,
                        &mut skipsize,
                    ));
                    (res.unwrap(), skipsize as u32)
                })
                .ok_or(gst::FlowError::Error)
        }
    }

    fn parent_convert(
        &self,
        src_val: impl gst::format::FormattedValue,
        dest_format: gst::Format,
    ) -> Option<gst::GenericFormattedValue> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GstBaseParseClass;
            let res = (*parent_class).convert.map(|f| {
                let mut dest_val = mem::MaybeUninit::uninit();

                let res = from_glib(f(
                    self.obj().unsafe_cast_ref::<BaseParse>().to_glib_none().0,
                    src_val.format().into_glib(),
                    src_val.into_raw_value(),
                    dest_format.into_glib(),
                    dest_val.as_mut_ptr(),
                ));
                (res, dest_val)
            });

            match res {
                Some((true, dest_val)) => Some(gst::GenericFormattedValue::new(
                    dest_format,
                    dest_val.assume_init(),
                )),
                _ => None,
            }
        }
    }
}

impl<T: BaseParseImpl> BaseParseImplExt for T {}

unsafe impl<T: BaseParseImpl> IsSubclassable<T> for BaseParse {
    fn class_init(klass: &mut glib::Class<Self>) {
        Self::parent_class_init::<T>(klass);
        let klass = klass.as_mut();
        klass.start = Some(base_parse_start::<T>);
        klass.stop = Some(base_parse_stop::<T>);
        klass.set_sink_caps = Some(base_parse_set_sink_caps::<T>);
        klass.handle_frame = Some(base_parse_handle_frame::<T>);
        klass.convert = Some(base_parse_convert::<T>);
    }
}

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

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

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

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

unsafe extern "C" fn base_parse_set_sink_caps<T: BaseParseImpl>(
    ptr: *mut ffi::GstBaseParse,
    caps: *mut gst::ffi::GstCaps,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let caps: Borrowed<gst::Caps> = from_glib_borrow(caps);

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

unsafe extern "C" fn base_parse_handle_frame<T: BaseParseImpl>(
    ptr: *mut ffi::GstBaseParse,
    frame: *mut ffi::GstBaseParseFrame,
    skipsize: *mut i32,
) -> gst::ffi::GstFlowReturn {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let instance = imp.obj();
    let instance = instance.unsafe_cast_ref::<BaseParse>();
    let wrap_frame = BaseParseFrame::new(frame, instance);

    let res = gst::panic_to_error!(imp, Err(gst::FlowError::Error), {
        imp.handle_frame(wrap_frame)
    });

    match res {
        Ok((flow, skip)) => {
            *skipsize = i32::try_from(skip).expect("skip is higher than i32::MAX");
            gst::FlowReturn::from_ok(flow)
        }
        Err(flow) => gst::FlowReturn::from_error(flow),
    }
    .into_glib()
}

unsafe extern "C" fn base_parse_convert<T: BaseParseImpl>(
    ptr: *mut ffi::GstBaseParse,
    source_format: gst::ffi::GstFormat,
    source_value: i64,
    dest_format: gst::ffi::GstFormat,
    dest_value: *mut i64,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();
    let source = gst::GenericFormattedValue::new(from_glib(source_format), source_value);

    let res = gst::panic_to_error!(imp, None, { imp.convert(source, from_glib(dest_format)) });

    match res {
        Some(dest) => {
            *dest_value = dest.into_raw_value();
            true
        }
        _ => false,
    }
    .into_glib()
}