forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

lib.rs248 lines, 9.4 KiBHistoryRawDownload
1//! `oxideav-ac3` as edith consumes it, over [`ec_ac3`].
2//!
3//! A shim, not a port: it carries the incumbent's package name and version so
4//! the swap is a `[patch.crates-io]` line, and it exposes exactly the items the
5//! replica names — the header surface it reads a track's rate and layout out of
6//! ([`syncinfo::parse`], [`bsi::parse`], [`eac3::bsi::parse`], `audio.rs:1954`,
7//! `2063`) and [`register_codecs`], which is how it gets a decoder at all
8//! (`audio.rs:2132`). The header modules are `ec_ac3`'s own: their signatures,
9//! their entry offsets (`bsi` after the five `syncinfo()` bytes, `eac3::bsi`
10//! after the 16-bit sync word) and their fields already match what the replica
11//! writes, so a re-export is the whole adapter.
12//!
13//! Two differences are owned here rather than at the call site:
14//!
15//! * **Sample format.** The incumbent hands out S16 little-endian and the
16//! replica reads it as such (`audio.rs:2160`, `chunks_exact(2)` over
17//! `/32768.0`); `ec_ac3` decodes to `f32`. The conversion is
18//! [`Ac3Decoder::receive_frame`], once, for every caller — which is why this
19//! shim writes its own [`oxideav_core::Decoder`] instead of wrapping
20//! `oxideav_core::EcDecoder`, whose job is the frames that need no
21//! conversion.
22//! * **Downmix request.** The incumbent takes the wanted channel count on
23//! [`CodecParameters::channels`] and `ec_ac3` takes a [`Downmix`] mode; the
24//! factory translates. `Some(2)` is the A/52 §7.8 stereo fold the replica
25//! asks for on anything wider than mono, `None` the stream's own layout.
26//!
27//! Encoding is not on the incumbent's own surface, so [`Ac3Encoder`] is
28//! shaped after this family's other software encoder shim instead —
29//! `rusty_aac::AacEncoder`'s `new`/`push_pcm_f32`/`next_packet`/
30//! `encoder_delay` — so an export path already wired to one SW audio
31//! encoder here can add this one the same way.
32
33#![forbid(unsafe_code)]
34
35pub use ec_ac3::{bsi, eac3, syncinfo};
36
37use ec_ac3::{Downmix, Options};
38use oxideav_core::{
39 AudioFrame, CodecId, CodecInfo, CodecParameters, CodecRegistry, Decoder, Frame, Packet, Result,
40};
41
42/// Register this crate's codecs — `ac3` and `eac3` — into `registry`.
43///
44/// Both ids reach the same decoder: it dispatches per packet on `bsid`, so the
45/// id picks the capability set and not the syntax.
46pub fn register_codecs(registry: &mut CodecRegistry) {
47 for id in ["ac3", "eac3"] {
48 registry.register(CodecInfo::new(CodecId::new(id)).decoder(open));
49 }
50}
51
52/// A decoder for `params`, folded down to `params.channels`.
53fn open(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
54 let options = Options {
55 downmix: match params.channels {
56 Some(1) => Downmix::Mono,
57 Some(2) => Downmix::Stereo,
58 _ => Downmix::Native,
59 },
60 ..Options::default()
61 };
62 Ok(Box::new(Ac3Decoder {
63 id: params.codec_id.clone(),
64 inner: ec_ac3::Ac3Decoder::with_options(options),
65 }))
66}
67
68/// The family's AC-3 decoder: one syncframe in, one S16 little-endian frame
69/// out.
70struct Ac3Decoder {
71 id: CodecId,
72 inner: ec_ac3::Ac3Decoder,
73}
74
75impl Decoder for Ac3Decoder {
76 fn codec_id(&self) -> &CodecId {
77 &self.id
78 }
79
80 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
81 Ok(ec_core::Decoder::send_packet(&mut self.inner, packet)?)
82 }
83
84 fn receive_frame(&mut self) -> Result<Frame> {
85 match ec_core::Decoder::receive_frame(&mut self.inner)? {
86 ec_core::Frame::Audio(audio) => Ok(Frame::Audio(AudioFrame {
87 samples: audio.samples as u32,
88 pts: audio.pts.map(|ts| ts.ticks),
89 data: audio.data.iter().map(|plane| s16le(plane)).collect(),
90 })),
91 other => Ok(other.into()),
92 }
93 }
94}
95
96/// Interleaved `f32` bytes as S16 little-endian, which is what the incumbent
97/// speaks. Full scale is 32768 in both directions, saturating: the replica's
98/// inverse is `/32768.0`, and a sample at or past `+1.0` has to land on
99/// `i16::MAX` rather than wrap to silence.
100fn s16le(samples: &[u8]) -> Vec<u8> {
101 let mut out = Vec::with_capacity(samples.len() / 2);
102 for chunk in samples.chunks_exact(4) {
103 let v = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
104 let scaled = (v * 32768.0).round().clamp(-32768.0, 32767.0) as i16;
105 out.extend_from_slice(&scaled.to_le_bytes());
106 }
107 out
108}
109
110/// How [`Ac3Encoder::new`] is configured.
111pub struct EncoderConfig {
112 pub sample_rate: u32,
113 pub channels: u16,
114 pub bitrate_kbps: u32,
115}
116
117/// An AC-3 encoder: PCM in, syncframes out.
118pub struct Ac3Encoder(ec_ac3::Ac3Encoder);
119
120impl Ac3Encoder {
121 pub fn new(sample_rate: u32, channels: u16, bitrate_kbps: u32) -> Result<Ac3Encoder> {
122 Ok(Ac3Encoder(ec_ac3::Ac3Encoder::new(ec_ac3::EncoderConfig {
123 sample_rate,
124 channels,
125 bitrate_kbps,
126 })?))
127 }
128
129 /// Samples of priming delay before the first audible one; a muxer states
130 /// this on the track's edit list / codec delay.
131 pub fn encoder_delay(&self) -> usize {
132 self.0.encoder_delay()
133 }
134
135 /// Feeds interleaved `f32` PCM, family order (L, R, C, LFE, Ls, Rs).
136 pub fn push_pcm_f32(&mut self, interleaved: &[f32]) -> Result<()> {
137 Ok(self.0.push_pcm_f32(interleaved)?)
138 }
139
140 /// Ends the stream, padding and flushing the last frame.
141 pub fn finish(&mut self) {
142 self.0.finish();
143 }
144
145 /// The next encoded syncframe; [`oxideav_core::Error`] with the
146 /// underlying `Eof`/`NeedMore` distinction once drained after
147 /// [`Ac3Encoder::finish`] or before enough PCM has arrived.
148 pub fn next_packet(&mut self) -> Result<Vec<u8>> {
149 Ok(self.0.next_packet()?)
150 }
151}
152
153#[cfg(test)]
154mod tests {
155 use super::*;
156
157 #[test]
158 fn full_scale_saturates_instead_of_wrapping() {
159 let pcm: Vec<u8> = [-1.5f32, -1.0, 0.0, 0.5, 1.0, 1.5]
160 .iter()
161 .flat_map(|v| v.to_le_bytes())
162 .collect();
163 let got: Vec<i16> = s16le(&pcm)
164 .chunks_exact(2)
165 .map(|s| i16::from_le_bytes([s[0], s[1]]))
166 .collect();
167 assert_eq!(got, [-32768, -32768, 0, 16384, 32767, 32767]);
168 }
169
170 #[test]
171 fn both_ids_are_registered_and_a_third_is_not() {
172 let mut registry = CodecRegistry::new();
173 register_codecs(&mut registry);
174 assert!(registry.has_decoder(&CodecId::new("ac3")));
175 assert!(registry.has_decoder(&CodecId::new("eac3")));
176 assert!(!registry.has_decoder(&CodecId::new("truehd")));
177 }
178
179 /// One second of stereo through [`Ac3Encoder`], then back through this
180 /// shim's own decoder: after dropping the encoder's priming delay, the
181 /// two channels should still correlate almost perfectly with the source.
182 #[test]
183 fn encode_then_decode_round_trips() {
184 let sample_rate = 48000u32;
185 let seconds = 1.0f32;
186 let n = (sample_rate as f32 * seconds) as usize;
187 let mut pcm = vec![0.0f32; n * 2];
188 for i in 0..n {
189 let t = i as f32 / sample_rate as f32;
190 pcm[2 * i] = 0.4 * (2.0 * std::f32::consts::PI * 440.0 * t).sin();
191 pcm[2 * i + 1] = 0.4 * (2.0 * std::f32::consts::PI * 660.0 * t).sin();
192 }
193
194 let mut enc = Ac3Encoder::new(sample_rate, 2, 192).unwrap();
195 enc.push_pcm_f32(&pcm).unwrap();
196 enc.finish();
197 let mut bitstream = Vec::new();
198 while let Ok(packet) = enc.next_packet() {
199 bitstream.extend_from_slice(&packet);
200 }
201
202 let mut registry = CodecRegistry::new();
203 register_codecs(&mut registry);
204 let params = CodecParameters {
205 channels: Some(2),
206 ..CodecParameters::audio(CodecId::new("ac3"))
207 };
208 let mut dec = registry.first_decoder(&params).unwrap();
209
210 let mut decoded_s16: Vec<i16> = Vec::new();
211 let mut offset = 0;
212 while offset < bitstream.len() {
213 let len = ec_ac3::frame_size(&bitstream[offset..]).unwrap();
214 let packet = oxideav_core::Packet::new(
215 0,
216 oxideav_core::TimeBase::new(1, sample_rate.into()),
217 bitstream[offset..offset + len].to_vec(),
218 );
219 dec.send_packet(&packet).unwrap();
220 offset += len;
221 while let Ok(Frame::Audio(frame)) = dec.receive_frame() {
222 for plane in &frame.data {
223 decoded_s16.extend(plane.chunks_exact(2).map(|b| i16::from_le_bytes([b[0], b[1]])));
224 }
225 }
226 }
227 let decoded: Vec<f32> = decoded_s16.iter().map(|&s| s as f32 / 32768.0).collect();
228
229 // Drop the encoder's priming delay (one block, both channels).
230 let delay = enc.encoder_delay() * 2;
231 let decoded = &decoded[delay.min(decoded.len())..];
232 let source = &pcm[..decoded.len().min(pcm.len())];
233 let decoded = &decoded[..source.len()];
234
235 let mean_s = source.iter().sum::<f32>() / source.len() as f32;
236 let mean_d = decoded.iter().sum::<f32>() / decoded.len() as f32;
237 let mut num = 0.0f64;
238 let (mut den_s, mut den_d) = (0.0f64, 0.0f64);
239 for (&s, &d) in source.iter().zip(decoded.iter()) {
240 let (s, d) = ((s - mean_s) as f64, (d - mean_d) as f64);
241 num += s * d;
242 den_s += s * s;
243 den_d += d * d;
244 }
245 let corr = num / (den_s.sqrt() * den_d.sqrt());
246 assert!(corr >= 0.99, "round-trip correlation too low: {corr}");
247 }
248}