1use std::io::{Error, ErrorKind, Read, Seek, SeekFrom};
4use std::{ptr, slice};
5
6use glib::translate::*;
7
8use crate::{Caps, Plugin, Rank, TypeFindFactory, TypeFindProbability, ffi};
9
10#[repr(transparent)]
11#[derive(Debug)]
12#[doc(alias = "GstTypeFind")]
13pub struct TypeFind(ffi::GstTypeFind);
14
15pub trait TypeFindImpl {
16 fn peek(&mut self, offset: i64, size: u32) -> Option<&[u8]>;
17 fn suggest(&mut self, probability: TypeFindProbability, caps: &Caps);
18 #[doc(alias = "get_length")]
19 fn length(&self) -> Option<u64> {
20 None
21 }
22}
23
24impl TypeFind {
25 #[doc(alias = "gst_type_find_register")]
26 pub fn register<F>(
27 plugin: Option<&Plugin>,
28 name: &str,
29 rank: Rank,
30 extensions: Option<&str>,
31 possible_caps: Option<&Caps>,
32 func: F,
33 ) -> Result<(), glib::error::BoolError>
34 where
35 F: Fn(&mut TypeFind) + Send + Sync + 'static,
36 {
37 skip_assert_initialized!();
38 unsafe {
39 let func: Box<F> = Box::new(func);
40 let func = Box::into_raw(func);
41
42 let res = ffi::gst_type_find_register(
43 plugin.to_glib_none().0,
44 name.to_glib_none().0,
45 rank.into_glib() as u32,
46 Some(type_find_trampoline::<F>),
47 extensions.to_glib_none().0,
48 possible_caps.to_glib_none().0,
49 func as *mut _,
50 Some(type_find_closure_drop::<F>),
51 );
52
53 glib::result_from_gboolean!(res, "Failed to register typefind factory")
54 }
55 }
56
57 #[doc(alias = "gst_type_find_peek")]
58 pub fn peek(&mut self, offset: i64, size: u32) -> Option<&[u8]> {
59 unsafe {
60 let data = ffi::gst_type_find_peek(&mut self.0, offset, size);
61 if data.is_null() {
62 None
63 } else if size == 0 {
64 Some(&[])
65 } else {
66 Some(slice::from_raw_parts(data, size as usize))
67 }
68 }
69 }
70
71 #[doc(alias = "gst_type_find_suggest")]
72 pub fn suggest(&mut self, probability: TypeFindProbability, caps: &Caps) {
73 unsafe {
74 ffi::gst_type_find_suggest(
75 &mut self.0,
76 probability.into_glib() as u32,
77 caps.to_glib_none().0,
78 );
79 }
80 }
81
82 #[doc(alias = "get_length")]
83 #[doc(alias = "gst_type_find_get_length")]
84 pub fn length(&mut self) -> Option<u64> {
85 unsafe {
86 let len = ffi::gst_type_find_get_length(&mut self.0);
87 if len == 0 { None } else { Some(len) }
88 }
89 }
90
91 pub fn as_reader(&mut self) -> TypeFindReader<'_> {
92 TypeFindReader::from(self)
93 }
94}
95
96pub struct TypeFindReader<'a> {
97 buf: &'a mut TypeFind,
98 pos: u64,
99}
100
101impl<'a> TypeFindReader<'a> {
102 pub fn into_typefind(self) -> &'a mut TypeFind {
103 self.buf
104 }
105
106 pub fn as_typefind(&mut self) -> &mut TypeFind {
107 self.buf
108 }
109
110 fn len(&mut self) -> u64 {
111 self.buf.length().unwrap_or(0)
112 }
113}
114
115impl<'a> From<&'a mut TypeFind> for TypeFindReader<'a> {
116 fn from(buf: &'a mut TypeFind) -> Self {
117 skip_assert_initialized!();
118 Self { buf, pos: 0 }
119 }
120}
121
122impl Read for TypeFindReader<'_> {
123 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
124 if self.pos > i64::MAX as u64 {
128 return Ok(0);
129 }
130
131 let max_len = buf.len().min(u32::MAX as usize);
133 if let Some(v) = self.buf.peek(self.pos as i64, max_len as u32) {
134 buf[..max_len].copy_from_slice(v);
135 self.pos += max_len as u64;
137 return Ok(max_len);
138 }
139
140 let remaining = match self.len().checked_sub(self.pos) {
142 Some(v) => v,
143 None => return Ok(0),
144 };
145
146 let remaining = remaining.min(u32::MAX as u64) as usize;
148 let max_len = remaining.min(buf.len());
149 if let Some(v) = self.buf.peek(self.pos as i64, max_len as u32) {
150 buf[..max_len].copy_from_slice(v);
151 self.pos += max_len as u64;
153 return Ok(max_len);
154 }
155
156 Ok(0)
157 }
158}
159
160impl Seek for TypeFindReader<'_> {
161 fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
162 match pos {
163 SeekFrom::Start(v) => {
164 if v >= i64::MAX as u64 {
165 return Err(Error::from(ErrorKind::FileTooLarge));
166 }
167
168 let len = self.len();
169 let v = len.min(v);
170 self.pos = v;
171 }
172 SeekFrom::End(v) => {
173 let Some(v) = self.len().checked_add_signed(v) else {
174 return Err(Error::from(ErrorKind::InvalidInput));
175 };
176 if v >= i64::MAX as u64 {
177 return Err(Error::from(ErrorKind::FileTooLarge));
178 }
179
180 self.pos = v;
181 }
182 SeekFrom::Current(v) => {
183 let Some(v) = self.pos.checked_add_signed(v) else {
184 return Err(Error::from(ErrorKind::InvalidInput));
185 };
186 if v >= i64::MAX as u64 {
187 return Err(Error::from(ErrorKind::FileTooLarge));
188 }
189
190 let len = self.len();
191 let v = len.min(v);
192 self.pos = v;
193 }
194 };
195
196 Ok(self.pos)
197 }
198}
199
200impl TypeFindFactory {
201 #[doc(alias = "gst_type_find_factory_call_function")]
202 pub fn call_function<T: TypeFindImpl + ?Sized>(&self, mut find: &mut T) {
203 unsafe {
204 let find_ptr = &mut find as *mut &mut T as glib::ffi::gpointer;
205 let mut find = ffi::GstTypeFind {
206 peek: Some(type_find_peek::<T>),
207 suggest: Some(type_find_suggest::<T>),
208 data: find_ptr,
209 get_length: Some(type_find_get_length::<T>),
210 _gst_reserved: [ptr::null_mut(); 4],
211 };
212
213 ffi::gst_type_find_factory_call_function(self.to_glib_none().0, &mut find)
214 }
215 }
216}
217
218unsafe extern "C" fn type_find_trampoline<F: Fn(&mut TypeFind) + Send + Sync + 'static>(
219 find: *mut ffi::GstTypeFind,
220 user_data: glib::ffi::gpointer,
221) {
222 unsafe {
223 let func: &F = &*(user_data as *const F);
224
225 let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
226 func(&mut *(find as *mut TypeFind));
227 }));
228
229 if let Err(err) = panic_result {
230 let cause = err
231 .downcast_ref::<&str>()
232 .copied()
233 .or_else(|| err.downcast_ref::<String>().map(|s| s.as_str()));
234 if let Some(cause) = cause {
235 crate::error!(
236 crate::CAT_RUST,
237 "Failed to call typefind function due to panic: {}",
238 cause
239 );
240 } else {
241 crate::error!(
242 crate::CAT_RUST,
243 "Failed to call typefind function due to panic"
244 );
245 }
246 }
247 }
248}
249
250unsafe extern "C" fn type_find_closure_drop<F: Fn(&mut TypeFind) + Send + Sync + 'static>(
251 data: glib::ffi::gpointer,
252) {
253 unsafe {
254 let _ = Box::<F>::from_raw(data as *mut _);
255 }
256}
257
258unsafe extern "C" fn type_find_peek<T: TypeFindImpl + ?Sized>(
259 data: glib::ffi::gpointer,
260 offset: i64,
261 size: u32,
262) -> *const u8 {
263 unsafe {
264 let find = &mut *(data as *mut &mut T);
265
266 let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
267 match find.peek(offset, size) {
268 None => ptr::null(),
269 Some(data) => data.as_ptr(),
270 }
271 }));
272
273 match panic_result {
274 Ok(res) => res,
275 Err(err) => {
276 let cause = err
277 .downcast_ref::<&str>()
278 .copied()
279 .or_else(|| err.downcast_ref::<String>().map(|s| s.as_str()));
280 if let Some(cause) = cause {
281 crate::error!(
282 crate::CAT_RUST,
283 "Failed to call typefind peek function due to panic: {}",
284 cause
285 );
286 } else {
287 crate::error!(
288 crate::CAT_RUST,
289 "Failed to call typefind peek function due to panic"
290 );
291 }
292
293 ptr::null()
294 }
295 }
296 }
297}
298
299unsafe extern "C" fn type_find_suggest<T: TypeFindImpl + ?Sized>(
300 data: glib::ffi::gpointer,
301 probability: u32,
302 caps: *mut ffi::GstCaps,
303) {
304 unsafe {
305 let find = &mut *(data as *mut &mut T);
306
307 let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
308 find.suggest(from_glib(probability as i32), &from_glib_borrow(caps));
309 }));
310
311 if let Err(err) = panic_result {
312 let cause = err
313 .downcast_ref::<&str>()
314 .copied()
315 .or_else(|| err.downcast_ref::<String>().map(|s| s.as_str()));
316 if let Some(cause) = cause {
317 crate::error!(
318 crate::CAT_RUST,
319 "Failed to call typefind suggest function due to panic: {}",
320 cause
321 );
322 } else {
323 crate::error!(
324 crate::CAT_RUST,
325 "Failed to call typefind suggest function due to panic"
326 );
327 }
328 }
329 }
330}
331
332unsafe extern "C" fn type_find_get_length<T: TypeFindImpl + ?Sized>(
333 data: glib::ffi::gpointer,
334) -> u64 {
335 unsafe {
336 let find = &*(data as *mut &mut T);
337
338 let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
339 find.length().unwrap_or(u64::MAX)
340 }));
341
342 match panic_result {
343 Ok(res) => res,
344 Err(err) => {
345 let cause = err
346 .downcast_ref::<&str>()
347 .copied()
348 .or_else(|| err.downcast_ref::<String>().map(|s| s.as_str()));
349 if let Some(cause) = cause {
350 crate::error!(
351 crate::CAT_RUST,
352 "Failed to call typefind length function due to panic: {}",
353 cause
354 );
355 } else {
356 crate::error!(
357 crate::CAT_RUST,
358 "Failed to call typefind length function due to panic"
359 );
360 }
361
362 u64::MAX
363 }
364 }
365 }
366}
367
368#[derive(Debug)]
369pub struct SliceTypeFind<T: AsRef<[u8]>> {
370 pub probability: Option<TypeFindProbability>,
371 pub caps: Option<Caps>,
372 data: T,
373}
374
375impl<T: AsRef<[u8]>> SliceTypeFind<T> {
376 pub fn new(data: T) -> SliceTypeFind<T> {
377 assert_initialized_main_thread!();
378 SliceTypeFind {
379 probability: None,
380 caps: None,
381 data,
382 }
383 }
384
385 pub fn run(&mut self) {
386 let factories = TypeFindFactory::factories();
387
388 for factory in factories {
389 factory.call_function(self);
390 if let Some(prob) = self.probability
391 && prob >= TypeFindProbability::Maximum
392 {
393 break;
394 }
395 }
396 }
397
398 pub fn type_find(data: T) -> (TypeFindProbability, Option<Caps>) {
399 assert_initialized_main_thread!();
400 let mut t = SliceTypeFind {
401 probability: None,
402 caps: None,
403 data,
404 };
405
406 t.run();
407
408 (t.probability.unwrap_or(TypeFindProbability::None), t.caps)
409 }
410}
411
412impl<T: AsRef<[u8]>> TypeFindImpl for SliceTypeFind<T> {
413 fn peek(&mut self, offset: i64, size: u32) -> Option<&[u8]> {
414 let data = self.data.as_ref();
415 let len = data.len();
416
417 let offset = if offset >= 0 {
418 usize::try_from(offset).ok()?
419 } else {
420 let offset = usize::try_from(offset.unsigned_abs()).ok()?;
421 if len < offset {
422 return None;
423 }
424
425 len - offset
426 };
427
428 let size = usize::try_from(size).ok()?;
429 let end_offset = offset.checked_add(size)?;
430 if end_offset <= len {
431 Some(&data[offset..end_offset])
432 } else {
433 None
434 }
435 }
436
437 fn suggest(&mut self, probability: TypeFindProbability, caps: &Caps) {
438 match self.probability {
439 None => {
440 self.probability = Some(probability);
441 self.caps = Some(caps.clone());
442 }
443 Some(old_probability) if old_probability < probability => {
444 self.probability = Some(probability);
445 self.caps = Some(caps.clone());
446 }
447 _ => (),
448 }
449 }
450 fn length(&self) -> Option<u64> {
451 Some(self.data.as_ref().len() as u64)
452 }
453}
454
455#[cfg(test)]
456mod tests {
457 use super::*;
458
459 #[test]
460 fn test_typefind_call_function() {
461 crate::init().unwrap();
462
463 let xml_factory = TypeFindFactory::factories()
464 .into_iter()
465 .find(|f| {
466 f.caps()
467 .map(|c| {
468 c.structure(0)
469 .map(|s| s.name() == "application/xml")
470 .unwrap_or(false)
471 })
472 .unwrap_or(false)
473 })
474 .unwrap();
475
476 let data = b"<?xml version=\"1.0\"?><test>test</test>";
477 let data = &data[..];
478 let mut typefind = SliceTypeFind::new(&data);
479 xml_factory.call_function(&mut typefind);
480
481 assert_eq!(
482 typefind.caps,
483 Some(Caps::builder("application/xml").build())
484 );
485 assert_eq!(typefind.probability, Some(TypeFindProbability::Minimum));
486 }
487
488 #[test]
489 fn test_typefind_register() {
490 crate::init().unwrap();
491
492 TypeFind::register(
493 None,
494 "test_typefind",
495 crate::Rank::PRIMARY,
496 None,
497 Some(&Caps::builder("test/test").build()),
498 |typefind| {
499 assert_eq!(typefind.length(), Some(8));
500 let mut found = false;
501 if let Some(data) = typefind.peek(0, 8)
502 && data == b"abcdefgh"
503 {
504 found = true;
505 }
506
507 if found {
508 typefind.suggest(
509 TypeFindProbability::Likely,
510 &Caps::builder("test/test").build(),
511 );
512 }
513 },
514 )
515 .unwrap();
516
517 let data = b"abcdefgh";
518 let data = &data[..];
519 let (probability, caps) = SliceTypeFind::type_find(data);
520
521 assert_eq!(caps, Some(Caps::builder("test/test").build()));
522 assert_eq!(probability, TypeFindProbability::Likely);
523 }
524}