forge
Explore
Log in

Don't you dare go Hollow

Expose Ac3Encoder on the family's export-facing shape

Browse files at this commit

1466a62e15261439803afa055b3e05a15e8c7e40Ahmet Kaan GümüşParent: 18654e6
  • feat
    • expose Ac3Encoder on the family's export-facing shape
Show full message
feat(ac3-enc-shim): expose Ac3Encoder on the family's export-facing shape

Ac3Encoder had zero callers outside crates/ec-ac3 -- the shim only wrapped
the decoder. Add new/push_pcm_f32/finish/next_packet/encoder_delay at the
same shape as rusty_aac's AacEncoder, the pattern an export path already
drives, plus a round trip test (encode 1s stereo, decode through this
shim's own decoder, corr >=0.99 past encoder_delay()).
shims/oxideav-ac3/src/lib.rsmodified+122 -0
@@ -23,6 +23,12 @@
23 //! [`CodecParameters::channels`] and `ec_ac3` takes a [`Downmix`] mode; the23 //! [`CodecParameters::channels`] and `ec_ac3` takes a [`Downmix`] mode; the
24 //! factory translates. `Some(2)` is the A/52 §7.8 stereo fold the replica24 //! 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.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.
26 32
27 #![forbid(unsafe_code)]33 #![forbid(unsafe_code)]
28 34
@@ -101,6 +107,49 @@ fn s16le(samples: &[u8]) -> Vec<u8> {
101 out107 out
102 }108 }
103 109
110+/// How [`Ac3Encoder::new`] is configured.
111+pub 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.
118+pub struct Ac3Encoder(ec_ac3::Ac3Encoder);
119+
120+impl 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+
104 #[cfg(test)]153 #[cfg(test)]
105 mod tests {154 mod tests {
106 use super::*;155 use super::*;
@@ -126,4 +175,77 @@ mod tests {
126 assert!(registry.has_decoder(&CodecId::new("eac3")));175 assert!(registry.has_decoder(&CodecId::new("eac3")));
127 assert!(!registry.has_decoder(&CodecId::new("truehd")));176 assert!(!registry.has_decoder(&CodecId::new("truehd")));
128 }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+ loop {
199+ match enc.next_packet() {
200+ Ok(packet) => bitstream.extend_from_slice(&packet),
201+ Err(_) => break,
202+ }
203+ }
204+
205+ let mut registry = CodecRegistry::new();
206+ register_codecs(&mut registry);
207+ let params = CodecParameters {
208+ channels: Some(2),
209+ ..CodecParameters::audio(CodecId::new("ac3"))
210+ };
211+ let mut dec = registry.first_decoder(&params).unwrap();
212+
213+ let mut decoded_s16: Vec<i16> = Vec::new();
214+ let mut offset = 0;
215+ while offset < bitstream.len() {
216+ let len = ec_ac3::frame_size(&bitstream[offset..]).unwrap();
217+ let packet = oxideav_core::Packet::new(
218+ 0,
219+ oxideav_core::TimeBase::new(1, sample_rate.into()),
220+ bitstream[offset..offset + len].to_vec(),
221+ );
222+ dec.send_packet(&packet).unwrap();
223+ offset += len;
224+ while let Ok(Frame::Audio(frame)) = dec.receive_frame() {
225+ for plane in &frame.data {
226+ decoded_s16.extend(plane.chunks_exact(2).map(|b| i16::from_le_bytes([b[0], b[1]])));
227+ }
228+ }
229+ }
230+ let decoded: Vec<f32> = decoded_s16.iter().map(|&s| s as f32 / 32768.0).collect();
231+
232+ // Drop the encoder's priming delay (one block, both channels).
233+ let delay = enc.encoder_delay() * 2;
234+ let decoded = &decoded[delay.min(decoded.len())..];
235+ let source = &pcm[..decoded.len().min(pcm.len())];
236+ let decoded = &decoded[..source.len()];
237+
238+ let mean_s = source.iter().sum::<f32>() / source.len() as f32;
239+ let mean_d = decoded.iter().sum::<f32>() / decoded.len() as f32;
240+ let mut num = 0.0f64;
241+ let (mut den_s, mut den_d) = (0.0f64, 0.0f64);
242+ for (&s, &d) in source.iter().zip(decoded.iter()) {
243+ let (s, d) = ((s - mean_s) as f64, (d - mean_d) as f64);
244+ num += s * d;
245+ den_s += s * s;
246+ den_d += d * d;
247+ }
248+ let corr = num / (den_s.sqrt() * den_d.sqrt());
249+ assert!(corr >= 0.99, "round-trip correlation too low: {corr}");
250+ }
129 }251 }