Debian Codegraph @

third_party/rust/mp4parse_capi/src/lib.rs

raw
1 //! C API for mp4parse module.
2 //!
3 //! Parses ISO Base Media Format aka video/mp4 streams.
4 //!
5 //! # Examples
6 //!
7 //! ```rust
8 //! use std::io::Read;
9 //!
10 //! extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
11 //! let mut input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
12 //! let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
13 //! match input.read(&mut buf) {
14 //! Ok(n) => n as isize,
15 //! Err(_) => -1,
16 //! }
17 //! }
18 //! let capi_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap();
19 //! let mut file = std::fs::File::open(capi_dir + "/../mp4parse/tests/minimal.mp4").unwrap();
20 //! let io = mp4parse_capi::Mp4parseIo {
21 //! read: Some(buf_read),
22 //! userdata: &mut file as *mut _ as *mut std::os::raw::c_void
23 //! };
24 //! let mut parser = std::ptr::null_mut();
25 //! unsafe {
26 //! let rv = mp4parse_capi::mp4parse_new(&io, &mut parser);
27 //! assert_eq!(rv, mp4parse_capi::Mp4parseStatus::Ok);
28 //! assert!(!parser.is_null());
29 //! mp4parse_capi::mp4parse_free(parser);
30 //! }
31 //! ```
32
33 // This Source Code Form is subject to the terms of the Mozilla Public
34 // License, v. 2.0. If a copy of the MPL was not distributed with this
35 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
36
37 use byteorder::WriteBytesExt;
38 use mp4parse::unstable::rational_scale;
39 use std::convert::TryFrom;
40 use std::convert::TryInto;
41
42 use std::io::Read;
43
44 // Symbols we need from our rust api.
45 use mp4parse::serialize_opus_header;
46 use mp4parse::unstable::{create_sample_table, CheckedInteger, Indice};
47 use mp4parse::AV1ConfigBox;
48 use mp4parse::AudioCodecSpecific;
49 use mp4parse::AvifContext;
50 use mp4parse::CodecType;
51 use mp4parse::MediaContext;
52 // Re-exported so consumers don't have to depend on mp4parse as well
53 pub use mp4parse::ParseStrictness;
54 use mp4parse::SampleEntry;
55 pub use mp4parse::Status as Mp4parseStatus;
56 use mp4parse::Track;
57 use mp4parse::TrackType;
58 use mp4parse::TryBox;
59 use mp4parse::TryHashMap;
60 use mp4parse::TryVec;
61 use mp4parse::VideoCodecSpecific;
62
63 // To ensure we don't use stdlib allocating types by accident
64 #[allow(dead_code)]
65 struct Vec;
66 #[allow(dead_code)]
67 struct Box;
68 #[allow(dead_code)]
69 struct HashMap;
70 #[allow(dead_code)]
71 struct String;
72
73 #[repr(C)]
74 #[derive(PartialEq, Eq, Debug, Default)]
75 pub enum Mp4parseTrackType {
76 #[default]
77 Video = 0,
78 Picture = 1,
79 AuxiliaryVideo = 2,
80 Audio = 3,
81 Metadata = 4,
82 }
83
84 #[allow(non_camel_case_types, clippy::upper_case_acronyms)]
85 #[repr(C)]
86 #[derive(PartialEq, Eq, Debug, Default)]
87 pub enum Mp4parseCodec {
88 #[default]
89 Unknown,
90 Aac,
91 Flac,
92 Opus,
93 Avc,
94 Vp9,
95 Av1,
96 Mp3,
97 Mp4v,
98 Jpeg, // for QT JPEG atom in video track
99 Ac3,
100 Ec3,
101 Alac,
102 H263,
103 Hevc,
104 #[cfg(feature = "3gpp")]
105 AMRNB,
106 #[cfg(feature = "3gpp")]
107 AMRWB,
108 }
109
110 #[repr(C)]
111 #[derive(PartialEq, Eq, Debug, Default)]
112 pub enum Mp4ParseEncryptionSchemeType {
113 #[default]
114 None,
115 Cenc,
116 Cbc1,
117 Cens,
118 Cbcs,
119 // Schemes also have a version component. At the time of writing, this does
120 // not impact handling, so we do not expose it. Note that this may need to
121 // be exposed in future, should the spec change.
122 }
123
124 #[repr(C)]
125 #[derive(Default, Debug)]
126 pub struct Mp4parseTrackInfo {
127 pub track_type: Mp4parseTrackType,
128 pub track_id: u32,
129 pub duration: u64,
130 pub media_time: CheckedInteger<i64>,
131 pub time_scale: u32,
132 }
133
134 #[repr(C)]
135 #[derive(Debug)]
136 pub struct Mp4parseByteData {
137 pub length: usize,
138 // cheddar can't handle generic type, so it needs to be multiple data types here.
139 pub data: *const u8,
140 pub indices: *const Indice,
141 }
142
143 impl Mp4parseByteData {
144 fn with_data(slice: &[u8]) -> Self {
145 Self {
146 length: slice.len(),
147 data: if !slice.is_empty() {
148 slice.as_ptr()
149 } else {
150 std::ptr::null()
151 },
152 indices: std::ptr::null(),
153 }
154 }
155 }
156
157 impl Default for Mp4parseByteData {
158 fn default() -> Self {
159 Self {
160 length: 0,
161 data: std::ptr::null(),
162 indices: std::ptr::null(),
163 }
164 }
165 }
166
167 impl Mp4parseByteData {
168 fn set_data(&mut self, data: &[u8]) {
169 self.length = data.len();
170 self.data = if data.is_empty() {
171 std::ptr::null()
172 } else {
173 data.as_ptr()
174 };
175 }
176
177 fn set_indices(&mut self, data: &[Indice]) {
178 self.length = data.len();
179 self.indices = if data.is_empty() {
180 std::ptr::null()
181 } else {
182 data.as_ptr()
183 };
184 }
185 }
186
187 #[repr(C)]
188 #[derive(Default)]
189 pub struct Mp4parsePsshInfo {
190 pub data: Mp4parseByteData,
191 }
192
193 #[repr(u8)]
194 #[derive(Debug, PartialEq, Eq)]
195 pub enum OptionalFourCc {
196 None,
197 Some([u8; 4]),
198 }
199
200 impl Default for OptionalFourCc {
201 fn default() -> Self {
202 Self::None
203 }
204 }
205
206 #[repr(C)]
207 #[derive(Default, Debug)]
208 pub struct Mp4parseSinfInfo {
209 pub original_format: OptionalFourCc,
210 pub scheme_type: Mp4ParseEncryptionSchemeType,
211 pub is_encrypted: u8,
212 pub iv_size: u8,
213 pub kid: Mp4parseByteData,
214 // Members for pattern encryption schemes, may be 0 (u8) or empty
215 // (Mp4parseByteData) if pattern encryption is not in use
216 pub crypt_byte_block: u8,
217 pub skip_byte_block: u8,
218 pub constant_iv: Mp4parseByteData,
219 // End pattern encryption scheme members
220 }
221
222 #[repr(C)]
223 #[derive(Default, Debug)]
224 pub struct Mp4parseTrackAudioSampleInfo {
225 pub codec_type: Mp4parseCodec,
226 pub channels: u16,
227 pub bit_depth: u16,
228 pub sample_rate: u32,
229 pub profile: u16,
230 pub extended_profile: u16,
231 pub codec_specific_config: Mp4parseByteData,
232 pub extra_data: Mp4parseByteData,
233 pub protected_data: Mp4parseSinfInfo,
234 }
235
236 #[repr(C)]
237 #[derive(Debug)]
238 pub struct Mp4parseTrackAudioInfo {
239 pub sample_info_count: u32,
240 pub sample_info: *const Mp4parseTrackAudioSampleInfo,
241 }
242
243 impl Default for Mp4parseTrackAudioInfo {
244 fn default() -> Self {
245 Self {
246 sample_info_count: 0,
247 sample_info: std::ptr::null(),
248 }
249 }
250 }
251
252 #[repr(C)]
253 #[derive(Default, Debug)]
254 pub struct Mp4parseTrackVideoSampleInfo {
255 pub codec_type: Mp4parseCodec,
256 pub image_width: u16,
257 pub image_height: u16,
258 pub extra_data: Mp4parseByteData,
259 pub protected_data: Mp4parseSinfInfo,
260 }
261
262 #[repr(C)]
263 #[derive(Debug)]
264 pub struct Mp4parseTrackVideoInfo {
265 pub display_width: u32,
266 pub display_height: u32,
267 pub rotation: u16,
268 pub sample_info_count: u32,
269 pub sample_info: *const Mp4parseTrackVideoSampleInfo,
270 pub pixel_aspect_ratio: f32,
271 }
272
273 impl Default for Mp4parseTrackVideoInfo {
274 fn default() -> Self {
275 Self {
276 display_width: 0,
277 display_height: 0,
278 rotation: 0,
279 sample_info_count: 0,
280 sample_info: std::ptr::null(),
281 pixel_aspect_ratio: 0.0,
282 }
283 }
284 }
285
286 #[repr(C)]
287 #[derive(Default, Debug)]
288 pub struct Mp4parseFragmentInfo {
289 pub fragment_duration: u64, // in ticks
290 pub time_scale: u64,
291 // TODO:
292 // info in trex box.
293 }
294
295 #[derive(Default)]
296 pub struct Mp4parseParser {
297 context: MediaContext,
298 opus_header: TryHashMap<(u32, usize), TryVec<u8>>,
299 pssh_data: Option<TryVec<u8>>,
300 sample_table: TryHashMap<u32, TryVec<Indice>>,
301 // Store a mapping from track index (not id) to associated sample
302 // descriptions. Because each track has a variable number of sample
303 // descriptions, and because we need the data to live long enough to be
304 // copied out by callers, we store these on the parser struct.
305 audio_track_sample_descriptions: TryHashMap<u32, TryVec<Mp4parseTrackAudioSampleInfo>>,
306 video_track_sample_descriptions: TryHashMap<u32, TryVec<Mp4parseTrackVideoSampleInfo>>,
307 }
308
309 #[repr(C)]
310 #[derive(Debug, Default)]
311 pub enum Mp4parseAvifLoopMode {
312 #[default]
313 NoEdits,
314 LoopByCount,
315 LoopInfinitely,
316 }
317
318 #[repr(C)]
319 #[derive(Debug)]
320 pub struct Mp4parseAvifInfo {
321 pub premultiplied_alpha: bool,
322 pub major_brand: [u8; 4],
323 pub unsupported_features_bitfield: u32,
324 /// The size of the image; should never be null unless using permissive parsing
325 pub spatial_extents: *const mp4parse::ImageSpatialExtentsProperty,
326 pub nclx_colour_information: *const mp4parse::NclxColourInformation,
327 pub icc_colour_information: Mp4parseByteData,
328 pub image_rotation: mp4parse::ImageRotation,
329 pub image_mirror: *const mp4parse::ImageMirror,
330 pub pixel_aspect_ratio: *const mp4parse::PixelAspectRatio,
331
332 /// Whether there is a `pitm` reference to the color image present.
333 pub has_primary_item: bool,
334 /// Bit depth for the item referenced by `pitm`, or 0 if values are inconsistent.
335 pub primary_item_bit_depth: u8,
336 /// Whether there is an `auxl` reference to the `pitm`-accompanying
337 /// alpha image present.
338 pub has_alpha_item: bool,
339 /// Bit depth for the alpha item used by the `pitm`, or 0 if values are inconsistent.
340 pub alpha_item_bit_depth: u8,
341
342 /// Whether there is a sequence. Can be true with no primary image.
343 pub has_sequence: bool,
344 /// Indicates whether the EditListBox requests that the image be looped.
345 pub loop_mode: Mp4parseAvifLoopMode,
346 /// Number of times to loop the animation during playback.
347 ///
348 /// The duration of the animation specified in `elst` must be looped to fill the
349 /// duration of the color track. If the resulting loop count is not an integer,
350 /// then it will be ceiled to play past and fill the entire track's duration.
351 pub loop_count: u64,
352 /// The color track's ID, which must be valid if has_sequence is true.
353 pub color_track_id: u32,
354 pub color_track_bit_depth: u8,
355 /// The track ID of the alpha track, will be 0 if no alpha track is present.
356 pub alpha_track_id: u32,
357 pub alpha_track_bit_depth: u8,
358 }
359
360 #[repr(C)]
361 #[derive(Debug)]
362 pub struct Mp4parseAvifImage {
363 pub primary_image: Mp4parseByteData,
364 /// If no alpha item exists, members' `.length` will be 0 and `.data` will be null
365 pub alpha_image: Mp4parseByteData,
366 }
367
368 /// A unified interface for the parsers which have different contexts, but
369 /// share the same pattern of construction. This allows unification of
370 /// argument validation from C and minimizes the surface of unsafe code.
371 trait ContextParser
372 where
373 Self: Sized,
374 {
375 type Context;
376
377 fn with_context(context: Self::Context) -> Self;
378
379 fn read<T: Read>(io: &mut T, strictness: ParseStrictness) -> mp4parse::Result<Self::Context>;
380 }
381
382 impl Mp4parseParser {
383 fn context(&self) -> &MediaContext {
384 &self.context
385 }
386
387 fn context_mut(&mut self) -> &mut MediaContext {
388 &mut self.context
389 }
390 }
391
392 impl ContextParser for Mp4parseParser {
393 type Context = MediaContext;
394
395 fn with_context(context: Self::Context) -> Self {
396 Self {
397 context,
398 ..Default::default()
399 }
400 }
401
402 fn read<T: Read>(io: &mut T, _strictness: ParseStrictness) -> mp4parse::Result<Self::Context> {
403 let r = mp4parse::read_mp4(io);
404 log::debug!("mp4parse::read_mp4 -> {:?}", r);
405 r
406 }
407 }
408
409 #[derive(Default)]
410 pub struct Mp4parseAvifParser {
411 context: AvifContext,
412 sample_table: TryHashMap<u32, TryVec<Indice>>,
413 }
414
415 impl Mp4parseAvifParser {
416 fn context(&self) -> &AvifContext {
417 &self.context
418 }
419 }
420
421 impl ContextParser for Mp4parseAvifParser {
422 type Context = AvifContext;
423
424 fn with_context(context: Self::Context) -> Self {
425 Self {
426 context,
427 ..Default::default()
428 }
429 }
430
431 fn read<T: Read>(io: &mut T, strictness: ParseStrictness) -> mp4parse::Result<Self::Context> {
432 let r = mp4parse::read_avif(io, strictness);
433 if r.is_err() {
434 log::debug!("{:?}", r);
435 }
436 log::trace!("mp4parse::read_avif -> {:?}", r);
437 r
438 }
439 }
440
441 #[repr(C)]
442 #[derive(Clone)]
443 pub struct Mp4parseIo {
444 pub read: Option<
445 extern "C" fn(buffer: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize,
446 >,
447 pub userdata: *mut std::os::raw::c_void,
448 }
449
450 impl Read for Mp4parseIo {
451 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
452 if buf.len() > isize::MAX as usize {
453 return Err(std::io::Error::new(
454 std::io::ErrorKind::Other,
455 "buf length overflow in Mp4parseIo Read impl",
456 ));
457 }
458 let rv = self.read.unwrap()(buf.as_mut_ptr(), buf.len(), self.userdata);
459 if rv >= 0 {
460 Ok(rv as usize)
461 } else {
462 Err(std::io::Error::new(
463 std::io::ErrorKind::Other,
464 "I/O error in Mp4parseIo Read impl",
465 ))
466 }
467 }
468 }
469
470 // C API wrapper functions.
471
472 /// Allocate an `Mp4parseParser*` to read from the supplied `Mp4parseIo` and
473 /// parse the content from the `Mp4parseIo` argument until EOF or error.
474 ///
475 /// # Safety
476 ///
477 /// This function is unsafe because it dereferences the `io` and `parser_out`
478 /// pointers given to it. The caller should ensure that the `Mp4ParseIo`
479 /// struct passed in is a valid pointer. The caller should also ensure the
480 /// members of io are valid: the `read` function should be sanely implemented,
481 /// and the `userdata` pointer should be valid. The `parser_out` should be a
482 /// valid pointer to a location containing a null pointer. Upon successful
483 /// return (`Mp4parseStatus::Ok`), that location will contain the address of
484 /// an `Mp4parseParser` allocated by this function.
485 ///
486 /// To avoid leaking memory, any successful return of this function must be
487 /// paired with a call to `mp4parse_free`. In the event of error, no memory
488 /// will be allocated and `mp4parse_free` must *not* be called.
489 #[no_mangle]
490 pub unsafe extern "C" fn mp4parse_new(
491 io: *const Mp4parseIo,
492 parser_out: *mut *mut Mp4parseParser,
493 ) -> Mp4parseStatus {
494 mp4parse_new_common(io, ParseStrictness::Normal, parser_out)
495 }
496
497 /// Allocate an `Mp4parseAvifParser*` to read from the supplied `Mp4parseIo`.
498 ///
499 /// See mp4parse_new; this function is identical except that it allocates an
500 /// `Mp4parseAvifParser`, which (when successful) must be paired with a call
501 /// to mp4parse_avif_free.
502 ///
503 /// # Safety
504 ///
505 /// Same as mp4parse_new.
506 #[no_mangle]
507 pub unsafe extern "C" fn mp4parse_avif_new(
508 io: *const Mp4parseIo,
509 strictness: ParseStrictness,
510 parser_out: *mut *mut Mp4parseAvifParser,
511 ) -> Mp4parseStatus {
512 mp4parse_new_common(io, strictness, parser_out)
513 }
514
515 unsafe fn mp4parse_new_common<P: ContextParser>(
516 io: *const Mp4parseIo,
517 strictness: ParseStrictness,
518 parser_out: *mut *mut P,
519 ) -> Mp4parseStatus {
520 // Validate arguments from C.
521 if io.is_null()
522 || (*io).userdata.is_null()
523 || (*io).read.is_none()
524 || parser_out.is_null()
525 || !(*parser_out).is_null()
526 {
527 Mp4parseStatus::BadArg
528 } else {
529 match mp4parse_new_common_safe(&mut (*io).clone(), strictness) {
530 Ok(parser) => {
531 *parser_out = parser;
532 Mp4parseStatus::Ok
533 }
534 Err(status) => status,
535 }
536 }
537 }
538
539 fn mp4parse_new_common_safe<T: Read, P: ContextParser>(
540 io: &mut T,
541 strictness: ParseStrictness,
542 ) -> Result<*mut P, Mp4parseStatus> {
543 P::read(io, strictness)
544 .map(P::with_context)
545 .and_then(|x| TryBox::try_new(x).map_err(mp4parse::Error::from))
546 .map(TryBox::into_raw)
547 .map_err(Mp4parseStatus::from)
548 }
549
550 /// Free an `Mp4parseParser*` allocated by `mp4parse_new()`.
551 ///
552 /// # Safety
553 ///
554 /// This function is unsafe because it creates a box from a raw pointer.
555 /// Callers should ensure that the parser pointer points to a valid
556 /// `Mp4parseParser` created by `mp4parse_new`.
557 #[no_mangle]
558 pub unsafe extern "C" fn mp4parse_free(parser: *mut Mp4parseParser) {
559 assert!(!parser.is_null());
560 let _ = TryBox::from_raw(parser);
561 }
562
563 /// Free an `Mp4parseAvifParser*` allocated by `mp4parse_avif_new()`.
564 ///
565 /// # Safety
566 ///
567 /// This function is unsafe because it creates a box from a raw pointer.
568 /// Callers should ensure that the parser pointer points to a valid
569 /// `Mp4parseAvifParser` created by `mp4parse_avif_new`.
570 #[no_mangle]
571 pub unsafe extern "C" fn mp4parse_avif_free(parser: *mut Mp4parseAvifParser) {
572 assert!(!parser.is_null());
573 let _ = TryBox::from_raw(parser);
574 }
575
576 /// Return the number of tracks parsed by previous `mp4parse_read()` call.
577 ///
578 /// # Safety
579 ///
580 /// This function is unsafe because it dereferences both the parser and count
581 /// raw pointers passed into it. Callers should ensure the parser pointer
582 /// points to a valid `Mp4parseParser`, and that the count pointer points an
583 /// appropriate memory location to have a `u32` written to.
584 #[no_mangle]
585 pub unsafe extern "C" fn mp4parse_get_track_count(
586 parser: *const Mp4parseParser,
587 count: *mut u32,
588 ) -> Mp4parseStatus {
589 // Validate arguments from C.
590 if parser.is_null() || count.is_null() {
591 return Mp4parseStatus::BadArg;
592 }
593 let context = (*parser).context();
594
595 // Make sure the track count fits in a u32.
596 if context.tracks.len() > u32::MAX as usize {
597 return Mp4parseStatus::Invalid;
598 }
599 *count = context.tracks.len() as u32;
600 Mp4parseStatus::Ok
601 }
602
603 /// Fill the supplied `Mp4parseTrackInfo` with metadata for `track`.
604 ///
605 /// # Safety
606 ///
607 /// This function is unsafe because it dereferences the the parser and info raw
608 /// pointers passed to it. Callers should ensure the parser pointer points to a
609 /// valid `Mp4parseParser` and that the info pointer points to a valid
610 /// `Mp4parseTrackInfo`.
611 #[no_mangle]
612 pub unsafe extern "C" fn mp4parse_get_track_info(
613 parser: *mut Mp4parseParser,
614 track_index: u32,
615 info: *mut Mp4parseTrackInfo,
616 ) -> Mp4parseStatus {
617 if parser.is_null() || info.is_null() {
618 return Mp4parseStatus::BadArg;
619 }
620
621 // Initialize fields to default values to ensure all fields are always valid.
622 *info = Default::default();
623
624 let context = (*parser).context_mut();
625 let track_index: usize = track_index as usize;
626 let info: &mut Mp4parseTrackInfo = &mut *info;
627
628 if track_index >= context.tracks.len() {
629 return Mp4parseStatus::BadArg;
630 }
631
632 info.track_type = match context.tracks[track_index].track_type {
633 TrackType::Video => Mp4parseTrackType::Video,
634 TrackType::Picture => Mp4parseTrackType::Picture,
635 TrackType::AuxiliaryVideo => Mp4parseTrackType::AuxiliaryVideo,
636 TrackType::Audio => Mp4parseTrackType::Audio,
637 TrackType::Metadata => Mp4parseTrackType::Metadata,
638 TrackType::Unknown => return Mp4parseStatus::Unsupported,
639 };
640
641 let track = &context.tracks[track_index];
642
643 if let (Some(timescale), Some(context_timescale)) = (track.timescale, context.timescale) {
644 info.time_scale = timescale.0 as u32;
645 let media_time: CheckedInteger<u64> = track
646 .media_time
647 .map_or(0.into(), |media_time| media_time.0.into());
648
649 // Empty duration is in the context's timescale, convert it and return it in the track's
650 // timescale
651 let empty_duration: CheckedInteger<u64> =
652 match track.empty_duration.map_or(Some(0), |empty_duration| {
653 rational_scale(empty_duration.0, context_timescale.0, timescale.0)
654 }) {
655 Some(time) => mp4parse::unstable::CheckedInteger(time),
656 None => return Mp4parseStatus::Invalid,
657 };
658
659 info.media_time = match media_time - empty_duration {
660 Some(difference) => difference,
661 None => return Mp4parseStatus::Invalid,
662 };
663
664 match track.duration {
665 Some(duration) => info.duration = duration.0,
666 None => {
667 // Duration unknown; stagefright returns 0 for this.
668 info.duration = 0
669 }
670 }
671 } else {
672 return Mp4parseStatus::Invalid;
673 }
674
675 info.track_id = match track.track_id {
676 Some(track_id) => track_id,
677 None => return Mp4parseStatus::Invalid,
678 };
679 Mp4parseStatus::Ok
680 }
681
682 /// Fill the supplied `Mp4parseTrackAudioInfo` with metadata for `track`.
683 ///
684 /// # Safety
685 ///
686 /// This function is unsafe because it dereferences the the parser and info raw
687 /// pointers passed to it. Callers should ensure the parser pointer points to a
688 /// valid `Mp4parseParser` and that the info pointer points to a valid
689 /// `Mp4parseTrackAudioInfo`.
690 #[no_mangle]
691 pub unsafe extern "C" fn mp4parse_get_track_audio_info(
692 parser: *mut Mp4parseParser,
693 track_index: u32,
694 info: *mut Mp4parseTrackAudioInfo,
695 ) -> Mp4parseStatus {
696 if parser.is_null() || info.is_null() {
697 return Mp4parseStatus::BadArg;
698 }
699
700 // Initialize fields to default values to ensure all fields are always valid.
701 *info = Default::default();
702
703 get_track_audio_info(&mut *parser, track_index, &mut *info).into()
704 }
705
706 fn get_track_audio_info(
707 parser: &mut Mp4parseParser,
708 track_index: u32,
709 info: &mut Mp4parseTrackAudioInfo,
710 ) -> Result<(), Mp4parseStatus> {
711 if let Some(sample_info) = parser.audio_track_sample_descriptions.get(&track_index) {
712 info.sample_info_count = sample_info.len() as u32;
713 info.sample_info = if sample_info.is_empty() {
714 std::ptr::null()
715 } else {
716 sample_info.as_ptr()
717 };
718 return Ok(());
719 }
720
721 let Mp4parseParser {
722 context,
723 opus_header,
724 ..
725 } = parser;
726
727 if track_index as usize >= context.tracks.len() {
728 return Err(Mp4parseStatus::BadArg);
729 }
730
731 let track = &context.tracks[track_index as usize];
732
733 if track.track_type != TrackType::Audio {
734 return Err(Mp4parseStatus::Invalid);
735 }
736
737 // Handle track.stsd
738 let stsd = match track.stsd {
739 Some(ref stsd) => stsd,
740 None => return Err(Mp4parseStatus::Invalid), // Stsd should be present
741 };
742
743 if stsd.descriptions.is_empty() {
744 return Err(Mp4parseStatus::Invalid); // Should have at least 1 description
745 }
746
747 let mut audio_sample_infos = TryVec::with_capacity(stsd.descriptions.len())?;
748 for (desc_i, description) in stsd.descriptions.iter().enumerate() {
749 let mut sample_info = Mp4parseTrackAudioSampleInfo::default();
750 let audio = match description {
751 SampleEntry::Audio(a) => a,
752 _ => return Err(Mp4parseStatus::Invalid),
753 };
754
755 // UNKNOWN for unsupported format.
756 sample_info.codec_type = match audio.codec_specific {
757 AudioCodecSpecific::OpusSpecificBox(_) => Mp4parseCodec::Opus,
758 AudioCodecSpecific::FLACSpecificBox(_) => Mp4parseCodec::Flac,
759 AudioCodecSpecific::ES_Descriptor(ref esds) if esds.audio_codec == CodecType::AAC => {
760 Mp4parseCodec::Aac
761 }
762 AudioCodecSpecific::ES_Descriptor(ref esds) if esds.audio_codec == CodecType::MP3 => {
763 Mp4parseCodec::Mp3
764 }
765 AudioCodecSpecific::ES_Descriptor(_) | AudioCodecSpecific::LPCM => {
766 Mp4parseCodec::Unknown
767 }
768 AudioCodecSpecific::MP3 => Mp4parseCodec::Mp3,
769 AudioCodecSpecific::ALACSpecificBox(_) => Mp4parseCodec::Alac,
770 #[cfg(feature = "3gpp")]
771 AudioCodecSpecific::AMRSpecificBox(_) => {
772 if audio.codec_type == CodecType::AMRNB {
773 Mp4parseCodec::AMRNB
774 } else {
775 Mp4parseCodec::AMRWB
776 }
777 }
778 };
779 sample_info.channels = audio.channelcount as u16;
780 sample_info.bit_depth = audio.samplesize;
781 sample_info.sample_rate = audio.samplerate as u32;
782 // sample_info.profile is handled below on a per case basis
783
784 match audio.codec_specific {
785 AudioCodecSpecific::ES_Descriptor(ref esds) => {
786 if esds.codec_esds.len() > u32::MAX as usize {
787 return Err(Mp4parseStatus::Invalid);
788 }
789 sample_info.extra_data.set_data(&esds.codec_esds);
790 sample_info
791 .codec_specific_config
792 .set_data(&esds.decoder_specific_data);
793 if let Some(rate) = esds.audio_sample_rate {
794 sample_info.sample_rate = rate;
795 }
796 if let Some(channels) = esds.audio_channel_count {
797 sample_info.channels = channels;
798 }
799 if let Some(profile) = esds.audio_object_type {
800 sample_info.profile = profile;
801 }
802 sample_info.extended_profile = match esds.extended_audio_object_type {
803 Some(extended_profile) => extended_profile,
804 _ => sample_info.profile,
805 };
806 }
807 AudioCodecSpecific::FLACSpecificBox(ref flac) => {
808 // Return the STREAMINFO metadata block in the codec_specific.
809 let streaminfo = &flac.blocks[0];
810 if streaminfo.block_type != 0 || streaminfo.data.len() != 34 {
811 return Err(Mp4parseStatus::Invalid);
812 }
813 sample_info.codec_specific_config.set_data(&streaminfo.data);
814 }
815 AudioCodecSpecific::OpusSpecificBox(ref opus) => {
816 let mut v = TryVec::new();
817 match serialize_opus_header(opus, &mut v) {
818 Err(_) => {
819 return Err(Mp4parseStatus::Invalid);
820 }
821 Ok(_) => {
822 opus_header.insert((track_index, desc_i), v)?;
823 if let Some(v) = opus_header.get(&(track_index, desc_i)) {
824 if v.len() > u32::MAX as usize {
825 return Err(Mp4parseStatus::Invalid);
826 }
827 sample_info.codec_specific_config.set_data(v);
828 }
829 }
830 }
831 }
832 AudioCodecSpecific::ALACSpecificBox(ref alac) => {
833 sample_info.codec_specific_config.set_data(&alac.data);
834 }
835 AudioCodecSpecific::MP3 | AudioCodecSpecific::LPCM => (),
836 #[cfg(feature = "3gpp")]
837 AudioCodecSpecific::AMRSpecificBox(_) => (),
838 }
839
840 if let Some(p) = audio
841 .protection_info
842 .iter()
843 .find(|sinf| sinf.tenc.is_some())
844 {
845 sample_info.protected_data.original_format =
846 OptionalFourCc::Some(p.original_format.value);
847 sample_info.protected_data.scheme_type = match p.scheme_type {
848 Some(ref scheme_type_box) => {
849 match scheme_type_box.scheme_type.value.as_ref() {
850 b"cenc" => Mp4ParseEncryptionSchemeType::Cenc,
851 b"cbcs" => Mp4ParseEncryptionSchemeType::Cbcs,
852 // We don't support other schemes, and shouldn't reach
853 // this case. Try to gracefully handle by treating as
854 // no encryption case.
855 _ => Mp4ParseEncryptionSchemeType::None,
856 }
857 }
858 None => Mp4ParseEncryptionSchemeType::None,
859 };
860 if let Some(ref tenc) = p.tenc {
861 sample_info.protected_data.is_encrypted = tenc.is_encrypted;
862 sample_info.protected_data.iv_size = tenc.iv_size;
863 sample_info.protected_data.kid.set_data(&(tenc.kid));
864 sample_info.protected_data.crypt_byte_block =
865 tenc.crypt_byte_block_count.unwrap_or(0);
866 sample_info.protected_data.skip_byte_block =
867 tenc.skip_byte_block_count.unwrap_or(0);
868 if let Some(ref iv_vec) = tenc.constant_iv {
869 if iv_vec.len() > u32::MAX as usize {
870 return Err(Mp4parseStatus::Invalid);
871 }
872 sample_info.protected_data.constant_iv.set_data(iv_vec);
873 };
874 }
875 }
876 audio_sample_infos.push(sample_info)?;
877 }
878
879 parser
880 .audio_track_sample_descriptions
881 .insert(track_index, audio_sample_infos)?;
882 match parser.audio_track_sample_descriptions.get(&track_index) {
883 Some(sample_info) => {
884 if sample_info.len() > u32::MAX as usize {
885 // Should never happen due to upper limits on number of sample
886 // descriptions a track can have, but lets be safe.
887 return Err(Mp4parseStatus::Invalid);
888 }
889 info.sample_info_count = sample_info.len() as u32;
890 info.sample_info = if sample_info.is_empty() {
891 std::ptr::null()
892 } else {
893 sample_info.as_ptr()
894 };
895 }
896 None => return Err(Mp4parseStatus::Invalid), // Shouldn't happen, we just inserted the info!
897 }
898
899 Ok(())
900 }
901
902 /// Fill the supplied `Mp4parseTrackVideoInfo` with metadata for `track`.
903 ///
904 /// # Safety
905 ///
906 /// This function is unsafe because it dereferences the the parser and info raw
907 /// pointers passed to it. Callers should ensure the parser pointer points to a
908 /// valid `Mp4parseParser` and that the info pointer points to a valid
909 /// `Mp4parseTrackVideoInfo`.
910 #[no_mangle]
911 pub unsafe extern "C" fn mp4parse_get_track_video_info(
912 parser: *mut Mp4parseParser,
913 track_index: u32,
914 info: *mut Mp4parseTrackVideoInfo,
915 ) -> Mp4parseStatus {
916 if parser.is_null() || info.is_null() {
917 return Mp4parseStatus::BadArg;
918 }
919
920 // Initialize fields to default values to ensure all fields are always valid.
921 *info = Default::default();
922
923 mp4parse_get_track_video_info_safe(&mut *parser, track_index, &mut *info).into()
924 }
925
926 fn mp4parse_get_track_video_info_safe(
927 parser: &mut Mp4parseParser,
928 track_index: u32,
929 info: &mut Mp4parseTrackVideoInfo,
930 ) -> Result<(), Mp4parseStatus> {
931 let context = parser.context();
932
933 if track_index as usize >= context.tracks.len() {
934 return Err(Mp4parseStatus::BadArg);
935 }
936
937 let track = &context.tracks[track_index as usize];
938
939 if track.track_type != TrackType::Video {
940 return Err(Mp4parseStatus::Invalid);
941 }
942
943 // Handle track.tkhd
944 if let Some(ref tkhd) = track.tkhd {
945 info.display_width = tkhd.width >> 16; // 16.16 fixed point
946 info.display_height = tkhd.height >> 16; // 16.16 fixed point
947 let matrix = (
948 tkhd.matrix.a >> 16,
949 tkhd.matrix.b >> 16,
950 tkhd.matrix.c >> 16,
951 tkhd.matrix.d >> 16,
952 );
953 info.rotation = match matrix {
954 (0, 1, -1, 0) => 90, // rotate 90 degrees
955 (-1, 0, 0, -1) => 180, // rotate 180 degrees
956 (0, -1, 1, 0) => 270, // rotate 270 degrees
957 _ => 0,
958 };
959 } else {
960 return Err(Mp4parseStatus::Invalid);
961 }
962
963 if let Some(ref stsd) = track.stsd {
964 for description in stsd.descriptions.iter() {
965 if let SampleEntry::Video(video) = description {
966 if let Some(ratio) = video.pixel_aspect_ratio {
967 info.pixel_aspect_ratio = ratio;
968 }
969 }
970 }
971 }
972
973 if let Some(sample_info) = parser.video_track_sample_descriptions.get(&track_index) {
974 info.sample_info_count = sample_info.len() as u32;
975 info.sample_info = if sample_info.is_empty() {
976 std::ptr::null()
977 } else {
978 sample_info.as_ptr()
979 };
980 return Ok(());
981 }
982
983 // Handle track.stsd
984 let stsd = match track.stsd {
985 Some(ref stsd) => stsd,
986 None => return Err(Mp4parseStatus::Invalid), // Stsd should be present
987 };
988
989 if stsd.descriptions.is_empty() {
990 return Err(Mp4parseStatus::Invalid); // Should have at least 1 description
991 }
992
993 let mut video_sample_infos = TryVec::with_capacity(stsd.descriptions.len())?;
994 for description in stsd.descriptions.iter() {
995 let mut sample_info = Mp4parseTrackVideoSampleInfo::default();
996 let video = match description {
997 SampleEntry::Video(v) => v,
998 _ => return Err(Mp4parseStatus::Invalid),
999 };
1000
1001 // UNKNOWN for unsupported format.
1002 sample_info.codec_type = match video.codec_specific {
1003 VideoCodecSpecific::VPxConfig(_) => Mp4parseCodec::Vp9,
1004 VideoCodecSpecific::AV1Config(_) => Mp4parseCodec::Av1,
1005 VideoCodecSpecific::AVCConfig(_) => Mp4parseCodec::Avc,
1006 VideoCodecSpecific::H263Config(_) => Mp4parseCodec::H263,
1007 VideoCodecSpecific::HEVCConfig(_) => Mp4parseCodec::Hevc,
1008 #[cfg(feature = "mp4v")]
1009 VideoCodecSpecific::ESDSConfig(_) => Mp4parseCodec::Mp4v,
1010 #[cfg(not(feature = "mp4v"))]
1011 VideoCodecSpecific::ESDSConfig(_) =>
1012 // MP4V (14496-2) video is unsupported.
1013 {
1014 Mp4parseCodec::Unknown
1015 }
1016 };
1017 sample_info.image_width = video.width;
1018 sample_info.image_height = video.height;
1019
1020 match video.codec_specific {
1021 VideoCodecSpecific::AV1Config(ref config) => {
1022 sample_info.extra_data.set_data(&config.raw_config);
1023 }
1024 VideoCodecSpecific::AVCConfig(ref data)
1025 | VideoCodecSpecific::ESDSConfig(ref data)
1026 | VideoCodecSpecific::HEVCConfig(ref data) => {
1027 sample_info.extra_data.set_data(data);
1028 }
1029 _ => {}
1030 }
1031
1032 if let Some(p) = video
1033 .protection_info
1034 .iter()
1035 .find(|sinf| sinf.tenc.is_some())
1036 {
1037 sample_info.protected_data.original_format =
1038 OptionalFourCc::Some(p.original_format.value);
1039 sample_info.protected_data.scheme_type = match p.scheme_type {
1040 Some(ref scheme_type_box) => {
1041 match scheme_type_box.scheme_type.value.as_ref() {
1042 b"cenc" => Mp4ParseEncryptionSchemeType::Cenc,
1043 b"cbcs" => Mp4ParseEncryptionSchemeType::Cbcs,
1044 // We don't support other schemes, and shouldn't reach
1045 // this case. Try to gracefully handle by treating as
1046 // no encryption case.
1047 _ => Mp4ParseEncryptionSchemeType::None,
1048 }
1049 }
1050 None => Mp4ParseEncryptionSchemeType::None,
1051 };
1052 if let Some(ref tenc) = p.tenc {
1053 sample_info.protected_data.is_encrypted = tenc.is_encrypted;
1054 sample_info.protected_data.iv_size = tenc.iv_size;
1055 sample_info.protected_data.kid.set_data(&(tenc.kid));
1056 sample_info.protected_data.crypt_byte_block =
1057 tenc.crypt_byte_block_count.unwrap_or(0);
1058 sample_info.protected_data.skip_byte_block =
1059 tenc.skip_byte_block_count.unwrap_or(0);
1060 if let Some(ref iv_vec) = tenc.constant_iv {
1061 if iv_vec.len() > u32::MAX as usize {
1062 return Err(Mp4parseStatus::Invalid);
1063 }
1064 sample_info.protected_data.constant_iv.set_data(iv_vec);
1065 };
1066 }
1067 }
1068 video_sample_infos.push(sample_info)?;
1069 }
1070
1071 parser
1072 .video_track_sample_descriptions
1073 .insert(track_index, video_sample_infos)?;
1074 match parser.video_track_sample_descriptions.get(&track_index) {
1075 Some(sample_info) => {
1076 if sample_info.len() > u32::MAX as usize {
1077 // Should never happen due to upper limits on number of sample
1078 // descriptions a track can have, but lets be safe.
1079 return Err(Mp4parseStatus::Invalid);
1080 }
1081 info.sample_info_count = sample_info.len() as u32;
1082 info.sample_info = if sample_info.is_empty() {
1083 std::ptr::null()
1084 } else {
1085 sample_info.as_ptr()
1086 };
1087 }
1088 None => return Err(Mp4parseStatus::Invalid), // Shouldn't happen, we just inserted the info!
1089 }
1090 Ok(())
1091 }
1092
1093 /// Return a struct containing meta information read by previous
1094 /// `mp4parse_avif_new()` call.
1095 ///
1096 /// `color_track_id`and `alpha_track_id` will be 0 if has_sequence is false.
1097 /// `alpha_track_id` will be 0 if no alpha aux track is present.
1098 ///
1099 /// # Safety
1100 ///
1101 /// This function is unsafe because it dereferences both the parser and
1102 /// avif_info raw pointers passed into it. Callers should ensure the parser
1103 /// pointer points to a valid `Mp4parseAvifParser`, and that the avif_info
1104 /// pointer points to a valid `Mp4parseAvifInfo`.
1105 #[no_mangle]
1106 pub unsafe extern "C" fn mp4parse_avif_get_info(
1107 parser: *const Mp4parseAvifParser,
1108 avif_info: *mut Mp4parseAvifInfo,
1109 ) -> Mp4parseStatus {
1110 if parser.is_null() || avif_info.is_null() {
1111 return Mp4parseStatus::BadArg;
1112 }
1113
1114 if let Ok(info) = mp4parse_avif_get_info_safe((*parser).context()) {
1115 *avif_info = info;
1116 Mp4parseStatus::Ok
1117 } else {
1118 Mp4parseStatus::Invalid
1119 }
1120 }
1121
1122 fn mp4parse_avif_get_info_safe(context: &AvifContext) -> mp4parse::Result<Mp4parseAvifInfo> {
1123 let info = Mp4parseAvifInfo {
1124 premultiplied_alpha: context.premultiplied_alpha,
1125 major_brand: context.major_brand.value,
1126 unsupported_features_bitfield: context.unsupported_features.into_bitfield(),
1127 spatial_extents: context.spatial_extents_ptr()?,
1128 nclx_colour_information: context
1129 .nclx_colour_information_ptr()
1130 .unwrap_or(Ok(std::ptr::null()))?,
1131 icc_colour_information: Mp4parseByteData::with_data(
1132 context.icc_colour_information().unwrap_or(Ok(&[]))?,
1133 ),
1134 image_rotation: context.image_rotation()?,
1135 image_mirror: context.image_mirror_ptr()?,
1136 pixel_aspect_ratio: context.pixel_aspect_ratio_ptr()?,
1137
1138 has_primary_item: context.primary_item_is_present(),
1139 primary_item_bit_depth: 0,
1140 has_alpha_item: context.alpha_item_is_present(),
1141 alpha_item_bit_depth: 0,
1142
1143 has_sequence: false,
1144 loop_mode: Mp4parseAvifLoopMode::NoEdits,
1145 loop_count: 0,
1146 color_track_id: 0,
1147 color_track_bit_depth: 0,
1148 alpha_track_id: 0,
1149 alpha_track_bit_depth: 0,
1150 };
1151
1152 fn get_bit_depth(data: &[u8]) -> u8 {
1153 if !data.is_empty() && data.iter().all(|v| *v == data[0]) {
1154 data[0]
1155 } else {
1156 0
1157 }
1158 }
1159 let primary_item_bit_depth =
1160 get_bit_depth(context.primary_item_bits_per_channel().unwrap_or(Ok(&[]))?);
1161 let alpha_item_bit_depth =
1162 get_bit_depth(context.alpha_item_bits_per_channel().unwrap_or(Ok(&[]))?);
1163
1164 if let Some(sequence) = &context.sequence {
1165 // Tracks must have track_id and samples
1166 fn get_track<T>(tracks: &TryVec<Track>, pred: T) -> Option<&Track>
1167 where
1168 T: Fn(&Track) -> bool,
1169 {
1170 tracks.iter().find(|track| {
1171 if track.track_id.is_none() {
1172 return false;
1173 }
1174 match &track.stsc {
1175 Some(stsc) => {
1176 if stsc.samples.is_empty() {
1177 return false;
1178 }
1179 if !pred(track) {
1180 return false;
1181 }
1182 stsc.samples.iter().any(|chunk| chunk.samples_per_chunk > 0)
1183 }
1184 _ => false,
1185 }
1186 })
1187 }
1188
1189 // Color track will be the first track found
1190 let color_track = match get_track(&sequence.tracks, |_| true) {
1191 Some(v) => v,
1192 _ => return Ok(info),
1193 };
1194
1195 // Alpha track will be the first track found with auxl.aux_for_track_id set to color_track's id
1196 let alpha_track = get_track(&sequence.tracks, |track| match &track.tref {
1197 Some(tref) => tref.has_auxl_reference(color_track.track_id.unwrap()),
1198 _ => false,
1199 });
1200
1201 fn get_av1c(track: &Track) -> Option<&AV1ConfigBox> {
1202 if let Some(stsd) = &track.stsd {
1203 for entry in &stsd.descriptions {
1204 if let SampleEntry::Video(video_entry) = entry {
1205 if let VideoCodecSpecific::AV1Config(av1c) = &video_entry.codec_specific {
1206 return Some(av1c);
1207 }
1208 }
1209 }
1210 }
1211
1212 None
1213 }
1214
1215 let color_track_id = color_track.track_id.unwrap();
1216 let color_track_bit_depth = match get_av1c(color_track) {
1217 Some(av1c) => av1c.bit_depth,
1218 _ => return Ok(info),
1219 };
1220
1221 let (alpha_track_id, alpha_track_bit_depth) = match alpha_track {
1222 Some(track) => (
1223 track.track_id.unwrap(),
1224 match get_av1c(track) {
1225 Some(av1c) => av1c.bit_depth,
1226 _ => return Ok(info),
1227 },
1228 ),
1229 _ => (0, 0),
1230 };
1231
1232 let (loop_mode, loop_count) = match color_track.tkhd.as_ref().map(|tkhd| tkhd.duration) {
1233 Some(movie_duration) if movie_duration == u64::MAX => {
1234 (Mp4parseAvifLoopMode::LoopInfinitely, 0)
1235 }
1236 Some(movie_duration) => match color_track.looped {
1237 Some(true) => match color_track.edited_duration.map(|v| v.0) {
1238 Some(segment_duration) => {
1239 match movie_duration.checked_div(segment_duration).and_then(|n| {
1240 match movie_duration.checked_rem(segment_duration) {
1241 Some(0) => Some(n.saturating_sub(1)),
1242 Some(_) => Some(n),
1243 None => None,
1244 }
1245 }) {
1246 Some(n) => (Mp4parseAvifLoopMode::LoopByCount, n),
1247 None => (Mp4parseAvifLoopMode::LoopInfinitely, 0),
1248 }
1249 }
1250 None => (Mp4parseAvifLoopMode::NoEdits, 0),
1251 },
1252 Some(false) => (Mp4parseAvifLoopMode::LoopByCount, 0),
1253 None => (Mp4parseAvifLoopMode::NoEdits, 0),
1254 },
1255 None => (Mp4parseAvifLoopMode::LoopInfinitely, 0),
1256 };
1257
1258 return Ok(Mp4parseAvifInfo {
1259 primary_item_bit_depth,
1260 alpha_item_bit_depth,
1261 has_sequence: true,
1262 loop_mode,
1263 loop_count,
1264 color_track_id,
1265 color_track_bit_depth,
1266 alpha_track_id,
1267 alpha_track_bit_depth,
1268 ..info
1269 });
1270 }
1271
1272 Ok(info)
1273 }
1274
1275 /// Return a pointer to the primary item parsed by previous `mp4parse_avif_new()` call.
1276 ///
1277 /// # Safety
1278 ///
1279 /// This function is unsafe because it dereferences both the parser and
1280 /// avif_image raw pointers passed into it. Callers should ensure the parser
1281 /// pointer points to a valid `Mp4parseAvifParser`, and that the avif_image
1282 /// pointer points to a valid `Mp4parseAvifImage`. If there was not a previous
1283 /// successful call to `mp4parse_avif_read()`, no guarantees are made as to
1284 /// the state of `avif_image`. If `avif_image.alpha_image.coded_data` is set to
1285 /// a positive `length` and non-null `data`, then the `avif_image` contains a
1286 /// valid alpha channel data. Otherwise, the image is opaque.
1287 #[no_mangle]
1288 pub unsafe extern "C" fn mp4parse_avif_get_image(
1289 parser: *const Mp4parseAvifParser,
1290 avif_image: *mut Mp4parseAvifImage,
1291 ) -> Mp4parseStatus {
1292 if parser.is_null() || avif_image.is_null() {
1293 return Mp4parseStatus::BadArg;
1294 }
1295
1296 if let Ok(image) = mp4parse_avif_get_image_safe(&*parser) {
1297 *avif_image = image;
1298 Mp4parseStatus::Ok
1299 } else {
1300 Mp4parseStatus::Invalid
1301 }
1302 }
1303
1304 pub fn mp4parse_avif_get_image_safe(
1305 parser: &Mp4parseAvifParser,
1306 ) -> mp4parse::Result<Mp4parseAvifImage> {
1307 let context = parser.context();
1308 Ok(Mp4parseAvifImage {
1309 primary_image: Mp4parseByteData::with_data(
1310 context.primary_item_coded_data().unwrap_or(&[]),
1311 ),
1312 alpha_image: Mp4parseByteData::with_data(context.alpha_item_coded_data().unwrap_or(&[])),
1313 })
1314 }
1315
1316 /// Fill the supplied `Mp4parseByteData` with index information from `track`.
1317 ///
1318 /// # Safety
1319 ///
1320 /// This function is unsafe because it dereferences the the parser and indices
1321 /// raw pointers passed to it. Callers should ensure the parser pointer points
1322 /// to a valid `Mp4parseParser` and that the indices pointer points to a valid
1323 /// `Mp4parseByteData`.
1324 #[no_mangle]
1325 pub unsafe extern "C" fn mp4parse_get_indice_table(
1326 parser: *mut Mp4parseParser,
1327 track_id: u32,
1328 indices: *mut Mp4parseByteData,
1329 ) -> Mp4parseStatus {
1330 if parser.is_null() {
1331 return Mp4parseStatus::BadArg;
1332 }
1333
1334 // Initialize fields to default values to ensure all fields are always valid.
1335 *indices = Default::default();
1336
1337 get_indice_table(
1338 &(*parser).context,
1339 &mut (*parser).sample_table,
1340 track_id,
1341 &mut *indices,
1342 )
1343 .into()
1344 }
1345
1346 /// Fill the supplied `Mp4parseByteData` with index information from `track`.
1347 ///
1348 /// # Safety
1349 ///
1350 /// This function is unsafe because it dereferences both the parser and
1351 /// indices raw pointers passed to it. Callers should ensure the parser
1352 /// points to a valid `Mp4parseAvifParser` and indices points to a valid
1353 /// `Mp4parseByteData`.
1354 #[no_mangle]
1355 pub unsafe extern "C" fn mp4parse_avif_get_indice_table(
1356 parser: *mut Mp4parseAvifParser,
1357 track_id: u32,
1358 indices: *mut Mp4parseByteData,
1359 timescale: *mut u64,
1360 ) -> Mp4parseStatus {
1361 if parser.is_null() {
1362 return Mp4parseStatus::BadArg;
1363 }
1364
1365 if indices.is_null() {
1366 return Mp4parseStatus::BadArg;
1367 }
1368
1369 if timescale.is_null() {
1370 return Mp4parseStatus::BadArg;
1371 }
1372
1373 // Initialize fields to default values to ensure all fields are always valid.
1374 *indices = Default::default();
1375
1376 if let Some(sequence) = &(*parser).context.sequence {
1377 // Use the top level timescale, and the track timescale if present.
1378 let mut found_timescale = false;
1379 if let Some(context_timescale) = sequence.timescale {
1380 *timescale = context_timescale.0;
1381 found_timescale = true;
1382 }
1383 let maybe_track_timescale = match sequence
1384 .tracks
1385 .iter()
1386 .find(|track| track.track_id == Some(track_id))
1387 {
1388 Some(track) => track.timescale,
1389 _ => None,
1390 };
1391 if let Some(track_timescale) = maybe_track_timescale {
1392 found_timescale = true;
1393 *timescale = track_timescale.0;
1394 }
1395 if !found_timescale {
1396 return Mp4parseStatus::Invalid;
1397 }
1398 return get_indice_table(
1399 sequence,
1400 &mut (*parser).sample_table,
1401 track_id,
1402 &mut *indices,
1403 )
1404 .into();
1405 }
1406
1407 Mp4parseStatus::BadArg
1408 }
1409
1410 fn get_indice_table(
1411 context: &MediaContext,
1412 sample_table_cache: &mut TryHashMap<u32, TryVec<Indice>>,
1413 track_id: u32,
1414 indices: &mut Mp4parseByteData,
1415 ) -> Result<(), Mp4parseStatus> {
1416 let tracks = &context.tracks;
1417 let track = match tracks.iter().find(|track| track.track_id == Some(track_id)) {
1418 Some(t) => t,
1419 _ => return Err(Mp4parseStatus::Invalid),
1420 };
1421
1422 if let Some(v) = sample_table_cache.get(&track_id) {
1423 indices.set_indices(v);
1424 return Ok(());
1425 }
1426
1427 let media_time = match &track.media_time {
1428 &Some(t) => i64::try_from(t.0).ok().map(Into::into),
1429 _ => None,
1430 };
1431
1432 let empty_duration: Option<CheckedInteger<_>> = match &track.empty_duration {
1433 &Some(e) => i64::try_from(e.0).ok().map(Into::into),
1434 _ => None,
1435 };
1436
1437 // Find the track start offset time from 'elst'.
1438 // 'media_time' maps start time onward, 'empty_duration' adds time offset
1439 // before first frame is displayed.
1440 let offset_time = match (empty_duration, media_time) {
1441 (Some(e), Some(m)) => (e - m).ok_or(Err(Mp4parseStatus::Invalid))?,
1442 (Some(e), None) => e,
1443 (None, Some(m)) => m,
1444 _ => 0.into(),
1445 };
1446
1447 if let Some(v) = create_sample_table(track, offset_time) {
1448 indices.set_indices(&v);
1449 sample_table_cache.insert(track_id, v)?;
1450 return Ok(());
1451 }
1452
1453 Err(Mp4parseStatus::Invalid)
1454 }
1455
1456 /// Fill the supplied `Mp4parseFragmentInfo` with metadata from fragmented file.
1457 ///
1458 /// # Safety
1459 ///
1460 /// This function is unsafe because it dereferences the the parser and
1461 /// info raw pointers passed to it. Callers should ensure the parser
1462 /// pointer points to a valid `Mp4parseParser` and that the info pointer points
1463 /// to a valid `Mp4parseFragmentInfo`.
1464 #[no_mangle]
1465 pub unsafe extern "C" fn mp4parse_get_fragment_info(
1466 parser: *mut Mp4parseParser,
1467 info: *mut Mp4parseFragmentInfo,
1468 ) -> Mp4parseStatus {
1469 if parser.is_null() || info.is_null() {
1470 return Mp4parseStatus::BadArg;
1471 }
1472
1473 // Initialize fields to default values to ensure all fields are always valid.
1474 *info = Default::default();
1475
1476 let context = (*parser).context();
1477 let info: &mut Mp4parseFragmentInfo = &mut *info;
1478
1479 info.fragment_duration = 0;
1480
1481 let duration = match context.mvex {
1482 Some(ref mvex) => mvex.fragment_duration,
1483 None => return Mp4parseStatus::Invalid,
1484 };
1485
1486 if let (Some(time), Some(scale)) = (duration, context.timescale) {
1487 info.fragment_duration = time.0;
1488 info.time_scale = scale.0;
1489 return Mp4parseStatus::Ok;
1490 };
1491 Mp4parseStatus::Invalid
1492 }
1493
1494 /// Determine if an mp4 file is fragmented. A fragmented file needs mvex table
1495 /// and contains no data in stts, stsc, and stco boxes.
1496 ///
1497 /// # Safety
1498 ///
1499 /// This function is unsafe because it dereferences the the parser and
1500 /// fragmented raw pointers passed to it. Callers should ensure the parser
1501 /// pointer points to a valid `Mp4parseParser` and that the fragmented pointer
1502 /// points to an appropriate memory location to have a `u8` written to.
1503 #[no_mangle]
1504 pub unsafe extern "C" fn mp4parse_is_fragmented(
1505 parser: *mut Mp4parseParser,
1506 track_id: u32,
1507 fragmented: *mut u8,
1508 ) -> Mp4parseStatus {
1509 if parser.is_null() {
1510 return Mp4parseStatus::BadArg;
1511 }
1512
1513 let context = (*parser).context_mut();
1514 let tracks = &context.tracks;
1515 (*fragmented) = false as u8;
1516
1517 if context.mvex.is_none() {
1518 return Mp4parseStatus::Ok;
1519 }
1520
1521 // check sample tables.
1522 let mut iter = tracks.iter();
1523 iter.find(|track| track.track_id == Some(track_id))
1524 .map_or(Mp4parseStatus::BadArg, |track| {
1525 match (&track.stsc, &track.stco, &track.stts) {
1526 (Some(stsc), Some(stco), Some(stts))
1527 if stsc.samples.is_empty()
1528 && stco.offsets.is_empty()
1529 && stts.samples.is_empty() =>
1530 {
1531 (*fragmented) = true as u8
1532 }
1533 _ => {}
1534 };
1535 Mp4parseStatus::Ok
1536 })
1537 }
1538
1539 /// Get 'pssh' system id and 'pssh' box content for eme playback.
1540 ///
1541 /// The data format of the `info` struct passed to gecko is:
1542 ///
1543 /// - system id (16 byte uuid)
1544 /// - pssh box size (32-bit native endian)
1545 /// - pssh box content (including header)
1546 ///
1547 /// # Safety
1548 ///
1549 /// This function is unsafe because it dereferences the the parser and
1550 /// info raw pointers passed to it. Callers should ensure the parser
1551 /// pointer points to a valid `Mp4parseParser` and that the fragmented pointer
1552 /// points to a valid `Mp4parsePsshInfo`.
1553 #[no_mangle]
1554 pub unsafe extern "C" fn mp4parse_get_pssh_info(
1555 parser: *mut Mp4parseParser,
1556 info: *mut Mp4parsePsshInfo,
1557 ) -> Mp4parseStatus {
1558 if parser.is_null() || info.is_null() {
1559 return Mp4parseStatus::BadArg;
1560 }
1561
1562 // Initialize fields to default values to ensure all fields are always valid.
1563 *info = Default::default();
1564
1565 get_pssh_info(&mut *parser, &mut *info).into()
1566 }
1567
1568 fn get_pssh_info(
1569 parser: &mut Mp4parseParser,
1570 info: &mut Mp4parsePsshInfo,
1571 ) -> Result<(), Mp4parseStatus> {
1572 let Mp4parseParser {
1573 context, pssh_data, ..
1574 } = parser;
1575
1576 if pssh_data.is_none() {
1577 let mut tmp = TryVec::new();
1578 for pssh in &context.psshs {
1579 let content_len = pssh
1580 .box_content
1581 .len()
1582 .try_into()
1583 .map_err(|_| Mp4parseStatus::Invalid)?;
1584 let mut data_len = TryVec::new();
1585 data_len.write_u32::<byteorder::NativeEndian>(content_len)?;
1586 tmp.extend_from_slice(pssh.system_id.as_slice())?;
1587 tmp.extend_from_slice(data_len.as_slice())?;
1588 tmp.extend_from_slice(pssh.box_content.as_slice())?;
1589 }
1590 *pssh_data = Some(tmp);
1591 }
1592
1593 match pssh_data {
1594 Some(ref data) => info.data.set_data(data),
1595 None => info.data = Default::default(),
1596 }
1597
1598 Ok(())
1599 }
1600
1601 #[cfg(test)]
1602 extern "C" fn error_read(_: *mut u8, _: usize, _: *mut std::os::raw::c_void) -> isize {
1603 -1
1604 }
1605
1606 #[cfg(test)]
1607 extern "C" fn valid_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
1608 let input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
1609
1610 let buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
1611 match input.read(buf) {
1612 Ok(n) => n as isize,
1613 Err(_) => -1,
1614 }
1615 }
1616
1617 #[test]
1618 fn get_track_count_null_parser() {
1619 unsafe {
1620 let mut count: u32 = 0;
1621 let rv = mp4parse_get_track_count(std::ptr::null(), std::ptr::null_mut());
1622 assert_eq!(rv, Mp4parseStatus::BadArg);
1623 let rv = mp4parse_get_track_count(std::ptr::null(), &mut count);
1624 assert_eq!(rv, Mp4parseStatus::BadArg);
1625 }
1626 }
1627
1628 #[test]
1629 fn arg_validation() {
1630 unsafe {
1631 let rv = mp4parse_new(std::ptr::null(), std::ptr::null_mut());
1632 assert_eq!(rv, Mp4parseStatus::BadArg);
1633
1634 // Passing a null Mp4parseIo is an error.
1635 let mut parser = std::ptr::null_mut();
1636 let rv = mp4parse_new(std::ptr::null(), &mut parser);
1637 assert_eq!(rv, Mp4parseStatus::BadArg);
1638 assert!(parser.is_null());
1639
1640 let null_mut: *mut std::os::raw::c_void = std::ptr::null_mut();
1641
1642 // Passing an Mp4parseIo with null members is an error.
1643 let io = Mp4parseIo {
1644 read: None,
1645 userdata: null_mut,
1646 };
1647 let mut parser = std::ptr::null_mut();
1648 let rv = mp4parse_new(&io, &mut parser);
1649 assert_eq!(rv, Mp4parseStatus::BadArg);
1650 assert!(parser.is_null());
1651
1652 let mut dummy_value = 42;
1653 let io = Mp4parseIo {
1654 read: None,
1655 userdata: &mut dummy_value as *mut _ as *mut std::os::raw::c_void,
1656 };
1657 let mut parser = std::ptr::null_mut();
1658 let rv = mp4parse_new(&io, &mut parser);
1659 assert_eq!(rv, Mp4parseStatus::BadArg);
1660 assert!(parser.is_null());
1661
1662 let mut dummy_info = Mp4parseTrackInfo {
1663 track_type: Mp4parseTrackType::Video,
1664 ..Default::default()
1665 };
1666 assert_eq!(
1667 Mp4parseStatus::BadArg,
1668 mp4parse_get_track_info(std::ptr::null_mut(), 0, &mut dummy_info)
1669 );
1670
1671 let mut dummy_video = Default::default();
1672 assert_eq!(
1673 Mp4parseStatus::BadArg,
1674 mp4parse_get_track_video_info(std::ptr::null_mut(), 0, &mut dummy_video)
1675 );
1676
1677 let mut dummy_audio = Default::default();
1678 assert_eq!(
1679 Mp4parseStatus::BadArg,
1680 mp4parse_get_track_audio_info(std::ptr::null_mut(), 0, &mut dummy_audio)
1681 );
1682 }
1683 }
1684
1685 #[test]
1686 fn parser_input_must_be_null() {
1687 let mut dummy_value = 42;
1688 let io = Mp4parseIo {
1689 read: Some(error_read),
1690 userdata: &mut dummy_value as *mut _ as *mut std::os::raw::c_void,
1691 };
1692 let mut parser = 0xDEAD_BEEF as *mut _;
1693 let rv = unsafe { mp4parse_new(&io, &mut parser) };
1694 assert_eq!(rv, Mp4parseStatus::BadArg);
1695 }
1696
1697 #[test]
1698 fn arg_validation_with_parser() {
1699 unsafe {
1700 let mut dummy_value = 42;
1701 let io = Mp4parseIo {
1702 read: Some(error_read),
1703 userdata: &mut dummy_value as *mut _ as *mut std::os::raw::c_void,
1704 };
1705 let mut parser = std::ptr::null_mut();
1706 let rv = mp4parse_new(&io, &mut parser);
1707 assert_eq!(rv, Mp4parseStatus::Io);
1708 assert!(parser.is_null());
1709
1710 // Null info pointers are an error.
1711 assert_eq!(
1712 Mp4parseStatus::BadArg,
1713 mp4parse_get_track_info(parser, 0, std::ptr::null_mut())
1714 );
1715 assert_eq!(
1716 Mp4parseStatus::BadArg,
1717 mp4parse_get_track_video_info(parser, 0, std::ptr::null_mut())
1718 );
1719 assert_eq!(
1720 Mp4parseStatus::BadArg,
1721 mp4parse_get_track_audio_info(parser, 0, std::ptr::null_mut())
1722 );
1723
1724 let mut dummy_info = Mp4parseTrackInfo {
1725 track_type: Mp4parseTrackType::Video,
1726 ..Default::default()
1727 };
1728 assert_eq!(
1729 Mp4parseStatus::BadArg,
1730 mp4parse_get_track_info(parser, 0, &mut dummy_info)
1731 );
1732
1733 let mut dummy_video = Default::default();
1734 assert_eq!(
1735 Mp4parseStatus::BadArg,
1736 mp4parse_get_track_video_info(parser, 0, &mut dummy_video)
1737 );
1738
1739 let mut dummy_audio = Default::default();
1740 assert_eq!(
1741 Mp4parseStatus::BadArg,
1742 mp4parse_get_track_audio_info(parser, 0, &mut dummy_audio)
1743 );
1744 }
1745 }
1746
1747 #[cfg(test)]
1748 fn parse_minimal_mp4() -> *mut Mp4parseParser {
1749 let mut file = std::fs::File::open("../mp4parse/tests/minimal.mp4").unwrap();
1750 let io = Mp4parseIo {
1751 read: Some(valid_read),
1752 userdata: &mut file as *mut _ as *mut std::os::raw::c_void,
1753 };
1754 let mut parser = std::ptr::null_mut();
1755 let rv = unsafe { mp4parse_new(&io, &mut parser) };
1756 assert_eq!(Mp4parseStatus::Ok, rv);
1757 parser
1758 }
1759
1760 #[test]
1761 fn minimal_mp4_parse_ok() {
1762 let parser = parse_minimal_mp4();
1763
1764 assert!(!parser.is_null());
1765
1766 unsafe {
1767 mp4parse_free(parser);
1768 }
1769 }
1770
1771 #[test]
1772 fn minimal_mp4_get_track_cout() {
1773 let parser = parse_minimal_mp4();
1774
1775 let mut count: u32 = 0;
1776 assert_eq!(Mp4parseStatus::Ok, unsafe {
1777 mp4parse_get_track_count(parser, &mut count)
1778 });
1779 assert_eq!(2, count);
1780
1781 unsafe {
1782 mp4parse_free(parser);
1783 }
1784 }
1785
1786 #[test]
1787 fn minimal_mp4_get_track_info() {
1788 let parser = parse_minimal_mp4();
1789
1790 let mut info = Mp4parseTrackInfo {
1791 track_type: Mp4parseTrackType::Video,
1792 ..Default::default()
1793 };
1794 assert_eq!(Mp4parseStatus::Ok, unsafe {
1795 mp4parse_get_track_info(parser, 0, &mut info)
1796 });
1797 assert_eq!(info.track_type, Mp4parseTrackType::Video);
1798 assert_eq!(info.track_id, 1);
1799 assert_eq!(info.duration, 512);
1800 assert_eq!(info.media_time, 0);
1801
1802 assert_eq!(Mp4parseStatus::Ok, unsafe {
1803 mp4parse_get_track_info(parser, 1, &mut info)
1804 });
1805 assert_eq!(info.track_type, Mp4parseTrackType::Audio);
1806 assert_eq!(info.track_id, 2);
1807 assert_eq!(info.duration, 2944);
1808 assert_eq!(info.media_time, 1024);
1809
1810 unsafe {
1811 mp4parse_free(parser);
1812 }
1813 }
1814
1815 #[test]
1816 fn minimal_mp4_get_track_video_info() {
1817 let parser = parse_minimal_mp4();
1818
1819 let mut video = Mp4parseTrackVideoInfo::default();
1820 assert_eq!(Mp4parseStatus::Ok, unsafe {
1821 mp4parse_get_track_video_info(parser, 0, &mut video)
1822 });
1823 assert_eq!(video.display_width, 320);
1824 assert_eq!(video.display_height, 240);
1825 assert_eq!(video.sample_info_count, 1);
1826
1827 unsafe {
1828 assert_eq!((*video.sample_info).image_width, 320);
1829 assert_eq!((*video.sample_info).image_height, 240);
1830 }
1831
1832 unsafe {
1833 mp4parse_free(parser);
1834 }
1835 }
1836
1837 #[test]
1838 fn minimal_mp4_get_track_audio_info() {
1839 let parser = parse_minimal_mp4();
1840
1841 let mut audio = Mp4parseTrackAudioInfo::default();
1842 assert_eq!(Mp4parseStatus::Ok, unsafe {
1843 mp4parse_get_track_audio_info(parser, 1, &mut audio)
1844 });
1845 assert_eq!(audio.sample_info_count, 1);
1846
1847 unsafe {
1848 assert_eq!((*audio.sample_info).channels, 1);
1849 assert_eq!((*audio.sample_info).bit_depth, 16);
1850 assert_eq!((*audio.sample_info).sample_rate, 48000);
1851 }
1852
1853 unsafe {
1854 mp4parse_free(parser);
1855 }
1856 }
1857
1858 #[test]
1859 fn minimal_mp4_get_track_info_invalid_track_number() {
1860 let parser = parse_minimal_mp4();
1861
1862 let mut info = Mp4parseTrackInfo {
1863 track_type: Mp4parseTrackType::Video,
1864 ..Default::default()
1865 };
1866 assert_eq!(Mp4parseStatus::BadArg, unsafe {
1867 mp4parse_get_track_info(parser, 3, &mut info)
1868 });
1869 assert_eq!(info.track_type, Mp4parseTrackType::Video);
1870 assert_eq!(info.track_id, 0);
1871 assert_eq!(info.duration, 0);
1872 assert_eq!(info.media_time, 0);
1873
1874 let mut video = Mp4parseTrackVideoInfo::default();
1875 assert_eq!(Mp4parseStatus::BadArg, unsafe {
1876 mp4parse_get_track_video_info(parser, 3, &mut video)
1877 });
1878 assert_eq!(video.display_width, 0);
1879 assert_eq!(video.display_height, 0);
1880 assert_eq!(video.sample_info_count, 0);
1881
1882 let mut audio = Default::default();
1883 assert_eq!(Mp4parseStatus::BadArg, unsafe {
1884 mp4parse_get_track_audio_info(parser, 3, &mut audio)
1885 });
1886 assert_eq!(audio.sample_info_count, 0);
1887
1888 unsafe {
1889 mp4parse_free(parser);
1890 }
1891 }
1892
1893 #[test]
1894 fn parse_no_timescale() {
1895 let mut file = std::fs::File::open("tests/no_timescale.mp4").expect("Unknown file");
1896 let io = Mp4parseIo {
1897 read: Some(valid_read),
1898 userdata: &mut file as *mut _ as *mut std::os::raw::c_void,
1899 };
1900
1901 unsafe {
1902 let mut parser = std::ptr::null_mut();
1903 let mut rv = mp4parse_new(&io, &mut parser);
1904 assert_eq!(rv, Mp4parseStatus::Ok);
1905 assert!(!parser.is_null());
1906
1907 // The file has a video track, but the track has a timescale of 0, so.
1908 let mut track_info = Mp4parseTrackInfo::default();
1909 rv = mp4parse_get_track_info(parser, 0, &mut track_info);
1910 assert_eq!(rv, Mp4parseStatus::Invalid);
1911 };
1912 }