-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathlib.rs
1948 lines (1731 loc) · 62.1 KB
/
lib.rs
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! C API for mp4parse module.
//!
//! Parses ISO Base Media Format aka video/mp4 streams.
//!
//! # Examples
//!
//! ```rust
//! extern crate mp4parse_capi;
//! use std::io::Read;
//!
//! extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
//! let mut input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
//! let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
//! match input.read(&mut buf) {
//! Ok(n) => n as isize,
//! Err(_) => -1,
//! }
//! }
//!
//! let mut file = std::fs::File::open("../mp4parse/tests/minimal.mp4").unwrap();
//! let io = mp4parse_capi::Mp4parseIo {
//! read: Some(buf_read),
//! userdata: &mut file as *mut _ as *mut std::os::raw::c_void
//! };
//! let mut parser = std::ptr::null_mut();
//! unsafe {
//! let rv = mp4parse_capi::mp4parse_new(&io, &mut parser);
//! assert_eq!(rv, mp4parse_capi::Mp4parseStatus::Ok);
//! assert!(!parser.is_null());
//! mp4parse_capi::mp4parse_free(parser);
//! }
//! ```
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
extern crate byteorder;
extern crate mp4parse;
extern crate num_traits;
use byteorder::WriteBytesExt;
use num_traits::{PrimInt, Zero};
use std::io::Read;
// Symbols we need from our rust api.
use mp4parse::read_avif;
use mp4parse::read_mp4;
use mp4parse::serialize_opus_header;
use mp4parse::AudioCodecSpecific;
use mp4parse::AvifContext;
use mp4parse::CodecType;
use mp4parse::Error;
use mp4parse::MediaContext;
use mp4parse::MediaScaledTime;
use mp4parse::MediaTimeScale;
use mp4parse::SampleEntry;
use mp4parse::Track;
use mp4parse::TrackScaledTime;
use mp4parse::TrackTimeScale;
use mp4parse::TrackType;
use mp4parse::TryBox;
use mp4parse::TryHashMap;
use mp4parse::TryVec;
use mp4parse::VideoCodecSpecific;
// To ensure we don't use stdlib allocating types by accident
#[allow(dead_code)]
struct Vec;
#[allow(dead_code)]
struct Box;
#[allow(dead_code)]
struct HashMap;
#[allow(dead_code)]
struct String;
#[repr(C)]
#[derive(PartialEq, Debug)]
pub enum Mp4parseStatus {
Ok = 0,
BadArg = 1,
Invalid = 2,
Unsupported = 3,
Eof = 4,
Io = 5,
Oom = 6,
}
#[repr(C)]
#[derive(PartialEq, Debug)]
pub enum Mp4parseTrackType {
Video = 0,
Audio = 1,
Metadata = 2,
}
impl Default for Mp4parseTrackType {
fn default() -> Self {
Mp4parseTrackType::Video
}
}
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(PartialEq, Debug)]
pub enum Mp4parseCodec {
Unknown,
Aac,
Flac,
Opus,
Avc,
Vp9,
Av1,
Mp3,
Mp4v,
Jpeg, // for QT JPEG atom in video track
Ac3,
Ec3,
Alac,
}
impl Default for Mp4parseCodec {
fn default() -> Self {
Mp4parseCodec::Unknown
}
}
#[repr(C)]
#[derive(PartialEq, Debug)]
pub enum Mp4ParseEncryptionSchemeType {
None,
Cenc,
Cbc1,
Cens,
Cbcs,
// Schemes also have a version component. At the time of writing, this does
// not impact handling, so we do not expose it. Note that this may need to
// be exposed in future, should the spec change.
}
impl Default for Mp4ParseEncryptionSchemeType {
fn default() -> Self {
Mp4ParseEncryptionSchemeType::None
}
}
#[repr(C)]
#[derive(Default, Debug)]
pub struct Mp4parseTrackInfo {
pub track_type: Mp4parseTrackType,
pub track_id: u32,
pub duration: u64,
pub media_time: i64, // wants to be u64? understand how elst adjustment works
// TODO(kinetik): include crypto guff
}
#[repr(C)]
#[derive(Default, Debug, PartialEq)]
pub struct Mp4parseIndice {
/// The byte offset in the file where the indexed sample begins.
pub start_offset: u64,
/// The byte offset in the file where the indexed sample ends. This is
/// equivalent to `start_offset` + the length in bytes of the indexed
/// sample. Typically this will be the `start_offset` of the next sample
/// in the file.
pub end_offset: u64,
/// The time in microseconds when the indexed sample should be displayed.
/// Analogous to the concept of presentation time stamp (pts).
pub start_composition: i64,
/// The time in microseconds when the indexed sample should stop being
/// displayed. Typically this would be the `start_composition` time of the
/// next sample if samples were ordered by composition time.
pub end_composition: i64,
/// The time in microseconds that the indexed sample should be decoded at.
/// Analogous to the concept of decode time stamp (dts).
pub start_decode: i64,
/// Set if the indexed sample is a sync sample. The meaning of sync is
/// somewhat codec specific, but essentially amounts to if the sample is a
/// key frame.
pub sync: bool,
}
#[repr(C)]
#[derive(Debug)]
pub struct Mp4parseByteData {
pub length: u32,
// cheddar can't handle generic type, so it needs to be multiple data types here.
pub data: *const u8,
pub indices: *const Mp4parseIndice,
}
impl Default for Mp4parseByteData {
fn default() -> Self {
Self {
length: 0,
data: std::ptr::null(),
indices: std::ptr::null(),
}
}
}
impl Mp4parseByteData {
fn set_data(&mut self, data: &[u8]) {
self.length = data.len() as u32;
self.data = data.as_ptr();
}
fn set_indices(&mut self, data: &[Mp4parseIndice]) {
self.length = data.len() as u32;
self.indices = data.as_ptr();
}
}
#[repr(C)]
#[derive(Default)]
pub struct Mp4parsePsshInfo {
pub data: Mp4parseByteData,
}
#[repr(C)]
#[derive(Default, Debug)]
pub struct Mp4parseSinfInfo {
pub scheme_type: Mp4ParseEncryptionSchemeType,
pub is_encrypted: u8,
pub iv_size: u8,
pub kid: Mp4parseByteData,
// Members for pattern encryption schemes, may be 0 (u8) or empty
// (Mp4parseByteData) if pattern encryption is not in use
pub crypt_byte_block: u8,
pub skip_byte_block: u8,
pub constant_iv: Mp4parseByteData,
// End pattern encryption scheme members
}
#[repr(C)]
#[derive(Default, Debug)]
pub struct Mp4parseTrackAudioSampleInfo {
pub codec_type: Mp4parseCodec,
pub channels: u16,
pub bit_depth: u16,
pub sample_rate: u32,
pub profile: u16,
pub extended_profile: u16,
pub codec_specific_config: Mp4parseByteData,
pub extra_data: Mp4parseByteData,
pub protected_data: Mp4parseSinfInfo,
}
#[repr(C)]
#[derive(Debug)]
pub struct Mp4parseTrackAudioInfo {
pub sample_info_count: u32,
pub sample_info: *const Mp4parseTrackAudioSampleInfo,
}
impl Default for Mp4parseTrackAudioInfo {
fn default() -> Self {
Self {
sample_info_count: 0,
sample_info: std::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Default, Debug)]
pub struct Mp4parseTrackVideoSampleInfo {
pub codec_type: Mp4parseCodec,
pub image_width: u16,
pub image_height: u16,
pub extra_data: Mp4parseByteData,
pub protected_data: Mp4parseSinfInfo,
}
#[repr(C)]
#[derive(Debug)]
pub struct Mp4parseTrackVideoInfo {
pub display_width: u32,
pub display_height: u32,
pub rotation: u16,
pub sample_info_count: u32,
pub sample_info: *const Mp4parseTrackVideoSampleInfo,
}
impl Default for Mp4parseTrackVideoInfo {
fn default() -> Self {
Self {
display_width: 0,
display_height: 0,
rotation: 0,
sample_info_count: 0,
sample_info: std::ptr::null(),
}
}
}
#[repr(C)]
#[derive(Default, Debug)]
pub struct Mp4parseFragmentInfo {
pub fragment_duration: u64,
// TODO:
// info in trex box.
}
#[derive(Default)]
pub struct Mp4parseParser {
context: MediaContext,
opus_header: TryHashMap<u32, TryVec<u8>>,
pssh_data: TryVec<u8>,
sample_table: TryHashMap<u32, TryVec<Mp4parseIndice>>,
// Store a mapping from track index (not id) to associated sample
// descriptions. Because each track has a variable number of sample
// descriptions, and because we need the data to live long enough to be
// copied out by callers, we store these on the parser struct.
audio_track_sample_descriptions: TryHashMap<u32, TryVec<Mp4parseTrackAudioSampleInfo>>,
video_track_sample_descriptions: TryHashMap<u32, TryVec<Mp4parseTrackVideoSampleInfo>>,
}
/// A unified interface for the parsers which have different contexts, but
/// share the same pattern of construction. This allows unification of
/// argument validation from C and minimizes the surface of unsafe code.
trait ContextParser
where
Self: Sized,
{
type Context: Default;
fn with_context(context: Self::Context) -> Self;
fn read<T: Read>(io: &mut T, context: &mut Self::Context) -> mp4parse::Result<()>;
}
impl Mp4parseParser {
fn context(&self) -> &MediaContext {
&self.context
}
fn context_mut(&mut self) -> &mut MediaContext {
&mut self.context
}
}
impl ContextParser for Mp4parseParser {
type Context = MediaContext;
fn with_context(context: Self::Context) -> Self {
Self {
context,
..Default::default()
}
}
fn read<T: Read>(io: &mut T, context: &mut Self::Context) -> mp4parse::Result<()> {
read_mp4(io, context)
}
}
#[derive(Default)]
pub struct Mp4parseAvifParser {
context: AvifContext,
}
impl Mp4parseAvifParser {
fn context(&self) -> &AvifContext {
&self.context
}
}
impl ContextParser for Mp4parseAvifParser {
type Context = AvifContext;
fn with_context(context: Self::Context) -> Self {
Self { context }
}
fn read<T: Read>(io: &mut T, context: &mut Self::Context) -> mp4parse::Result<()> {
read_avif(io, context)
}
}
#[repr(C)]
#[derive(Clone)]
pub struct Mp4parseIo {
pub read: Option<
extern "C" fn(buffer: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize,
>,
pub userdata: *mut std::os::raw::c_void,
}
impl Read for Mp4parseIo {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if buf.len() > isize::max_value() as usize {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"buf length overflow in Mp4parseIo Read impl",
));
}
let rv = self.read.unwrap()(buf.as_mut_ptr(), buf.len(), self.userdata);
if rv >= 0 {
Ok(rv as usize)
} else {
Err(std::io::Error::new(
std::io::ErrorKind::Other,
"I/O error in Mp4parseIo Read impl",
))
}
}
}
// C API wrapper functions.
/// Allocate an `Mp4parseParser*` to read from the supplied `Mp4parseIo` and
/// parse the content from the `Mp4parseIo` argument until EOF or error.
///
/// # Safety
///
/// This function is unsafe because it dereferences the `io` and `parser_out`
/// pointers given to it. The caller should ensure that the `Mp4ParseIo`
/// struct passed in is a valid pointer. The caller should also ensure the
/// members of io are valid: the `read` function should be sanely implemented,
/// and the `userdata` pointer should be valid. The `parser_out` should be a
/// valid pointer to a location containing a null pointer. Upon successful
/// return (`Mp4parseStatus::Ok`), that location will contain the address of
/// an `Mp4parseParser` allocated by this function.
///
/// To avoid leaking memory, any successful return of this function must be
/// paired with a call to `mp4parse_free`. In the event of error, no memory
/// will be allocated and `mp4parse_free` must *not* be called.
#[no_mangle]
pub unsafe extern "C" fn mp4parse_new(
io: *const Mp4parseIo,
parser_out: *mut *mut Mp4parseParser,
) -> Mp4parseStatus {
mp4parse_new_common(io, parser_out)
}
/// Allocate an `Mp4parseAvifParser*` to read from the supplied `Mp4parseIo`.
///
/// See mp4parse_new; this function is identical except that it allocates an
/// `Mp4parseAvifParser`, which (when successful) must be paired with a call
/// to mp4parse_avif_free.
///
/// # Safety
///
/// Same as mp4parse_new.
#[no_mangle]
pub unsafe extern "C" fn mp4parse_avif_new(
io: *const Mp4parseIo,
parser_out: *mut *mut Mp4parseAvifParser,
) -> Mp4parseStatus {
mp4parse_new_common(io, parser_out)
}
unsafe fn mp4parse_new_common<P: ContextParser>(
io: *const Mp4parseIo,
parser_out: *mut *mut P,
) -> Mp4parseStatus {
// Validate arguments from C.
if io.is_null()
|| (*io).userdata.is_null()
|| (*io).read.is_none()
|| parser_out.is_null()
|| !(*parser_out).is_null()
{
Mp4parseStatus::BadArg
} else {
match mp4parse_new_common_safe(&mut (*io).clone()) {
Ok(parser) => {
*parser_out = parser;
Mp4parseStatus::Ok
}
Err(status) => status,
}
}
}
fn mp4parse_new_common_safe<T: Read, P: ContextParser>(
io: &mut T,
) -> Result<*mut P, Mp4parseStatus> {
let mut context = P::Context::default();
P::read(io, &mut context)
.map(|_| P::with_context(context))
.and_then(TryBox::try_new)
.map(TryBox::into_raw)
.map_err(Mp4parseStatus::from)
}
impl From<mp4parse::Error> for Mp4parseStatus {
fn from(error: mp4parse::Error) -> Self {
match error {
Error::NoMoov | Error::InvalidData(_) => Mp4parseStatus::Invalid,
Error::Unsupported(_) => Mp4parseStatus::Unsupported,
Error::UnexpectedEOF => Mp4parseStatus::Eof,
Error::Io(_) => {
// Getting std::io::ErrorKind::UnexpectedEof is normal
// but our From trait implementation should have converted
// those to our Error::UnexpectedEOF variant.
Mp4parseStatus::Io
}
Error::OutOfMemory => Mp4parseStatus::Oom,
}
}
}
impl From<Result<(), Mp4parseStatus>> for Mp4parseStatus {
fn from(result: Result<(), Mp4parseStatus>) -> Self {
match result {
Ok(()) => Mp4parseStatus::Ok,
Err(Mp4parseStatus::Ok) => unreachable!(),
Err(e) => e,
}
}
}
/// Free an `Mp4parseParser*` allocated by `mp4parse_new()`.
///
/// # Safety
///
/// This function is unsafe because it creates a box from a raw pointer.
/// Callers should ensure that the parser pointer points to a valid
/// `Mp4parseParser` created by `mp4parse_new`.
#[no_mangle]
pub unsafe extern "C" fn mp4parse_free(parser: *mut Mp4parseParser) {
assert!(!parser.is_null());
let _ = TryBox::from_raw(parser);
}
/// Free an `Mp4parseAvifParser*` allocated by `mp4parse_avif_new()`.
///
/// # Safety
///
/// This function is unsafe because it creates a box from a raw pointer.
/// Callers should ensure that the parser pointer points to a valid
/// `Mp4parseAvifParser` created by `mp4parse_avif_new`.
#[no_mangle]
pub unsafe extern "C" fn mp4parse_avif_free(parser: *mut Mp4parseAvifParser) {
assert!(!parser.is_null());
let _ = TryBox::from_raw(parser);
}
/// Return the number of tracks parsed by previous `mp4parse_read()` call.
///
/// # Safety
///
/// This function is unsafe because it dereferences both the parser and count
/// raw pointers passed into it. Callers should ensure the parser pointer
/// points to a valid `Mp4parseParser`, and that the count pointer points an
/// appropriate memory location to have a `u32` written to.
#[no_mangle]
pub unsafe extern "C" fn mp4parse_get_track_count(
parser: *const Mp4parseParser,
count: *mut u32,
) -> Mp4parseStatus {
// Validate arguments from C.
if parser.is_null() || count.is_null() {
return Mp4parseStatus::BadArg;
}
let context = (*parser).context();
// Make sure the track count fits in a u32.
if context.tracks.len() > u32::max_value() as usize {
return Mp4parseStatus::Invalid;
}
*count = context.tracks.len() as u32;
Mp4parseStatus::Ok
}
/// Calculate numerator * scale / denominator, if possible.
///
/// Applying the associativity of integer arithmetic, we divide first
/// and add the remainder after multiplying each term separately
/// to preserve precision while leaving more headroom. That is,
/// (n * s) / d is split into floor(n / d) * s + (n % d) * s / d.
///
/// Return None on overflow or if the denominator is zero.
fn rational_scale<T, S>(numerator: T, denominator: T, scale2: S) -> Option<T>
where
T: PrimInt + Zero,
S: PrimInt,
{
if denominator.is_zero() {
return None;
}
let integer = numerator / denominator;
let remainder = numerator % denominator;
num_traits::cast(scale2).and_then(|s| match integer.checked_mul(&s) {
Some(integer) => remainder
.checked_mul(&s)
.and_then(|remainder| (remainder / denominator).checked_add(&integer)),
None => None,
})
}
fn media_time_to_us(time: MediaScaledTime, scale: MediaTimeScale) -> Option<u64> {
let microseconds_per_second = 1_000_000;
rational_scale::<u64, u64>(time.0, scale.0, microseconds_per_second)
}
fn track_time_to_us<T>(time: TrackScaledTime<T>, scale: TrackTimeScale<T>) -> Option<T>
where
T: PrimInt + Zero,
{
assert_eq!(time.1, scale.1);
let microseconds_per_second = 1_000_000;
rational_scale::<T, u64>(time.0, scale.0, microseconds_per_second)
}
/// Fill the supplied `Mp4parseTrackInfo` with metadata for `track`.
///
/// # Safety
///
/// This function is unsafe because it dereferences the the parser and info raw
/// pointers passed to it. Callers should ensure the parser pointer points to a
/// valid `Mp4parseParser` and that the info pointer points to a valid
/// `Mp4parseTrackInfo`.
#[no_mangle]
pub unsafe extern "C" fn mp4parse_get_track_info(
parser: *mut Mp4parseParser,
track_index: u32,
info: *mut Mp4parseTrackInfo,
) -> Mp4parseStatus {
if parser.is_null() || info.is_null() {
return Mp4parseStatus::BadArg;
}
// Initialize fields to default values to ensure all fields are always valid.
*info = Default::default();
let context = (*parser).context_mut();
let track_index: usize = track_index as usize;
let info: &mut Mp4parseTrackInfo = &mut *info;
if track_index >= context.tracks.len() {
return Mp4parseStatus::BadArg;
}
info.track_type = match context.tracks[track_index].track_type {
TrackType::Video => Mp4parseTrackType::Video,
TrackType::Audio => Mp4parseTrackType::Audio,
TrackType::Metadata => Mp4parseTrackType::Metadata,
TrackType::Unknown => return Mp4parseStatus::Unsupported,
};
let track = &context.tracks[track_index];
if let (Some(track_timescale), Some(context_timescale)) = (track.timescale, context.timescale) {
let media_time = match track.media_time.map_or(Some(0), |media_time| {
track_time_to_us(media_time, track_timescale)
}) {
Some(time) => time as i64,
None => return Mp4parseStatus::Invalid,
};
let empty_duration = match track.empty_duration.map_or(Some(0), |empty_duration| {
media_time_to_us(empty_duration, context_timescale)
}) {
Some(time) => time as i64,
None => return Mp4parseStatus::Invalid,
};
info.media_time = media_time - empty_duration;
if let Some(track_duration) = track.duration {
match track_time_to_us(track_duration, track_timescale) {
Some(duration) => info.duration = duration,
None => return Mp4parseStatus::Invalid,
}
} else {
// Duration unknown; stagefright returns 0 for this.
info.duration = 0
}
} else {
return Mp4parseStatus::Invalid;
}
info.track_id = match track.track_id {
Some(track_id) => track_id,
None => return Mp4parseStatus::Invalid,
};
Mp4parseStatus::Ok
}
/// Fill the supplied `Mp4parseTrackAudioInfo` with metadata for `track`.
///
/// # Safety
///
/// This function is unsafe because it dereferences the the parser and info raw
/// pointers passed to it. Callers should ensure the parser pointer points to a
/// valid `Mp4parseParser` and that the info pointer points to a valid
/// `Mp4parseTrackAudioInfo`.
#[no_mangle]
pub unsafe extern "C" fn mp4parse_get_track_audio_info(
parser: *mut Mp4parseParser,
track_index: u32,
info: *mut Mp4parseTrackAudioInfo,
) -> Mp4parseStatus {
if parser.is_null() || info.is_null() {
return Mp4parseStatus::BadArg;
}
// Initialize fields to default values to ensure all fields are always valid.
*info = Default::default();
get_track_audio_info(&mut *parser, track_index, &mut *info).into()
}
fn get_track_audio_info(
parser: &mut Mp4parseParser,
track_index: u32,
info: &mut Mp4parseTrackAudioInfo,
) -> Result<(), Mp4parseStatus> {
let Mp4parseParser {
context,
opus_header,
..
} = parser;
if track_index as usize >= context.tracks.len() {
return Err(Mp4parseStatus::BadArg);
}
let track = &context.tracks[track_index as usize];
if track.track_type != TrackType::Audio {
return Err(Mp4parseStatus::Invalid);
}
// Handle track.stsd
let stsd = match track.stsd {
Some(ref stsd) => stsd,
None => return Err(Mp4parseStatus::Invalid), // Stsd should be present
};
if stsd.descriptions.is_empty() {
return Err(Mp4parseStatus::Invalid); // Should have at least 1 description
}
let mut audio_sample_infos = TryVec::with_capacity(stsd.descriptions.len())?;
for description in stsd.descriptions.iter() {
let mut sample_info = Mp4parseTrackAudioSampleInfo::default();
let audio = match description {
SampleEntry::Audio(a) => a,
_ => return Err(Mp4parseStatus::Invalid),
};
// UNKNOWN for unsupported format.
sample_info.codec_type = match audio.codec_specific {
AudioCodecSpecific::OpusSpecificBox(_) => Mp4parseCodec::Opus,
AudioCodecSpecific::FLACSpecificBox(_) => Mp4parseCodec::Flac,
AudioCodecSpecific::ES_Descriptor(ref esds) if esds.audio_codec == CodecType::AAC => {
Mp4parseCodec::Aac
}
AudioCodecSpecific::ES_Descriptor(ref esds) if esds.audio_codec == CodecType::MP3 => {
Mp4parseCodec::Mp3
}
AudioCodecSpecific::ES_Descriptor(_) | AudioCodecSpecific::LPCM => {
Mp4parseCodec::Unknown
}
AudioCodecSpecific::MP3 => Mp4parseCodec::Mp3,
AudioCodecSpecific::ALACSpecificBox(_) => Mp4parseCodec::Alac,
};
sample_info.channels = audio.channelcount as u16;
sample_info.bit_depth = audio.samplesize;
sample_info.sample_rate = audio.samplerate as u32;
// sample_info.profile is handled below on a per case basis
match audio.codec_specific {
AudioCodecSpecific::ES_Descriptor(ref esds) => {
if esds.codec_esds.len() > std::u32::MAX as usize {
return Err(Mp4parseStatus::Invalid);
}
sample_info.extra_data.length = esds.codec_esds.len() as u32;
sample_info.extra_data.data = esds.codec_esds.as_ptr();
sample_info.codec_specific_config.length = esds.decoder_specific_data.len() as u32;
sample_info.codec_specific_config.data = esds.decoder_specific_data.as_ptr();
if let Some(rate) = esds.audio_sample_rate {
sample_info.sample_rate = rate;
}
if let Some(channels) = esds.audio_channel_count {
sample_info.channels = channels;
}
if let Some(profile) = esds.audio_object_type {
sample_info.profile = profile;
}
sample_info.extended_profile = match esds.extended_audio_object_type {
Some(extended_profile) => extended_profile,
_ => sample_info.profile,
};
}
AudioCodecSpecific::FLACSpecificBox(ref flac) => {
// Return the STREAMINFO metadata block in the codec_specific.
let streaminfo = &flac.blocks[0];
if streaminfo.block_type != 0 || streaminfo.data.len() != 34 {
return Err(Mp4parseStatus::Invalid);
}
sample_info.codec_specific_config.length = streaminfo.data.len() as u32;
sample_info.codec_specific_config.data = streaminfo.data.as_ptr();
}
AudioCodecSpecific::OpusSpecificBox(ref opus) => {
let mut v = TryVec::new();
match serialize_opus_header(opus, &mut v) {
Err(_) => {
return Err(Mp4parseStatus::Invalid);
}
Ok(_) => {
opus_header.insert(track_index, v)?;
if let Some(v) = opus_header.get(&track_index) {
if v.len() > std::u32::MAX as usize {
return Err(Mp4parseStatus::Invalid);
}
sample_info.codec_specific_config.length = v.len() as u32;
sample_info.codec_specific_config.data = v.as_ptr();
}
}
}
}
AudioCodecSpecific::ALACSpecificBox(ref alac) => {
sample_info.codec_specific_config.length = alac.data.len() as u32;
sample_info.codec_specific_config.data = alac.data.as_ptr();
}
AudioCodecSpecific::MP3 | AudioCodecSpecific::LPCM => (),
}
if let Some(p) = audio
.protection_info
.iter()
.find(|sinf| sinf.tenc.is_some())
{
sample_info.protected_data.scheme_type = match p.scheme_type {
Some(ref scheme_type_box) => {
match scheme_type_box.scheme_type.value.as_ref() {
b"cenc" => Mp4ParseEncryptionSchemeType::Cenc,
b"cbcs" => Mp4ParseEncryptionSchemeType::Cbcs,
// We don't support other schemes, and shouldn't reach
// this case. Try to gracefully handle by treating as
// no encryption case.
_ => Mp4ParseEncryptionSchemeType::None,
}
}
None => Mp4ParseEncryptionSchemeType::None,
};
if let Some(ref tenc) = p.tenc {
sample_info.protected_data.is_encrypted = tenc.is_encrypted;
sample_info.protected_data.iv_size = tenc.iv_size;
sample_info.protected_data.kid.set_data(&(tenc.kid));
sample_info.protected_data.crypt_byte_block = match tenc.crypt_byte_block_count {
Some(n) => n,
None => 0,
};
sample_info.protected_data.skip_byte_block = match tenc.skip_byte_block_count {
Some(n) => n,
None => 0,
};
if let Some(ref iv_vec) = tenc.constant_iv {
if iv_vec.len() > std::u32::MAX as usize {
return Err(Mp4parseStatus::Invalid);
}
sample_info.protected_data.constant_iv.set_data(iv_vec);
};
}
}
audio_sample_infos.push(sample_info)?;
}
parser
.audio_track_sample_descriptions
.insert(track_index, audio_sample_infos)?;
match parser.audio_track_sample_descriptions.get(&track_index) {
Some(sample_info) => {
if sample_info.len() > std::u32::MAX as usize {
// Should never happen due to upper limits on number of sample
// descriptions a track can have, but lets be safe.
return Err(Mp4parseStatus::Invalid);
}
info.sample_info_count = sample_info.len() as u32;
info.sample_info = sample_info.as_ptr();
}
None => return Err(Mp4parseStatus::Invalid), // Shouldn't happen, we just inserted the info!
}
Ok(())
}
/// Fill the supplied `Mp4parseTrackVideoInfo` with metadata for `track`.
///
/// # Safety
///
/// This function is unsafe because it dereferences the the parser and info raw
/// pointers passed to it. Callers should ensure the parser pointer points to a
/// valid `Mp4parseParser` and that the info pointer points to a valid
/// `Mp4parseTrackVideoInfo`.
#[no_mangle]
pub unsafe extern "C" fn mp4parse_get_track_video_info(
parser: *mut Mp4parseParser,
track_index: u32,
info: *mut Mp4parseTrackVideoInfo,
) -> Mp4parseStatus {
if parser.is_null() || info.is_null() {
return Mp4parseStatus::BadArg;
}
// Initialize fields to default values to ensure all fields are always valid.
*info = Default::default();
mp4parse_get_track_video_info_safe(&mut *parser, track_index, &mut *info).into()
}
fn mp4parse_get_track_video_info_safe(
parser: &mut Mp4parseParser,
track_index: u32,
info: &mut Mp4parseTrackVideoInfo,
) -> Result<(), Mp4parseStatus> {
let context = parser.context();
if track_index as usize >= context.tracks.len() {
return Err(Mp4parseStatus::BadArg);
}
let track = &context.tracks[track_index as usize];
if track.track_type != TrackType::Video {
return Err(Mp4parseStatus::Invalid);
}
// Handle track.tkhd
if let Some(ref tkhd) = track.tkhd {
info.display_width = tkhd.width >> 16; // 16.16 fixed point
info.display_height = tkhd.height >> 16; // 16.16 fixed point
let matrix = (
tkhd.matrix.a >> 16,
tkhd.matrix.b >> 16,
tkhd.matrix.c >> 16,
tkhd.matrix.d >> 16,
);
info.rotation = match matrix {
(0, 1, -1, 0) => 90, // rotate 90 degrees
(-1, 0, 0, -1) => 180, // rotate 180 degrees
(0, -1, 1, 0) => 270, // rotate 270 degrees
_ => 0,
};
} else {
return Err(Mp4parseStatus::Invalid);
}
// Handle track.stsd
let stsd = match track.stsd {
Some(ref stsd) => stsd,
None => return Err(Mp4parseStatus::Invalid), // Stsd should be present
};
if stsd.descriptions.is_empty() {
return Err(Mp4parseStatus::Invalid); // Should have at least 1 description
}
let mut video_sample_infos = TryVec::with_capacity(stsd.descriptions.len())?;
for description in stsd.descriptions.iter() {
let mut sample_info = Mp4parseTrackVideoSampleInfo::default();
let video = match description {
SampleEntry::Video(v) => v,
_ => return Err(Mp4parseStatus::Invalid),
};
// UNKNOWN for unsupported format.
sample_info.codec_type = match video.codec_specific {
VideoCodecSpecific::VPxConfig(_) => Mp4parseCodec::Vp9,
VideoCodecSpecific::AV1Config(_) => Mp4parseCodec::Av1,
VideoCodecSpecific::AVCConfig(_) => Mp4parseCodec::Avc,
VideoCodecSpecific::ESDSConfig(_) =>
// MP4V (14496-2) video is unsupported.
{
Mp4parseCodec::Unknown
}
};
sample_info.image_width = video.width;
sample_info.image_height = video.height;
match video.codec_specific {
VideoCodecSpecific::AVCConfig(ref data) | VideoCodecSpecific::ESDSConfig(ref data) => {
sample_info.extra_data.set_data(data);
}
_ => {}
}
if let Some(p) = video
.protection_info
.iter()
.find(|sinf| sinf.tenc.is_some())
{
sample_info.protected_data.scheme_type = match p.scheme_type {
Some(ref scheme_type_box) => {
match scheme_type_box.scheme_type.value.as_ref() {
b"cenc" => Mp4ParseEncryptionSchemeType::Cenc,
b"cbcs" => Mp4ParseEncryptionSchemeType::Cbcs,
// We don't support other schemes, and shouldn't reach
// this case. Try to gracefully handle by treating as
// no encryption case.
_ => Mp4ParseEncryptionSchemeType::None,
}
}