Skip to main content

zvidlib_container/
codec_config.rs

1//! Portable derivation of WebCodecs codec strings and [`CodecProfile`] values
2//! from raw MP4 `avcC`/`hvcC`/`av1C`/`vpcC` codec configuration boxes and for VP8,
3//! which has none, and the VP9 codec configuration record
4//! ([`Vp9CodecConfig`]).
5//!
6//! This module contains no browser (`web_sys`) types so it can be unit
7//! tested natively. It is consumed by the browser WebCodecs decoder factory
8//! to build the `codec` string WebCodecs' `isConfigSupported`/`VideoDecoder`
9//! APIs require, and to select a normalized [`CodecProfile`].
10
11use crate::codec::CodecProfile;
12use crate::media::Codec;
13use crate::{Av1CodecConfigurationRecord, Error, ErrorKind, Limits, Result};
14#[doc(inline)]
15pub use zvidlib_core::AvcConfigurationRecord;
16#[doc(inline)]
17pub use zvidlib_core::codec_config::Vp9CodecConfig;
18use zvidlib_core::codec_config::box_payload;
19
20/// A codec string plus the normalized profile it was derived from.
21#[derive(Clone, Debug, Eq, PartialEq)]
22pub struct DerivedCodecString {
23    pub codec_string: String,
24    pub profile: CodecProfile,
25}
26
27/// Derives a WebCodecs `codec` string and [`CodecProfile`] from a track's
28/// complete raw codec configuration box (including its size/fourcc header):
29/// `avcC`, `hvcC`, `av1C` or Opus's `dOps`. Vorbis has no MP4 box, so its
30/// configuration is the Xiph-laced `CodecPrivate` [`crate::VorbisConfig`]
31/// reads.
32pub fn derive_codec_string(codec: Codec, decoder_config: &[u8]) -> Result<DerivedCodecString> {
33    match codec {
34        Codec::Hevc => derive_hevc(decoder_config),
35        // `avc1.PPCCLL` from the `avcC` record; only the profiles a decoder
36        // here can output are given a profile, so a High 10 or 4:4:4 track
37        // is refused here rather than on its first frame.
38        Codec::H264 => {
39            let record = zvidlib_core::AvcConfigurationRecord::parse(decoder_config)?;
40            let profile = record.codec_profile()?;
41            if !record.is_8bit_420() {
42                return Err(Error::new(
43                    ErrorKind::Unsupported,
44                    "H.264 decoding supports 8-bit 4:2:0 streams only",
45                ));
46            }
47            Ok(DerivedCodecString {
48                codec_string: record.codec_string(),
49                profile,
50            })
51        }
52        Codec::Av1 => derive_av1(decoder_config),
53        // VP8 has one profile and no configuration record, so its WebCodecs
54        // string is the bare codec name.
55        Codec::Vp8 => Ok(DerivedCodecString {
56            codec_string: "vp8".to_owned(),
57            profile: CodecProfile::Vp8,
58        }),
59        // Opus and Vorbis each have a single codec string; the configuration
60        // is still checked so a track the browser is handed is one zvidlib
61        // could also decode itself.
62        Codec::Opus => {
63            crate::OpusHead::from_dops(decoder_config)?;
64            Ok(DerivedCodecString {
65                codec_string: "opus".into(),
66                profile: CodecProfile::Opus,
67            })
68        }
69        Codec::Vorbis => {
70            crate::VorbisConfig::from_codec_private(decoder_config)?;
71            Ok(DerivedCodecString {
72                codec_string: "vorbis".into(),
73                profile: CodecProfile::Vorbis,
74            })
75        }
76        Codec::Vp9 => {
77            let config = Vp9CodecConfig::parse(decoder_config)?;
78            Ok(DerivedCodecString {
79                codec_string: config.codec_string(),
80                profile: config.codec_profile()?,
81            })
82        }
83        Codec::UncompressedVideo | Codec::Aac => Err(Error::new(
84            ErrorKind::Unsupported,
85            "codec string derivation only supports H.264, HEVC, AV1, VP8, VP9, Opus and Vorbis",
86        )),
87        _ => Err(Error::new(
88            ErrorKind::Unsupported,
89            "codec string derivation only supports H.264, HEVC, AV1, VP8, VP9, Opus and Vorbis",
90        )),
91    }
92}
93
94// --- HEVC (hvcC) -----------------------------------------------------------
95//
96// ISO/IEC 14496-15 HEVCDecoderConfigurationRecord layout (relevant prefix):
97// unsigned int(8) configurationVersion;
98// unsigned int(2) general_profile_space;
99// unsigned int(1) general_tier_flag;
100// unsigned int(5) general_profile_idc;
101// unsigned int(32) general_profile_compatibility_flags;
102// unsigned int(48) general_constraint_indicator_flags;
103// unsigned int(8) general_level_idc;
104
105fn derive_hevc(decoder_config: &[u8]) -> Result<DerivedCodecString> {
106    let payload = box_payload(decoder_config, b"hvcC")?;
107    if payload.len() < 13 {
108        return Err(Error::new(
109            ErrorKind::MalformedMedia,
110            "hvcC configuration is too short",
111        ));
112    }
113    let profile_space = (payload[1] >> 6) & 0b11;
114    let tier_flag = (payload[1] >> 5) & 0b1;
115    let profile_idc = payload[1] & 0b0001_1111;
116    let compatibility_flags = u32::from_be_bytes(payload[2..6].try_into().expect("4 bytes"));
117    let constraint_flags = &payload[6..12];
118    let level_idc = payload[12];
119
120    // General profile/tier/level string per ISO/IEC 14496-15 Annex E and the
121    // WebCodecs HEVC registration ("hev1"/"hvc1" fourcc followed by a dot,
122    // then the general_profile_space letter (if any) plus profile_idc, tier
123    // ('L' or 'H'), level_idc, then '.' plus each constraint byte in hex,
124    // trailing zero bytes omitted).
125    let profile_space_letter = match profile_space {
126        0 => String::new(),
127        1 => "A".to_owned(),
128        2 => "B".to_owned(),
129        3 => "C".to_owned(),
130        _ => unreachable!("profile_space is masked to 2 bits"),
131    };
132    let tier_letter = if tier_flag == 1 { 'H' } else { 'L' };
133
134    let mut constraint_hex = String::new();
135    let mut last_nonzero = None;
136    for (index, byte) in constraint_flags.iter().enumerate() {
137        if *byte != 0 {
138            last_nonzero = Some(index);
139        }
140    }
141    if let Some(last) = last_nonzero {
142        for byte in &constraint_flags[..=last] {
143            constraint_hex.push('.');
144            constraint_hex.push_str(&format!("{byte:02X}"));
145        }
146    }
147
148    let codec_string = format!(
149        "hev1.{profile_space_letter}{profile_idc}.{compatibility_flags:X}.{tier_letter}{level_idc}{constraint_hex}"
150    );
151
152    let profile = match profile_idc {
153        2 => CodecProfile::HevcMain10,
154        _ => CodecProfile::HevcMain,
155    };
156
157    Ok(DerivedCodecString {
158        codec_string,
159        profile,
160    })
161}
162
163// --- AV1 (av1C) --------------------------------------------------------
164//
165// AV1 Codec ISO Media File Format Binding, AV1CodecConfigurationRecord:
166// unsigned int (1) marker = 1;
167// unsigned int (7) version = 1;
168// unsigned int (3) seq_profile;
169// unsigned int (5) seq_level_idx_0;
170// unsigned int (1) seq_tier_0;
171// unsigned int (1) high_bitdepth;
172// unsigned int (1) twelve_bit;
173// unsigned int (1) monochrome;
174// unsigned int (1) chroma_subsampling_x;
175// unsigned int (1) chroma_subsampling_y;
176// unsigned int (2) chroma_sample_position;
177// ...
178
179fn derive_av1(decoder_config: &[u8]) -> Result<DerivedCodecString> {
180    let record = Av1CodecConfigurationRecord::parse(decoder_config, &Limits::default())?;
181    let seq_profile = record.seq_profile;
182    let seq_level_idx_0 = record.seq_level_idx_0;
183
184    let bit_depth: u32 = if record.high_bitdepth {
185        if seq_profile == 2 && record.twelve_bit {
186            12
187        } else {
188            10
189        }
190    } else {
191        8
192    };
193
194    let tier_letter = if record.seq_tier_0 { 'H' } else { 'M' };
195    let mono = u8::from(record.monochrome);
196    let chroma_subsampling_x = u8::from(record.chroma_subsampling_x);
197    let chroma_subsampling_y = u8::from(record.chroma_subsampling_y);
198    let chroma_sample_position = record.chroma_sample_position;
199    let codec_string = format!(
200        "av01.{seq_profile}.{seq_level_idx_0:02}{tier_letter}.{bit_depth:02}.{mono}.{chroma_subsampling_x}{chroma_subsampling_y}{chroma_sample_position}"
201    );
202
203    Ok(DerivedCodecString {
204        codec_string,
205        profile: match seq_profile {
206            0 => CodecProfile::Av1Main,
207            1 => CodecProfile::Av1High,
208            2 => CodecProfile::Av1Professional,
209            _ => unreachable!("validated AV1 profile"),
210        },
211    })
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    fn boxed(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
219        let mut bytes = (8 + payload.len() as u32).to_be_bytes().to_vec();
220        bytes.extend_from_slice(kind);
221        bytes.extend_from_slice(payload);
222        bytes
223    }
224
225    #[test]
226    fn derives_hevc_main_profile_codec_string() {
227        // configurationVersion=1, profile_space=0, tier=0, profile_idc=1 (Main)
228        let mut payload = vec![1_u8, 0b0000_0001];
229        payload.extend_from_slice(&0x6000_0000_u32.to_be_bytes()); // compatibility flags
230        payload.extend_from_slice(&[0, 0, 0, 0, 0, 0]); // constraint flags (all zero)
231        payload.push(93); // general_level_idc
232        payload.extend_from_slice(&[0; 12]); // remaining fixed fields (not parsed)
233        let hvcc = boxed(b"hvcC", &payload);
234
235        let derived = derive_codec_string(Codec::Hevc, &hvcc).unwrap();
236        assert_eq!(derived.codec_string, "hev1.1.60000000.L93");
237        assert_eq!(derived.profile, CodecProfile::HevcMain);
238    }
239
240    #[test]
241    fn derives_hevc_main10_profile_from_profile_idc_two() {
242        let mut payload = vec![1_u8, 0b0000_0010];
243        payload.extend_from_slice(&0x6000_0000_u32.to_be_bytes());
244        payload.extend_from_slice(&[0xB0, 0, 0, 0, 0, 0]);
245        payload.push(120);
246        payload.extend_from_slice(&[0; 12]);
247        let hvcc = boxed(b"hvcC", &payload);
248
249        let derived = derive_codec_string(Codec::Hevc, &hvcc).unwrap();
250        assert_eq!(derived.profile, CodecProfile::HevcMain10);
251        assert_eq!(derived.codec_string, "hev1.2.60000000.L120.B0");
252    }
253
254    #[test]
255    fn derives_av1_main_profile_codec_string() {
256        // marker=1, version=1, seq_profile=0, seq_level_idx_0=4 (matching the
257        // repo's existing av1C test fixture bytes: [0x81, 0, 0, 0]).
258        let av1c = boxed(b"av1C", &[0x81, 0x04, 0, 0]);
259        let derived = derive_codec_string(Codec::Av1, &av1c).unwrap();
260        assert_eq!(derived.profile, CodecProfile::Av1Main);
261        assert_eq!(derived.codec_string, "av01.0.04M.08.0.000");
262    }
263
264    #[test]
265    fn av1_codec_string_carries_every_chroma_sample_position() {
266        // 4:2:0 color with each `chroma_sample_position`; the value is the last
267        // digit of the `av01.` string.
268        for pos in 0..4u8 {
269            let av1c = boxed(b"av1C", &[0x81, 0x04, 0x0c | pos, 0]);
270            let derived = derive_codec_string(Codec::Av1, &av1c).unwrap();
271            assert_eq!(derived.profile, CodecProfile::Av1Main);
272            assert_eq!(derived.codec_string, format!("av01.0.04M.08.0.11{pos}"));
273        }
274    }
275
276    #[test]
277    fn distinguishes_av1_high_and_professional_profiles() {
278        let high = boxed(b"av1C", &[0x81, 0x24, 0, 0]);
279        assert_eq!(
280            derive_codec_string(Codec::Av1, &high).unwrap().profile,
281            CodecProfile::Av1High
282        );
283        let professional = boxed(b"av1C", &[0x81, 0x44, 0x68, 0]);
284        assert_eq!(
285            derive_codec_string(Codec::Av1, &professional)
286                .unwrap()
287                .profile,
288            CodecProfile::Av1Professional
289        );
290    }
291
292    #[test]
293    fn rejects_wrong_fourcc() {
294        let bogus = boxed(b"esds", &[0, 0, 0, 0]);
295        let error = derive_codec_string(Codec::Hevc, &bogus).unwrap_err();
296        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
297    }
298
299    #[test]
300    fn rejects_truncated_configuration() {
301        let short = boxed(b"hvcC", &[1, 2]);
302        let error = derive_codec_string(Codec::Hevc, &short).unwrap_err();
303        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
304
305        let short_av1 = boxed(b"av1C", &[1]);
306        let error = derive_codec_string(Codec::Av1, &short_av1).unwrap_err();
307        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
308    }
309
310    #[test]
311    fn derives_the_vp8_codec_string_without_a_configuration_record() {
312        let derived = derive_codec_string(Codec::Vp8, &[]).unwrap();
313        assert_eq!(derived.codec_string, "vp8");
314        assert_eq!(derived.profile, CodecProfile::Vp8);
315    }
316
317    /// An `avcC` box for `profile` whose SPS carries `sps_tail` after the
318    /// profile, flags and level bytes.
319    fn avcc(profile: u8, sps_tail: &[u8]) -> Vec<u8> {
320        let mut sps = vec![0x67, profile, 0x00, 0x1f];
321        sps.extend_from_slice(sps_tail);
322        let pps = [0x68, 0xeb, 0xe3, 0xcb, 0x22, 0xc0];
323        let mut record = vec![1, profile, 0x00, 0x1f, 0xff, 0xe1];
324        record.extend_from_slice(&(sps.len() as u16).to_be_bytes());
325        record.extend_from_slice(&sps);
326        record.push(1);
327        record.extend_from_slice(&(pps.len() as u16).to_be_bytes());
328        record.extend_from_slice(&pps);
329        boxed(b"avcC", &record)
330    }
331
332    #[test]
333    fn derives_the_h264_codec_string_and_profile_from_avcc() {
334        // High: seq_parameter_set_id 0, chroma_format_idc 1, 8-bit luma and
335        // chroma (`1 010 1 1`), then the rest of the SPS.
336        let high = avcc(100, &[0xac, 0xd9, 0x40, 0x50]);
337        let derived = derive_codec_string(Codec::H264, &high).unwrap();
338        assert_eq!(derived.codec_string, "avc1.64001F");
339        assert_eq!(derived.profile, CodecProfile::H264High);
340
341        // Main and Baseline carry no chroma format or bit depth.
342        let main = avcc(77, &[0x80]);
343        let derived = derive_codec_string(Codec::H264, &main).unwrap();
344        assert_eq!(derived.codec_string, "avc1.4D001F");
345        assert_eq!(derived.profile, CodecProfile::H264Main);
346        let derived = derive_codec_string(Codec::H264, &avcc(66, &[0x80])).unwrap();
347        assert_eq!(derived.profile, CodecProfile::H264Baseline);
348
349        // `1 011 1 1`: seq_parameter_set_id 0, chroma_format_idc 2 (4:2:2),
350        // 8-bit luma and chroma. The High 4:2:2 profile is refused for its
351        // profile, and a High-profile SPS with 4:2:2 chroma for its format.
352        let error = derive_codec_string(Codec::H264, &avcc(122, &[0xbe])).unwrap_err();
353        assert_eq!(error.kind(), ErrorKind::Unsupported);
354        let error = derive_codec_string(Codec::H264, &avcc(100, &[0xbe])).unwrap_err();
355        assert_eq!(error.kind(), ErrorKind::Unsupported);
356
357        let error = derive_codec_string(Codec::H264, &boxed(b"avcC", &[1])).unwrap_err();
358        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
359    }
360
361    #[test]
362    fn rejects_unsupported_codecs() {
363        let error = derive_codec_string(Codec::Aac, &boxed(b"esds", &[0; 4])).unwrap_err();
364        assert_eq!(error.kind(), ErrorKind::Unsupported);
365        let error =
366            derive_codec_string(Codec::UncompressedVideo, &boxed(b"hvcC", &[0; 13])).unwrap_err();
367        assert_eq!(error.kind(), ErrorKind::Unsupported);
368    }
369
370    fn vpcc(version: u8, record: &[u8]) -> Vec<u8> {
371        let mut payload = vec![version, 0, 0, 0];
372        payload.extend_from_slice(record);
373        boxed(b"vpcC", &payload)
374    }
375
376    #[test]
377    fn reads_a_version_1_vpcc_box_and_derives_its_codec_string() {
378        // Profile 0, level 3.1, 8-bit, colocated 4:2:0, limited range,
379        // BT.709 color description, no initialization data.
380        let bytes = vpcc(1, &[0, 31, 0x82, 1, 1, 1, 0, 0]);
381        let config = Vp9CodecConfig::parse(&bytes).unwrap();
382        assert_eq!(
383            config,
384            Vp9CodecConfig {
385                profile: 0,
386                level: 31,
387                bit_depth: 8,
388                chroma_subsampling: 1,
389                video_full_range: false,
390                color_primaries: 1,
391                transfer_characteristics: 1,
392                matrix_coefficients: 1,
393            }
394        );
395        assert!(config.is_420());
396        let derived = derive_codec_string(Codec::Vp9, &bytes).unwrap();
397        assert_eq!(derived.codec_string, "vp09.00.31.08");
398        assert_eq!(derived.profile, CodecProfile::Vp9Profile0);
399
400        let ten_bit = vpcc(1, &[2, 0, 0xa1, 9, 16, 9, 0, 0]);
401        let config = Vp9CodecConfig::parse(&ten_bit).unwrap();
402        assert!(config.video_full_range);
403        assert_eq!(config.codec_profile().unwrap(), CodecProfile::Vp9Profile2);
404        // Level 0 is unspecified, which the codec string cannot say.
405        assert_eq!(config.codec_string(), "vp09.02.10.10");
406    }
407
408    #[test]
409    fn reads_a_version_0_vpcc_box() {
410        let bytes = vpcc(0, &[1, 20, 0x80, 0x30, 0x80, 0, 0]);
411        let config = Vp9CodecConfig::parse(&bytes).unwrap();
412        assert_eq!(config.profile, 1);
413        assert_eq!(config.level, 20);
414        assert_eq!(config.bit_depth, 8);
415        assert_eq!(config.chroma_subsampling, 3);
416        assert!(config.video_full_range);
417    }
418
419    #[test]
420    fn reads_webm_codec_private_features() {
421        assert_eq!(
422            Vp9CodecConfig::parse(&[]).unwrap(),
423            Vp9CodecConfig::default()
424        );
425        let config = Vp9CodecConfig::parse(&[1, 1, 0, 2, 1, 40, 3, 1, 8, 4, 1, 1]).unwrap();
426        assert_eq!((config.profile, config.level, config.bit_depth), (0, 40, 8));
427        assert_eq!(config.chroma_subsampling, 1);
428        // Unknown features are skipped.
429        assert_eq!(
430            Vp9CodecConfig::parse(&[9, 2, 7, 7, 1, 1, 2])
431                .unwrap()
432                .profile,
433            2
434        );
435    }
436
437    #[test]
438    fn rejects_malformed_vp9_configurations() {
439        for bytes in [
440            vec![1, 1],
441            vec![1, 2, 0, 0],
442            vec![3, 1, 9],
443            vpcc(1, &[0, 10]),
444            vpcc(2, &[0, 10, 0x80, 1, 1, 1, 0, 0]),
445            vpcc(1, &[4, 10, 0x80, 1, 1, 1, 0, 0]),
446            vpcc(1, &[0, 10, 0x90, 1, 1, 1, 0, 0]),
447        ] {
448            let error = Vp9CodecConfig::parse(&bytes).unwrap_err();
449            assert_eq!(error.kind(), ErrorKind::MalformedMedia, "{bytes:?}");
450        }
451        let config = Vp9CodecConfig::parse(&[1, 1, 0, 2, 1, 41, 4, 1, 1]).unwrap();
452        assert_eq!(Vp9CodecConfig::parse(&config.to_vpcc()).unwrap(), config);
453        let mut inconsistent = vpcc(1, &[0, 10, 0x80, 1, 1, 1, 0, 0]);
454        inconsistent[3] += 1;
455        assert!(Vp9CodecConfig::parse(&inconsistent).is_err());
456    }
457}