zvidlib-container 0.5.25

MP4 and WebM muxing and demuxing for zvidlib
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
//! Portable derivation of WebCodecs codec strings and [`CodecProfile`] values
//! from raw MP4 `avcC`/`hvcC`/`av1C`/`vpcC` codec configuration boxes and for VP8,
//! which has none, and the VP9 codec configuration record
//! ([`Vp9CodecConfig`]).
//!
//! This module contains no browser (`web_sys`) types so it can be unit
//! tested natively. It is consumed by the browser WebCodecs decoder factory
//! to build the `codec` string WebCodecs' `isConfigSupported`/`VideoDecoder`
//! APIs require, and to select a normalized [`CodecProfile`].

use crate::codec::CodecProfile;
use crate::media::Codec;
use crate::{Av1CodecConfigurationRecord, Error, ErrorKind, Limits, Result};
#[doc(inline)]
pub use zvidlib_core::AvcConfigurationRecord;
#[doc(inline)]
pub use zvidlib_core::codec_config::Vp9CodecConfig;
use zvidlib_core::codec_config::box_payload;

/// A codec string plus the normalized profile it was derived from.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DerivedCodecString {
    pub codec_string: String,
    pub profile: CodecProfile,
}

/// Derives a WebCodecs `codec` string and [`CodecProfile`] from a track's
/// complete raw codec configuration box (including its size/fourcc header):
/// `avcC`, `hvcC`, `av1C` or Opus's `dOps`. Vorbis has no MP4 box, so its
/// configuration is the Xiph-laced `CodecPrivate` [`crate::VorbisConfig`]
/// reads.
pub fn derive_codec_string(codec: Codec, decoder_config: &[u8]) -> Result<DerivedCodecString> {
    match codec {
        Codec::Hevc => derive_hevc(decoder_config),
        // `avc1.PPCCLL` from the `avcC` record; only the profiles a decoder
        // here can output are given a profile, so a High 10 or 4:4:4 track
        // is refused here rather than on its first frame.
        Codec::H264 => {
            let record = zvidlib_core::AvcConfigurationRecord::parse(decoder_config)?;
            let profile = record.codec_profile()?;
            if !record.is_8bit_420() {
                return Err(Error::new(
                    ErrorKind::Unsupported,
                    "H.264 decoding supports 8-bit 4:2:0 streams only",
                ));
            }
            Ok(DerivedCodecString {
                codec_string: record.codec_string(),
                profile,
            })
        }
        Codec::Av1 => derive_av1(decoder_config),
        // VP8 has one profile and no configuration record, so its WebCodecs
        // string is the bare codec name.
        Codec::Vp8 => Ok(DerivedCodecString {
            codec_string: "vp8".to_owned(),
            profile: CodecProfile::Vp8,
        }),
        // Opus and Vorbis each have a single codec string; the configuration
        // is still checked so a track the browser is handed is one zvidlib
        // could also decode itself.
        Codec::Opus => {
            crate::OpusHead::from_dops(decoder_config)?;
            Ok(DerivedCodecString {
                codec_string: "opus".into(),
                profile: CodecProfile::Opus,
            })
        }
        Codec::Vorbis => {
            crate::VorbisConfig::from_codec_private(decoder_config)?;
            Ok(DerivedCodecString {
                codec_string: "vorbis".into(),
                profile: CodecProfile::Vorbis,
            })
        }
        Codec::Vp9 => {
            let config = Vp9CodecConfig::parse(decoder_config)?;
            Ok(DerivedCodecString {
                codec_string: config.codec_string(),
                profile: config.codec_profile()?,
            })
        }
        Codec::UncompressedVideo | Codec::Aac => Err(Error::new(
            ErrorKind::Unsupported,
            "codec string derivation only supports H.264, HEVC, AV1, VP8, VP9, Opus and Vorbis",
        )),
        _ => Err(Error::new(
            ErrorKind::Unsupported,
            "codec string derivation only supports H.264, HEVC, AV1, VP8, VP9, Opus and Vorbis",
        )),
    }
}

// --- HEVC (hvcC) -----------------------------------------------------------
//
// ISO/IEC 14496-15 HEVCDecoderConfigurationRecord layout (relevant prefix):
// unsigned int(8) configurationVersion;
// unsigned int(2) general_profile_space;
// unsigned int(1) general_tier_flag;
// unsigned int(5) general_profile_idc;
// unsigned int(32) general_profile_compatibility_flags;
// unsigned int(48) general_constraint_indicator_flags;
// unsigned int(8) general_level_idc;

fn derive_hevc(decoder_config: &[u8]) -> Result<DerivedCodecString> {
    let payload = box_payload(decoder_config, b"hvcC")?;
    if payload.len() < 13 {
        return Err(Error::new(
            ErrorKind::MalformedMedia,
            "hvcC configuration is too short",
        ));
    }
    let profile_space = (payload[1] >> 6) & 0b11;
    let tier_flag = (payload[1] >> 5) & 0b1;
    let profile_idc = payload[1] & 0b0001_1111;
    let compatibility_flags = u32::from_be_bytes(payload[2..6].try_into().expect("4 bytes"));
    let constraint_flags = &payload[6..12];
    let level_idc = payload[12];

    // General profile/tier/level string per ISO/IEC 14496-15 Annex E and the
    // WebCodecs HEVC registration ("hev1"/"hvc1" fourcc followed by a dot,
    // then the general_profile_space letter (if any) plus profile_idc, tier
    // ('L' or 'H'), level_idc, then '.' plus each constraint byte in hex,
    // trailing zero bytes omitted).
    let profile_space_letter = match profile_space {
        0 => String::new(),
        1 => "A".to_owned(),
        2 => "B".to_owned(),
        3 => "C".to_owned(),
        _ => unreachable!("profile_space is masked to 2 bits"),
    };
    let tier_letter = if tier_flag == 1 { 'H' } else { 'L' };

    let mut constraint_hex = String::new();
    let mut last_nonzero = None;
    for (index, byte) in constraint_flags.iter().enumerate() {
        if *byte != 0 {
            last_nonzero = Some(index);
        }
    }
    if let Some(last) = last_nonzero {
        for byte in &constraint_flags[..=last] {
            constraint_hex.push('.');
            constraint_hex.push_str(&format!("{byte:02X}"));
        }
    }

    let codec_string = format!(
        "hev1.{profile_space_letter}{profile_idc}.{compatibility_flags:X}.{tier_letter}{level_idc}{constraint_hex}"
    );

    let profile = match profile_idc {
        2 => CodecProfile::HevcMain10,
        _ => CodecProfile::HevcMain,
    };

    Ok(DerivedCodecString {
        codec_string,
        profile,
    })
}

// --- AV1 (av1C) --------------------------------------------------------
//
// AV1 Codec ISO Media File Format Binding, AV1CodecConfigurationRecord:
// unsigned int (1) marker = 1;
// unsigned int (7) version = 1;
// unsigned int (3) seq_profile;
// unsigned int (5) seq_level_idx_0;
// unsigned int (1) seq_tier_0;
// unsigned int (1) high_bitdepth;
// unsigned int (1) twelve_bit;
// unsigned int (1) monochrome;
// unsigned int (1) chroma_subsampling_x;
// unsigned int (1) chroma_subsampling_y;
// unsigned int (2) chroma_sample_position;
// ...

fn derive_av1(decoder_config: &[u8]) -> Result<DerivedCodecString> {
    let record = Av1CodecConfigurationRecord::parse(decoder_config, &Limits::default())?;
    let seq_profile = record.seq_profile;
    let seq_level_idx_0 = record.seq_level_idx_0;

    let bit_depth: u32 = if record.high_bitdepth {
        if seq_profile == 2 && record.twelve_bit {
            12
        } else {
            10
        }
    } else {
        8
    };

    let tier_letter = if record.seq_tier_0 { 'H' } else { 'M' };
    let mono = u8::from(record.monochrome);
    let chroma_subsampling_x = u8::from(record.chroma_subsampling_x);
    let chroma_subsampling_y = u8::from(record.chroma_subsampling_y);
    let chroma_sample_position = record.chroma_sample_position;
    let codec_string = format!(
        "av01.{seq_profile}.{seq_level_idx_0:02}{tier_letter}.{bit_depth:02}.{mono}.{chroma_subsampling_x}{chroma_subsampling_y}{chroma_sample_position}"
    );

    Ok(DerivedCodecString {
        codec_string,
        profile: match seq_profile {
            0 => CodecProfile::Av1Main,
            1 => CodecProfile::Av1High,
            2 => CodecProfile::Av1Professional,
            _ => unreachable!("validated AV1 profile"),
        },
    })
}

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

    fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
        let mut bytes = (8 + payload.len() as u32).to_be_bytes().to_vec();
        bytes.extend_from_slice(kind);
        bytes.extend_from_slice(payload);
        bytes
    }

    #[test]
    fn derives_hevc_main_profile_codec_string() {
        // configurationVersion=1, profile_space=0, tier=0, profile_idc=1 (Main)
        let mut payload = vec![1_u8, 0b0000_0001];
        payload.extend_from_slice(&0x6000_0000_u32.to_be_bytes()); // compatibility flags
        payload.extend_from_slice(&[0, 0, 0, 0, 0, 0]); // constraint flags (all zero)
        payload.push(93); // general_level_idc
        payload.extend_from_slice(&[0; 12]); // remaining fixed fields (not parsed)
        let hvcc = boxed(b"hvcC", &payload);

        let derived = derive_codec_string(Codec::Hevc, &hvcc).unwrap();
        assert_eq!(derived.codec_string, "hev1.1.60000000.L93");
        assert_eq!(derived.profile, CodecProfile::HevcMain);
    }

    #[test]
    fn derives_hevc_main10_profile_from_profile_idc_two() {
        let mut payload = vec![1_u8, 0b0000_0010];
        payload.extend_from_slice(&0x6000_0000_u32.to_be_bytes());
        payload.extend_from_slice(&[0xB0, 0, 0, 0, 0, 0]);
        payload.push(120);
        payload.extend_from_slice(&[0; 12]);
        let hvcc = boxed(b"hvcC", &payload);

        let derived = derive_codec_string(Codec::Hevc, &hvcc).unwrap();
        assert_eq!(derived.profile, CodecProfile::HevcMain10);
        assert_eq!(derived.codec_string, "hev1.2.60000000.L120.B0");
    }

    #[test]
    fn derives_av1_main_profile_codec_string() {
        // marker=1, version=1, seq_profile=0, seq_level_idx_0=4 (matching the
        // repo's existing av1C test fixture bytes: [0x81, 0, 0, 0]).
        let av1c = boxed(b"av1C", &[0x81, 0x04, 0, 0]);
        let derived = derive_codec_string(Codec::Av1, &av1c).unwrap();
        assert_eq!(derived.profile, CodecProfile::Av1Main);
        assert_eq!(derived.codec_string, "av01.0.04M.08.0.000");
    }

    #[test]
    fn av1_codec_string_carries_every_chroma_sample_position() {
        // 4:2:0 color with each `chroma_sample_position`; the value is the last
        // digit of the `av01.` string.
        for pos in 0..4u8 {
            let av1c = boxed(b"av1C", &[0x81, 0x04, 0x0c | pos, 0]);
            let derived = derive_codec_string(Codec::Av1, &av1c).unwrap();
            assert_eq!(derived.profile, CodecProfile::Av1Main);
            assert_eq!(derived.codec_string, format!("av01.0.04M.08.0.11{pos}"));
        }
    }

    #[test]
    fn distinguishes_av1_high_and_professional_profiles() {
        let high = boxed(b"av1C", &[0x81, 0x24, 0, 0]);
        assert_eq!(
            derive_codec_string(Codec::Av1, &high).unwrap().profile,
            CodecProfile::Av1High
        );
        let professional = boxed(b"av1C", &[0x81, 0x44, 0x68, 0]);
        assert_eq!(
            derive_codec_string(Codec::Av1, &professional)
                .unwrap()
                .profile,
            CodecProfile::Av1Professional
        );
    }

    #[test]
    fn rejects_wrong_fourcc() {
        let bogus = boxed(b"esds", &[0, 0, 0, 0]);
        let error = derive_codec_string(Codec::Hevc, &bogus).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
    }

    #[test]
    fn rejects_truncated_configuration() {
        let short = boxed(b"hvcC", &[1, 2]);
        let error = derive_codec_string(Codec::Hevc, &short).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::MalformedMedia);

        let short_av1 = boxed(b"av1C", &[1]);
        let error = derive_codec_string(Codec::Av1, &short_av1).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
    }

    #[test]
    fn derives_the_vp8_codec_string_without_a_configuration_record() {
        let derived = derive_codec_string(Codec::Vp8, &[]).unwrap();
        assert_eq!(derived.codec_string, "vp8");
        assert_eq!(derived.profile, CodecProfile::Vp8);
    }

    /// An `avcC` box for `profile` whose SPS carries `sps_tail` after the
    /// profile, flags and level bytes.
    fn avcc(profile: u8, sps_tail: &[u8]) -> Vec<u8> {
        let mut sps = vec![0x67, profile, 0x00, 0x1f];
        sps.extend_from_slice(sps_tail);
        let pps = [0x68, 0xeb, 0xe3, 0xcb, 0x22, 0xc0];
        let mut record = vec![1, profile, 0x00, 0x1f, 0xff, 0xe1];
        record.extend_from_slice(&(sps.len() as u16).to_be_bytes());
        record.extend_from_slice(&sps);
        record.push(1);
        record.extend_from_slice(&(pps.len() as u16).to_be_bytes());
        record.extend_from_slice(&pps);
        boxed(b"avcC", &record)
    }

    #[test]
    fn derives_the_h264_codec_string_and_profile_from_avcc() {
        // High: seq_parameter_set_id 0, chroma_format_idc 1, 8-bit luma and
        // chroma (`1 010 1 1`), then the rest of the SPS.
        let high = avcc(100, &[0xac, 0xd9, 0x40, 0x50]);
        let derived = derive_codec_string(Codec::H264, &high).unwrap();
        assert_eq!(derived.codec_string, "avc1.64001F");
        assert_eq!(derived.profile, CodecProfile::H264High);

        // Main and Baseline carry no chroma format or bit depth.
        let main = avcc(77, &[0x80]);
        let derived = derive_codec_string(Codec::H264, &main).unwrap();
        assert_eq!(derived.codec_string, "avc1.4D001F");
        assert_eq!(derived.profile, CodecProfile::H264Main);
        let derived = derive_codec_string(Codec::H264, &avcc(66, &[0x80])).unwrap();
        assert_eq!(derived.profile, CodecProfile::H264Baseline);

        // `1 011 1 1`: seq_parameter_set_id 0, chroma_format_idc 2 (4:2:2),
        // 8-bit luma and chroma. The High 4:2:2 profile is refused for its
        // profile, and a High-profile SPS with 4:2:2 chroma for its format.
        let error = derive_codec_string(Codec::H264, &avcc(122, &[0xbe])).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Unsupported);
        let error = derive_codec_string(Codec::H264, &avcc(100, &[0xbe])).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Unsupported);

        let error = derive_codec_string(Codec::H264, &boxed(b"avcC", &[1])).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
    }

    #[test]
    fn rejects_unsupported_codecs() {
        let error = derive_codec_string(Codec::Aac, &boxed(b"esds", &[0; 4])).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Unsupported);
        let error =
            derive_codec_string(Codec::UncompressedVideo, &boxed(b"hvcC", &[0; 13])).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Unsupported);
    }

    fn vpcc(version: u8, record: &[u8]) -> Vec<u8> {
        let mut payload = vec![version, 0, 0, 0];
        payload.extend_from_slice(record);
        boxed(b"vpcC", &payload)
    }

    #[test]
    fn reads_a_version_1_vpcc_box_and_derives_its_codec_string() {
        // Profile 0, level 3.1, 8-bit, colocated 4:2:0, limited range,
        // BT.709 color description, no initialization data.
        let bytes = vpcc(1, &[0, 31, 0x82, 1, 1, 1, 0, 0]);
        let config = Vp9CodecConfig::parse(&bytes).unwrap();
        assert_eq!(
            config,
            Vp9CodecConfig {
                profile: 0,
                level: 31,
                bit_depth: 8,
                chroma_subsampling: 1,
                video_full_range: false,
                color_primaries: 1,
                transfer_characteristics: 1,
                matrix_coefficients: 1,
            }
        );
        assert!(config.is_420());
        let derived = derive_codec_string(Codec::Vp9, &bytes).unwrap();
        assert_eq!(derived.codec_string, "vp09.00.31.08");
        assert_eq!(derived.profile, CodecProfile::Vp9Profile0);

        let ten_bit = vpcc(1, &[2, 0, 0xa1, 9, 16, 9, 0, 0]);
        let config = Vp9CodecConfig::parse(&ten_bit).unwrap();
        assert!(config.video_full_range);
        assert_eq!(config.codec_profile().unwrap(), CodecProfile::Vp9Profile2);
        // Level 0 is unspecified, which the codec string cannot say.
        assert_eq!(config.codec_string(), "vp09.02.10.10");
    }

    #[test]
    fn reads_a_version_0_vpcc_box() {
        let bytes = vpcc(0, &[1, 20, 0x80, 0x30, 0x80, 0, 0]);
        let config = Vp9CodecConfig::parse(&bytes).unwrap();
        assert_eq!(config.profile, 1);
        assert_eq!(config.level, 20);
        assert_eq!(config.bit_depth, 8);
        assert_eq!(config.chroma_subsampling, 3);
        assert!(config.video_full_range);
    }

    #[test]
    fn reads_webm_codec_private_features() {
        assert_eq!(
            Vp9CodecConfig::parse(&[]).unwrap(),
            Vp9CodecConfig::default()
        );
        let config = Vp9CodecConfig::parse(&[1, 1, 0, 2, 1, 40, 3, 1, 8, 4, 1, 1]).unwrap();
        assert_eq!((config.profile, config.level, config.bit_depth), (0, 40, 8));
        assert_eq!(config.chroma_subsampling, 1);
        // Unknown features are skipped.
        assert_eq!(
            Vp9CodecConfig::parse(&[9, 2, 7, 7, 1, 1, 2])
                .unwrap()
                .profile,
            2
        );
    }

    #[test]
    fn rejects_malformed_vp9_configurations() {
        for bytes in [
            vec![1, 1],
            vec![1, 2, 0, 0],
            vec![3, 1, 9],
            vpcc(1, &[0, 10]),
            vpcc(2, &[0, 10, 0x80, 1, 1, 1, 0, 0]),
            vpcc(1, &[4, 10, 0x80, 1, 1, 1, 0, 0]),
            vpcc(1, &[0, 10, 0x90, 1, 1, 1, 0, 0]),
        ] {
            let error = Vp9CodecConfig::parse(&bytes).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::MalformedMedia, "{bytes:?}");
        }
        let config = Vp9CodecConfig::parse(&[1, 1, 0, 2, 1, 41, 4, 1, 1]).unwrap();
        assert_eq!(Vp9CodecConfig::parse(&config.to_vpcc()).unwrap(), config);
        let mut inconsistent = vpcc(1, &[0, 10, 0x80, 1, 1, 1, 0, 0]);
        inconsistent[3] += 1;
        assert!(Vp9CodecConfig::parse(&inconsistent).is_err());
    }
}