zvidlib-core 0.5.2

Shared types, I/O, codec traits and the SIMD override 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
//! The H.264/AVC decoder configuration record (`avcC`, ISO/IEC 14496-15
//! 5.3.3.1) and the few sequence parameter set fields capability discovery
//! needs from it.

use crate::{CodecProfile, Error, ErrorKind, Result};

/// An H.264 track's `AVCDecoderConfigurationRecord`, as an MP4 `avcC` box or a
/// Matroska `CodecPrivate` element carries it.
///
/// The parameter sets are kept as the NAL units the record stores, header byte
/// included and emulation prevention intact, which is the form every platform
/// decoder takes them in. The chroma format and bit depths are read from the
/// first sequence parameter set, not from the record's optional High-profile
/// extension, since a record from a Baseline or Main stream has no extension
/// and some muxers write one that disagrees with the stream.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AvcConfigurationRecord {
    /// `AVCProfileIndication`: 66 is Baseline, 77 Main, 100 High.
    pub profile_idc: u8,
    /// `profile_compatibility`, the `constraint_set0..5_flag` byte.
    pub constraint_flags: u8,
    /// `AVCLevelIndication`, the level times ten (`31` is level 3.1).
    pub level_idc: u8,
    /// The size in bytes of each sample's NAL unit length prefix: 1, 2 or 4.
    pub length_size: usize,
    /// The sequence parameter sets, as NAL units.
    pub sequence_parameter_sets: Vec<Vec<u8>>,
    /// The picture parameter sets, as NAL units.
    pub picture_parameter_sets: Vec<Vec<u8>>,
    /// 0 is monochrome, 1 is 4:2:0, 2 is 4:2:2 and 3 is 4:4:4, from the
    /// first sequence parameter set.
    pub chroma_format_idc: u8,
    /// `bit_depth_luma_minus8 + 8`, from the first sequence parameter set.
    pub bit_depth_luma: u8,
    /// `bit_depth_chroma_minus8 + 8`, from the first sequence parameter set.
    pub bit_depth_chroma: u8,
}

/// NAL unit type of a sequence parameter set.
const NAL_SPS: u8 = 7;
/// NAL unit type of a picture parameter set.
const NAL_PPS: u8 = 8;

impl AvcConfigurationRecord {
    /// Parses a complete `avcC` box (size and fourcc included) or its bare
    /// payload, which begins with `configurationVersion` 1.
    pub fn parse(decoder_config: &[u8]) -> Result<Self> {
        let payload = avcc_payload(decoder_config)?;
        if payload.len() < 7 {
            return Err(malformed("avcC configuration is too short"));
        }
        if payload[0] != 1 {
            return Err(malformed("avcC configurationVersion is not 1"));
        }
        let profile_idc = payload[1];
        let constraint_flags = payload[2];
        let level_idc = payload[3];
        let length_size = usize::from(payload[4] & 0b11) + 1;
        if length_size == 3 {
            return Err(malformed("avcC NAL unit length size of 3 bytes is invalid"));
        }
        let mut cursor = 5;
        let sps_count = usize::from(payload[cursor] & 0b1_1111);
        cursor += 1;
        let sequence_parameter_sets = read_sets(payload, &mut cursor, sps_count, NAL_SPS)?;
        let pps_count = usize::from(
            *payload
                .get(cursor)
                .ok_or_else(|| malformed("avcC configuration ends before its PPS count"))?,
        );
        cursor += 1;
        let picture_parameter_sets = read_sets(payload, &mut cursor, pps_count, NAL_PPS)?;
        let first_sps = sequence_parameter_sets
            .first()
            .ok_or_else(|| malformed("avcC configuration does not contain an SPS"))?;
        if picture_parameter_sets.is_empty() {
            return Err(malformed("avcC configuration does not contain a PPS"));
        }
        let sps = SpsSummary::parse(first_sps)?;
        Ok(Self {
            profile_idc,
            constraint_flags,
            level_idc,
            length_size,
            sequence_parameter_sets,
            picture_parameter_sets,
            chroma_format_idc: sps.chroma_format_idc,
            bit_depth_luma: sps.bit_depth_luma,
            bit_depth_chroma: sps.bit_depth_chroma,
        })
    }

    /// The WebCodecs codec string for this record, `avc1.PPCCLL` (RFC 6381
    /// 3.3): the profile, constraint flags and level as two hex digits each.
    pub fn codec_string(&self) -> String {
        format!(
            "avc1.{:02X}{:02X}{:02X}",
            self.profile_idc, self.constraint_flags, self.level_idc
        )
    }

    /// The normalized profile: Baseline (constrained or not), Main or High.
    ///
    /// Every other profile - Extended, and the High 10, 4:2:2 and 4:4:4
    /// profiles none of zvidlib's decoders output - is reported unsupported.
    pub fn codec_profile(&self) -> Result<CodecProfile> {
        match self.profile_idc {
            66 => Ok(CodecProfile::H264Baseline),
            77 => Ok(CodecProfile::H264Main),
            100 => Ok(CodecProfile::H264High),
            other => Err(Error::new(
                ErrorKind::Unsupported,
                format!(
                    "H.264 profile_idc {other} is unsupported; only Baseline (66), Main (77) and High (100) are"
                ),
            )),
        }
    }

    /// Whether the stream is 8-bit 4:2:0, the only format the hardware
    /// decoders' NV12 output carries.
    pub fn is_8bit_420(&self) -> bool {
        self.chroma_format_idc == 1 && self.bit_depth_luma == 8 && self.bit_depth_chroma == 8
    }
}

fn avcc_payload(decoder_config: &[u8]) -> Result<&[u8]> {
    if decoder_config.len() >= 8 && &decoder_config[4..8] == b"avcC" {
        let declared = u32::from_be_bytes(decoder_config[..4].try_into().expect("four bytes"));
        if usize::try_from(declared).ok() != Some(decoder_config.len()) {
            return Err(malformed(
                "avcC box size does not match its configuration bytes",
            ));
        }
        return Ok(&decoder_config[8..]);
    }
    if decoder_config.first() == Some(&1) {
        return Ok(decoder_config);
    }
    Err(malformed("H.264 configuration is not an avcC record"))
}

fn read_sets(
    payload: &[u8],
    cursor: &mut usize,
    count: usize,
    nal_type: u8,
) -> Result<Vec<Vec<u8>>> {
    let mut sets = Vec::with_capacity(count);
    for _ in 0..count {
        let length = payload
            .get(*cursor..*cursor + 2)
            .ok_or_else(|| malformed("avcC parameter set length is truncated"))?;
        let length = usize::from(u16::from_be_bytes([length[0], length[1]]));
        *cursor += 2;
        let unit = payload
            .get(*cursor..*cursor + length)
            .ok_or_else(|| malformed("avcC parameter set is truncated"))?;
        *cursor += length;
        if unit.first().map(|header| header & 0x1f) != Some(nal_type) {
            return Err(malformed(if nal_type == NAL_SPS {
                "avcC SPS entry is not a sequence parameter set"
            } else {
                "avcC PPS entry is not a picture parameter set"
            }));
        }
        sets.push(unit.to_vec());
    }
    Ok(sets)
}

/// The leading fields of a sequence parameter set (ITU-T H.264 7.3.2.1.1)
/// that say what the decoded pictures look like.
struct SpsSummary {
    chroma_format_idc: u8,
    bit_depth_luma: u8,
    bit_depth_chroma: u8,
}

impl SpsSummary {
    fn parse(unit: &[u8]) -> Result<Self> {
        let rbsp = unescape(unit.get(1..).unwrap_or_default());
        let mut bits = BitReader::new(&rbsp);
        let profile_idc = bits.read_bits(8)? as u8;
        bits.read_bits(16)?; // constraint flags, reserved bits and level_idc
        bits.read_ue()?; // seq_parameter_set_id
        // Profiles that carry chroma_format_idc and the bit depths explicitly;
        // every other profile is 8-bit 4:2:0.
        if matches!(
            profile_idc,
            100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
        ) {
            let chroma_format_idc = bits.read_ue()?;
            if chroma_format_idc > 3 {
                return Err(malformed("H.264 SPS chroma_format_idc is out of range"));
            }
            if chroma_format_idc == 3 {
                bits.read_bits(1)?; // separate_color_plane_flag
            }
            let luma = bits.read_ue()?;
            let chroma = bits.read_ue()?;
            if luma > 6 || chroma > 6 {
                return Err(malformed("H.264 SPS bit depth is out of range"));
            }
            return Ok(Self {
                chroma_format_idc: chroma_format_idc as u8,
                bit_depth_luma: luma as u8 + 8,
                bit_depth_chroma: chroma as u8 + 8,
            });
        }
        Ok(Self {
            chroma_format_idc: 1,
            bit_depth_luma: 8,
            bit_depth_chroma: 8,
        })
    }
}

/// Removes the emulation prevention bytes (`00 00 03` becomes `00 00`).
fn unescape(escaped: &[u8]) -> Vec<u8> {
    let mut output = Vec::with_capacity(escaped.len());
    let mut zeros = 0;
    for &byte in escaped {
        if zeros >= 2 && byte == 3 {
            zeros = 0;
            continue;
        }
        zeros = if byte == 0 { zeros + 1 } else { 0 };
        output.push(byte);
    }
    output
}

struct BitReader<'a> {
    data: &'a [u8],
    position: usize,
}

impl<'a> BitReader<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data, position: 0 }
    }

    fn read_bit(&mut self) -> Result<u32> {
        let byte = self
            .data
            .get(self.position / 8)
            .ok_or_else(|| malformed("H.264 SPS is truncated"))?;
        let bit = (byte >> (7 - self.position % 8)) & 1;
        self.position += 1;
        Ok(u32::from(bit))
    }

    fn read_bits(&mut self, count: u32) -> Result<u32> {
        let mut value = 0;
        for _ in 0..count {
            value = (value << 1) | self.read_bit()?;
        }
        Ok(value)
    }

    /// An unsigned Exp-Golomb code, `ue(v)`.
    fn read_ue(&mut self) -> Result<u32> {
        let mut leading_zeros = 0;
        while self.read_bit()? == 0 {
            leading_zeros += 1;
            if leading_zeros > 31 {
                return Err(malformed("H.264 SPS Exp-Golomb code is too long"));
            }
        }
        Ok((1u32 << leading_zeros) - 1 + self.read_bits(leading_zeros)?)
    }
}

fn malformed(message: impl Into<String>) -> Error {
    Error::new(ErrorKind::MalformedMedia, message)
}

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

    /// The High-profile 8-bit 4:2:0 SPS and PPS of the 256x140 x264 fixture
    /// in `crates/zvidlib-h264-decoder/tests/fixtures`.
    const HIGH_SPS: &[u8] = &[
        0x67, 0x64, 0x00, 0x0c, 0xac, 0xd9, 0x41, 0x01, 0x3f, 0xbf, 0xfc, 0x00, 0x8c, 0x00, 0x91,
        0xa8, 0x28, 0x28, 0x32, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x60, 0x1e,
        0x28, 0x53, 0x2c,
    ];
    const PPS: &[u8] = &[0x68, 0xe9, 0x38, 0x44, 0xb2, 0x2c];

    fn record(profile: u8, sps: &[&[u8]], pps: &[&[u8]]) -> Vec<u8> {
        let mut payload = vec![1, profile, 0x00, 0x0c, 0xff, 0xe0 | sps.len() as u8];
        for set in sps {
            payload.extend_from_slice(&(set.len() as u16).to_be_bytes());
            payload.extend_from_slice(set);
        }
        payload.push(pps.len() as u8);
        for set in pps {
            payload.extend_from_slice(&(set.len() as u16).to_be_bytes());
            payload.extend_from_slice(set);
        }
        let mut boxed = ((payload.len() + 8) as u32).to_be_bytes().to_vec();
        boxed.extend_from_slice(b"avcC");
        boxed.extend_from_slice(&payload);
        boxed
    }

    /// A field of a synthetic SPS.
    enum Field {
        /// A fixed-width `(value, width)` field.
        Bits(u32, u32),
        /// An unsigned Exp-Golomb code.
        Ue(u32),
    }
    use Field::{Bits, Ue};

    /// An SPS NAL unit carrying `fields`, then a stop bit.
    fn sps(fields: &[Field]) -> Vec<u8> {
        let mut bits = Vec::new();
        let mut push = |value: u32, width: u32| {
            for shift in (0..width).rev() {
                bits.push((value >> shift) & 1 == 1);
            }
        };
        for field in fields {
            match *field {
                Bits(value, width) => push(value, width),
                Ue(value) => {
                    let coded = value + 1;
                    let width = 32 - coded.leading_zeros();
                    push(0, width - 1);
                    push(coded, width);
                }
            }
        }
        bits.push(true);
        let mut unit = vec![0x67];
        unit.extend(bits.chunks(8).map(|chunk| {
            chunk.iter().enumerate().fold(0u8, |byte, (index, &bit)| {
                byte | (u8::from(bit) << (7 - index))
            })
        }));
        unit
    }

    #[test]
    fn parses_a_high_profile_box_and_its_bare_payload() {
        let boxed = record(100, &[HIGH_SPS], &[PPS]);
        let parsed = AvcConfigurationRecord::parse(&boxed).unwrap();
        assert_eq!(parsed.profile_idc, 100);
        assert_eq!(parsed.level_idc, 12);
        assert_eq!(parsed.length_size, 4);
        assert_eq!(parsed.sequence_parameter_sets, [HIGH_SPS.to_vec()]);
        assert_eq!(parsed.picture_parameter_sets, [PPS.to_vec()]);
        assert!(parsed.is_8bit_420());
        assert_eq!(parsed.codec_string(), "avc1.64000C");
        assert_eq!(parsed.codec_profile().unwrap(), CodecProfile::H264High);
        assert_eq!(AvcConfigurationRecord::parse(&boxed[8..]).unwrap(), parsed);
    }

    #[test]
    fn maps_baseline_and_main_and_refuses_other_profiles() {
        // A Baseline SPS has no chroma or bit-depth fields: profile 66, the
        // constrained flags, level 3.0, then seq_parameter_set_id 0.
        let baseline = sps(&[Bits(66, 8), Bits(0xc0, 8), Bits(30, 8), Ue(0)]);
        let mut boxed = record(66, &[&baseline], &[PPS]);
        boxed[10] = 0xc0;
        boxed[11] = 30;
        let parsed = AvcConfigurationRecord::parse(&boxed).unwrap();
        assert_eq!(parsed.codec_profile().unwrap(), CodecProfile::H264Baseline);
        assert!(parsed.is_8bit_420());
        assert_eq!(parsed.codec_string(), "avc1.42C01E");

        let parsed = AvcConfigurationRecord::parse(&record(77, &[&baseline], &[PPS])).unwrap();
        assert_eq!(parsed.codec_profile().unwrap(), CodecProfile::H264Main);

        let error = AvcConfigurationRecord::parse(&record(88, &[&baseline], &[PPS]))
            .unwrap()
            .codec_profile()
            .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Unsupported);
    }

    #[test]
    fn reads_high_10_and_4_4_4_formats_from_the_sps() {
        // High 10: chroma_format_idc 1, 10-bit luma and chroma.
        let high10 = sps(&[Bits(110, 8), Bits(0, 16), Ue(0), Ue(1), Ue(2), Ue(2)]);
        let parsed = AvcConfigurationRecord::parse(&record(110, &[&high10], &[PPS])).unwrap();
        assert_eq!(
            (
                parsed.chroma_format_idc,
                parsed.bit_depth_luma,
                parsed.bit_depth_chroma
            ),
            (1, 10, 10)
        );
        assert!(!parsed.is_8bit_420());
        assert_eq!(
            parsed.codec_profile().unwrap_err().kind(),
            ErrorKind::Unsupported
        );

        // High 4:4:4 Predictive: chroma_format_idc 3 carries a
        // separate_color_plane_flag before the bit depths.
        let high444 = sps(&[
            Bits(244, 8),
            Bits(0, 16),
            Ue(0),
            Ue(3),
            Bits(0, 1),
            Ue(0),
            Ue(0),
        ]);
        let parsed = AvcConfigurationRecord::parse(&record(244, &[&high444], &[PPS])).unwrap();
        assert_eq!(parsed.chroma_format_idc, 3);
        assert_eq!((parsed.bit_depth_luma, parsed.bit_depth_chroma), (8, 8));
        assert!(!parsed.is_8bit_420());
    }

    #[test]
    fn rejects_malformed_records() {
        let good = record(100, &[HIGH_SPS], &[PPS]);
        for (name, bytes) in [
            ("empty", Vec::new()),
            ("not avcC", vec![2, 100, 0, 30, 0xff, 0xe1]),
            ("truncated", good[..good.len() - 2].to_vec()),
            ("box size mismatch", {
                let mut bytes = good.clone();
                bytes[3] = bytes[3].wrapping_add(1);
                bytes
            }),
            ("no SPS", record(100, &[], &[PPS])),
            ("no PPS", record(100, &[HIGH_SPS], &[])),
            ("SPS slot holds a PPS", record(100, &[PPS], &[PPS])),
            ("length size 3", {
                let mut bytes = good.clone();
                bytes[12] = 0xfe;
                bytes
            }),
        ] {
            let error = AvcConfigurationRecord::parse(&bytes)
                .err()
                .unwrap_or_else(|| panic!("{name} must be rejected"));
            assert_eq!(error.kind(), ErrorKind::MalformedMedia, "{name}");
        }
    }

    #[test]
    fn unescapes_emulation_prevention_bytes() {
        assert_eq!(unescape(&[0, 0, 3, 1, 0, 0, 3, 0]), [0, 0, 1, 0, 0, 0]);
        assert_eq!(unescape(&[0, 3, 0, 0, 3]), [0, 3, 0, 0]);
    }
}