forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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