forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

edith_surface.rs151 lines, 6.3 KiBHistoryRawDownload
1//! The AC-3 path exactly as the replica drives it: read the rate and the
2//! layout out of the first syncframe's headers, ask the registry for a decoder
3//! folded to that layout, decode, and read the frame back as S16 little-endian
4//! (`engine/src/audio.rs:1954-2170`).
5//!
6//! Missing fixtures skip rather than fail, as the `ec-ac3` matrix does;
7//! `scripts/gen-fixtures.sh` writes them.
8
9use std::path::{Path, PathBuf};
10
11use oxideav_ac3::{bsi, eac3, register_codecs, syncinfo};
12use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Error, Frame, Packet, TimeBase};
13
14fn fixture(name: &str) -> Option<Vec<u8>> {
15 let path: PathBuf = Path::new(env!("CARGO_MANIFEST_DIR"))
16 .join("../../fixtures/audio")
17 .join(name);
18 std::fs::read(path).ok()
19}
20
21/// `engine/src/audio.rs:2130` — a fresh decoder out of a fresh registry.
22fn ac3_decoder(codec: &str, channels: Option<u16>) -> Box<dyn Decoder> {
23 let mut registry = CodecRegistry::new();
24 register_codecs(&mut registry);
25 let mut params = CodecParameters::audio(CodecId::new(codec));
26 params.channels = channels;
27 registry.first_decoder(&params).expect("no AC-3 decoder")
28}
29
30/// `engine/src/audio.rs:2150` — one syncframe in, interleaved `f32` and the
31/// frames per channel out; `None` when the decoder wants more input.
32fn decode_ac3(decoder: &mut Box<dyn Decoder>, bytes: &[u8]) -> Option<(Vec<f32>, u64)> {
33 let packet = Packet::new(0, TimeBase::new(1, 48_000), bytes.to_vec());
34 decoder.send_packet(&packet).expect("AC-3 decode failed");
35 match decoder.receive_frame() {
36 Ok(Frame::Audio(audio)) => Some((
37 audio.data[0]
38 .as_chunks::<2>()
39 .0
40 .iter()
41 .map(|s| f32::from(i16::from_le_bytes(*s)) / 32768.0)
42 .collect(),
43 u64::from(audio.samples),
44 )),
45 Ok(other) => panic!("AC-3 decoder handed back {other:?}"),
46 Err(Error::NeedMore) => None,
47 Err(e) => panic!("AC-3 decode failed: {e:?}"),
48 }
49}
50
51/// `engine/src/audio.rs:2061` — rate and `nfchans` out of the bit stream,
52/// whichever syntax it is.
53fn header(codec: &str, frame: &[u8]) -> (u32, usize) {
54 if codec == "eac3" {
55 let bsi = eac3::bsi::parse(frame.get(2..).unwrap_or_default()).expect("E-AC-3 bsi");
56 (bsi.sample_rate, bsi.nfchans)
57 } else {
58 let sync = syncinfo::parse(frame).expect("AC-3 syncinfo");
59 let bsi = bsi::parse(frame.get(5..).unwrap_or_default()).expect("AC-3 bsi");
60 (sync.sample_rate, bsi.nfchans)
61 }
62}
63
64fn rms(pcm: &[f32]) -> f64 {
65 (pcm.iter().map(|&v| f64::from(v) * f64::from(v)).sum::<f64>() / pcm.len().max(1) as f64).sqrt()
66}
67
68/// Every generated layout, opened the way a timeline source is opened: wider
69/// than mono folds to stereo, mono stays mono, and neither decodes to silence
70/// (the replica's mono `corner-cut` exists because the incumbent did).
71#[test]
72fn the_replicas_open_path_lands_on_audible_pcm() {
73 let cases = [
74 ("ac3-5.1-48000.ac3", "ac3", 48_000, 5, 2),
75 ("ac3-stereo-48000.ac3", "ac3", 48_000, 2, 2),
76 ("ac3-mono-44100.ac3", "ac3", 44_100, 1, 1),
77 ("eac3-5.1-48000.eac3", "eac3", 48_000, 5, 2),
78 ("eac3-mono-48000.eac3", "eac3", 48_000, 1, 1),
79 ];
80 let mut ran = 0;
81 for (name, codec, rate, nfchans_want, channels_want) in cases {
82 let Some(data) = fixture(name) else { continue };
83 ran += 1;
84
85 let (sample_rate, nfchans) = header(codec, &data);
86 assert_eq!(sample_rate, rate, "{name}: sample rate");
87 assert_eq!(nfchans, nfchans_want, "{name}: nfchans");
88
89 let requested = (nfchans > 1).then_some(2);
90 let mut decoder = ac3_decoder(codec, requested);
91 let (pcm, samples) = decode_ac3(&mut decoder, &data).expect("the first syncframe decoded");
92 let channels = (pcm.len() as u64 / samples.max(1)) as u16;
93 assert_eq!(channels, channels_want, "{name}: decoded channels");
94 assert!(samples > 0, "{name}: no samples");
95 assert!(rms(&pcm) > 1e-3, "{name}: decoded to silence, rms {}", rms(&pcm));
96
97 // The replica then feeds the rest of the stream frame by frame; a
98 // second frame proves the packet walk does not desync on the shim's
99 // conversion.
100 let size = ec_ac3::frame_size(&data).expect("frame size");
101 if let Some(next) = data.get(size..).filter(|rest| rest.len() > size) {
102 let (pcm, samples) = decode_ac3(&mut decoder, next).expect("the second syncframe");
103 assert_eq!((pcm.len() as u64 / samples.max(1)) as u16, channels_want);
104 }
105 }
106 assert!(ran > 0, "no AC-3 fixtures: run scripts/gen-fixtures.sh");
107}
108
109/// A packet holding two or three syncframes, handed over the registry's
110/// decoder the way the replica hands it packets: one call, one output frame.
111/// The samples are the frames decoded one at a time, back to back.
112#[test]
113fn a_packet_of_two_and_three_syncframes_decodes_to_its_frames() {
114 let cases = [
115 ("ac3-5.1-48000.ac3", "ac3", Some(2)),
116 ("eac3-5.1-48000.eac3", "eac3", Some(2)),
117 ];
118 let mut ran = 0;
119 for (name, codec, requested) in cases {
120 let Some(data) = fixture(name) else { continue };
121 ran += 1;
122 let mut frames = Vec::new();
123 let mut pos = 0;
124 while let Ok(len) = ec_ac3::frame_size(&data[pos..]) {
125 frames.push(&data[pos..pos + len]);
126 pos += len;
127 if frames.len() == 3 {
128 break;
129 }
130 }
131 assert_eq!(frames.len(), 3, "{name}: three syncframes");
132
133 let mut single = ac3_decoder(codec, requested);
134 let mut reference = Vec::new();
135 let mut reference_samples = 0;
136 for frame in &frames {
137 let (pcm, samples) = decode_ac3(&mut single, frame).expect("one frame");
138 reference.extend(pcm);
139 reference_samples += samples;
140 }
141
142 for n in [2usize, 3] {
143 let mut decoder = ac3_decoder(codec, requested);
144 let packet: Vec<u8> = frames[..n].concat();
145 let (pcm, samples) = decode_ac3(&mut decoder, &packet).expect("the packet decodes");
146 assert_eq!(samples, reference_samples / 3 * n as u64, "{name}: {n} frames, samples");
147 assert_eq!(pcm, reference[..pcm.len()], "{name}: {n} frames, PCM");
148 }
149 }
150 assert!(ran > 0, "no AC-3 fixtures: run scripts/gen-fixtures.sh");
151}