forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.5 MiBcdccbc2Tahinli12 hours ago4263 commits

dependent.rs272 lines, 10.7 KiBHistoryRawDownload
1//! E-AC-3 dependent substreams (Annex E, E.3.8): the channels a dependent
2//! substream adds to the frame its independent substream 0 starts.
3//!
4//! A dependent substream is an Annex E syncframe in its own right, with its
5//! own `audfrm()` and `audblk()`, so it is decoded by the same pipeline as an
6//! independent one, with a [`Core`](crate::decoder) of its own. What makes it a
7//! dependent is the custom channel map in its `bsi()`, which names the
8//! loudspeaker positions its coded channels fill.
9//!
10//! Placement follows ffmpeg (`ff_eac3_custom_channel_map_locations` and the
11//! custom-map code in `eac3dec.c`), which is the oracle the tests use:
12//!
13//! - The map is 16 bits, bit 15 (`0x8000`) first. Table E2.5, as a `u16`:
14//! `0x8000` L, `0x4000` C, `0x2000` R, `0x1000` Ls, `0x0800` Rs,
15//! `0x0400` Lc/Rc pair, `0x0200` Lrs/Rrs pair, `0x0100` Cs, `0x0080` Ts,
16//! `0x0040` Lsd/Rsd pair, `0x0020` Lw/Rw pair, `0x0010` Vhl/Vhr pair,
17//! `0x0008` Vhc, `0x0004` Lts/Rts pair, `0x0002` LFE2, `0x0001` LFE.
18//! - A position the independent substream already has replaces that channel.
19//! Any other position is added.
20//! - The frame's channels are output in the layout's canonical order, which is
21//! the bit order of the channel layout mask (see [`rank`]).
22//!
23//! Refused by name, never dropped in silence: a dependent substream without a
24//! custom channel map, or whose map names a position this build has no
25//! [`ChannelPosition`] for (Ts, Lsd/Rsd, Lw/Rw, Vhl/Vhr, Vhc, Lts/Rts, LFE2),
26//! is [`Error::Unsupported`]. A map whose channel count disagrees with the
27//! substream is [`Error::Corrupt`].
28
29use ec_core::{BitReader, ChannelPosition, Error, Result};
30
31use crate::bsi::Acmod;
32use crate::eac3::{self, Eac3Bsi, StreamType};
33use crate::syncinfo::SYNCWORD;
34
35/// One channel of a frame: where it plays, and one sample per sample frame.
36#[derive(Debug, Clone, PartialEq)]
37pub(crate) struct Channel {
38 pub(crate) position: ChannelPosition,
39 pub(crate) samples: Vec<f32>,
40}
41
42/// The header of the dependent substream that starts `data`, if one does.
43///
44/// Anything else (an independent syncframe, junk, a header that does not
45/// parse) is `None`, so the caller decides what a tail of bytes means.
46pub(crate) fn peek(data: &[u8]) -> Option<Eac3Bsi> {
47 // Six bytes are needed for the sync word and bsid; AC-3 (bsid <= 10) has
48 // no dependent substreams.
49 if data.len() < 6 || u16::from_be_bytes([data[0], data[1]]) != SYNCWORD || data[5] >> 3 <= 10 {
50 return None;
51 }
52 let hdr = eac3::parse_from(&mut BitReader::new(data)).ok()?;
53 (hdr.strmtyp == StreamType::Dependent).then_some(hdr)
54}
55
56/// The loudspeaker positions a dependent substream's `channels` coded channels
57/// fill, in coded order, from its custom channel map (Table E2.5).
58pub(crate) fn positions(map: Option<u16>, channels: usize, acmod: Acmod, lfeon: bool) -> Result<Vec<ChannelPosition>> {
59 use ChannelPosition::*;
60 let Some(map) = map else {
61 return Err(Error::unsupported(
62 "E-AC-3 dependent substream without a channel map",
63 "its channels have to be placed by the custom channel map (Table E2.5); \
64 without one this build cannot tell which loudspeakers they feed",
65 ));
66 };
67 // Bit `i` counted from the top (0x8000 is i = 0) names entry `i` of the
68 // table; a pair is two channels, in ascending canonical order.
69 let mut out = Vec::new();
70 for i in 0..16 {
71 if map & (0x8000 >> i) == 0 {
72 continue;
73 }
74 let names: &[ChannelPosition] = match i {
75 0 => &[FrontLeft],
76 1 => &[FrontCenter],
77 2 => &[FrontRight],
78 3 => &[SideLeft],
79 4 => &[SideRight],
80 5 => &[FrontLeftOfCenter, FrontRightOfCenter],
81 6 => &[BackLeft, BackRight],
82 7 => &[BackCenter],
83 15 => &[Lfe],
84 _ => {
85 return Err(Error::unsupported(
86 format!(
87 "E-AC-3 dependent substream: channel map {map:#06x} names {}",
88 unsupported_name(i)
89 ),
90 "that channel has no ChannelPosition in this build",
91 ));
92 }
93 };
94 out.extend_from_slice(names);
95 }
96 if out.len() != channels {
97 return Err(Error::corrupt(format!(
98 "E-AC-3 dependent substream: channel map {map:#06x} names {} channels, \
99 the substream carries {channels}",
100 out.len()
101 )));
102 }
103 let slots = slot_order(acmod, lfeon);
104 let mut placed = out.clone();
105 for (k, position) in out.into_iter().enumerate() {
106 placed[usize::from(slots[k])] = position;
107 }
108 Ok(placed)
109}
110
111fn slot_order(acmod: Acmod, lfeon: bool) -> &'static [u8] {
112 match (acmod, lfeon) {
113 (Acmod::DualMono | Acmod::Stereo, false) => &[0, 1],
114 (Acmod::DualMono | Acmod::Stereo, true) => &[0, 1, 2],
115 (Acmod::Mono, false) => &[0],
116 (Acmod::Mono, true) => &[0, 1],
117 (Acmod::Surround3_0, false) => &[0, 2, 1],
118 (Acmod::Surround3_0, true) => &[0, 2, 1, 3],
119 (Acmod::Surround2_1, false) => &[0, 1, 2],
120 (Acmod::Surround2_1, true) => &[0, 1, 3, 2],
121 (Acmod::Surround3_1, false) => &[0, 2, 1, 3],
122 (Acmod::Surround3_1, true) => &[0, 2, 1, 4, 3],
123 (Acmod::Surround2_2, false) => &[0, 1, 2, 3],
124 (Acmod::Surround2_2, true) => &[0, 1, 4, 2, 3],
125 (Acmod::Surround3_2, false) => &[0, 2, 1, 3, 4],
126 (Acmod::Surround3_2, true) => &[0, 2, 1, 5, 3, 4],
127 }
128}
129
130/// The Table E2.5 name of the map entry `i` that this build cannot place.
131fn unsupported_name(i: usize) -> &'static str {
132 match i {
133 8 => "Ts (0x0080)",
134 9 => "Lsd/Rsd (0x0040)",
135 10 => "Lw/Rw (0x0020)",
136 11 => "Vhl/Vhr (0x0010)",
137 12 => "Vhc (0x0008)",
138 13 => "Lts/Rts (0x0004)",
139 _ => "LFE2 (0x0002)",
140 }
141}
142
143/// Rank of a position in the canonical channel order (the bit order of the
144/// layout mask: FL FR FC LFE BL BR FLC FRC BC SL SR).
145fn rank(p: ChannelPosition) -> u8 {
146 use ChannelPosition::*;
147 match p {
148 FrontLeft => 0,
149 FrontRight => 1,
150 FrontCenter => 2,
151 Lfe => 3,
152 BackLeft => 4,
153 BackRight => 5,
154 FrontLeftOfCenter => 6,
155 FrontRightOfCenter => 7,
156 BackCenter => 8,
157 SideLeft => 9,
158 SideRight => 10,
159 }
160}
161
162/// Merge a dependent substream's channels into the frame's: a channel at a
163/// position the frame already has replaces that channel, any other is added.
164/// The result is in canonical channel order.
165pub(crate) fn merge(mut frame: Vec<Channel>, dependent: Vec<Channel>) -> Vec<Channel> {
166 for ch in dependent {
167 match frame.iter_mut().find(|c| c.position == ch.position) {
168 Some(slot) => slot.samples = ch.samples,
169 None => frame.push(ch),
170 }
171 }
172 frame.sort_by_key(|c| rank(c.position));
173 frame
174}
175
176/// De-interleave `samples`, which hold one value per position per sample
177/// frame, into one [`Channel`] per position.
178pub(crate) fn split(samples: &[f32], positions: &[ChannelPosition]) -> Vec<Channel> {
179 let n = positions.len();
180 positions
181 .iter()
182 .enumerate()
183 .map(|(c, &position)| Channel {
184 position,
185 samples: if n == 0 {
186 Vec::new()
187 } else {
188 samples.iter().skip(c).step_by(n).copied().collect()
189 },
190 })
191 .collect()
192}
193
194/// Interleave channels frame by frame. The frame count is the shortest
195/// channel, so unequal channels cannot index past their end.
196pub(crate) fn interleave(channels: &[Channel]) -> Vec<f32> {
197 let frames = channels.iter().map(|c| c.samples.len()).min().unwrap_or(0);
198 let mut out = Vec::with_capacity(frames * channels.len());
199 for f in 0..frames {
200 out.extend(channels.iter().map(|c| c.samples[f]));
201 }
202 out
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208 use ChannelPosition::*;
209
210 fn ch(position: ChannelPosition, v: f32) -> Channel {
211 Channel { position, samples: vec![v, v] }
212 }
213
214 #[test]
215 fn map_bits_name_positions_as_ffmpeg_does() {
216 assert_eq!(positions(Some(0x8000), 1, Acmod::Mono, false).unwrap(), vec![FrontLeft]);
217 assert_eq!(positions(Some(0x0400), 2, Acmod::Stereo, false).unwrap(), vec![FrontLeftOfCenter, FrontRightOfCenter]);
218 assert_eq!(positions(Some(0x0200), 2, Acmod::Stereo, false).unwrap(), vec![BackLeft, BackRight]);
219 assert_eq!(positions(Some(0x1800), 2, Acmod::Stereo, false).unwrap(), vec![SideLeft, SideRight]);
220 assert_eq!(positions(Some(0x0001), 1, Acmod::Mono, false).unwrap(), vec![Lfe]);
221 assert_eq!(positions(Some(0x8400), 3, Acmod::Surround2_1, false).unwrap(), vec![FrontLeft, FrontLeftOfCenter, FrontRightOfCenter]);
222 }
223
224 #[test]
225 fn unnamed_and_missing_maps_are_refused_by_name() {
226 for map in [None, Some(0x0080), Some(0x0040), Some(0x0010), Some(0x0004), Some(0x0002)] {
227 let err = positions(map, 2, Acmod::Stereo, false).expect_err("refused");
228 assert!(matches!(err, Error::Unsupported { .. }), "{map:?}: {err}");
229 }
230 }
231
232 #[test]
233 fn map_that_disagrees_with_the_channel_count_is_corrupt() {
234 assert!(matches!(positions(Some(0x1800), 1, Acmod::Mono, false), Err(Error::Corrupt { .. })));
235 assert!(matches!(positions(Some(0x0400), 3, Acmod::Surround2_1, false), Err(Error::Corrupt { .. })));
236 }
237
238 #[test]
239 fn merge_replaces_a_core_position_and_appends_the_rest_in_order() {
240 let core = vec![
241 ch(FrontLeft, 1.0),
242 ch(FrontRight, 2.0),
243 ch(FrontCenter, 3.0),
244 ch(Lfe, 4.0),
245 ch(BackLeft, 5.0),
246 ch(BackRight, 6.0),
247 ];
248 // Replace BL/BR, add SL/SR (the dependent lists them out of order).
249 let dep = vec![ch(BackLeft, 7.0), ch(BackRight, 8.0)];
250 let merged = merge(core.clone(), dep);
251 assert_eq!(merged.len(), 6);
252 assert_eq!(merged[4].samples, vec![7.0, 7.0]);
253 assert_eq!(merged[5].samples, vec![8.0, 8.0]);
254
255 let side = vec![ch(SideRight, 10.0), ch(SideLeft, 9.0)];
256 let merged = merge(core, side);
257 let order: Vec<_> = merged.iter().map(|c| c.position).collect();
258 assert_eq!(
259 order,
260 vec![FrontLeft, FrontRight, FrontCenter, Lfe, BackLeft, BackRight, SideLeft, SideRight]
261 );
262 assert_eq!(merged[6].samples, vec![9.0, 9.0]);
263 }
264
265 #[test]
266 fn split_and_interleave_round_trip() {
267 let interleaved = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; // 3 frames of 2 channels
268 let chans = split(&interleaved, &[FrontLeft, FrontRight]);
269 assert_eq!(chans[0].samples, vec![1.0, 3.0, 5.0]);
270 assert_eq!(interleave(&chans), interleaved.to_vec());
271 }
272}