-
Notifications
You must be signed in to change notification settings - Fork 62
/
lib.rs
2373 lines (2102 loc) · 74.4 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
//! Module for parsing ISO Base Media Format aka video/mp4 streams.
// 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/.
#[cfg(feature = "fuzz")]
extern crate afl;
#[macro_use]
extern crate log;
extern crate byteorder;
extern crate bitreader;
extern crate num_traits;
use byteorder::{ReadBytesExt, WriteBytesExt};
use bitreader::{BitReader, ReadInto};
use std::io::{Read, Take};
use std::io::Cursor;
use std::cmp;
use num_traits::Num;
#[cfg(feature = "mp4parse_fallible")]
extern crate mp4parse_fallible;
#[cfg(feature = "mp4parse_fallible")]
use mp4parse_fallible::FallibleVec;
#[macro_use]
mod macros;
mod boxes;
use boxes::{BoxType, FourCC};
// Unit tests.
#[cfg(test)]
mod tests;
// Arbitrary buffer size limit used for raw read_bufs on a box.
const BUF_SIZE_LIMIT: usize = 1024 * 1024;
// Max table length. Calculating in worth case for one week long video, one
// frame per table entry in 30 fps.
const TABLE_SIZE_LIMIT: u32 = 30 * 60 * 60 * 24 * 7;
// TODO: vec_push() and vec_reserve() needs to be replaced when Rust supports
// fallible memory allocation in raw_vec.
#[allow(unreachable_code)]
pub fn vec_push<T>(vec: &mut Vec<T>, val: T) -> std::result::Result<(), ()> {
#[cfg(feature = "mp4parse_fallible")]
{
return FallibleVec::try_push(vec, val);
}
vec.push(val);
Ok(())
}
#[allow(unreachable_code)]
pub fn vec_reserve<T>(vec: &mut Vec<T>, size: usize) -> std::result::Result<(), ()> {
#[cfg(feature = "mp4parse_fallible")]
{
return FallibleVec::try_reserve(vec, size);
}
vec.reserve(size);
Ok(())
}
#[allow(unreachable_code)]
fn allocate_read_buf(size: usize) -> std::result::Result<Vec<u8>, ()> {
#[cfg(feature = "mp4parse_fallible")]
{
let mut buf: Vec<u8> = Vec::new();
FallibleVec::try_reserve(&mut buf, size)?;
unsafe { buf.set_len(size); }
return Ok(buf);
}
Ok(vec![0; size])
}
/// Describes parser failures.
///
/// This enum wraps the standard `io::Error` type, unified with
/// our own parser error states and those of crates we use.
#[derive(Debug)]
pub enum Error {
/// Parse error caused by corrupt or malformed data.
InvalidData(&'static str),
/// Parse error caused by limited parser support rather than invalid data.
Unsupported(&'static str),
/// Reflect `std::io::ErrorKind::UnexpectedEof` for short data.
UnexpectedEOF,
/// Propagate underlying errors from `std::io`.
Io(std::io::Error),
/// read_mp4 terminated without detecting a moov box.
NoMoov,
/// Out of memory
OutOfMemory,
}
impl From<bitreader::BitReaderError> for Error {
fn from(_: bitreader::BitReaderError) -> Error {
Error::InvalidData("invalid data")
}
}
impl From<std::io::Error> for Error {
fn from(err: std::io::Error) -> Error {
match err.kind() {
std::io::ErrorKind::UnexpectedEof => Error::UnexpectedEOF,
_ => Error::Io(err),
}
}
}
impl From<std::string::FromUtf8Error> for Error {
fn from(_: std::string::FromUtf8Error) -> Error {
Error::InvalidData("invalid utf8")
}
}
impl From<()> for Error {
fn from(_: ()) -> Error {
Error::OutOfMemory
}
}
/// Result shorthand using our Error enum.
pub type Result<T> = std::result::Result<T, Error>;
/// Basic ISO box structure.
///
/// mp4 files are a sequence of possibly-nested 'box' structures. Each box
/// begins with a header describing the length of the box's data and a
/// four-byte box type which identifies the type of the box. Together these
/// are enough to interpret the contents of that section of the file.
#[derive(Debug, Clone, Copy)]
struct BoxHeader {
/// Box type.
name: BoxType,
/// Size of the box in bytes.
size: u64,
/// Offset to the start of the contained data (or header size).
offset: u64,
/// Uuid for extended type.
uuid: Option<[u8; 16]>,
}
/// File type box 'ftyp'.
#[derive(Debug)]
struct FileTypeBox {
major_brand: FourCC,
minor_version: u32,
compatible_brands: Vec<FourCC>,
}
/// Movie header box 'mvhd'.
#[derive(Debug)]
struct MovieHeaderBox {
pub timescale: u32,
duration: u64,
}
#[derive(Debug, Clone, Copy)]
pub struct Matrix {
pub a: i32, // 16.16 fix point
pub b: i32, // 16.16 fix point
pub u: i32, // 2.30 fix point
pub c: i32, // 16.16 fix point
pub d: i32, // 16.16 fix point
pub v: i32, // 2.30 fix point
pub x: i32, // 16.16 fix point
pub y: i32, // 16.16 fix point
pub w: i32, // 2.30 fix point
}
/// Track header box 'tkhd'
#[derive(Debug, Clone)]
pub struct TrackHeaderBox {
track_id: u32,
pub disabled: bool,
pub duration: u64,
pub width: u32,
pub height: u32,
pub matrix: Matrix,
}
/// Edit list box 'elst'
#[derive(Debug)]
struct EditListBox {
edits: Vec<Edit>,
}
#[derive(Debug)]
struct Edit {
segment_duration: u64,
media_time: i64,
media_rate_integer: i16,
media_rate_fraction: i16,
}
/// Media header box 'mdhd'
#[derive(Debug)]
struct MediaHeaderBox {
timescale: u32,
duration: u64,
}
// Chunk offset box 'stco' or 'co64'
#[derive(Debug)]
pub struct ChunkOffsetBox {
pub offsets: Vec<u64>,
}
// Sync sample box 'stss'
#[derive(Debug)]
pub struct SyncSampleBox {
pub samples: Vec<u32>,
}
// Sample to chunk box 'stsc'
#[derive(Debug)]
pub struct SampleToChunkBox {
pub samples: Vec<SampleToChunk>,
}
#[derive(Debug)]
pub struct SampleToChunk {
pub first_chunk: u32,
pub samples_per_chunk: u32,
pub sample_description_index: u32,
}
// Sample size box 'stsz'
#[derive(Debug)]
pub struct SampleSizeBox {
pub sample_size: u32,
pub sample_sizes: Vec<u32>,
}
// Time to sample box 'stts'
#[derive(Debug)]
pub struct TimeToSampleBox {
pub samples: Vec<Sample>,
}
#[repr(C)]
#[derive(Debug)]
pub struct Sample {
pub sample_count: u32,
pub sample_delta: u32,
}
#[derive(Debug, Clone, Copy)]
pub enum TimeOffsetVersion {
Version0(u32),
Version1(i32),
}
#[derive(Debug, Clone)]
pub struct TimeOffset {
pub sample_count: u32,
pub time_offset: TimeOffsetVersion,
}
#[derive(Debug)]
pub struct CompositionOffsetBox {
pub samples: Vec<TimeOffset>,
}
// Handler reference box 'hdlr'
#[derive(Debug)]
struct HandlerBox {
handler_type: FourCC,
}
// Sample description box 'stsd'
#[derive(Debug)]
pub struct SampleDescriptionBox {
pub descriptions: Vec<SampleEntry>,
}
#[derive(Debug, Clone)]
pub enum SampleEntry {
Audio(AudioSampleEntry),
Video(VideoSampleEntry),
Unknown,
}
#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Default)]
pub struct ES_Descriptor {
pub audio_codec: CodecType,
pub audio_object_type: Option<u16>,
pub extended_audio_object_type: Option<u16>,
pub audio_sample_rate: Option<u32>,
pub audio_channel_count: Option<u16>,
pub codec_esds: Vec<u8>,
pub decoder_specific_data: Vec<u8>, // Data in DECODER_SPECIFIC_TAG
}
#[allow(non_camel_case_types)]
#[derive(Debug, Clone)]
pub enum AudioCodecSpecific {
ES_Descriptor(ES_Descriptor),
FLACSpecificBox(FLACSpecificBox),
OpusSpecificBox(OpusSpecificBox),
ALACSpecificBox(ALACSpecificBox),
MP3,
LPCM,
}
#[derive(Debug, Clone)]
pub struct AudioSampleEntry {
pub codec_type: CodecType,
data_reference_index: u16,
pub channelcount: u32,
pub samplesize: u16,
pub samplerate: f64,
pub codec_specific: AudioCodecSpecific,
pub protection_info: Vec<ProtectionSchemeInfoBox>,
}
#[derive(Debug, Clone)]
pub enum VideoCodecSpecific {
AVCConfig(Vec<u8>),
VPxConfig(VPxConfigBox),
AV1Config(AV1ConfigBox),
ESDSConfig(Vec<u8>),
}
#[derive(Debug, Clone)]
pub struct VideoSampleEntry {
pub codec_type: CodecType,
data_reference_index: u16,
pub width: u16,
pub height: u16,
pub codec_specific: VideoCodecSpecific,
pub protection_info: Vec<ProtectionSchemeInfoBox>,
}
/// Represent a Video Partition Codec Configuration 'vpcC' box (aka vp9).
#[derive(Debug, Clone)]
pub struct VPxConfigBox {
profile: u8,
level: u8,
pub bit_depth: u8,
pub color_space: u8, // Really an enum
pub chroma_subsampling: u8,
transfer_function: u8,
matrix: Option<u8>, // Available in 'VP Codec ISO Media File Format' version 1 only.
video_full_range: bool,
pub codec_init: Vec<u8>, // Empty for vp8/vp9.
}
#[derive(Debug, Clone)]
pub struct AV1ConfigBox {
pub profile: u8,
pub level: u8,
pub tier: u8,
pub bit_depth: u8,
pub monochrome: bool,
pub chroma_subsampling_x: u8,
pub chroma_subsampling_y: u8,
pub chroma_sample_position: u8,
pub initial_presentation_delay_present: bool,
pub initial_presentation_delay_minus_one: u8,
pub config_obus: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct FLACMetadataBlock {
pub block_type: u8,
pub data: Vec<u8>,
}
/// Represet a FLACSpecificBox 'dfLa'
#[derive(Debug, Clone)]
pub struct FLACSpecificBox {
version: u8,
pub blocks: Vec<FLACMetadataBlock>,
}
#[derive(Debug, Clone)]
struct ChannelMappingTable {
stream_count: u8,
coupled_count: u8,
channel_mapping: Vec<u8>,
}
/// Represent an OpusSpecificBox 'dOps'
#[derive(Debug, Clone)]
pub struct OpusSpecificBox {
pub version: u8,
output_channel_count: u8,
pre_skip: u16,
input_sample_rate: u32,
output_gain: i16,
channel_mapping_family: u8,
channel_mapping_table: Option<ChannelMappingTable>,
}
/// Represent an ALACSpecificBox 'alac'
#[derive(Debug, Clone)]
pub struct ALACSpecificBox {
version: u8,
pub data: Vec<u8>,
}
#[derive(Debug)]
pub struct MovieExtendsBox {
pub fragment_duration: Option<MediaScaledTime>,
}
pub type ByteData = Vec<u8>;
#[derive(Debug, Default)]
pub struct ProtectionSystemSpecificHeaderBox {
pub system_id: ByteData,
pub kid: Vec<ByteData>,
pub data: ByteData,
// The entire pssh box (include header) required by Gecko.
pub box_content: ByteData,
}
#[derive(Debug, Default, Clone)]
pub struct SchemeTypeBox {
pub scheme_type: FourCC,
pub scheme_version: u32,
}
#[derive(Debug, Default, Clone)]
pub struct TrackEncryptionBox {
pub is_encrypted: u8,
pub iv_size: u8,
pub kid: Vec<u8>,
// Members for pattern encryption schemes
pub crypt_byte_block_count: Option<u8>,
pub skip_byte_block_count: Option<u8>,
pub constant_iv: Option<Vec<u8>>,
// End pattern encryption scheme members
}
#[derive(Debug, Default, Clone)]
pub struct ProtectionSchemeInfoBox {
pub code_name: String,
pub scheme_type: Option<SchemeTypeBox>,
pub tenc: Option<TrackEncryptionBox>,
}
/// Internal data structures.
#[derive(Debug, Default)]
pub struct MediaContext {
pub timescale: Option<MediaTimeScale>,
/// Tracks found in the file.
pub tracks: Vec<Track>,
pub mvex: Option<MovieExtendsBox>,
pub psshs: Vec<ProtectionSystemSpecificHeaderBox>
}
impl MediaContext {
pub fn new() -> MediaContext {
Default::default()
}
}
#[derive(Debug, PartialEq)]
pub enum TrackType {
Audio,
Video,
Metadata,
Unknown,
}
impl Default for TrackType {
fn default() -> Self { TrackType::Unknown }
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CodecType {
Unknown,
MP3,
AAC,
FLAC,
Opus,
H264, // 14496-10
MP4V, // 14496-2
AV1,
VP9,
VP8,
EncryptedVideo,
EncryptedAudio,
LPCM, // QT
ALAC,
}
impl Default for CodecType {
fn default() -> Self { CodecType::Unknown }
}
/// The media's global (mvhd) timescale in units per second.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct MediaTimeScale(pub u64);
/// A time to be scaled by the media's global (mvhd) timescale.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct MediaScaledTime(pub u64);
/// The track's local (mdhd) timescale.
/// Members are timescale units per second and the track id.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct TrackTimeScale<T: Num>(pub T, pub usize);
/// A time to be scaled by the track's local (mdhd) timescale.
/// Members are time in scale units and the track id.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct TrackScaledTime<T: Num>(pub T, pub usize);
impl <T> std::ops::Add for TrackScaledTime<T> where T: Num {
type Output = TrackScaledTime<T>;
fn add(self, other: TrackScaledTime<T>) -> TrackScaledTime<T> {
TrackScaledTime::<T>(self.0 + other.0, self.1)
}
}
#[derive(Debug, Default)]
pub struct Track {
pub id: usize,
pub track_type: TrackType,
pub empty_duration: Option<MediaScaledTime>,
pub media_time: Option<TrackScaledTime<u64>>,
pub timescale: Option<TrackTimeScale<u64>>,
pub duration: Option<TrackScaledTime<u64>>,
pub track_id: Option<u32>,
pub tkhd: Option<TrackHeaderBox>, // TODO(kinetik): find a nicer way to export this.
pub stsd: Option<SampleDescriptionBox>,
pub stts: Option<TimeToSampleBox>,
pub stsc: Option<SampleToChunkBox>,
pub stsz: Option<SampleSizeBox>,
pub stco: Option<ChunkOffsetBox>, // It is for stco or co64.
pub stss: Option<SyncSampleBox>,
pub ctts: Option<CompositionOffsetBox>,
}
impl Track {
fn new(id: usize) -> Track {
Track { id: id, ..Default::default() }
}
}
struct BMFFBox<'a, T: 'a + Read> {
head: BoxHeader,
content: Take<&'a mut T>,
}
struct BoxIter<'a, T: 'a + Read> {
src: &'a mut T,
}
impl<'a, T: Read> BoxIter<'a, T> {
fn new(src: &mut T) -> BoxIter<T> {
BoxIter { src: src }
}
fn next_box(&mut self) -> Result<Option<BMFFBox<T>>> {
let r = read_box_header(self.src);
match r {
Ok(h) => Ok(Some(BMFFBox {
head: h,
content: self.src.take(h.size - h.offset),
})),
Err(Error::UnexpectedEOF) => Ok(None),
Err(e) => Err(e),
}
}
}
impl<'a, T: Read> Read for BMFFBox<'a, T> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.content.read(buf)
}
}
impl<'a, T: Read> BMFFBox<'a, T> {
fn bytes_left(&self) -> usize {
self.content.limit() as usize
}
fn get_header(&self) -> &BoxHeader {
&self.head
}
fn box_iter<'b>(&'b mut self) -> BoxIter<BMFFBox<'a, T>> {
BoxIter::new(self)
}
}
impl<'a, T: Read> Drop for BMFFBox<'a, T> {
fn drop(&mut self) {
if self.content.limit() > 0 {
let name: FourCC = From::from(self.head.name);
debug!("Dropping {} bytes in '{}'", self.content.limit(), name);
}
}
}
/// Read and parse a box header.
///
/// Call this first to determine the type of a particular mp4 box
/// and its length. Used internally for dispatching to specific
/// parsers for the internal content, or to get the length to
/// skip unknown or uninteresting boxes.
fn read_box_header<T: ReadBytesExt>(src: &mut T) -> Result<BoxHeader> {
let size32 = be_u32(src)?;
let name = BoxType::from(be_u32(src)?);
let size = match size32 {
// valid only for top-level box and indicates it's the last box in the file. usually mdat.
0 => return Err(Error::Unsupported("unknown sized box")),
1 => {
let size64 = be_u64(src)?;
if size64 < 16 {
return Err(Error::InvalidData("malformed wide size"));
}
size64
}
2...7 => return Err(Error::InvalidData("malformed size")),
_ => size32 as u64,
};
let mut offset = match size32 {
1 => 4 + 4 + 8,
_ => 4 + 4,
};
let uuid = if name == BoxType::UuidBox {
if size >= offset + 16 {
let mut buffer = [0u8; 16];
let count = src.read(&mut buffer)?;
offset += count as u64;
if count == 16 {
Some(buffer)
} else {
debug!("malformed uuid (short read), skipping");
None
}
} else {
debug!("malformed uuid, skipping");
None
}
} else {
None
};
assert!(offset <= size);
Ok(BoxHeader {
name: name,
size: size,
offset: offset,
uuid: uuid,
})
}
/// Parse the extra header fields for a full box.
fn read_fullbox_extra<T: ReadBytesExt>(src: &mut T) -> Result<(u8, u32)> {
let version = src.read_u8()?;
let flags_a = src.read_u8()?;
let flags_b = src.read_u8()?;
let flags_c = src.read_u8()?;
Ok((version,
(flags_a as u32) << 16 | (flags_b as u32) << 8 | (flags_c as u32)))
}
/// Skip over the entire contents of a box.
fn skip_box_content<T: Read>(src: &mut BMFFBox<T>) -> Result<()> {
// Skip the contents of unknown chunks.
let to_skip = {
let header = src.get_header();
debug!("{:?} (skipped)", header);
(header.size - header.offset) as usize
};
assert_eq!(to_skip, src.bytes_left());
skip(src, to_skip)
}
/// Skip over the remain data of a box.
fn skip_box_remain<T: Read>(src: &mut BMFFBox<T>) -> Result<()> {
let remain = {
let header = src.get_header();
let len = src.bytes_left();
debug!("remain {} (skipped) in {:?}", len, header);
len
};
skip(src, remain)
}
/// Read the contents of a box, including sub boxes.
///
/// Metadata is accumulated in the passed-through `MediaContext` struct,
/// which can be examined later.
pub fn read_mp4<T: Read>(f: &mut T, context: &mut MediaContext) -> Result<()> {
let mut found_ftyp = false;
let mut found_moov = false;
// TODO(kinetik): Top-level parsing should handle zero-sized boxes
// rather than throwing an error.
let mut iter = BoxIter::new(f);
while let Some(mut b) = iter.next_box()? {
// box ordering: ftyp before any variable length box (inc. moov),
// but may not be first box in file if file signatures etc. present
// fragmented mp4 order: ftyp, moov, pairs of moof/mdat (1-multiple), mfra
// "special": uuid, wide (= 8 bytes)
// isom: moov, mdat, free, skip, udta, ftyp, moof, mfra
// iso2: pdin, meta
// iso3: meco
// iso5: styp, sidx, ssix, prft
// unknown, maybe: id32
// qt: pnot
// possibly allow anything where all printable and/or all lowercase printable
// "four printable characters from the ISO 8859-1 character set"
match b.head.name {
BoxType::FileTypeBox => {
let ftyp = read_ftyp(&mut b)?;
found_ftyp = true;
debug!("{:?}", ftyp);
}
BoxType::MovieBox => {
read_moov(&mut b, context)?;
found_moov = true;
}
_ => skip_box_content(&mut b)?,
};
check_parser_state!(b.content);
if found_moov {
debug!("found moov {}, could stop pure 'moov' parser now", if found_ftyp {
"and ftyp"
} else {
"but no ftyp"
});
}
}
// XXX(kinetik): This isn't perfect, as a "moov" with no contents is
// treated as okay but we haven't found anything useful. Needs more
// thought for clearer behaviour here.
if found_moov {
Ok(())
} else {
Err(Error::NoMoov)
}
}
fn parse_mvhd<T: Read>(f: &mut BMFFBox<T>) -> Result<(MovieHeaderBox, Option<MediaTimeScale>)> {
let mvhd = read_mvhd(f)?;
if mvhd.timescale == 0 {
return Err(Error::InvalidData("zero timescale in mdhd"));
}
let timescale = Some(MediaTimeScale(mvhd.timescale as u64));
Ok((mvhd, timescale))
}
fn read_moov<T: Read>(f: &mut BMFFBox<T>, context: &mut MediaContext) -> Result<()> {
let mut iter = f.box_iter();
while let Some(mut b) = iter.next_box()? {
match b.head.name {
BoxType::MovieHeaderBox => {
let (mvhd, timescale) = parse_mvhd(&mut b)?;
context.timescale = timescale;
debug!("{:?}", mvhd);
}
BoxType::TrackBox => {
let mut track = Track::new(context.tracks.len());
read_trak(&mut b, &mut track)?;
vec_push(&mut context.tracks, track)?;
}
BoxType::MovieExtendsBox => {
let mvex = read_mvex(&mut b)?;
debug!("{:?}", mvex);
context.mvex = Some(mvex);
}
BoxType::ProtectionSystemSpecificHeaderBox => {
let pssh = read_pssh(&mut b)?;
debug!("{:?}", pssh);
vec_push(&mut context.psshs, pssh)?;
}
_ => skip_box_content(&mut b)?,
};
check_parser_state!(b.content);
}
Ok(())
}
fn read_pssh<T: Read>(src: &mut BMFFBox<T>) -> Result<ProtectionSystemSpecificHeaderBox> {
let len = src.bytes_left();
let mut box_content = read_buf(src, len)?;
let (system_id, kid, data) = {
let pssh = &mut Cursor::new(box_content.as_slice());
let (version, _) = read_fullbox_extra(pssh)?;
let system_id = read_buf(pssh, 16)?;
let mut kid: Vec<ByteData> = Vec::new();
if version > 0 {
let count = be_u32_with_limit(pssh)?;
for _ in 0..count {
let item = read_buf(pssh, 16)?;
vec_push(&mut kid, item)?;
}
}
let data_size = be_u32_with_limit(pssh)? as usize;
let data = read_buf(pssh, data_size)?;
(system_id, kid, data)
};
let mut pssh_box = Vec::new();
write_be_u32(&mut pssh_box, src.head.size as u32)?;
pssh_box.extend_from_slice(b"pssh");
pssh_box.append(&mut box_content);
Ok(ProtectionSystemSpecificHeaderBox {
system_id: system_id,
kid: kid,
data: data,
box_content: pssh_box,
})
}
fn read_mvex<T: Read>(src: &mut BMFFBox<T>) -> Result<MovieExtendsBox> {
let mut iter = src.box_iter();
let mut fragment_duration = None;
while let Some(mut b) = iter.next_box()? {
match b.head.name {
BoxType::MovieExtendsHeaderBox => {
let duration = read_mehd(&mut b)?;
fragment_duration = Some(duration);
},
_ => skip_box_content(&mut b)?,
}
}
Ok(MovieExtendsBox {
fragment_duration: fragment_duration,
})
}
fn read_mehd<T: Read>(src: &mut BMFFBox<T>) -> Result<MediaScaledTime> {
let (version, _) = read_fullbox_extra(src)?;
let fragment_duration = match version {
1 => be_u64(src)?,
0 => be_u32(src)? as u64,
_ => return Err(Error::InvalidData("unhandled mehd version")),
};
Ok(MediaScaledTime(fragment_duration))
}
fn read_trak<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<()> {
let mut iter = f.box_iter();
while let Some(mut b) = iter.next_box()? {
match b.head.name {
BoxType::TrackHeaderBox => {
let tkhd = read_tkhd(&mut b)?;
track.track_id = Some(tkhd.track_id);
track.tkhd = Some(tkhd.clone());
debug!("{:?}", tkhd);
}
BoxType::EditBox => read_edts(&mut b, track)?,
BoxType::MediaBox => read_mdia(&mut b, track)?,
_ => skip_box_content(&mut b)?,
};
check_parser_state!(b.content);
}
Ok(())
}
fn read_edts<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<()> {
let mut iter = f.box_iter();
while let Some(mut b) = iter.next_box()? {
match b.head.name {
BoxType::EditListBox => {
let elst = read_elst(&mut b)?;
if elst.edits.len() < 1 {
debug!("empty edit list");
continue;
}
let mut empty_duration = 0;
let mut idx = 0;
if elst.edits[idx].media_time == -1 {
if elst.edits.len() < 2 {
debug!("expected additional edit, ignoring edit list");
continue;
}
empty_duration = elst.edits[idx].segment_duration;
idx += 1;
}
track.empty_duration = Some(MediaScaledTime(empty_duration));
let media_time = elst.edits[idx].media_time;
if media_time < 0 {
debug!("unexpected negative media time in edit");
}
track.media_time = Some(TrackScaledTime::<u64>(std::cmp::max(0, media_time) as u64,
track.id));
if elst.edits.len() > 2 {
debug!("ignoring edit list with {} entries", elst.edits.len());
}
debug!("{:?}", elst);
}
_ => skip_box_content(&mut b)?,
};
check_parser_state!(b.content);
}
Ok(())
}
fn parse_mdhd<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<(MediaHeaderBox, Option<TrackScaledTime<u64>>, Option<TrackTimeScale<u64>>)> {
let mdhd = read_mdhd(f)?;
let duration = match mdhd.duration {
std::u64::MAX => None,
duration => Some(TrackScaledTime::<u64>(duration, track.id)),
};
if mdhd.timescale == 0 {
return Err(Error::InvalidData("zero timescale in mdhd"));
}
let timescale = Some(TrackTimeScale::<u64>(mdhd.timescale as u64, track.id));
Ok((mdhd, duration, timescale))
}
fn read_mdia<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<()> {
let mut iter = f.box_iter();
while let Some(mut b) = iter.next_box()? {
match b.head.name {
BoxType::MediaHeaderBox => {
let (mdhd, duration, timescale) = parse_mdhd(&mut b, track)?;
track.duration = duration;
track.timescale = timescale;
debug!("{:?}", mdhd);
}
BoxType::HandlerBox => {
let hdlr = read_hdlr(&mut b)?;
match hdlr.handler_type.value.as_ref() {
"vide" => track.track_type = TrackType::Video,
"soun" => track.track_type = TrackType::Audio,
"meta" => track.track_type = TrackType::Metadata,
_ => (),
}
debug!("{:?}", hdlr);
}
BoxType::MediaInformationBox => read_minf(&mut b, track)?,
_ => skip_box_content(&mut b)?,
};
check_parser_state!(b.content);
}
Ok(())
}
fn read_minf<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<()> {
let mut iter = f.box_iter();
while let Some(mut b) = iter.next_box()? {
match b.head.name {
BoxType::SampleTableBox => read_stbl(&mut b, track)?,
_ => skip_box_content(&mut b)?,
};
check_parser_state!(b.content);
}
Ok(())
}
fn read_stbl<T: Read>(f: &mut BMFFBox<T>, track: &mut Track) -> Result<()> {
let mut iter = f.box_iter();
while let Some(mut b) = iter.next_box()? {
match b.head.name {
BoxType::SampleDescriptionBox => {
let stsd = read_stsd(&mut b, track)?;
debug!("{:?}", stsd);
track.stsd = Some(stsd);
}
BoxType::TimeToSampleBox => {
let stts = read_stts(&mut b)?;
debug!("{:?}", stts);
track.stts = Some(stts);
}
BoxType::SampleToChunkBox => {
let stsc = read_stsc(&mut b)?;
debug!("{:?}", stsc);
track.stsc = Some(stsc);
}
BoxType::SampleSizeBox => {
let stsz = read_stsz(&mut b)?;
debug!("{:?}", stsz);
track.stsz = Some(stsz);
}
BoxType::ChunkOffsetBox => {
let stco = read_stco(&mut b)?;
debug!("{:?}", stco);
track.stco = Some(stco);
}
BoxType::ChunkLargeOffsetBox => {