zvidlib-container 0.5.11

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
//! The AAC decoder configuration of an MP4 `mp4a` sample entry: the
//! `AudioSpecificConfig` (ISO/IEC 14496-3 1.6.2.1) in its `esds` box, resolved
//! against the sample entry into the stream zvidlib decodes.
//!
//! AAC-LC is decoded as it is. HE-AAC v1 (spectral band replication, SBR,
//! object type 5) and HE-AAC v2 (SBR plus parametric stereo, PS, object type
//! 29) wrap an AAC-LC core, and are signaled in one of three ways:
//!
//! - hierarchically, the configuration naming object type 5 or 29 first and
//!   the AAC-LC core after it;
//! - with the backward-compatible extension, an AAC-LC configuration followed
//!   by the `0x2b7` (and for PS also `0x548`) sync extension, as AudioToolbox
//!   and FFmpeg write it;
//! - implicitly, a plain AAC-LC configuration whose access units carry SBR in
//!   their fill elements. The configuration does not say so, but a sample
//!   entry giving twice the core sample rate (and two channels over a mono
//!   core, for PS) does, as FFmpeg writes it when it remuxes ADTS.
//!
//! An implicitly signaled stream is given an explicit configuration, so every
//! decoder backend learns the output format before the first access unit.

use crate::mp4_demux::AacTrackConfig;
use crate::{Error, ErrorKind, Result};

/// AAC-LC.
const AOT_LC: u8 = 2;
/// Spectral band replication, HE-AAC v1.
const AOT_SBR: u8 = 5;
/// Parametric stereo, HE-AAC v2.
const AOT_PS: u8 = 29;

/// The backward-compatible SBR extension's sync word.
const SBR_SYNC: u32 = 0x2b7;
/// The backward-compatible PS extension's sync word.
const PS_SYNC: u32 = 0x548;

const FREQUENCIES: [u32; 13] = [
    96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000, 12_000, 11_025, 8_000,
    7_350,
];

/// The highest core sample rate an implicitly signaled SBR stream can have:
/// its output rate, twice the core's, is at most 48 kHz.
const MAX_IMPLICIT_SBR_CORE_RATE: u32 = 24_000;

/// What an `AudioSpecificConfig` says about the stream.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct AudioSpecificConfig {
    /// The core's object type: 2 for AAC-LC, the core of HE-AAC as well.
    pub core_object_type: u8,
    pub core_sample_rate: u32,
    pub channel_config: u8,
    /// The SBR output sample rate when SBR is explicitly signaled.
    pub sbr_sample_rate: Option<u32>,
    /// Whether parametric stereo is explicitly signaled.
    pub ps: bool,
}

impl AudioSpecificConfig {
    pub(crate) fn parse(bytes: &[u8]) -> Result<Self> {
        let mut bits = AscBits::new(bytes);
        let mut object_type = read_object_type(&mut bits)?;
        let core_sample_rate = read_frequency(&mut bits)?;
        let channel_config = bits.read(4)? as u8;
        let mut sbr_sample_rate = None;
        let mut ps = false;
        if matches!(object_type, AOT_SBR | AOT_PS) {
            ps = object_type == AOT_PS;
            sbr_sample_rate = Some(read_frequency(&mut bits)?);
            object_type = read_object_type(&mut bits)?;
        }
        if channel_config == 0 || channel_config > 7 {
            return Err(unsupported(
                "AAC program-config-element channel layouts are unsupported",
            ));
        }
        let mut config = Self {
            core_object_type: object_type,
            core_sample_rate,
            channel_config,
            sbr_sample_rate,
            ps,
        };
        if object_type != AOT_LC {
            return Ok(config);
        }
        // GASpecificConfig: frameLengthFlag, dependsOnCoreCoder (with a
        // 14-bit coreCoderDelay) and extensionFlag, which AAC-LC leaves 0.
        bits.read(1)?;
        if bits.read(1)? == 1 {
            bits.read(14)?;
        }
        bits.read(1)?;
        if sbr_sample_rate.is_none() && bits.remaining() >= 16 {
            // A truncated extension is ignored like any other trailing bits.
            let _ = config.read_sync_extension(&mut bits);
        }
        Ok(config)
    }

    /// The backward-compatible extension that may follow an AAC-LC
    /// configuration. Anything other than a well-formed SBR extension leaves
    /// the configuration as it was: decoders ignore trailing bits they do not
    /// recognize.
    fn read_sync_extension(&mut self, bits: &mut AscBits) -> Result<()> {
        if bits.read(11)? != SBR_SYNC {
            return Ok(());
        }
        let Ok(extension_type) = read_object_type(bits) else {
            return Ok(());
        };
        if extension_type != AOT_SBR {
            return Ok(());
        }
        if bits.read(1)? == 0 {
            return Ok(());
        }
        let Ok(sbr_sample_rate) = read_frequency(bits) else {
            return Ok(());
        };
        self.sbr_sample_rate = Some(sbr_sample_rate);
        if bits.remaining() >= 12 && bits.read(11)? == PS_SYNC {
            self.ps = bits.read(1)? == 1;
        }
        Ok(())
    }

    /// Whether the core is AAC-LC, the only core zvidlib decodes.
    pub(crate) fn is_aac_lc_core(&self) -> bool {
        self.core_object_type == AOT_LC
    }

    /// Resolves this configuration, parsed from `asc`, against its `mp4a`
    /// sample entry's sample rate and channel count into the stream zvidlib
    /// decodes. The core must be AAC-LC.
    pub(crate) fn resolve(
        mut self,
        asc: &[u8],
        entry_rate: u32,
        entry_channels: u16,
    ) -> Result<AacTrackConfig> {
        let core_channels = u16::from(self.channel_config);
        let mut audio_specific_config = asc.to_vec();
        if self.sbr_sample_rate.is_none()
            && self.core_sample_rate <= MAX_IMPLICIT_SBR_CORE_RATE
            && Some(entry_rate) == self.core_sample_rate.checked_mul(2)
        {
            self.sbr_sample_rate = Some(entry_rate);
            self.ps = core_channels == 1 && entry_channels == 2;
            audio_specific_config = explicit_sbr_config(asc, &self)?;
        }
        // Parametric stereo turns a mono core into stereo, and only a mono one.
        self.ps &= core_channels == 1;
        let sample_rate = self.sbr_sample_rate.unwrap_or(self.core_sample_rate);
        let channels = if self.ps { 2 } else { core_channels };
        if entry_rate != sample_rate && entry_rate != self.core_sample_rate {
            return Err(malformed(
                "AAC AudioSpecificConfig sample rate disagrees with mp4a",
            ));
        }
        if entry_channels != channels && entry_channels != core_channels {
            return Err(malformed(
                "AAC AudioSpecificConfig channel count disagrees with mp4a",
            ));
        }
        Ok(AacTrackConfig {
            audio_object_type: self.signaled_object_type(),
            sample_rate,
            channels,
            audio_specific_config,
        })
    }

    /// The audio object type the stream is identified by, as in its
    /// `mp4a.40.N` codec string.
    fn signaled_object_type(&self) -> u8 {
        match (self.sbr_sample_rate, self.ps) {
            (Some(_), true) => AOT_PS,
            (Some(_), false) => AOT_SBR,
            (None, _) => self.core_object_type,
        }
    }
}

/// An explicit configuration for an implicitly signaled SBR stream: the AAC-LC
/// configuration with the backward-compatible extension appended, as
/// AudioToolbox and FFmpeg write HE-AAC. It goes after the GASpecificConfig,
/// so the original bits are kept up to their end and anything after them is
/// replaced.
fn explicit_sbr_config(asc: &[u8], config: &AudioSpecificConfig) -> Result<Vec<u8>> {
    let mut bits = AscBits::new(asc);
    read_object_type(&mut bits)?;
    read_frequency(&mut bits)?;
    bits.read(4)?;
    bits.read(1)?;
    if bits.read(1)? == 1 {
        bits.read(14)?;
    }
    bits.read(1)?;
    let core_bits = bits.position;
    let mut writer = BitWriter::default();
    let mut reader = AscBits::new(asc);
    for _ in 0..core_bits {
        writer.write(reader.read(1)?, 1);
    }
    writer.write(SBR_SYNC, 11);
    writer.write(u32::from(AOT_SBR), 5);
    writer.write(1, 1);
    let rate = config.sbr_sample_rate.expect("an SBR configuration");
    match FREQUENCIES.iter().position(|&frequency| frequency == rate) {
        Some(index) => writer.write(index as u32, 4),
        None => {
            writer.write(15, 4);
            writer.write(rate, 24);
        }
    }
    if config.ps {
        writer.write(PS_SYNC, 11);
        writer.write(1, 1);
    }
    Ok(writer.finish())
}

fn read_object_type(bits: &mut AscBits) -> Result<u8> {
    let object_type = bits.read(5)? as u8;
    if object_type == 31 {
        return Ok(32 + bits.read(6)? as u8);
    }
    Ok(object_type)
}

fn read_frequency(bits: &mut AscBits) -> Result<u32> {
    let index = bits.read(4)? as usize;
    if index == 15 {
        return bits.read(24);
    }
    FREQUENCIES
        .get(index)
        .copied()
        .ok_or_else(|| malformed("AAC AudioSpecificConfig has an invalid sample rate"))
}

struct AscBits<'a> {
    bytes: &'a [u8],
    position: usize,
}

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

    fn remaining(&self) -> usize {
        self.bytes.len() * 8 - self.position
    }

    fn read(&mut self, count: usize) -> Result<u32> {
        if count > 32 || count > self.remaining() {
            return Err(malformed("truncated AAC AudioSpecificConfig"));
        }
        let mut value = 0_u32;
        for _ in 0..count {
            value = (value << 1)
                | u32::from((self.bytes[self.position / 8] >> (7 - self.position % 8)) & 1);
            self.position += 1;
        }
        Ok(value)
    }
}

#[derive(Default)]
struct BitWriter {
    bytes: Vec<u8>,
    bits: usize,
}

impl BitWriter {
    fn write(&mut self, value: u32, count: usize) {
        for shift in (0..count).rev() {
            if self.bits % 8 == 0 {
                self.bytes.push(0);
            }
            let bit = ((value >> shift) & 1) as u8;
            *self.bytes.last_mut().expect("a byte was pushed") |= bit << (7 - self.bits % 8);
            self.bits += 1;
        }
    }

    fn finish(self) -> Vec<u8> {
        self.bytes
    }
}

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

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

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

    fn resolve(asc: &[u8], rate: u32, channels: u16) -> Result<AacTrackConfig> {
        AudioSpecificConfig::parse(asc)?.resolve(asc, rate, channels)
    }

    fn resolved(asc: &[u8], rate: u32, channels: u16) -> AacTrackConfig {
        resolve(asc, rate, channels).unwrap()
    }

    #[test]
    fn plain_aac_lc_is_decoded_at_its_own_rate() {
        let config = resolved(&[0x11, 0x90], 48_000, 2);
        assert_eq!(
            (
                config.audio_object_type,
                config.sample_rate,
                config.channels
            ),
            (2, 48_000, 2)
        );
        assert_eq!(config.audio_specific_config, [0x11, 0x90]);
    }

    #[test]
    fn a_disabled_backward_compatible_sbr_extension_stays_aac_lc() {
        // The bundled sample's configuration: the extension with
        // sbrPresentFlag 0.
        let config = resolved(&[0x11, 0x90, 0x56, 0xe5, 0x00], 48_000, 2);
        assert_eq!((config.audio_object_type, config.sample_rate), (2, 48_000));
    }

    #[test]
    fn backward_compatible_he_aac_v1_decodes_at_the_sbr_rate() {
        // AudioToolbox's HE-AAC: 22.05 kHz stereo core, SBR to 44.1 kHz. Its
        // sample entry gives the core rate and FFmpeg's the output rate.
        let asc = [0x13, 0x90, 0x56, 0xe5, 0xa0];
        for rate in [22_050, 44_100] {
            let config = resolved(&asc, rate, 2);
            assert_eq!(
                (
                    config.audio_object_type,
                    config.sample_rate,
                    config.channels
                ),
                (5, 44_100, 2)
            );
            assert_eq!(config.audio_specific_config, asc);
        }
    }

    #[test]
    fn backward_compatible_he_aac_v2_decodes_a_mono_core_to_stereo() {
        let asc = [0x13, 0x88, 0x56, 0xe5, 0xa5, 0x48, 0x80];
        for (rate, channels) in [(22_050, 2), (44_100, 2), (44_100, 1)] {
            let config = resolved(&asc, rate, channels);
            assert_eq!(
                (
                    config.audio_object_type,
                    config.sample_rate,
                    config.channels
                ),
                (29, 44_100, 2)
            );
        }
    }

    #[test]
    fn hierarchical_signaling_names_the_core_after_the_extension() {
        // Object type 29, 22.05 kHz, mono, extension 44.1 kHz, core AAC-LC.
        let mut writer = BitWriter::default();
        for (value, count) in [(29, 5), (7, 4), (1, 4), (4, 4), (2, 5), (0, 3)] {
            writer.write(value, count);
        }
        let config = resolved(&writer.finish(), 44_100, 2);
        assert_eq!(
            (
                config.audio_object_type,
                config.sample_rate,
                config.channels
            ),
            (29, 44_100, 2)
        );
    }

    #[test]
    fn implicit_sbr_is_made_explicit_from_the_sample_entry() {
        // FFmpeg's remux of HE-AAC v1 from ADTS: an AAC-LC configuration and
        // a sample entry at twice its rate.
        let config = resolved(&[0x13, 0x90], 44_100, 2);
        assert_eq!(
            (
                config.audio_object_type,
                config.sample_rate,
                config.channels
            ),
            (5, 44_100, 2)
        );
        assert_eq!(config.audio_specific_config, [0x13, 0x90, 0x56, 0xe5, 0xa0]);
        let reparsed = AudioSpecificConfig::parse(&config.audio_specific_config).unwrap();
        assert_eq!(reparsed.sbr_sample_rate, Some(44_100));
        assert!(!reparsed.ps);
    }

    #[test]
    fn implicit_ps_is_made_explicit_from_a_stereo_entry_over_a_mono_core() {
        let config = resolved(&[0x13, 0x88], 44_100, 2);
        assert_eq!(
            (
                config.audio_object_type,
                config.sample_rate,
                config.channels
            ),
            (29, 44_100, 2)
        );
        assert_eq!(
            config.audio_specific_config,
            [0x13, 0x88, 0x56, 0xe5, 0xa5, 0x48, 0x80]
        );
    }

    #[test]
    fn an_entry_at_twice_a_high_core_rate_is_not_taken_for_sbr() {
        let error = resolve(&[0x11, 0x88], 96_000, 1).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
    }

    #[test]
    fn mismatched_entries_and_other_object_types_are_reported() {
        assert_eq!(
            resolve(&[0x11, 0x90], 44_100, 2).unwrap_err().kind(),
            ErrorKind::MalformedMedia
        );
        assert_eq!(
            resolve(&[0x11, 0x90], 48_000, 1).unwrap_err().kind(),
            ErrorKind::MalformedMedia
        );
        // AAC Main.
        let main = AudioSpecificConfig::parse(&[0x09, 0x90]).unwrap();
        assert!(!main.is_aac_lc_core());
        assert_eq!(main.core_object_type, 1);
    }
}