forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB231663eTahinli3 months ago1475 commits

decoder.rs389 lines, 14.6 KiBHistoryRawDownload
1//! The public decoder: syncframes in, interleaved `f32` audio frames out.
2
3use ec_core::{
4 AudioFrame, AudioParameters, Buf, ChannelLayout, ChannelPosition, CodecId, CodecParameters,
5 Decoder, Error, Frame, MediaParameters, Packet, Result, SampleFormat, Timestamp,
6};
7
8use crate::bsi::{self, Acmod, Bsi};
9use crate::decode::{Core, Syntax};
10use crate::eac3;
11use crate::syncinfo;
12use crate::transform::BLOCK_SAMPLES;
13
14/// Blocks per AC-3 syncframe (A/52 §5.3.3); E-AC-3 states its own count.
15const AC3_BLOCKS: usize = 6;
16
17/// How the decoder should fold the coded channels down, if at all.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
19pub enum Downmix {
20 /// Hand out every coded channel in the stream's own layout.
21 #[default]
22 Native,
23 /// A/52 §7.8.2 Lo/Ro stereo downmix.
24 Stereo,
25 /// The §7.8.2 mono sum of that stereo downmix.
26 Mono,
27}
28
29/// Decoder knobs. The defaults are what the standard asks a decoder to do.
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub struct Options {
32 /// Fraction of the `dynrng` compression to apply, `0.0` to `1.0`.
33 ///
34 /// §7.7.1: "the AC-3 decoder shall, by default, implement the compression
35 /// characteristic indicated by the `dynrng` values", so this defaults to
36 /// full. Set it to `0.0` for the original dynamic range; the raw words stay
37 /// visible either way through [`crate::FrameInfo`].
38 pub drc_scale: f32,
39 /// Channel folding, off by default.
40 pub downmix: Downmix,
41 /// Generate the pseudo-random noise the format asks for: dither in place
42 /// of zero-bit mantissas (§7.3.4) and the blend that fills the spectral
43 /// extension band (§E3.6.4.2.4). On by default, because both are what the
44 /// standard asks a decoder to do.
45 ///
46 /// Neither sequence is specified — §7.3.4 says "any reasonably random
47 /// sequence" and §E3.6.4.2.4 just names a zero-mean unit-variance source —
48 /// so two conformant decoders differ by exactly this noise and nothing
49 /// else. Turning it off is how a comparison against another decoder
50 /// isolates everything that *is* specified.
51 pub dither: bool,
52}
53
54impl Default for Options {
55 fn default() -> Options {
56 Options {
57 drc_scale: 1.0,
58 downmix: Downmix::Native,
59 dither: true,
60 }
61 }
62}
63
64/// What a decoded frame's header said, for callers that route on it rather
65/// than on the samples: rate, layout and the metadata AC-3 carries per frame.
66#[derive(Debug, Clone, PartialEq)]
67pub struct FrameInfo {
68 /// AC-3 or E-AC-3.
69 pub syntax: Syntax,
70 /// Sample rate in Hz.
71 pub sample_rate: u32,
72 /// Full-bandwidth channels, LFE excluded.
73 pub nfchans: usize,
74 /// LFE present.
75 pub lfeon: bool,
76 /// Dialogue normalisation in -dB. Surfaced, never applied: the volume
77 /// control that has to combine it with the listener's setting is not in
78 /// this crate (§7.6).
79 pub dialnorm: u8,
80 /// Heavy compression word, when the frame carried one (§7.7.2).
81 pub compr: Option<u8>,
82 /// Centre mix level as a linear gain, when the mode has three fronts.
83 pub center_mix_level: Option<f32>,
84 /// Surround mix level as a linear gain, when the mode has surrounds.
85 pub surround_mix_level: Option<f32>,
86 /// Bit stream mode (Table 5.7).
87 pub bsmod: u8,
88 /// Audio coding mode.
89 pub acmod: Acmod,
90 /// Samples per channel this frame produced.
91 pub samples: usize,
92}
93
94/// An AC-3 / E-AC-3 decoder.
95///
96/// One packet is one syncframe (plus any E-AC-3 substreams that belong to it),
97/// which is how every container this family reads stores the format.
98pub struct Ac3Decoder {
99 core: Core,
100 params: CodecParameters,
101 options: Options,
102 pending: Option<Frame>,
103 info: Option<FrameInfo>,
104 /// Set by [`Decoder::flush`]; the next drained call reports end of stream.
105 flushed: bool,
106}
107
108impl Default for Ac3Decoder {
109 fn default() -> Ac3Decoder {
110 Ac3Decoder::new()
111 }
112}
113
114impl Ac3Decoder {
115 /// A decoder with default [`Options`] and no stream configuration yet;
116 /// everything it needs comes from the first syncframe.
117 pub fn new() -> Ac3Decoder {
118 Ac3Decoder::with_options(Options::default())
119 }
120
121 /// A decoder with explicit options.
122 pub fn with_options(options: Options) -> Ac3Decoder {
123 Ac3Decoder {
124 core: Core::new(),
125 params: CodecParameters::new(CodecId::Ac3),
126 options,
127 pending: None,
128 info: None,
129 flushed: false,
130 }
131 }
132
133 /// The options in force; changes take effect on the next packet.
134 pub fn options_mut(&mut self) -> &mut Options {
135 &mut self.options
136 }
137
138 /// What the last decoded frame's header said.
139 pub fn frame_info(&self) -> Option<&FrameInfo> {
140 self.info.as_ref()
141 }
142
143 /// Decode one syncframe into interleaved `f32` samples.
144 ///
145 /// `data` starts at a sync word. Truncated input is [`Error::NeedMore`], a
146 /// broken bit stream [`Error::Corrupt`], and a construct this build does
147 /// not implement [`Error::Unsupported`] with the reason named — never a
148 /// panic, on any input.
149 pub fn decode_frame(&mut self, data: &[u8]) -> Result<AudioFrame> {
150 let mut samples = Vec::new();
151 let (info, consumed) = self.decode_substream(data, &mut samples)?;
152 let _ = consumed;
153 let layout = self.layout(&info);
154 let interleaved = self.fold(samples, &info);
155 let channels = layout.channel_count();
156 let count = interleaved.len().checked_div(channels).unwrap_or(0);
157 self.info = Some(info.clone());
158 self.params.media = MediaParameters::Audio(AudioParameters {
159 sample_rate: info.sample_rate,
160 layout: layout.clone(),
161 format: Some(SampleFormat::F32),
162 bits_per_sample: None,
163 });
164 self.params.codec = match info.syntax {
165 Syntax::Ac3 => CodecId::Ac3,
166 Syntax::Eac3 => CodecId::EAc3,
167 };
168 let mut bytes = Vec::with_capacity(interleaved.len() * 4);
169 for v in &interleaved {
170 bytes.extend_from_slice(&v.to_le_bytes());
171 }
172 AudioFrame::try_new(
173 SampleFormat::F32,
174 false,
175 layout,
176 info.sample_rate,
177 count,
178 vec![Buf::from_vec(bytes)],
179 )
180 }
181
182 /// Decode one independent substream, appending interleaved samples.
183 /// Returns the frame's header summary and the bytes it consumed.
184 fn decode_substream(&mut self, data: &[u8], out: &mut Vec<f32>) -> Result<(FrameInfo, usize)> {
185 // Six bytes, not five: the sixth is where both syntaxes put bsid.
186 if data.len() < 6 {
187 return Err(Error::NeedMore);
188 }
189 // The syntax is decided by bsid, which sits five bytes in for AC-3 and
190 // two for E-AC-3 — so read it where both agree it can be found: after
191 // the sync word, E-AC-3 puts strmtyp/substreamid/frmsiz first, and
192 // bsid is at a fixed offset from the frame start in both.
193 let bsid = data[5] >> 3;
194 let mut r = ec_core::BitReader::new(data);
195 if bsid <= 10 {
196 let sync = syncinfo::parse_from(&mut r)?;
197 let bsi = bsi::parse_from(&mut r)?;
198 if data.len() < sync.frame_size {
199 return Err(Error::NeedMore);
200 }
201 self.core.drc_scale = self.options.drc_scale;
202 self.core.dither_on = self.options.dither;
203 self.core
204 .start_frame(Syntax::Ac3, sync.fscod as usize, &bsi);
205 for blk in 0..AC3_BLOCKS {
206 self.core.block(&mut r, blk, out)?;
207 }
208 Ok((
209 self.info_from(Syntax::Ac3, sync.sample_rate, &bsi, AC3_BLOCKS),
210 sync.frame_size,
211 ))
212 } else {
213 let hdr = eac3::bsi::parse_from(&mut r)?;
214 if data.len() < hdr.frame_size {
215 return Err(Error::NeedMore);
216 }
217 if hdr.strmtyp == eac3::StreamType::Dependent {
218 return Err(Error::unsupported(
219 "E-AC-3 dependent substream as the first substream of a packet",
220 "a dependent substream carries channel extensions for an \
221 independent one that has to be decoded first",
222 ));
223 }
224 self.core.drc_scale = self.options.drc_scale;
225 self.core.dither_on = self.options.dither;
226 eac3::decode_frame(&mut self.core, &mut r, &hdr, out)?;
227 Ok((
228 self.info_from(Syntax::Eac3, hdr.sample_rate, &hdr.bsi, hdr.nblocks),
229 hdr.frame_size,
230 ))
231 }
232 }
233
234 fn info_from(&self, syntax: Syntax, sample_rate: u32, bsi: &Bsi, nblocks: usize) -> FrameInfo {
235 FrameInfo {
236 syntax,
237 sample_rate,
238 nfchans: bsi.nfchans,
239 lfeon: bsi.lfeon,
240 dialnorm: bsi.dialnorm,
241 compr: bsi.compr,
242 center_mix_level: bsi.cmixlev.map(bsi::center_mix_level),
243 surround_mix_level: bsi.surmixlev.map(bsi::surround_mix_level),
244 bsmod: bsi.bsmod,
245 acmod: bsi.acmod,
246 samples: nblocks * BLOCK_SAMPLES,
247 }
248 }
249
250 /// The channel layout the coded channels are handed out in.
251 fn native_layout(&self, info: &FrameInfo) -> ChannelLayout {
252 use ChannelPosition::*;
253 let mut positions: Vec<ChannelPosition> = match info.acmod {
254 Acmod::DualMono => vec![FrontLeft, FrontRight],
255 Acmod::Mono => vec![FrontCenter],
256 Acmod::Stereo => vec![FrontLeft, FrontRight],
257 Acmod::Surround3_0 => vec![FrontLeft, FrontRight, FrontCenter],
258 Acmod::Surround2_1 => vec![FrontLeft, FrontRight, BackCenter],
259 Acmod::Surround3_1 => vec![FrontLeft, FrontRight, FrontCenter, BackCenter],
260 Acmod::Surround2_2 => vec![FrontLeft, FrontRight, BackLeft, BackRight],
261 Acmod::Surround3_2 => vec![FrontLeft, FrontRight, FrontCenter, BackLeft, BackRight],
262 };
263 if info.lfeon {
264 let fronts = match info.acmod {
265 Acmod::Mono => 1,
266 Acmod::Surround3_0 | Acmod::Surround3_1 | Acmod::Surround3_2 => 3,
267 _ => 2,
268 };
269 positions.insert(fronts.min(positions.len()), Lfe);
270 }
271 match positions.len() {
272 1 => ChannelLayout::Mono,
273 2 => ChannelLayout::Stereo,
274 _ if positions == ChannelLayout::Surround5_1.positions() => ChannelLayout::Surround5_1,
275 _ => ChannelLayout::Custom(positions),
276 }
277 }
278
279 fn layout(&self, info: &FrameInfo) -> ChannelLayout {
280 match self.options.downmix {
281 Downmix::Native => self.native_layout(info),
282 Downmix::Stereo => ChannelLayout::Stereo,
283 Downmix::Mono => ChannelLayout::Mono,
284 }
285 }
286
287 /// Apply the requested downmix, if any (§7.8.2).
288 fn fold(&self, samples: Vec<f32>, info: &FrameInfo) -> Vec<f32> {
289 if self.options.downmix == Downmix::Native {
290 return samples;
291 }
292 let layout = self.native_layout(info);
293 let positions = layout.positions().to_vec();
294 let channels = positions.len();
295 if channels == 0 {
296 return samples;
297 }
298 let clev = info.center_mix_level.unwrap_or(0.707);
299 let slev = info.surround_mix_level.unwrap_or(0.707);
300 // §7.8.2 with the standard's own coefficients, then one scaling so a
301 // full-scale input cannot overflow the downmix — the standard's fixed
302 // -7.65 dB would quieten every stereo listener instead.
303 let (mut left, mut right) = (Vec::new(), Vec::new());
304 for &p in &positions {
305 let (l, r) = match p {
306 ChannelPosition::FrontLeft => (1.0, 0.0),
307 ChannelPosition::FrontRight => (0.0, 1.0),
308 ChannelPosition::FrontCenter => (clev, clev),
309 ChannelPosition::BackLeft | ChannelPosition::SideLeft => (slev, 0.0),
310 ChannelPosition::BackRight | ChannelPosition::SideRight => (0.0, slev),
311 // A single surround channel feeds both sides at 0.7 × slev.
312 ChannelPosition::BackCenter => (0.7 * slev, 0.7 * slev),
313 // The LFE is not part of a §7.8.2 downmix.
314 _ => (0.0, 0.0),
315 };
316 left.push(l);
317 right.push(r);
318 }
319 let peak = left
320 .iter()
321 .sum::<f32>()
322 .max(right.iter().sum::<f32>())
323 .max(1.0);
324 let frames = samples.len() / channels;
325 match self.options.downmix {
326 Downmix::Stereo => {
327 let mut out = vec![0.0; frames * 2];
328 for f in 0..frames {
329 let block = &samples[f * channels..(f + 1) * channels];
330 let (mut lo, mut ro) = (0.0, 0.0);
331 for (ch, &v) in block.iter().enumerate() {
332 lo += v * left[ch];
333 ro += v * right[ch];
334 }
335 out[f * 2] = lo / peak;
336 out[f * 2 + 1] = ro / peak;
337 }
338 out
339 }
340 _ => {
341 let mut out = vec![0.0; frames];
342 for f in 0..frames {
343 let block = &samples[f * channels..(f + 1) * channels];
344 let mut m = 0.0;
345 for (ch, &v) in block.iter().enumerate() {
346 m += v * (left[ch] + right[ch]);
347 }
348 out[f] = m / (2.0 * peak);
349 }
350 out
351 }
352 }
353 }
354}
355
356impl Decoder for Ac3Decoder {
357 fn codec_parameters(&self) -> &CodecParameters {
358 &self.params
359 }
360
361 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
362 let mut frame = self.decode_frame(&packet.data)?;
363 frame.pts = packet.pts.map(|ts| Timestamp::new(ts, packet.time_base));
364 self.pending = Some(Frame::Audio(frame));
365 Ok(())
366 }
367
368 fn receive_frame(&mut self) -> Result<Frame> {
369 match self.pending.take() {
370 Some(frame) => Ok(frame),
371 None if self.flushed => Err(Error::Eof),
372 None => Err(Error::NeedMore),
373 }
374 }
375
376 fn flush(&mut self) -> Result<()> {
377 // Nothing is held back: one packet in, one frame out. The overlap-add
378 // tail belongs to the *next* frame, so there is no delayed frame to
379 // drain — draining it would emit a half block of silence.
380 self.flushed = true;
381 Ok(())
382 }
383
384 fn reset(&mut self) {
385 self.core.reset();
386 self.pending = None;
387 self.flushed = false;
388 }
389}