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
use crate::*;

// ItemInformationBox. ISO/IEC 14496-12:2022 Section 8.11.6
// This is used to work out what the items are

ext! {
    name: Iinf,
    versions: [0, 1],
    flags: {}
}

ext! {
    name: ItemInfoEntry,
    versions: [0, 1, 2, 3],
    flags: {item_not_in_presentation = 0,}
}

/// Describes one item stored in an `iinf` item information box.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ItemInfoEntry {
    /// Item identifier used by other item metadata boxes.
    pub item_id: u32,

    /// Index into the item protection box, or zero when unprotected.
    pub item_protection_index: u16,

    /// Version 2 and 3 item type, such as `mime` or `uri `.
    pub item_type: Option<FourCC>,

    /// Human-readable item name.
    pub item_name: String,

    /// MIME content type for `mime` item entries.
    pub content_type: Option<String>,

    /// MIME content encoding for `mime` item entries.
    pub content_encoding: Option<String>,

    /// URI payload for `uri ` item entries.
    pub item_uri_type: Option<String>,

    /// Whether the item is excluded from presentation.
    pub item_not_in_presentation: bool,
}

impl AtomExt for ItemInfoEntry {
    const KIND_EXT: FourCC = FourCC::new(b"infe");

    type Ext = ItemInfoEntryExt;

    /// Encodes the item info entry body and version/flags extension.
    fn encode_body_ext<B: BufMut>(&self, buf: &mut B) -> Result<Self::Ext> {
        // TODO: maybe work harder at versioning
        let version: ItemInfoEntryVersion = if self.item_id > u16::MAX as u32 {
            ItemInfoEntryVersion::V3
        } else {
            // version 0 or 2, since we don't support version 1 yet
            if self.item_type.is_some() {
                ItemInfoEntryVersion::V2
            } else {
                ItemInfoEntryVersion::V0
            }
        };
        if (version == ItemInfoEntryVersion::V0) || (version == ItemInfoEntryVersion::V1) {
            (self.item_id as u16).encode(buf)?;
            self.item_protection_index.encode(buf)?;
            self.item_name.as_str().encode(buf)?;
            let content_type = self.content_type.as_deref().ok_or(Error::MissingContent(
                "content_type required for infe version 0 or 1",
            ))?;
            content_type.encode(buf)?;
            self.content_encoding.as_deref().unwrap_or("").encode(buf)?;
            if version == ItemInfoEntryVersion::V1 {
                return Err(Error::Unsupported("infe version 1 extensions"));
            }
        } else {
            if version == ItemInfoEntryVersion::V2 {
                (self.item_id as u16).encode(buf)?;
            } else {
                self.item_id.encode(buf)?;
            }
            self.item_protection_index.encode(buf)?;
            Some(self.item_type).encode(buf)?;
            self.item_name.as_str().encode(buf)?;
            if self.item_type == Some(FourCC::new(b"mime")) {
                let content_type = self.content_type.as_deref().ok_or(Error::MissingContent(
                    "content_type required with 'mime' item_type",
                ))?;
                content_type.encode(buf)?;
                self.content_encoding.as_deref().unwrap_or("").encode(buf)?;
            } else if self.item_type == Some(FourCC::new(b"uri ")) {
                let item_uri_type = self.item_uri_type.as_ref().ok_or(Error::MissingContent(
                    "item_uri_type required with 'uri ' item_type",
                ))?;
                item_uri_type.as_str().encode(buf)?;
            }
        }
        Ok(ItemInfoEntryExt {
            version,
            item_not_in_presentation: self.item_not_in_presentation,
        })
    }

    /// Decodes the item info entry body for the parsed version/flags extension.
    fn decode_body_ext<B: Buf>(buf: &mut B, ext: Self::Ext) -> Result<Self> {
        let item_id: u32;
        let item_protection_index;
        let mut item_type = None;
        let item_name;
        let mut content_type = None;
        let mut content_encoding = None;
        let mut item_uri_type = None;
        if (ext.version == ItemInfoEntryVersion::V0) || (ext.version == ItemInfoEntryVersion::V1) {
            item_id = u16::decode(buf)? as u32;
            item_protection_index = u16::decode(buf)?;
            item_name = String::decode(buf)?;
            content_type = Some(String::decode(buf)?);
            content_encoding = Some(String::decode(buf)?);
            if ext.version == ItemInfoEntryVersion::V1 {
                return Err(Error::Unsupported("infe version 1 extensions"));
            }
        } else {
            if ext.version == ItemInfoEntryVersion::V2 {
                item_id = u16::decode(buf)? as u32;
            } else {
                item_id = u32::decode(buf)?;
            }
            item_protection_index = u16::decode(buf)?;
            item_type = Some(FourCC::decode(buf)?);
            item_name = String::decode(buf)?;
            if item_type == Some(FourCC::new(b"mime")) {
                content_type = Some(String::decode(buf)?);
                content_encoding = Some(String::decode(buf)?);
            } else if item_type == Some(FourCC::new(b"uri ")) {
                item_uri_type = Some(String::decode(buf)?);
            }
        }
        Ok(ItemInfoEntry {
            item_id,
            item_protection_index,
            item_type,
            item_name,
            content_type,
            content_encoding,
            item_uri_type,
            item_not_in_presentation: ext.item_not_in_presentation,
        })
    }
}

/// Item information box containing every item entry.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Iinf {
    /// Item info entries in file order.
    pub item_infos: Vec<ItemInfoEntry>,
}

impl AtomExt for Iinf {
    type Ext = IinfExt;

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

    /// Decodes an item information box for the parsed version/flags extension.
    fn decode_body_ext<B: Buf>(buf: &mut B, ext: IinfExt) -> Result<Self> {
        let mut item_infos = vec![];
        let entry_count = if ext.version == IinfVersion::V0 {
            u16::decode(buf)? as usize
        } else {
            u32::decode(buf)? as usize
        };
        for _ in 0..entry_count {
            item_infos.push(ItemInfoEntry::decode(buf)?);
        }
        Ok(Iinf { item_infos })
    }

    /// Encodes an item information box and chooses the smallest entry-count version.
    fn encode_body_ext<B: BufMut>(&self, buf: &mut B) -> Result<IinfExt> {
        let version;
        if self.item_infos.len() > u16::MAX as usize {
            version = IinfVersion::V1;
            (self.item_infos.len() as u32).encode(buf)?
        } else {
            version = IinfVersion::V0;
            (self.item_infos.len() as u16).encode(buf)?
        }
        for item_info in &self.item_infos {
            item_info.encode(buf)?;
        }

        Ok(IinfExt { version })
    }
}

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

    const ENCODED_IINF_LIBAVIF_MIME: &[u8] = &[
        0, 0, 0, 65, 105, 105, 110, 102, 0, 0, 0, 0, 0, 1, 0, 0, 0, 51, 105, 110, 102, 101, 2, 0,
        0, 0, 0, 1, 0, 0, 109, 105, 109, 101, 73, 116, 101, 109, 0, 99, 111, 110, 116, 101, 110,
        116, 45, 116, 121, 112, 101, 0, 117, 110, 107, 110, 111, 119, 110, 47, 109, 105, 109, 101,
        0,
    ];

    /// Decodes a libavif-style `mime` item info box.
    #[test]
    fn test_iinf_libavif_decode_mime() {
        let buf: &mut std::io::Cursor<&&[u8]> =
            &mut std::io::Cursor::new(&ENCODED_IINF_LIBAVIF_MIME);

        let iinf: Iinf = Iinf {
            item_infos: vec![ItemInfoEntry {
                item_id: 1,
                item_protection_index: 0,
                item_type: Some(FourCC::new(b"mime")),
                item_name: "Item".to_string(),
                content_type: Some("content-type".to_string()),
                content_encoding: Some("unknown/mime".to_string()),
                item_uri_type: None,
                item_not_in_presentation: false,
            }],
        };
        let decoded = Iinf::decode(buf).unwrap();
        assert_eq!(decoded, iinf);
    }

    /// Encodes a libavif-style `mime` item info box.
    #[test]
    fn test_iinf_avif_encode_mime() {
        let iinf: Iinf = Iinf {
            item_infos: vec![ItemInfoEntry {
                item_id: 1,
                item_protection_index: 0,
                item_type: Some(FourCC::new(b"mime")),
                item_name: "Item".to_string(),
                content_type: Some("content-type".to_string()),
                content_encoding: Some("unknown/mime".to_string()),
                item_uri_type: None,
                item_not_in_presentation: false,
            }],
        };
        let mut buf = Vec::new();
        iinf.encode(&mut buf).unwrap();

        assert_eq!(buf.as_slice(), ENCODED_IINF_LIBAVIF_MIME);
    }

    const ENCODED_IINF_LIBAVIF_URI: &[u8] = &[
        0, 0, 0, 50, 105, 105, 110, 102, 0, 0, 0, 0, 0, 1, 0, 0, 0, 36, 105, 110, 102, 101, 2, 0,
        0, 0, 0, 1, 0, 0, 117, 114, 105, 32, 73, 116, 101, 109, 0, 117, 114, 105, 58, 47, 47, 116,
        101, 115, 116, 0,
    ];

    const ENCODED_IINF_LIBAVIF_URI_V3: &[u8] = &[
        0, 0, 0, 67, b'i', b'i', b'n', b'f', 0, 0, 0, 0, 0, 1, 0, 0, 0, 53, b'i', b'n', b'f', b'e',
        3, 0, 0, 0, 0, 1, 0, 0, 0, 0, b'm', b'i', b'm', b'e', b'I', b't', b'e', b'm', 0, b'c',
        b'o', b'n', b't', b'e', b'n', b't', b'-', b't', b'y', b'p', b'e', 0, b'u', b'n', b'k',
        b'n', b'o', b'w', b'n', b'/', b'm', b'i', b'm', b'e', 0,
    ];

    /// Decodes an item info box version 3 entry.
    #[test]
    fn test_iinf_libavif_decode_mime_v3() {
        let buf: &mut std::io::Cursor<&&[u8]> =
            &mut std::io::Cursor::new(&ENCODED_IINF_LIBAVIF_URI_V3);

        let iinf: Iinf = Iinf {
            item_infos: vec![ItemInfoEntry {
                item_id: 65536,
                item_protection_index: 0,
                item_type: Some(FourCC::new(b"mime")),
                item_name: "Item".to_string(),
                content_type: Some("content-type".to_string()),
                content_encoding: Some("unknown/mime".to_string()),
                item_uri_type: None,
                item_not_in_presentation: false,
            }],
        };
        let decoded = Iinf::decode(buf).unwrap();
        assert_eq!(decoded, iinf);
    }

    /// Encodes a item info box version 3 entry.
    #[test]
    fn test_iinf_avif_encode_mime_v3() {
        let iinf: Iinf = Iinf {
            item_infos: vec![ItemInfoEntry {
                item_id: 65536,
                item_protection_index: 0,
                item_type: Some(FourCC::new(b"mime")),
                item_name: "Item".to_string(),
                content_type: Some("content-type".to_string()),
                content_encoding: Some("unknown/mime".to_string()),
                item_uri_type: None,
                item_not_in_presentation: false,
            }],
        };
        let mut buf = Vec::new();
        iinf.encode(&mut buf).unwrap();

        assert_eq!(buf.as_slice(), ENCODED_IINF_LIBAVIF_URI_V3);
    }

    /// Decodes a libavif-style `uri ` item info box.
    #[test]
    fn test_iinf_libavif_decode_uri() {
        let buf: &mut std::io::Cursor<&&[u8]> =
            &mut std::io::Cursor::new(&ENCODED_IINF_LIBAVIF_URI);

        let iinf: Iinf = Iinf {
            item_infos: vec![ItemInfoEntry {
                item_id: 1,
                item_protection_index: 0,
                item_type: Some(FourCC::new(b"uri ")),
                item_name: "Item".to_string(),
                content_type: None,
                content_encoding: None,
                item_uri_type: Some("uri://test".to_string()),
                item_not_in_presentation: false,
            }],
        };
        let decoded = Iinf::decode(buf).unwrap();
        assert_eq!(decoded, iinf);
    }

    /// Encodes a libavif-style `uri ` item info box.
    #[test]
    fn test_iinf_avif_encode_uri() {
        let iinf: Iinf = Iinf {
            item_infos: vec![ItemInfoEntry {
                item_id: 1,
                item_protection_index: 0,
                item_type: Some(FourCC::new(b"uri ")),
                item_name: "Item".to_string(),
                content_type: None,
                content_encoding: None,
                item_uri_type: Some("uri://test".to_string()),
                item_not_in_presentation: false,
            }],
        };
        let mut buf = Vec::new();
        iinf.encode(&mut buf).unwrap();

        assert_eq!(buf.as_slice(), ENCODED_IINF_LIBAVIF_URI);
    }

    /// Rejects a `uri ` item info box when the URI payload is missing.
    #[test]
    fn test_iinf_avif_encode_uri_invalid() {
        let iinf: Iinf = Iinf {
            item_infos: vec![ItemInfoEntry {
                item_id: 1,
                item_protection_index: 0,
                item_type: Some(FourCC::new(b"uri ")),
                item_name: "Item".to_string(),
                content_type: None,
                content_encoding: None,
                item_uri_type: None, // encode will return an error because this is empty
                item_not_in_presentation: false,
            }],
        };
        let mut buf = Vec::new();
        assert!(matches!(
            iinf.encode(&mut buf),
            Err(Error::MissingContent(_))
        ));
    }

    /// Rejects a version 0 item info entry when its required content type is missing.
    #[test]
    fn test_iinf_encode_v0_without_content_type_returns_error() {
        let iinf = Iinf {
            item_infos: vec![ItemInfoEntry {
                item_id: 1,
                item_protection_index: 0,
                item_type: None,
                item_name: "Item".to_string(),
                content_type: None,
                content_encoding: None,
                item_uri_type: None,
                item_not_in_presentation: false,
            }],
        };
        let mut buf = Vec::new();

        assert!(matches!(
            iinf.encode(&mut buf),
            Err(Error::MissingContent(_))
        ));
    }

    /// Rejects a `mime` item info entry when its required content type is missing.
    #[test]
    fn test_iinf_encode_mime_without_content_type_returns_error() {
        let iinf = Iinf {
            item_infos: vec![ItemInfoEntry {
                item_id: 1,
                item_protection_index: 0,
                item_type: Some(FourCC::new(b"mime")),
                item_name: "Item".to_string(),
                content_type: None,
                content_encoding: None,
                item_uri_type: None,
                item_not_in_presentation: false,
            }],
        };
        let mut buf = Vec::new();

        assert!(matches!(
            iinf.encode(&mut buf),
            Err(Error::MissingContent(_))
        ));
    }

    /// Version 1 `infe` entries are reported as unsupported, not panicked.
    #[test]
    fn test_iinf_decode_unsupported_infe_v1_returns_error() {
        let body: &[u8] = &[
            // iinf version/flags and one entry
            0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // infe atom header
            0x00, 0x00, 0x00, 0x13, b'i', b'n', b'f', b'e', // infe version 1, no flags
            0x01, 0x00, 0x00, 0x00,
            // item_id, item_protection_index, item_name, content_type,
            // content_encoding
            0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        let result = Iinf::decode_body(&mut std::io::Cursor::new(body));

        assert!(matches!(
            result,
            Err(Error::Unsupported("infe version 1 extensions"))
        ));

        let fuzz_body: &[u8] = &[
            0x00, 0x00, 0x00, 0x00, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x80,
            0x01, 0x00, 0x00, 0x04, 0x00, b'p', b'y', b't', b'f',
        ];
        let fuzz_result = Iinf::decode_body(&mut std::io::Cursor::new(fuzz_body));

        assert!(matches!(
            fuzz_result,
            Err(Error::UnexpectedBox(kind)) if kind == FourCC::new(b"\0\0A\x80")
        ));
    }
}