forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

bsi.rs325 lines, 10.1 KiBHistoryRawDownload
1//! `bsi()` — AC-3 bit stream information (A/52 §5.3.2), including the
2//! alternate syntax of Annex D that `bsid == 6` streams carry.
3
4use ec_core::{BitReader, Error, Result};
5
6use crate::tables;
7
8/// Audio coding mode (Table 5.8): how many channels there are and where.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10pub enum Acmod {
11 /// 1+1: two completely independent programs (dual mono).
12 DualMono,
13 /// 1/0: centre only.
14 Mono,
15 /// 2/0: left, right.
16 #[default]
17 Stereo,
18 /// 3/0: left, centre, right.
19 Surround3_0,
20 /// 2/1: left, right, mono surround.
21 Surround2_1,
22 /// 3/1: left, centre, right, mono surround.
23 Surround3_1,
24 /// 2/2: left, right, left surround, right surround.
25 Surround2_2,
26 /// 3/2: left, centre, right, left surround, right surround.
27 Surround3_2,
28}
29
30impl Acmod {
31 /// The raw 3-bit code.
32 pub fn code(self) -> u8 {
33 self as u8
34 }
35
36 /// From the raw 3-bit code; anything wider is masked to 3 bits.
37 pub fn from_code(code: u8) -> Acmod {
38 match code & 7 {
39 0 => Acmod::DualMono,
40 1 => Acmod::Mono,
41 2 => Acmod::Stereo,
42 3 => Acmod::Surround3_0,
43 4 => Acmod::Surround2_1,
44 5 => Acmod::Surround3_1,
45 6 => Acmod::Surround2_2,
46 _ => Acmod::Surround3_2,
47 }
48 }
49
50 /// Full-bandwidth channels, excluding the LFE.
51 pub fn nfchans(self) -> usize {
52 tables::NFCHANS[self.code() as usize]
53 }
54
55 /// True when a centre channel is coded (acmod 3, 5, 7).
56 pub fn has_center(self) -> bool {
57 matches!(self.code(), 3 | 5 | 7)
58 }
59
60 /// Number of surround channels coded: 0, 1 (mono surround) or 2.
61 pub fn surround_channels(self) -> usize {
62 match self.code() {
63 4 | 5 => 1,
64 6 | 7 => 2,
65 _ => 0,
66 }
67 }
68}
69
70/// Centre mix level in linear gain (Table 5.9). The reserved code takes the
71/// middle value, as §7.8.2 instructs.
72pub fn center_mix_level(cmixlev: u8) -> f32 {
73 match cmixlev {
74 0 => 0.707,
75 2 => 0.500,
76 _ => 0.595,
77 }
78}
79
80/// Surround mix level in linear gain (Table 5.10). The reserved code takes the
81/// middle value, as §7.8.2 instructs.
82pub fn surround_mix_level(surmixlev: u8) -> f32 {
83 match surmixlev {
84 0 => 0.707,
85 2 => 0.0,
86 _ => 0.500,
87 }
88}
89
90/// Everything `bsi()` carries. Optional fields are [`None`] when their
91/// presence bit was clear, which is the difference between "the encoder said
92/// 0 dB" and "the encoder said nothing".
93#[derive(Debug, Clone, PartialEq, Eq, Default)]
94pub struct Bsi {
95 /// Bit stream identification: 8 for standard AC-3, 6 for the Annex D
96 /// alternate syntax, 16 for E-AC-3 (which uses [`crate::eac3::bsi`]).
97 pub bsid: u8,
98 /// Bit stream mode (Table 5.7).
99 pub bsmod: u8,
100 /// Audio coding mode.
101 pub acmod: Acmod,
102 /// Centre mix level code, present with three front channels.
103 pub cmixlev: Option<u8>,
104 /// Surround mix level code, present with a surround channel.
105 pub surmixlev: Option<u8>,
106 /// Dolby Surround mode, present in 2/0.
107 pub dsurmod: Option<u8>,
108 /// LFE channel present.
109 pub lfeon: bool,
110 /// Dialogue normalisation, in -dB below full scale (1..=31).
111 pub dialnorm: u8,
112 /// Heavy compression gain word.
113 pub compr: Option<u8>,
114 /// Language code (deprecated by the standard, still carried).
115 pub langcod: Option<u8>,
116 /// Mixing level in dB SPL, when audio production info is present.
117 pub mixlevel: Option<u8>,
118 /// Room type, when audio production info is present.
119 pub roomtyp: Option<u8>,
120 /// Second program's dialogue normalisation, in 1+1 mode.
121 pub dialnorm2: Option<u8>,
122 /// Second program's heavy compression gain word, in 1+1 mode.
123 pub compr2: Option<u8>,
124 /// Copyright bit.
125 pub copyrightb: bool,
126 /// Original bit stream bit.
127 pub origbs: bool,
128 /// Preferred stereo downmix mode (Annex D `dmixmod`).
129 pub dmixmod: Option<u8>,
130 /// Lt/Rt centre and surround mix levels (Annex D).
131 pub ltrt_mixlev: Option<(u8, u8)>,
132 /// Lo/Ro centre and surround mix levels (Annex D).
133 pub loro_mixlev: Option<(u8, u8)>,
134 /// Dolby Surround EX mode (Annex D `dsurexmod`).
135 pub dsurexmod: Option<u8>,
136 /// Full-bandwidth channels, excluding the LFE.
137 pub nfchans: usize,
138 /// Coded channels including the LFE — what a decoder hands out natively.
139 pub channels: usize,
140}
141
142/// Parse `bsi()` from the bits that follow `syncinfo()`.
143///
144/// `data` starts at the first byte after the five `syncinfo()` bytes, which is
145/// how every caller has it: `bsi::parse(&frame[5..])`.
146pub fn parse(data: &[u8]) -> Result<Bsi> {
147 parse_from(&mut BitReader::new(data))
148}
149
150/// [`parse`] against a reader the caller keeps, so a decoder can carry on into
151/// the first audio block on the same bit position.
152pub fn parse_from(r: &mut BitReader<'_>) -> Result<Bsi> {
153 let bsid = r.read_bits(5)? as u8;
154 if bsid > 10 {
155 return Err(Error::unsupported(
156 format!("AC-3 bsi: bsid = {bsid}"),
157 "bsid above 10 is Enhanced AC-3; parse it with eac3::bsi",
158 ));
159 }
160 let bsmod = r.read_bits(3)? as u8;
161 let acmod = Acmod::from_code(r.read_bits(3)? as u8);
162 let cmixlev = (acmod.code() & 1 != 0 && acmod.code() != 1)
163 .then(|| r.read_bits(2))
164 .transpose()?
165 .map(|v| v as u8);
166 let surmixlev = (acmod.code() & 4 != 0)
167 .then(|| r.read_bits(2))
168 .transpose()?
169 .map(|v| v as u8);
170 let dsurmod = (acmod == Acmod::Stereo)
171 .then(|| r.read_bits(2))
172 .transpose()?
173 .map(|v| v as u8);
174 let lfeon = r.read_bit()?;
175 let dialnorm = r.read_bits(5)? as u8;
176 let compr = read_optional(r, 8)?;
177 let langcod = read_optional(r, 8)?;
178 let (mixlevel, roomtyp) = if r.read_bit()? {
179 (Some(r.read_bits(5)? as u8), Some(r.read_bits(2)? as u8))
180 } else {
181 (None, None)
182 };
183 let (mut dialnorm2, mut compr2) = (None, None);
184 if acmod == Acmod::DualMono {
185 dialnorm2 = Some(r.read_bits(5)? as u8);
186 compr2 = read_optional(r, 8)?;
187 let _langcod2 = read_optional(r, 8)?;
188 if r.read_bit()? {
189 let _mixlevel2 = r.read_bits(5)?;
190 let _roomtyp2 = r.read_bits(2)?;
191 }
192 }
193 let copyrightb = r.read_bit()?;
194 let origbs = r.read_bit()?;
195
196 let mut bsi = Bsi {
197 bsid,
198 bsmod,
199 acmod,
200 cmixlev,
201 surmixlev,
202 dsurmod,
203 lfeon,
204 dialnorm,
205 compr,
206 langcod,
207 mixlevel,
208 roomtyp,
209 dialnorm2,
210 compr2,
211 copyrightb,
212 origbs,
213 dmixmod: None,
214 ltrt_mixlev: None,
215 loro_mixlev: None,
216 dsurexmod: None,
217 nfchans: acmod.nfchans(),
218 channels: acmod.nfchans() + usize::from(lfeon),
219 };
220
221 if bsid == 6 {
222 // Annex D: the time code fields are replaced by the extra mix and
223 // downmix metadata a modern encoder actually has to say.
224 if r.read_bit()? {
225 bsi.dmixmod = Some(r.read_bits(2)? as u8);
226 bsi.ltrt_mixlev = Some((r.read_bits(3)? as u8, r.read_bits(3)? as u8));
227 bsi.loro_mixlev = Some((r.read_bits(3)? as u8, r.read_bits(3)? as u8));
228 }
229 if r.read_bit()? {
230 bsi.dsurexmod = Some(r.read_bits(2)? as u8);
231 let _dheadphonmod = r.read_bits(2)?;
232 let _adconvtyp = r.read_bit()?;
233 let _xbsi2 = r.read_bits(8)?;
234 let _encinfo = r.read_bit()?;
235 }
236 } else {
237 if r.read_bit()? {
238 let _timecod1 = r.read_bits(14)?;
239 }
240 if r.read_bit()? {
241 let _timecod2 = r.read_bits(14)?;
242 }
243 }
244 if r.read_bit()? {
245 let addbsil = r.read_bits(6)? as u64;
246 r.skip_bits((addbsil + 1) * 8)?;
247 }
248 Ok(bsi)
249}
250
251/// A presence bit followed by an `n`-bit value.
252fn read_optional(r: &mut BitReader<'_>, n: u32) -> Result<Option<u8>> {
253 if r.read_bit()? {
254 Ok(Some(r.read_bits(n)? as u8))
255 } else {
256 Ok(None)
257 }
258}
259
260#[cfg(test)]
261mod tests {
262 use super::*;
263 use ec_core::BitWriter;
264
265 fn write_minimal_bsi(bsid: u8, acmod: u8, lfeon: bool, dialnorm: u8) -> Vec<u8> {
266 let mut w = BitWriter::new();
267 w.write_bits(u32::from(bsid), 5);
268 w.write_bits(0, 3); // bsmod
269 w.write_bits(u32::from(acmod), 3);
270 if acmod & 1 != 0 && acmod != 1 {
271 w.write_bits(1, 2); // cmixlev
272 }
273 if acmod & 4 != 0 {
274 w.write_bits(0, 2); // surmixlev
275 }
276 if acmod == 2 {
277 w.write_bits(0, 2); // dsurmod
278 }
279 w.write_bit(lfeon);
280 w.write_bits(u32::from(dialnorm), 5);
281 w.write_bit(false); // compre
282 w.write_bit(false); // langcode
283 w.write_bit(false); // audprodie
284 w.write_bit(false); // copyrightb
285 w.write_bit(false); // origbs
286 w.write_bit(false); // timecod1e
287 w.write_bit(false); // timecod2e
288 w.write_bit(false); // addbsie
289 w.align_to_byte();
290 w.into_bytes()
291 }
292
293 #[test]
294 fn parses_a_5_1_header() {
295 let bytes = write_minimal_bsi(8, 7, true, 27);
296 let bsi = parse(&bytes).unwrap();
297 assert_eq!(bsi.acmod, Acmod::Surround3_2);
298 assert_eq!(bsi.nfchans, 5);
299 assert!(bsi.lfeon);
300 assert_eq!(bsi.channels, 6);
301 assert_eq!(bsi.dialnorm, 27);
302 assert_eq!(bsi.cmixlev, Some(1));
303 assert_eq!(bsi.surmixlev, Some(0));
304 }
305
306 #[test]
307 fn parses_mono_and_refuses_eac3_bsid() {
308 let bsi = parse(&write_minimal_bsi(8, 1, false, 31)).unwrap();
309 assert_eq!(bsi.acmod, Acmod::Mono);
310 assert_eq!(bsi.channels, 1);
311 assert!(matches!(
312 parse(&write_minimal_bsi(16, 7, true, 27)),
313 Err(Error::Unsupported { .. })
314 ));
315 assert!(matches!(parse(&[]), Err(Error::NeedMore)));
316 }
317
318 #[test]
319 fn mix_levels_follow_tables_5_9_and_5_10() {
320 assert_eq!(center_mix_level(0), 0.707);
321 assert_eq!(center_mix_level(2), 0.500);
322 assert_eq!(center_mix_level(3), center_mix_level(1));
323 assert_eq!(surround_mix_level(2), 0.0);
324 }
325}