gstreamer 0.25.2

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

use std::io::{Error, ErrorKind, Read, Seek, SeekFrom};
use std::{ptr, slice};

use glib::translate::*;

use crate::{Caps, Plugin, Rank, TypeFindFactory, TypeFindProbability, ffi};

#[repr(transparent)]
#[derive(Debug)]
#[doc(alias = "GstTypeFind")]
pub struct TypeFind(ffi::GstTypeFind);

pub trait TypeFindImpl {
    fn peek(&mut self, offset: i64, size: u32) -> Option<&[u8]>;
    fn suggest(&mut self, probability: TypeFindProbability, caps: &Caps);
    #[doc(alias = "get_length")]
    fn length(&self) -> Option<u64> {
        None
    }
}

impl TypeFind {
    #[doc(alias = "gst_type_find_register")]
    pub fn register<F>(
        plugin: Option<&Plugin>,
        name: &str,
        rank: Rank,
        extensions: Option<&str>,
        possible_caps: Option<&Caps>,
        func: F,
    ) -> Result<(), glib::error::BoolError>
    where
        F: Fn(&mut TypeFind) + Send + Sync + 'static,
    {
        skip_assert_initialized!();
        unsafe {
            let func: Box<F> = Box::new(func);
            let func = Box::into_raw(func);

            let res = ffi::gst_type_find_register(
                plugin.to_glib_none().0,
                name.to_glib_none().0,
                rank.into_glib() as u32,
                Some(type_find_trampoline::<F>),
                extensions.to_glib_none().0,
                possible_caps.to_glib_none().0,
                func as *mut _,
                Some(type_find_closure_drop::<F>),
            );

            glib::result_from_gboolean!(res, "Failed to register typefind factory")
        }
    }

    #[doc(alias = "gst_type_find_peek")]
    pub fn peek(&mut self, offset: i64, size: u32) -> Option<&[u8]> {
        unsafe {
            let data = ffi::gst_type_find_peek(&mut self.0, offset, size);
            if data.is_null() {
                None
            } else if size == 0 {
                Some(&[])
            } else {
                Some(slice::from_raw_parts(data, size as usize))
            }
        }
    }

    #[doc(alias = "gst_type_find_suggest")]
    pub fn suggest(&mut self, probability: TypeFindProbability, caps: &Caps) {
        unsafe {
            ffi::gst_type_find_suggest(
                &mut self.0,
                probability.into_glib() as u32,
                caps.to_glib_none().0,
            );
        }
    }

    #[doc(alias = "get_length")]
    #[doc(alias = "gst_type_find_get_length")]
    pub fn length(&mut self) -> Option<u64> {
        unsafe {
            let len = ffi::gst_type_find_get_length(&mut self.0);
            if len == 0 { None } else { Some(len) }
        }
    }

    pub fn as_reader(&mut self) -> TypeFindReader<'_> {
        TypeFindReader::from(self)
    }
}

pub struct TypeFindReader<'a> {
    buf: &'a mut TypeFind,
    pos: u64,
}

impl<'a> TypeFindReader<'a> {
    pub fn into_typefind(self) -> &'a mut TypeFind {
        self.buf
    }

    pub fn as_typefind(&mut self) -> &mut TypeFind {
        self.buf
    }

    fn len(&mut self) -> u64 {
        self.buf.length().unwrap_or(0)
    }
}

impl<'a> From<&'a mut TypeFind> for TypeFindReader<'a> {
    fn from(buf: &'a mut TypeFind) -> Self {
        skip_assert_initialized!();
        Self { buf, pos: 0 }
    }
}

impl Read for TypeFindReader<'_> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        // Negative positions are used for reading relative to the end
        // of the buffer, which makes no sense in this context so consider
        // this situation EOF.
        if self.pos > i64::MAX as u64 {
            return Ok(0);
        }

        // First do a unchecked peek as a fast path before calling into len()
        let max_len = buf.len().min(u32::MAX as usize);
        if let Some(v) = self.buf.peek(self.pos as i64, max_len as u32) {
            buf[..max_len].copy_from_slice(v);
            // pos < i64::MAX so can't possibly overflow
            self.pos += max_len as u64;
            return Ok(max_len);
        }

        // Read failed, less data might be available.
        let remaining = match self.len().checked_sub(self.pos) {
            Some(v) => v,
            None => return Ok(0),
        };

        // Try reading the remaining data.
        let remaining = remaining.min(u32::MAX as u64) as usize;
        let max_len = remaining.min(buf.len());
        if let Some(v) = self.buf.peek(self.pos as i64, max_len as u32) {
            buf[..max_len].copy_from_slice(v);
            // pos < i64::MAX so can't possibly overflow
            self.pos += max_len as u64;
            return Ok(max_len);
        }

        Ok(0)
    }
}

impl Seek for TypeFindReader<'_> {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        match pos {
            SeekFrom::Start(v) => {
                if v >= i64::MAX as u64 {
                    return Err(Error::from(ErrorKind::FileTooLarge));
                }

                let len = self.len();
                let v = len.min(v);
                self.pos = v;
            }
            SeekFrom::End(v) => {
                let Some(v) = self.len().checked_add_signed(v) else {
                    return Err(Error::from(ErrorKind::InvalidInput));
                };
                if v >= i64::MAX as u64 {
                    return Err(Error::from(ErrorKind::FileTooLarge));
                }

                self.pos = v;
            }
            SeekFrom::Current(v) => {
                let Some(v) = self.pos.checked_add_signed(v) else {
                    return Err(Error::from(ErrorKind::InvalidInput));
                };
                if v >= i64::MAX as u64 {
                    return Err(Error::from(ErrorKind::FileTooLarge));
                }

                let len = self.len();
                let v = len.min(v);
                self.pos = v;
            }
        };

        Ok(self.pos)
    }
}

impl TypeFindFactory {
    #[doc(alias = "gst_type_find_factory_call_function")]
    pub fn call_function<T: TypeFindImpl + ?Sized>(&self, mut find: &mut T) {
        unsafe {
            let find_ptr = &mut find as *mut &mut T as glib::ffi::gpointer;
            let mut find = ffi::GstTypeFind {
                peek: Some(type_find_peek::<T>),
                suggest: Some(type_find_suggest::<T>),
                data: find_ptr,
                get_length: Some(type_find_get_length::<T>),
                _gst_reserved: [ptr::null_mut(); 4],
            };

            ffi::gst_type_find_factory_call_function(self.to_glib_none().0, &mut find)
        }
    }
}

unsafe extern "C" fn type_find_trampoline<F: Fn(&mut TypeFind) + Send + Sync + 'static>(
    find: *mut ffi::GstTypeFind,
    user_data: glib::ffi::gpointer,
) {
    unsafe {
        let func: &F = &*(user_data as *const F);

        let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            func(&mut *(find as *mut TypeFind));
        }));

        if let Err(err) = panic_result {
            let cause = err
                .downcast_ref::<&str>()
                .copied()
                .or_else(|| err.downcast_ref::<String>().map(|s| s.as_str()));
            if let Some(cause) = cause {
                crate::error!(
                    crate::CAT_RUST,
                    "Failed to call typefind function due to panic: {}",
                    cause
                );
            } else {
                crate::error!(
                    crate::CAT_RUST,
                    "Failed to call typefind function due to panic"
                );
            }
        }
    }
}

unsafe extern "C" fn type_find_closure_drop<F: Fn(&mut TypeFind) + Send + Sync + 'static>(
    data: glib::ffi::gpointer,
) {
    unsafe {
        let _ = Box::<F>::from_raw(data as *mut _);
    }
}

unsafe extern "C" fn type_find_peek<T: TypeFindImpl + ?Sized>(
    data: glib::ffi::gpointer,
    offset: i64,
    size: u32,
) -> *const u8 {
    unsafe {
        let find = &mut *(data as *mut &mut T);

        let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            match find.peek(offset, size) {
                None => ptr::null(),
                Some(data) => data.as_ptr(),
            }
        }));

        match panic_result {
            Ok(res) => res,
            Err(err) => {
                let cause = err
                    .downcast_ref::<&str>()
                    .copied()
                    .or_else(|| err.downcast_ref::<String>().map(|s| s.as_str()));
                if let Some(cause) = cause {
                    crate::error!(
                        crate::CAT_RUST,
                        "Failed to call typefind peek function due to panic: {}",
                        cause
                    );
                } else {
                    crate::error!(
                        crate::CAT_RUST,
                        "Failed to call typefind peek function due to panic"
                    );
                }

                ptr::null()
            }
        }
    }
}

unsafe extern "C" fn type_find_suggest<T: TypeFindImpl + ?Sized>(
    data: glib::ffi::gpointer,
    probability: u32,
    caps: *mut ffi::GstCaps,
) {
    unsafe {
        let find = &mut *(data as *mut &mut T);

        let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            find.suggest(from_glib(probability as i32), &from_glib_borrow(caps));
        }));

        if let Err(err) = panic_result {
            let cause = err
                .downcast_ref::<&str>()
                .copied()
                .or_else(|| err.downcast_ref::<String>().map(|s| s.as_str()));
            if let Some(cause) = cause {
                crate::error!(
                    crate::CAT_RUST,
                    "Failed to call typefind suggest function due to panic: {}",
                    cause
                );
            } else {
                crate::error!(
                    crate::CAT_RUST,
                    "Failed to call typefind suggest function due to panic"
                );
            }
        }
    }
}

unsafe extern "C" fn type_find_get_length<T: TypeFindImpl + ?Sized>(
    data: glib::ffi::gpointer,
) -> u64 {
    unsafe {
        let find = &*(data as *mut &mut T);

        let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            find.length().unwrap_or(u64::MAX)
        }));

        match panic_result {
            Ok(res) => res,
            Err(err) => {
                let cause = err
                    .downcast_ref::<&str>()
                    .copied()
                    .or_else(|| err.downcast_ref::<String>().map(|s| s.as_str()));
                if let Some(cause) = cause {
                    crate::error!(
                        crate::CAT_RUST,
                        "Failed to call typefind length function due to panic: {}",
                        cause
                    );
                } else {
                    crate::error!(
                        crate::CAT_RUST,
                        "Failed to call typefind length function due to panic"
                    );
                }

                u64::MAX
            }
        }
    }
}

#[derive(Debug)]
pub struct SliceTypeFind<T: AsRef<[u8]>> {
    pub probability: Option<TypeFindProbability>,
    pub caps: Option<Caps>,
    data: T,
}

impl<T: AsRef<[u8]>> SliceTypeFind<T> {
    pub fn new(data: T) -> SliceTypeFind<T> {
        assert_initialized_main_thread!();
        SliceTypeFind {
            probability: None,
            caps: None,
            data,
        }
    }

    pub fn run(&mut self) {
        let factories = TypeFindFactory::factories();

        for factory in factories {
            factory.call_function(self);
            if let Some(prob) = self.probability
                && prob >= TypeFindProbability::Maximum
            {
                break;
            }
        }
    }

    pub fn type_find(data: T) -> (TypeFindProbability, Option<Caps>) {
        assert_initialized_main_thread!();
        let mut t = SliceTypeFind {
            probability: None,
            caps: None,
            data,
        };

        t.run();

        (t.probability.unwrap_or(TypeFindProbability::None), t.caps)
    }
}

impl<T: AsRef<[u8]>> TypeFindImpl for SliceTypeFind<T> {
    fn peek(&mut self, offset: i64, size: u32) -> Option<&[u8]> {
        let data = self.data.as_ref();
        let len = data.len();

        let offset = if offset >= 0 {
            usize::try_from(offset).ok()?
        } else {
            let offset = usize::try_from(offset.unsigned_abs()).ok()?;
            if len < offset {
                return None;
            }

            len - offset
        };

        let size = usize::try_from(size).ok()?;
        let end_offset = offset.checked_add(size)?;
        if end_offset <= len {
            Some(&data[offset..end_offset])
        } else {
            None
        }
    }

    fn suggest(&mut self, probability: TypeFindProbability, caps: &Caps) {
        match self.probability {
            None => {
                self.probability = Some(probability);
                self.caps = Some(caps.clone());
            }
            Some(old_probability) if old_probability < probability => {
                self.probability = Some(probability);
                self.caps = Some(caps.clone());
            }
            _ => (),
        }
    }
    fn length(&self) -> Option<u64> {
        Some(self.data.as_ref().len() as u64)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

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

        let xml_factory = TypeFindFactory::factories()
            .into_iter()
            .find(|f| {
                f.caps()
                    .map(|c| {
                        c.structure(0)
                            .map(|s| s.name() == "application/xml")
                            .unwrap_or(false)
                    })
                    .unwrap_or(false)
            })
            .unwrap();

        let data = b"<?xml version=\"1.0\"?><test>test</test>";
        let data = &data[..];
        let mut typefind = SliceTypeFind::new(&data);
        xml_factory.call_function(&mut typefind);

        assert_eq!(
            typefind.caps,
            Some(Caps::builder("application/xml").build())
        );
        assert_eq!(typefind.probability, Some(TypeFindProbability::Minimum));
    }

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

        TypeFind::register(
            None,
            "test_typefind",
            crate::Rank::PRIMARY,
            None,
            Some(&Caps::builder("test/test").build()),
            |typefind| {
                assert_eq!(typefind.length(), Some(8));
                let mut found = false;
                if let Some(data) = typefind.peek(0, 8)
                    && data == b"abcdefgh"
                {
                    found = true;
                }

                if found {
                    typefind.suggest(
                        TypeFindProbability::Likely,
                        &Caps::builder("test/test").build(),
                    );
                }
            },
        )
        .unwrap();

        let data = b"abcdefgh";
        let data = &data[..];
        let (probability, caps) = SliceTypeFind::type_find(data);

        assert_eq!(caps, Some(Caps::builder("test/test").build()));
        assert_eq!(probability, TypeFindProbability::Likely);
    }
}