-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathlib.rs
More file actions
4891 lines (4359 loc) · 163 KB
/
lib.rs
File metadata and controls
4891 lines (4359 loc) · 163 KB
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/.
// `clippy::upper_case_acronyms` is a nightly-only lint as of 2021-03-15, so we
// allow `clippy::unknown_clippy_lints` to ignore it on stable - but
// `clippy::unknown_clippy_lints` has been renamed in nightly, so we need to
// allow `renamed_and_removed_lints` to ignore a warning for that.
#![allow(renamed_and_removed_lints)]
#![allow(clippy::unknown_clippy_lints)]
#![allow(clippy::upper_case_acronyms)]
#[macro_use]
extern crate log;
extern crate bitreader;
extern crate byteorder;
extern crate fallible_collections;
extern crate num_traits;
use bitreader::{BitReader, ReadInto};
use byteorder::{ReadBytesExt, WriteBytesExt};
use fallible_collections::TryRead;
use fallible_collections::TryReserveError;
use num_traits::Num;
use std::convert::{TryFrom, TryInto as _};
use std::fmt;
use std::io::Cursor;
use std::io::{Read, Take};
#[macro_use]
mod macros;
mod boxes;
use boxes::{BoxType, FourCC};
// Unit tests.
#[cfg(test)]
mod tests;
#[cfg(feature = "unstable-api")]
pub mod unstable;
/// The 'mif1' brand indicates structural requirements on files
/// See HEIF (ISO 23008-12:2017) § 10.2.1
const MIF1_BRAND: FourCC = FourCC { value: *b"mif1" };
/// A trait to indicate a type can be infallibly converted to `u64`.
/// This should only be implemented for infallible conversions, so only unsigned types are valid.
trait ToU64 {
// Remove when https://github.com/rust-lang/rust-clippy/issues/6727 is resolved
#[allow(clippy::wrong_self_convention)]
fn to_u64(self) -> u64;
}
/// Statically verify that the platform `usize` can fit within a `u64`.
/// If the size won't fit on the given platform, this will fail at compile time, but if a type
/// which can fail TryInto<usize> is used, it may panic.
impl ToU64 for usize {
fn to_u64(self) -> u64 {
static_assertions::const_assert!(
std::mem::size_of::<usize>() <= std::mem::size_of::<u64>()
);
self.try_into().expect("usize -> u64 conversion failed")
}
}
/// A trait to indicate a type can be infallibly converted to `usize`.
/// This should only be implemented for infallible conversions, so only unsigned types are valid.
pub trait ToUsize {
// Remove when https://github.com/rust-lang/rust-clippy/issues/6727 is resolved
#[allow(clippy::wrong_self_convention)]
fn to_usize(self) -> usize;
}
/// Statically verify that the given type can fit within a `usize`.
/// If the size won't fit on the given platform, this will fail at compile time, but if a type
/// which can fail TryInto<usize> is used, it may panic.
macro_rules! impl_to_usize_from {
( $from_type:ty ) => {
impl ToUsize for $from_type {
fn to_usize(self) -> usize {
static_assertions::const_assert!(
std::mem::size_of::<$from_type>() <= std::mem::size_of::<usize>()
);
self.try_into().expect(concat!(
stringify!($from_type),
" -> usize conversion failed"
))
}
}
};
}
impl_to_usize_from!(u8);
impl_to_usize_from!(u16);
impl_to_usize_from!(u32);
/// Indicate the current offset (i.e., bytes already read) in a reader
trait Offset {
fn offset(&self) -> u64;
}
/// Wraps a reader to track the current offset
struct OffsetReader<'a, T: 'a> {
reader: &'a mut T,
offset: u64,
}
impl<'a, T> OffsetReader<'a, T> {
fn new(reader: &'a mut T) -> Self {
Self { reader, offset: 0 }
}
}
impl<'a, T> Offset for OffsetReader<'a, T> {
fn offset(&self) -> u64 {
self.offset
}
}
impl<'a, T: Read> Read for OffsetReader<'a, T> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let bytes_read = self.reader.read(buf)?;
self.offset = self
.offset
.checked_add(bytes_read.to_u64())
.expect("total bytes read too large for offset type");
Ok(bytes_read)
}
}
pub type TryVec<T> = fallible_collections::TryVec<T>;
pub type TryString = fallible_collections::TryVec<u8>;
pub type TryHashMap<K, V> = fallible_collections::TryHashMap<K, V>;
pub type TryBox<T> = fallible_collections::TryBox<T>;
// 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;
/// 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 std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl std::error::Error for Error {}
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<std::str::Utf8Error> for Error {
fn from(_: std::str::Utf8Error) -> Error {
Error::InvalidData("invalid utf8")
}
}
impl From<std::num::TryFromIntError> for Error {
fn from(_: std::num::TryFromIntError) -> Error {
Error::Unsupported("integer conversion failed")
}
}
impl From<Error> for std::io::Error {
fn from(err: Error) -> Self {
let kind = match err {
Error::InvalidData(_) => std::io::ErrorKind::InvalidData,
Error::UnexpectedEOF => std::io::ErrorKind::UnexpectedEof,
Error::Io(io_err) => return io_err,
_ => std::io::ErrorKind::Other,
};
Self::new(kind, err)
}
}
impl From<TryReserveError> for Error {
fn from(_: TryReserveError) -> Error {
Error::OutOfMemory
}
}
/// Result shorthand using our Error enum.
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// 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.
///
/// See ISOBMFF (ISO 14496-12:2015) § 4.2
#[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]>,
}
impl BoxHeader {
const MIN_SIZE: u64 = 8; // 4-byte size + 4-byte type
const MIN_LARGE_SIZE: u64 = 16; // 4-byte size + 4-byte type + 16-byte size
}
/// File type box 'ftyp'.
#[derive(Debug)]
struct FileTypeBox {
major_brand: FourCC,
minor_version: u32,
compatible_brands: TryVec<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: TryVec<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: TryVec<u64>,
}
// Sync sample box 'stss'
#[derive(Debug)]
pub struct SyncSampleBox {
pub samples: TryVec<u32>,
}
// Sample to chunk box 'stsc'
#[derive(Debug)]
pub struct SampleToChunkBox {
pub samples: TryVec<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: TryVec<u32>,
}
// Time to sample box 'stts'
#[derive(Debug)]
pub struct TimeToSampleBox {
pub samples: TryVec<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: TryVec<TimeOffset>,
}
// Handler reference box 'hdlr'
#[derive(Debug)]
struct HandlerBox {
handler_type: FourCC,
}
// Sample description box 'stsd'
#[derive(Debug)]
pub struct SampleDescriptionBox {
pub descriptions: TryVec<SampleEntry>,
}
#[derive(Debug)]
pub enum SampleEntry {
Audio(AudioSampleEntry),
Video(VideoSampleEntry),
Unknown,
}
/// An Elementary Stream Descriptor
/// See MPEG-4 Systems (ISO 14496-1:2010) § 7.2.6.5
#[allow(non_camel_case_types)]
#[derive(Debug, 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>,
#[cfg(feature = "mp4v")]
pub video_codec: CodecType,
pub codec_esds: TryVec<u8>,
pub decoder_specific_data: TryVec<u8>, // Data in DECODER_SPECIFIC_TAG
}
#[allow(non_camel_case_types)]
#[derive(Debug)]
pub enum AudioCodecSpecific {
ES_Descriptor(ES_Descriptor),
FLACSpecificBox(FLACSpecificBox),
OpusSpecificBox(OpusSpecificBox),
ALACSpecificBox(ALACSpecificBox),
MP3,
LPCM,
#[cfg(feature = "3gpp")]
AMRSpecificBox(TryVec<u8>),
}
#[derive(Debug)]
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: TryVec<ProtectionSchemeInfoBox>,
}
#[derive(Debug)]
pub enum VideoCodecSpecific {
AVCConfig(TryVec<u8>),
VPxConfig(VPxConfigBox),
AV1Config(AV1ConfigBox),
ESDSConfig(TryVec<u8>),
H263Config(TryVec<u8>),
}
#[derive(Debug)]
pub struct VideoSampleEntry {
pub codec_type: CodecType,
data_reference_index: u16,
pub width: u16,
pub height: u16,
pub codec_specific: VideoCodecSpecific,
pub protection_info: TryVec<ProtectionSchemeInfoBox>,
}
/// Represent a Video Partition Codec Configuration 'vpcC' box (aka vp9). The meaning of each
/// field is covered in detail in "VP Codec ISO Media File Format Binding".
#[derive(Debug)]
pub struct VPxConfigBox {
/// An integer that specifies the VP codec profile.
profile: u8,
/// An integer that specifies a VP codec level all samples conform to the following table.
/// For a description of the various levels, please refer to the VP9 Bitstream Specification.
level: u8,
/// An integer that specifies the bit depth of the luma and color components. Valid values
/// are 8, 10, and 12.
pub bit_depth: u8,
/// Really an enum defined by the "Colour primaries" section of ISO 23091-2:2019 § 8.1.
pub colour_primaries: u8,
/// Really an enum defined by "VP Codec ISO Media File Format Binding".
pub chroma_subsampling: u8,
/// Really an enum defined by the "Transfer characteristics" section of ISO 23091-2:2019 § 8.2.
transfer_characteristics: u8,
/// Really an enum defined by the "Matrix coefficients" section of ISO 23091-2:2019 § 8.3.
/// Available in 'VP Codec ISO Media File Format' version 1 only.
matrix_coefficients: Option<u8>,
/// Indicates the black level and range of the luma and chroma signals. 0 = legal range
/// (e.g. 16-235 for 8 bit sample depth); 1 = full range (e.g. 0-255 for 8-bit sample depth).
video_full_range_flag: bool,
/// This is not used for VP8 and VP9 . Intended for binary codec initialization data.
pub codec_init: TryVec<u8>,
}
/// See AV1-ISOBMFF § 2.3.3 https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
#[derive(Debug)]
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,
// The raw config contained in the av1c box. Because some decoders accept this data as a binary
// blob, rather than as structured data, we store the blob here for convenience.
pub raw_config: TryVec<u8>,
}
impl AV1ConfigBox {
/// See https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
const CONFIG_OBUS_OFFSET: usize = 4;
pub fn config_obus(&self) -> &[u8] {
&self.raw_config[Self::CONFIG_OBUS_OFFSET..]
}
}
#[derive(Debug)]
pub struct FLACMetadataBlock {
pub block_type: u8,
pub data: TryVec<u8>,
}
/// Represents a FLACSpecificBox 'dfLa'
#[derive(Debug)]
pub struct FLACSpecificBox {
version: u8,
pub blocks: TryVec<FLACMetadataBlock>,
}
#[derive(Debug)]
struct ChannelMappingTable {
stream_count: u8,
coupled_count: u8,
channel_mapping: TryVec<u8>,
}
/// Represent an OpusSpecificBox 'dOps'
#[derive(Debug)]
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)]
pub struct ALACSpecificBox {
version: u8,
pub data: TryVec<u8>,
}
#[derive(Debug)]
pub struct MovieExtendsBox {
pub fragment_duration: Option<MediaScaledTime>,
}
pub type ByteData = TryVec<u8>;
#[derive(Debug, Default)]
pub struct ProtectionSystemSpecificHeaderBox {
pub system_id: ByteData,
pub kid: TryVec<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)]
pub struct TrackEncryptionBox {
pub is_encrypted: u8,
pub iv_size: u8,
pub kid: TryVec<u8>,
// Members for pattern encryption schemes
pub crypt_byte_block_count: Option<u8>,
pub skip_byte_block_count: Option<u8>,
pub constant_iv: Option<TryVec<u8>>,
// End pattern encryption scheme members
}
#[derive(Debug, Default)]
pub struct ProtectionSchemeInfoBox {
pub original_format: FourCC,
pub scheme_type: Option<SchemeTypeBox>,
pub tenc: Option<TrackEncryptionBox>,
}
/// Represents a userdata box 'udta'.
/// Currently, only the metadata atom 'meta'
/// is parsed.
#[derive(Debug, Default)]
pub struct UserdataBox {
pub meta: Option<MetadataBox>,
}
/// Represents possible contents of the
/// ©gen or gnre atoms within a metadata box.
/// 'udta.meta.ilst' may only have either a
/// standard genre box 'gnre' or a custom
/// genre box '©gen', but never both at once.
#[derive(Debug, PartialEq)]
pub enum Genre {
/// A standard ID3v1 numbered genre.
StandardGenre(u8),
/// Any custom genre string.
CustomGenre(TryString),
}
/// Represents the contents of a 'stik'
/// atom that indicates content types within
/// iTunes.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum MediaType {
/// Movie is stored as 0 in a 'stik' atom.
Movie, // 0
/// Normal is stored as 1 in a 'stik' atom.
Normal, // 1
/// AudioBook is stored as 2 in a 'stik' atom.
AudioBook, // 2
/// WhackedBookmark is stored as 5 in a 'stik' atom.
WhackedBookmark, // 5
/// MusicVideo is stored as 6 in a 'stik' atom.
MusicVideo, // 6
/// ShortFilm is stored as 9 in a 'stik' atom.
ShortFilm, // 9
/// TVShow is stored as 10 in a 'stik' atom.
TVShow, // 10
/// Booklet is stored as 11 in a 'stik' atom.
Booklet, // 11
/// An unknown 'stik' value.
Unknown(u8),
}
/// Represents the parental advisory rating on the track,
/// stored within the 'rtng' atom.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum AdvisoryRating {
/// Clean is always stored as 2 in an 'rtng' atom.
Clean, // 2
/// A value of 0 in an 'rtng' atom indicates 'Inoffensive'
Inoffensive, // 0
/// Any non 2 or 0 value in 'rtng' indicates the track is explicit.
Explicit(u8),
}
/// Represents the contents of 'ilst' atoms within
/// a metadata box 'meta', parsed as iTunes metadata using
/// the conventional tags.
#[derive(Debug, Default)]
pub struct MetadataBox {
/// The album name, '©alb'
pub album: Option<TryString>,
/// The artist name '©art' or '©ART'
pub artist: Option<TryString>,
/// The album artist 'aART'
pub album_artist: Option<TryString>,
/// Track comments '©cmt'
pub comment: Option<TryString>,
/// The date or year field '©day'
///
/// This is stored as an arbitrary string,
/// and may not necessarily be in a valid date
/// format.
pub year: Option<TryString>,
/// The track title '©nam'
pub title: Option<TryString>,
/// The track genre '©gen' or 'gnre'.
pub genre: Option<Genre>,
/// The track number 'trkn'.
pub track_number: Option<u8>,
/// The disc number 'disk'
pub disc_number: Option<u8>,
/// The total number of tracks on the disc,
/// stored in 'trkn'
pub total_tracks: Option<u8>,
/// The total number of discs in the album,
/// stored in 'disk'
pub total_discs: Option<u8>,
/// The composer of the track '©wrt'
pub composer: Option<TryString>,
/// The encoder used to create this track '©too'
pub encoder: Option<TryString>,
/// The encoded-by settingo this track '©enc'
pub encoded_by: Option<TryString>,
/// The tempo or BPM of the track 'tmpo'
pub beats_per_minute: Option<u8>,
/// Copyright information of the track 'cprt'
pub copyright: Option<TryString>,
/// Whether or not this track is part of a compilation 'cpil'
pub compilation: Option<bool>,
/// The advisory rating of this track 'rtng'
pub advisory: Option<AdvisoryRating>,
/// The personal rating of this track, 'rate'.
///
/// This is stored in the box as string data, but
/// the format is an integer percentage from 0 - 100,
/// where 100 is displayed as 5 stars out of 5.
pub rating: Option<TryString>,
/// The grouping this track belongs to '©grp'
pub grouping: Option<TryString>,
/// The media type of this track 'stik'
pub media_type: Option<MediaType>, // stik
/// Whether or not this track is a podcast 'pcst'
pub podcast: Option<bool>,
/// The category of ths track 'catg'
pub category: Option<TryString>,
/// The podcast keyword 'keyw'
pub keyword: Option<TryString>,
/// The podcast url 'purl'
pub podcast_url: Option<TryString>,
/// The podcast episode GUID 'egid'
pub podcast_guid: Option<TryString>,
/// The description of the track 'desc'
pub description: Option<TryString>,
/// The long description of the track 'ldes'.
///
/// Unlike other string fields, the long description field
/// can be longer than 256 characters.
pub long_description: Option<TryString>,
/// The lyrics of the track '©lyr'.
///
/// Unlike other string fields, the lyrics field
/// can be longer than 256 characters.
pub lyrics: Option<TryString>,
/// The name of the TV network this track aired on 'tvnn'.
pub tv_network_name: Option<TryString>,
/// The name of the TV Show for this track 'tvsh'.
pub tv_show_name: Option<TryString>,
/// The name of the TV Episode for this track 'tven'.
pub tv_episode_name: Option<TryString>,
/// The number of the TV Episode for this track 'tves'.
pub tv_episode_number: Option<u8>,
/// The season of the TV Episode of this track 'tvsn'.
pub tv_season: Option<u8>,
/// The date this track was purchased 'purd'.
pub purchase_date: Option<TryString>,
/// Whether or not this track supports gapless playback 'pgap'
pub gapless_playback: Option<bool>,
/// Any cover artwork attached to this track 'covr'
///
/// 'covr' is unique in that it may contain multiple 'data' sub-entries,
/// each an image file. Here, each subentry's raw binary data is exposed,
/// which may contain image data in JPEG or PNG format.
pub cover_art: Option<TryVec<TryVec<u8>>>,
/// The owner of the track 'ownr'
pub owner: Option<TryString>,
/// Whether or not this track is HD Video 'hdvd'
pub hd_video: Option<bool>,
/// The name of the track to sort by 'sonm'
pub sort_name: Option<TryString>,
/// The name of the album to sort by 'soal'
pub sort_album: Option<TryString>,
/// The name of the artist to sort by 'soar'
pub sort_artist: Option<TryString>,
/// The name of the album artist to sort by 'soaa'
pub sort_album_artist: Option<TryString>,
/// The name of the composer to sort by 'soco'
pub sort_composer: Option<TryString>,
/// Metadata
#[cfg(feature = "meta-xml")]
pub xml: Option<XmlBox>,
}
/// See ISOBMFF (ISO 14496-12:2015) § 8.11.2.1
#[cfg(feature = "meta-xml")]
#[derive(Debug)]
pub enum XmlBox {
/// XML metadata
StringXmlBox(TryString),
/// Binary XML metadata
BinaryXmlBox(TryVec<u8>),
}
/// Internal data structures.
#[derive(Debug, Default)]
pub struct MediaContext {
pub timescale: Option<MediaTimeScale>,
/// Tracks found in the file.
pub tracks: TryVec<Track>,
pub mvex: Option<MovieExtendsBox>,
pub psshs: TryVec<ProtectionSystemSpecificHeaderBox>,
pub userdata: Option<Result<UserdataBox>>,
#[cfg(feature = "meta-xml")]
pub metadata: Option<Result<MetadataBox>>,
}
/// An ISOBMFF item as described by an iloc box. For the sake of avoiding copies,
/// this can either be represented by the `Location` variant, which indicates
/// where the data exists within a `MediaDataBox` stored separately, or the
/// `Data` variant which owns the data. Unfortunately, it's not simple to
/// represent this as a [`std::borrow::Cow`], or other reference-based type, because
/// multiple instances may references different parts of the same [`MediaDataBox`]
/// and we want to avoid the copy that splitting the storage would entail.
#[derive(Debug)]
enum IsobmffItem {
Location(Extent),
Data(TryVec<u8>),
}
#[derive(Debug)]
struct AvifItem {
/// The `item_ID` from ISOBMFF (ISO 14496-12:2015)
///
/// See [`read_iloc`]
id: ItemId,
/// AV1 Image Item per <https://aomediacodec.github.io/av1-avif/#image-item>
image_data: IsobmffItem,
}
impl AvifItem {
fn with_data_location(id: ItemId, extent: Extent) -> Result<Self> {
Ok(Self {
id,
image_data: IsobmffItem::Location(extent),
})
}
fn with_inline_data(id: ItemId) -> Result<Self> {
Ok(Self {
id,
image_data: IsobmffItem::Data(TryVec::new()),
})
}
}
#[derive(Debug)]
pub struct AvifContext {
/// Level of deviation from the specification before failing the parse
strictness: ParseStrictness,
/// Referred to by the `Location` variants of the `AvifItem`s in this struct
item_storage: TryVec<MediaDataBox>,
/// The item indicated by the `pitm` box, See ISOBMFF (ISO 14496-12:2015) § 8.11.4
primary_item: AvifItem,
/// Associated alpha channel for the primary item, if any
alpha_item: Option<AvifItem>,
/// If true, divide RGB values by the alpha value.
/// See `prem` in MIAF (ISO 23000-22:2019) § 7.3.5.2
pub premultiplied_alpha: bool,
/// All properties associated with `primary_item` or `alpha_item`
item_properties: ItemPropertiesBox,
}
impl AvifContext {
pub fn primary_item(&self) -> &[u8] {
self.item_as_slice(&self.primary_item)
}
pub fn alpha_item(&self) -> Option<&[u8]> {
self.alpha_item
.as_ref()
.map(|item| self.item_as_slice(item))
}
pub fn spatial_extents_ptr(&self) -> *const ImageSpatialExtentsProperty {
match self
.item_properties
.get(self.primary_item.id, BoxType::ImageSpatialExtentsProperty)
{
Some(ItemProperty::ImageSpatialExtents(ispe)) => ispe,
Some(other_property) => panic!("property key mismatch: {:?}", other_property),
None => {
assert!(
self.strictness == ParseStrictness::Permissive,
"ispe is a mandatory property",
);
std::ptr::null()
}
}
}
pub fn image_rotation(&self) -> ImageRotation {
match self
.item_properties
.get(self.primary_item.id, BoxType::ImageRotation)
{
Some(ItemProperty::Rotation(irot)) => *irot,
Some(other_property) => panic!("property key mismatch: {:?}", other_property),
None => ImageRotation::D0,
}
}
pub fn image_mirror_ptr(&self) -> *const ImageMirror {
match self
.item_properties
.get(self.primary_item.id, BoxType::ImageMirror)
{
Some(ItemProperty::Mirroring(imir)) => imir,
Some(other_property) => panic!("property key mismatch: {:?}", other_property),
None => std::ptr::null(),
}
}
/// A helper for the various `AvifItem`s to expose a reference to the
/// underlying data while avoiding copies.
fn item_as_slice<'a>(&'a self, item: &'a AvifItem) -> &'a [u8] {
match &item.image_data {
IsobmffItem::Location(extent) => {
for mdat in &self.item_storage {
if let Some(slice) = mdat.get(extent) {
return slice;
}
}
unreachable!(
"IsobmffItem::Location requires the location exists in AvifContext::item_storage"
);
}
IsobmffItem::Data(data) => data.as_slice(),
}
}
}
struct AvifMeta {
item_references: TryVec<SingleItemTypeReferenceBox>,
item_properties: ItemPropertiesBox,
primary_item_id: ItemId,
iloc_items: TryHashMap<ItemId, ItemLocationBoxItem>,
}
/// A Media Data Box
/// See ISOBMFF (ISO 14496-12:2015) § 8.1.1
struct MediaDataBox {
/// Offset of `data` from the beginning of the "file". See ConstructionMethod::File.
/// Note: the file may not be an actual file, read_avif supports any `&mut impl Read`
/// source for input. However we try to match the terminology used in the spec.
file_offset: u64,
data: TryVec<u8>,
}
impl fmt::Debug for MediaDataBox {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("MediaDataBox")
.field("file_offset", &self.file_offset)
.field("data", &format_args!("{} bytes", self.data.len()))
.finish()
}
}
impl MediaDataBox {
/// Convert an absolute offset to an offset relative to the beginning of the
/// `self.data` field. Returns None if the offset would be negative.
///
/// # Panics
///
/// Panics if the offset would overflow a `usize`.
fn file_offset_to_data_offset(&self, offset: u64) -> Option<usize> {
let start = offset
.checked_sub(self.file_offset)?
.try_into()
.expect("usize overflow");
Some(start)
}
/// Return a slice from the MediaDataBox specified by the provided `extent`.
/// Returns `None` if the extent isn't fully contained by the MediaDataBox.
///
/// # Panics
///
/// Panics if either the offset or length (if the extent is bounded) of the
/// slice would overflow a `usize`.
pub fn get<'a>(&'a self, extent: &'a Extent) -> Option<&'a [u8]> {
match extent {
Extent::WithLength { offset, len } => {
let start = self.file_offset_to_data_offset(*offset)?;
let end = start.checked_add(*len).expect("usize overflow");
self.data.get(start..end)
}
Extent::ToEnd { offset } => {
let start = self.file_offset_to_data_offset(*offset)?;
self.data.get(start..)
}
}
}
}
#[cfg(test)]
mod media_data_box_tests {
use super::*;
impl MediaDataBox {
fn at_offset(file_offset: u64, data: std::vec::Vec<u8>) -> Self {
MediaDataBox {
file_offset,
data: data.into(),
}
}
}
#[test]
fn extent_with_length_before_mdat_returns_none() {
let mdat = MediaDataBox::at_offset(100, vec![1; 5]);
let extent = Extent::WithLength { offset: 0, len: 2 };
assert!(mdat.get(&extent).is_none());