mp4-track 0.1.0

Track-level MP4 reader and progressive writer with bounded parsing
Documentation
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
use std::fmt;

/// A four-byte ISO box or sample-entry code.
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FourCc(pub [u8; 4]);

impl FourCc {
    /// Creates a code from its four bytes.
    pub const fn new(bytes: [u8; 4]) -> Self {
        Self(bytes)
    }

    /// Returns the code bytes.
    pub const fn into_bytes(self) -> [u8; 4] {
        self.0
    }

    /// Returns printable text, replacing invalid bytes.
    pub fn as_lossy_str(&self) -> String {
        String::from_utf8_lossy(&self.0).into_owned()
    }
}

impl Default for FourCc {
    fn default() -> Self {
        Self(*b"    ")
    }
}

impl From<[u8; 4]> for FourCc {
    fn from(value: [u8; 4]) -> Self {
        Self(value)
    }
}

impl TryFrom<&str> for FourCc {
    type Error = &'static str;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let bytes: [u8; 4] = value
            .as_bytes()
            .try_into()
            .map_err(|_| "a fourcc must contain four bytes")?;
        Ok(Self(bytes))
    }
}

impl fmt::Display for FourCc {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.0 {
            if byte.is_ascii_graphic() || byte == b' ' {
                write!(f, "{}", char::from(byte))?;
            } else {
                write!(f, "\\x{byte:02x}")?;
            }
        }
        Ok(())
    }
}

impl fmt::Debug for FourCc {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "FourCc({self})")
    }
}

/// A track identifier stored in track and fragment headers.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
pub struct TrackId(pub u32);

/// File-type brands from the `ftyp` box.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct Brands {
    /// Primary file brand.
    pub major: FourCc,
    /// Brand minor version.
    pub minor_version: u32,
    /// Compatible brands in stored order.
    pub compatible: Vec<FourCc>,
}

/// The media role of a track.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TrackKind {
    /// Video media.
    Video,
    /// Audio media.
    Audio,
    /// Timed text or subtitle media.
    Subtitle,
    /// Another handler type.
    Other(FourCc),
}

/// Codec configuration from a sample description.
#[derive(Clone, Debug, PartialEq)]
pub enum Codec {
    /// AVC configuration for an `avc1` or `avc3` entry.
    H264 {
        /// Stored sample-entry code.
        entry: FourCc,
        /// Decoder configuration.
        config: AvcConfig,
    },
    /// HEVC configuration for an `hvc1` or `hev1` entry.
    H265 {
        /// Stored sample-entry code.
        entry: FourCc,
        /// Decoder configuration.
        config: HevcConfig,
    },
    /// AAC configuration from an `mp4a` entry.
    Aac {
        /// Decoder configuration.
        config: AacConfig,
    },
    /// Opus configuration from an `Opus` entry.
    Opus {
        /// Decoder configuration.
        config: OpusConfig,
    },
    /// An unrecognized sample entry whose body is preserved.
    Other {
        /// Stored sample-entry code.
        entry: FourCc,
        /// Complete sample-entry body after the size and code fields.
        raw: Vec<u8>,
    },
}

/// A preserved sample-entry child box.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SidecarBox {
    /// Box code.
    pub kind: FourCc,
    /// Box body bytes.
    pub payload: Vec<u8>,
}

/// AVC decoder configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AvcConfig {
    /// Complete `avcC` payload.
    pub raw: Vec<u8>,
    /// AVC profile indication.
    pub profile: u8,
    /// Profile compatibility flags.
    pub profile_compat: u8,
    /// AVC level indication.
    pub level: u8,
    /// NAL unit length field width in bytes.
    pub nal_length_size: u8,
    /// Sequence parameter sets.
    pub sps: Vec<Vec<u8>>,
    /// Picture parameter sets.
    pub pps: Vec<Vec<u8>>,
    /// Preserved `pasp`, `btrt`, `fiel`, and `colr` boxes in stored order.
    pub sidecars: Vec<SidecarBox>,
}

/// One HEVC NAL array.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NalArray {
    /// NAL unit type.
    pub nal_type: u8,
    /// NAL units in stored order.
    pub nals: Vec<Vec<u8>>,
}

/// HEVC decoder configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HevcConfig {
    /// Complete `hvcC` payload.
    pub raw: Vec<u8>,
    /// NAL unit length field width in bytes.
    pub nal_length_size: u8,
    /// Parameter-set arrays in stored order.
    pub arrays: Vec<NalArray>,
    /// Preserved `pasp`, `btrt`, `fiel`, and `colr` boxes in stored order.
    pub sidecars: Vec<SidecarBox>,
}

/// AAC decoder configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AacConfig {
    /// Complete `esds` payload, including full-box fields.
    pub raw_esds: Vec<u8>,
    /// MPEG-4 object type indication.
    pub object_type: u8,
    /// Decoder-specific AudioSpecificConfig bytes.
    pub audio_specific_config: Vec<u8>,
    /// Channel count from the audio sample entry.
    pub channels: u16,
    /// Sample rate from the audio sample entry, or the media timescale when
    /// the entry stores no rate.
    pub sample_rate: u32,
    /// Preserved `pasp`, `btrt`, `fiel`, and `colr` boxes in stored order.
    pub sidecars: Vec<SidecarBox>,
}

/// Opus decoder configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OpusConfig {
    /// Complete `dOps` payload.
    pub raw: Vec<u8>,
    /// Output channel count.
    pub channels: u8,
    /// Decoder pre-skip in samples.
    pub pre_skip: u16,
    /// Input sample rate from the identification header.
    pub input_sample_rate: u32,
    /// Output gain in Q7.8 decibels.
    pub output_gain: i16,
    /// Channel mapping family.
    pub mapping_family: u8,
    /// Preserved `pasp`, `btrt`, `fiel`, and `colr` boxes in stored order.
    pub sidecars: Vec<SidecarBox>,
}

/// One movie edit-list entry.
#[derive(Clone, Debug, PartialEq)]
pub struct Edit {
    /// Segment duration in movie timescale units.
    pub segment_duration: u64,
    /// Media start time, or `None` for an empty edit.
    pub media_time: Option<u64>,
    /// Playback rate stored as 16.16 fixed point.
    pub media_rate: f32,
}

/// The box used for chunk offsets.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChunkOffsetKind {
    /// 32-bit offsets.
    Stco,
    /// 64-bit offsets.
    Co64,
    /// No progressive chunk offsets.
    None,
}

/// Parsed track metadata.
#[derive(Clone, Debug, PartialEq)]
pub struct Track {
    /// Track identifier.
    pub id: TrackId,
    /// Handler role.
    pub kind: TrackKind,
    /// Handler display name.
    pub handler_name: String,
    /// Media timescale.
    pub timescale: u32,
    /// Sum of sample durations in media units.
    pub duration: u64,
    /// ISO 639-2/T language code.
    pub language: String,
    /// Whether the track is enabled.
    pub enabled: bool,
    /// Display width.
    pub width: f64,
    /// Display height.
    pub height: f64,
    /// Primary sample description.
    pub codec: Codec,
    /// Movie edit list.
    pub edit_list: Vec<Edit>,
    /// Number of samples.
    pub sample_count: u32,
    /// Stored chunk-offset width.
    pub chunk_offsets: ChunkOffsetKind,
    /// Stored sync-sample count, or `None` when every sample is sync.
    pub sync_sample_count: Option<u32>,
}

impl Track {
    /// Returns the media time of the single non-empty edit.
    pub fn presentation_offset(&self) -> Option<u64> {
        let mut non_empty = self
            .edit_list
            .iter()
            .filter(|edit| edit.media_time.is_some());
        let first = non_empty.next()?;
        if non_empty.next().is_some() {
            return None;
        }
        first.media_time
    }
}

/// Location and timing for one sample.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SampleInfo {
    /// Zero-based track sample index.
    pub index: u32,
    /// Absolute byte offset.
    pub offset: u64,
    /// Sample size in bytes.
    pub size: u32,
    /// Decode time in media units.
    pub dts: u64,
    /// Signed composition-time offset.
    pub cts_offset: i64,
    /// Presentation time before edit-list mapping.
    pub pts: i64,
    /// Sample duration in media units.
    pub duration: u32,
    /// Whether this is a random-access sample.
    pub is_sync: bool,
    /// Zero-based chunk index, or fragment index for fragmented input.
    pub chunk: u32,
    /// One-based sample-description index.
    pub description_index: u32,
}

/// Sample bytes and parsed metadata.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Sample {
    /// Parsed sample metadata.
    pub info: SampleInfo,
    /// Encoded sample bytes.
    pub data: Vec<u8>,
}

/// One parsed movie fragment.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Fragment {
    /// Fragment sequence number.
    pub sequence_number: u32,
    /// Absolute `moof` offset.
    pub moof_offset: u64,
    /// Track runs in stored order.
    pub runs: Vec<TrackRun>,
}

/// Samples from one fragment track run.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TrackRun {
    /// Referenced track.
    pub track: TrackId,
    /// Expanded samples.
    pub samples: Vec<SampleInfo>,
}

/// A top-level event message.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Event {
    /// Event scheme identifier URI.
    pub scheme_id_uri: String,
    /// Scheme-specific value.
    pub value: String,
    /// Event timescale.
    pub timescale: u32,
    /// Presentation time.
    pub presentation_time: u64,
    /// Event duration.
    pub event_duration: u32,
    /// Event identifier.
    pub id: u32,
    /// Scheme-specific message bytes.
    pub message_data: Vec<u8>,
}

/// Parsed user metadata.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct Metadata {
    /// Metadata entries in stored order.
    pub entries: Vec<(MetaKey, MetaValue)>,
}

/// A recognized metadata key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MetaKey {
    /// Title.
    Title,
    /// Artist.
    Artist,
    /// Album.
    Album,
    /// Album artist.
    AlbumArtist,
    /// Composer.
    Composer,
    /// Genre.
    Genre,
    /// Comment.
    Comment,
    /// Release date.
    Date,
    /// Another four-byte key.
    Other(FourCc),
}

/// A metadata value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MetaValue {
    /// UTF-8 text.
    Text(String),
    /// Uninterpreted bytes.
    Binary(Vec<u8>),
    /// Big-endian integer.
    Integer(i64),
}

/// A tolerated file oddity.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Warning {
    /// Bytes remain after the last complete top-level box.
    TrailingBytes {
        /// Offset where trailing data begins.
        at: u64,
        /// Number of trailing bytes.
        count: u64,
    },
    /// An unknown box was skipped.
    UnknownBox {
        /// Unknown box code.
        kind: FourCc,
        /// Enclosing box code, when known.
        parent: Option<FourCc>,
    },
}

/// Resource bounds applied while opening and reading.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
    /// Maximum accepted movie box size. Defaults to 256 MiB.
    pub max_moov_bytes: u64,
    /// Maximum accepted fragment box size. Defaults to 64 MiB.
    pub max_moof_bytes: u64,
    /// Maximum bytes read for one sample. Defaults to 64 MiB.
    pub max_sample_bytes: u32,
    /// Maximum fragment count. Defaults to one million.
    pub max_fragments: u32,
    /// Maximum expanded sample count for one track. Defaults to 500,000.
    pub max_sample_count: u32,
    /// Maximum structural nesting. Defaults to 32.
    pub max_depth: u8,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_moov_bytes: 256 * 1024 * 1024,
            max_moof_bytes: 64 * 1024 * 1024,
            max_sample_bytes: 64 * 1024 * 1024,
            max_fragments: 1_000_000,
            max_sample_count: 500_000,
            max_depth: 32,
        }
    }
}

/// Writer selection for chunk-offset boxes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChunkOffsetChoice {
    /// Select the narrowest valid offset box.
    Auto,
    /// Always write 64-bit offsets.
    Co64,
}

/// File-level writer settings.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WriterConfig {
    /// Movie timescale. Defaults to 1000.
    pub movie_timescale: u32,
    /// Primary output brand.
    pub major_brand: FourCc,
    /// Compatible output brands.
    pub compatible_brands: Vec<FourCc>,
    /// Chunk-offset width selection.
    pub chunk_offsets: ChunkOffsetChoice,
}

impl Default for WriterConfig {
    fn default() -> Self {
        Self {
            movie_timescale: 1000,
            major_brand: FourCc(*b"isom"),
            compatible_brands: vec![FourCc(*b"isom"), FourCc(*b"iso2"), FourCc(*b"mp41")],
            chunk_offsets: ChunkOffsetChoice::Auto,
        }
    }
}

/// Track settings supplied to the writer.
#[derive(Clone, Debug, PartialEq)]
pub struct TrackConfig {
    /// Handler role.
    pub kind: TrackKind,
    /// Media timescale.
    pub timescale: u32,
    /// ISO 639-2/T language code.
    pub language: String,
    /// Handler display name.
    pub handler_name: String,
    /// Sample description.
    pub codec: Codec,
    /// Display width.
    pub width: f64,
    /// Display height.
    pub height: f64,
    /// Movie edit list.
    pub edit_list: Vec<Edit>,
}

/// One sample supplied to the writer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SampleInput<'a> {
    /// Encoded sample bytes.
    pub data: &'a [u8],
    /// Decode duration in media units.
    pub duration: u32,
    /// Signed composition-time offset.
    pub cts_offset: i32,
    /// Whether this is a random-access sample.
    pub is_sync: bool,
}