forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

lib.rs129 lines, 4.9 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#![forbid(unsafe_code)]
28
29pub use ec_ac3::{bsi, eac3, syncinfo};
30
31use ec_ac3::{Downmix, Options};
32use oxideav_core::{
33 AudioFrame, CodecId, CodecInfo, CodecParameters, CodecRegistry, Decoder, Frame, Packet, Result,
34};
35
36/// Register this crate's codecs — `ac3` and `eac3` — into `registry`.
37///
38/// Both ids reach the same decoder: it dispatches per packet on `bsid`, so the
39/// id picks the capability set and not the syntax.
40pub fn register_codecs(registry: &mut CodecRegistry) {
41 for id in ["ac3", "eac3"] {
42 registry.register(CodecInfo::new(CodecId::new(id)).decoder(open));
43 }
44}
45
46/// A decoder for `params`, folded down to `params.channels`.
47fn open(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
48 let options = Options {
49 downmix: match params.channels {
50 Some(1) => Downmix::Mono,
51 Some(2) => Downmix::Stereo,
52 _ => Downmix::Native,
53 },
54 ..Options::default()
55 };
56 Ok(Box::new(Ac3Decoder {
57 id: params.codec_id.clone(),
58 inner: ec_ac3::Ac3Decoder::with_options(options),
59 }))
60}
61
62/// The family's AC-3 decoder: one syncframe in, one S16 little-endian frame
63/// out.
64struct Ac3Decoder {
65 id: CodecId,
66 inner: ec_ac3::Ac3Decoder,
67}
68
69impl Decoder for Ac3Decoder {
70 fn codec_id(&self) -> &CodecId {
71 &self.id
72 }
73
74 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
75 Ok(ec_core::Decoder::send_packet(&mut self.inner, packet)?)
76 }
77
78 fn receive_frame(&mut self) -> Result<Frame> {
79 match ec_core::Decoder::receive_frame(&mut self.inner)? {
80 ec_core::Frame::Audio(audio) => Ok(Frame::Audio(AudioFrame {
81 samples: audio.samples as u32,
82 pts: audio.pts.map(|ts| ts.ticks),
83 data: audio.data.iter().map(|plane| s16le(plane)).collect(),
84 })),
85 other => Ok(other.into()),
86 }
87 }
88}
89
90/// Interleaved `f32` bytes as S16 little-endian, which is what the incumbent
91/// speaks. Full scale is 32768 in both directions, saturating: the replica's
92/// inverse is `/32768.0`, and a sample at or past `+1.0` has to land on
93/// `i16::MAX` rather than wrap to silence.
94fn s16le(samples: &[u8]) -> Vec<u8> {
95 let mut out = Vec::with_capacity(samples.len() / 2);
96 for chunk in samples.chunks_exact(4) {
97 let v = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
98 let scaled = (v * 32768.0).round().clamp(-32768.0, 32767.0) as i16;
99 out.extend_from_slice(&scaled.to_le_bytes());
100 }
101 out
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 #[test]
109 fn full_scale_saturates_instead_of_wrapping() {
110 let pcm: Vec<u8> = [-1.5f32, -1.0, 0.0, 0.5, 1.0, 1.5]
111 .iter()
112 .flat_map(|v| v.to_le_bytes())
113 .collect();
114 let got: Vec<i16> = s16le(&pcm)
115 .chunks_exact(2)
116 .map(|s| i16::from_le_bytes([s[0], s[1]]))
117 .collect();
118 assert_eq!(got, [-32768, -32768, 0, 16384, 32767, 32767]);
119 }
120
121 #[test]
122 fn both_ids_are_registered_and_a_third_is_not() {
123 let mut registry = CodecRegistry::new();
124 register_codecs(&mut registry);
125 assert!(registry.has_decoder(&CodecId::new("ac3")));
126 assert!(registry.has_decoder(&CodecId::new("eac3")));
127 assert!(!registry.has_decoder(&CodecId::new("truehd")));
128 }
129}