mp4-atom 0.17.0

A MP4/ISOBMFF atom decoder and encoder
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
mod ac3;
mod amr;
mod audio;
mod av01;
mod btrt;
mod camm;
mod ccst;
mod chnl;
mod colr;
mod eac3;
mod evte;
mod fiel;
mod flac;
mod ftab;
mod h264;
mod hevc;
mod jpeg;
mod mebx;
mod metadata;
mod mett;
mod metx;
mod mp3;
mod mp4a;
mod opus;
mod pasp;
mod pcm;
mod plaintext;
mod spatial;
mod st3d;
mod sv3d;
mod taic;
mod tx3g;
mod uncv;
mod urim;
mod vexu;
mod visual;
mod vp9;
mod wvtt;

pub use ac3::*;
pub use amr::*;
pub use audio::*;
pub use av01::*;
pub use btrt::*;
pub use camm::*;
pub use ccst::*;
pub use chnl::*;
pub use colr::*;
pub use eac3::*;
pub use evte::*;
pub use fiel::*;
pub use flac::*;
pub use ftab::*;
pub use h264::*;
pub use hevc::*;
pub use jpeg::*;
pub use mebx::*;
pub use metadata::*;
pub use mett::*;
pub use metx::*;
pub use mp3::*;
pub use mp4a::*;
pub use opus::*;
pub use pasp::*;
pub use pcm::*;
pub use plaintext::*;
pub use spatial::*;
pub use st3d::*;
pub use sv3d::*;
pub use taic::*;
pub use tx3g::*;
pub use uncv::*;
pub use urim::*;
pub use vexu::*;
pub use visual::*;
pub use vp9::*;
pub use wvtt::*;

use crate::*;
use derive_more::From;

#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Stsd {
    pub codecs: Vec<Codec>,
}

/// Called a "sample entry" in the ISOBMFF specification.
#[derive(Debug, Clone, PartialEq, Eq, From)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Codec {
    // H264
    Avc1(Avc1),

    // H264: SPS/PPS may also be inline
    Avc3(Avc3),

    // Photo - JPEG (QuickTime Motion JPEG)
    Jpeg(Jpeg),

    // HEVC: SPS/PPS/VPS is inline
    Hev1(Hev1),

    // HEVC: SPS/PPS/VPS is in a separate atom
    Hvc1(Hvc1),

    // VP8
    Vp08(Vp08),

    // VP9
    Vp09(Vp09),

    // AV1
    Av01(Av01),

    // AAC
    Mp4a(Mp4a),

    // MP3
    Mp3(Mp3),

    // Text
    Tx3g(Tx3g),

    // Opus
    Opus(Opus),

    // Uncompressed video
    Uncv(Uncv),

    // FLAC audio
    Flac(Flac),

    // AC-3 audio
    Ac3(Ac3),

    // EAC-3 audio
    Eac3(Eac3),

    // Uncompressed audio
    // ipcm and fpcm are from 23003-5.
    Ipcm(Ipcm),
    Fpcm(Fpcm),
    // sowt / twos and in24 / in32 / fl32 / fl64 / lpcm are Quicktime (QTFF-2001).
    // s16l seems to be something that VLC produced at some point.
    Sowt(Sowt),
    Twos(Twos),
    Lpcm(Lpcm),
    In24(In24),
    In32(In32),
    Fl32(Fl32),
    Fl64(Fl64),
    S16l(S16l),

    // WebVTT, ISO/IEC 14496-30
    Wvtt(Wvtt),

    // 3GPP Narrowband audio (3GPP TS 26.244 or ETSI TS 126 244)
    Samr(Samr),

    // Text-based timed metadata
    Mett(Mett),

    // XML-based timed metadata
    Metx(Metx),

    // URI-based timed metadata
    Urim(Urim),

    // Camera motion metadata (gyroscope/accelerometer), used by Google devices
    Camm(Camm),

    // CMAF/DASH Event Message track, carrying `Emsg` boxes as samples
    // (ISO/IEC 23001-18).
    Evte(Evte),

    // Structured/"boxed" timed metadata, QuickTime "Metadata Media"
    Mebx(Mebx),

    // Unknown
    Unknown(FourCC, Vec<u8>),
}

impl Codec {
    /// A video track's sample entry fields (frame size, ...);
    /// `None` for any other codec.
    pub fn visual(&self) -> Option<&Visual> {
        Some(match self {
            Self::Avc1(avc1) => &avc1.visual,
            Self::Avc3(avc3) => &avc3.visual,
            Self::Jpeg(jpeg) => &jpeg.visual,
            Self::Hev1(hev1) => &hev1.visual,
            Self::Hvc1(hvc1) => &hvc1.visual,
            Self::Vp08(vp08) => &vp08.visual,
            Self::Vp09(vp09) => &vp09.visual,
            Self::Av01(av01) => &av01.visual,
            Self::Uncv(uncv) => &uncv.visual,
            _ => return None,
        })
    }

    /// An audio track's sample entry fields (sample rate, channel count, ...);
    /// `None` for any other codec.
    pub fn audio(&self) -> Option<&Audio> {
        Some(match self {
            Self::Mp4a(mp4a) => &mp4a.audio,
            Self::Mp3(mp3) => &mp3.audio,
            Self::Opus(opus) => &opus.audio,
            Self::Flac(flac) => &flac.audio,
            Self::Ac3(ac3) => &ac3.audio,
            Self::Eac3(eac3) => &eac3.audio,
            Self::Ipcm(pcm) => &pcm.audio,
            Self::Fpcm(pcm) => &pcm.audio,
            Self::Sowt(pcm) => &pcm.audio,
            Self::Twos(pcm) => &pcm.audio,
            Self::Lpcm(pcm) => &pcm.audio,
            Self::In24(pcm) => &pcm.audio,
            Self::In32(pcm) => &pcm.audio,
            Self::Fl32(pcm) => &pcm.audio,
            Self::Fl64(pcm) => &pcm.audio,
            Self::S16l(pcm) => &pcm.audio,
            _ => return None,
        })
    }

    /// A timed metadata track's sample entry fields (data reference index);
    /// `None` for any other codec.
    pub fn metadata(&self) -> Option<&MetaData> {
        Some(match self {
            Self::Mett(mett) => &mett.metadata,
            Self::Metx(metx) => &metx.metadata,
            Self::Urim(urim) => &urim.metadata,
            Self::Camm(camm) => &camm.metadata,
            Self::Evte(evte) => &evte.metadata,
            Self::Mebx(mebx) => &mebx.metadata,
            _ => return None,
        })
    }
}

impl Decode for Codec {
    fn decode<B: Buf>(buf: &mut B) -> Result<Self> {
        let atom = Any::decode(buf)?;
        Ok(match atom {
            Any::Avc1(atom) => atom.into(),
            Any::Avc3(atom) => atom.into(),
            Any::Jpeg(atom) => atom.into(),
            Any::Hev1(atom) => atom.into(),
            Any::Hvc1(atom) => atom.into(),
            Any::Vp08(atom) => atom.into(),
            Any::Vp09(atom) => atom.into(),
            Any::Mp4a(atom) => atom.into(),
            Any::Mp3(atom) => atom.into(),
            Any::Tx3g(atom) => atom.into(),
            Any::Av01(atom) => atom.into(),
            Any::Opus(atom) => atom.into(),
            Any::Uncv(atom) => atom.into(),
            Any::Flac(atom) => atom.into(),
            Any::Ac3(atom) => atom.into(),
            Any::Eac3(atom) => atom.into(),
            Any::Ipcm(atom) => atom.into(),
            Any::Fpcm(atom) => atom.into(),
            Any::Sowt(atom) => atom.into(),
            Any::Twos(atom) => atom.into(),
            Any::Lpcm(atom) => atom.into(),
            Any::In24(atom) => atom.into(),
            Any::In32(atom) => atom.into(),
            Any::Fl32(atom) => atom.into(),
            Any::Fl64(atom) => atom.into(),
            Any::S16l(atom) => atom.into(),
            Any::Wvtt(atom) => atom.into(),
            Any::Samr(atom) => atom.into(),
            Any::Mett(atom) => atom.into(),
            Any::Metx(atom) => atom.into(),
            Any::Urim(atom) => atom.into(),
            Any::Camm(atom) => atom.into(),
            Any::Evte(atom) => atom.into(),
            Any::Mebx(atom) => atom.into(),
            Any::Unknown(four_cc, body) => Self::Unknown(four_cc, body),
            unknown => {
                crate::decode_unknown(&unknown, Stsd::KIND)?;

                // The atom kind is known elsewhere in the hierarchy, but is not a supported
                // sample entry. Re-encode its body so the unknown entry remains a valid box.
                let kind = unknown.kind();
                let mut encoded = Vec::new();
                unknown.encode(&mut encoded)?;
                Self::Unknown(kind, encoded.split_off(8))
            }
        })
    }
}

impl Encode for Codec {
    fn encode<B: BufMut>(&self, buf: &mut B) -> Result<()> {
        match self {
            Self::Unknown(..) => Err(Error::UnknownCodec),
            Self::Avc1(atom) => atom.encode(buf),
            Self::Avc3(atom) => atom.encode(buf),
            Self::Jpeg(atom) => atom.encode(buf),
            Self::Hev1(atom) => atom.encode(buf),
            Self::Hvc1(atom) => atom.encode(buf),
            Self::Vp08(atom) => atom.encode(buf),
            Self::Vp09(atom) => atom.encode(buf),
            Self::Mp4a(atom) => atom.encode(buf),
            Self::Mp3(atom) => atom.encode(buf),
            Self::Tx3g(atom) => atom.encode(buf),
            Self::Av01(atom) => atom.encode(buf),
            Self::Opus(atom) => atom.encode(buf),
            Self::Uncv(atom) => atom.encode(buf),
            Self::Flac(atom) => atom.encode(buf),
            Self::Ac3(atom) => atom.encode(buf),
            Self::Eac3(atom) => atom.encode(buf),
            Self::Ipcm(atom) => atom.encode(buf),
            Self::Fpcm(atom) => atom.encode(buf),
            Self::Sowt(atom) => atom.encode(buf),
            Self::Twos(atom) => atom.encode(buf),
            Self::Lpcm(atom) => atom.encode(buf),
            Self::In24(atom) => atom.encode(buf),
            Self::In32(atom) => atom.encode(buf),
            Self::Fl32(atom) => atom.encode(buf),
            Self::Fl64(atom) => atom.encode(buf),
            Self::S16l(atom) => atom.encode(buf),
            Self::Wvtt(atom) => atom.encode(buf),
            Self::Samr(atom) => atom.encode(buf),
            Self::Mett(atom) => atom.encode(buf),
            Self::Metx(atom) => atom.encode(buf),
            Self::Urim(atom) => atom.encode(buf),
            Self::Camm(atom) => atom.encode(buf),
            Self::Evte(atom) => atom.encode(buf),
            Self::Mebx(atom) => atom.encode(buf),
        }
    }
}

impl AtomExt for Stsd {
    type Ext = ();

    const KIND_EXT: FourCC = FourCC::new(b"stsd");

    fn decode_body_ext<B: Buf>(buf: &mut B, _ext: ()) -> Result<Self> {
        let codec_count = u32::decode(buf)?;
        let mut codecs = Vec::new();

        for _ in 0..codec_count {
            let codec = Codec::decode(buf)?;
            codecs.push(codec);
        }

        Ok(Stsd { codecs })
    }

    fn encode_body_ext<B: BufMut>(&self, buf: &mut B) -> Result<()> {
        (self.codecs.len() as u32).encode(buf)?;
        for codec in &self.codecs {
            codec.encode(buf)?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_codec_visual() {
        let visual = Visual {
            width: 640,
            height: 480,
            ..Default::default()
        };
        let codec = Codec::from(Jpeg {
            visual: visual.clone(),
            ..Default::default()
        });
        assert_eq!(codec.visual(), Some(&visual));
        assert_eq!(codec.audio(), None);
        assert_eq!(codec.metadata(), None);
    }

    #[test]
    fn test_codec_audio() {
        let audio = Audio {
            data_reference_index: 1,
            channel_count: 2,
            sample_size: 16,
            sample_rate: 44100.into(),
        };
        let codec = Codec::from(Mp3 {
            audio: audio.clone(),
        });
        assert_eq!(codec.audio(), Some(&audio));
        assert_eq!(codec.visual(), None);
    }

    #[test]
    fn test_codec_metadata() {
        let metadata = MetaData {
            data_reference_index: 3,
        };
        let codec = Codec::from(Camm {
            metadata: metadata.clone(),
        });
        assert_eq!(codec.metadata(), Some(&metadata));
        assert_eq!(codec.visual(), None);
        assert_eq!(codec.audio(), None);
    }

    #[test]
    fn test_codec_neither() {
        for codec in [
            Codec::from(Tx3g::default()),
            Codec::Unknown(FourCC::new(b"dvh9"), vec![]),
        ] {
            assert_eq!(codec.visual(), None);
            assert_eq!(codec.audio(), None);
            assert_eq!(codec.metadata(), None);
        }
    }

    #[cfg(not(feature = "strict"))]
    mod not_strict {
        use super::*;

        #[test]
        fn unknown_codec_parses() {
            let input = b"\0\0\0\x1cstsd\0\0\0\0\0\0\0\x01\0\0\0\x0cdvh9\x01\x02\x03\x04";
            let mut buf = input.as_slice();

            let stsd = Stsd::decode(&mut buf).unwrap();
            assert_eq!(
                stsd.codecs,
                vec![Codec::Unknown(FourCC::new(b"dvh9"), vec![1, 2, 3, 4])]
            );
        }

        #[test]
        fn unknown_codec_not_emitted() {
            let stsd = Stsd {
                codecs: vec![Codec::Unknown(FourCC::new(b"dvh9"), vec![1, 2, 3, 4])],
            };
            assert_eq!(
                stsd.codecs,
                vec![Codec::Unknown(FourCC::new(b"dvh9"), vec![1, 2, 3, 4])]
            );
            let mut output = Vec::new();
            assert!(matches!(
                stsd.encode(&mut output),
                Err(crate::Error::UnknownCodec)
            ));
        }
    }
}