forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

trim.rs272 lines, 10.1 KiBHistoryRawDownload
1//! Whole-file Ogg Vorbis decode through the `Decoder` trait, with the granule
2//! trim the decoder does itself. The oracle is ffmpeg (labelled as such: this
3//! is not a conformance claim).
4//!
5//! Files are encoded by ffmpeg's libvorbis from a sine of an exact length, so
6//! the length the stream states is known independently of either decoder.
7
8use std::fs::File;
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use ec_core::{Buf, Decoder, Demuxer, Frame, Packet, TimeBase};
13use ec_ogg::{OggDemuxer, granule_of, granule_side_data};
14use ec_vorbis::VorbisDecoder;
15
16fn scratch() -> PathBuf {
17 let dir = std::env::temp_dir().join(format!("ec-vorbis-trim-{}", std::process::id()));
18 std::fs::create_dir_all(&dir).expect("scratch dir");
19 dir
20}
21
22/// A sine of `seconds` at `rate`, libvorbis-encoded to `path`. Returns the
23/// number of sample frames the source holds.
24fn encode(path: &Path, rate: u32, channels: u32, seconds: f64) -> usize {
25 let status = Command::new("ffmpeg")
26 .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"])
27 .arg(format!(
28 "sine=frequency=440:sample_rate={rate}:duration={seconds}"
29 ))
30 .args([
31 "-ac",
32 &channels.to_string(),
33 "-c:a",
34 "libvorbis",
35 "-q:a",
36 "4",
37 ])
38 .arg(path)
39 .status()
40 .expect("ffmpeg");
41 assert!(
42 status.success(),
43 "ffmpeg could not encode {}",
44 path.display()
45 );
46 (f64::from(rate) * seconds).round() as usize
47}
48
49/// ffmpeg's own decode, planar f32, one vector per channel.
50fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
51 let out = Command::new("ffmpeg")
52 .args(["-nostdin", "-v", "error", "-i"])
53 .arg(path)
54 .args(["-map", "0:a:0", "-f", "f32le", "-"])
55 .output()
56 .expect("ffmpeg");
57 assert!(out.status.success(), "ffmpeg refused {}", path.display());
58 deinterleave(&out.stdout, channels)
59}
60
61fn deinterleave(bytes: &[u8], channels: usize) -> Vec<Vec<f32>> {
62 let mut planes = vec![Vec::new(); channels];
63 for (i, chunk) in bytes.as_chunks::<4>().0.iter().enumerate() {
64 planes[i % channels].push(f32::from_le_bytes(*chunk));
65 }
66 planes
67}
68
69/// The Ogg Vorbis file's headers and audio packets, in order, with the
70/// granule each packet carries (if any).
71struct Stream {
72 extradata: Buf,
73 channels: usize,
74 packets: Vec<(Vec<u8>, Option<i64>)>,
75}
76
77fn open(path: &Path) -> Stream {
78 let mut demuxer = OggDemuxer::open(File::open(path).expect("open")).expect("ogg");
79 let stream = demuxer
80 .streams()
81 .iter()
82 .find(|s| s.params.codec == ec_core::CodecId::Vorbis)
83 .expect("a Vorbis stream")
84 .clone();
85 let extradata = stream.params.extradata.clone().expect("headers");
86 let channels = stream.params.audio().expect("audio").layout.channel_count();
87 let mut packets = Vec::new();
88 loop {
89 let packet = match demuxer.next_packet() {
90 Ok(packet) => packet,
91 Err(e) if e.is_eof() => break,
92 Err(e) => panic!("demux {}: {e}", path.display()),
93 };
94 if packet.stream == stream.index {
95 packets.push((packet.data.to_vec(), granule_of(&packet)));
96 }
97 }
98 Stream {
99 extradata,
100 channels,
101 packets,
102 }
103}
104
105/// Run every packet through the `Decoder` trait, then flush, and answer the
106/// planar output. Frames are collected exactly as a consumer receives them.
107fn decode_through_trait(stream: &Stream, packets: &[(Vec<u8>, Option<i64>)]) -> Vec<Vec<f32>> {
108 let mut decoder = VorbisDecoder::from_extradata(&stream.extradata).expect("headers");
109 let mut planes = vec![Vec::new(); stream.channels];
110 let take = |decoder: &mut VorbisDecoder, planes: &mut Vec<Vec<f32>>| loop {
111 match decoder.receive_frame() {
112 Ok(Frame::Audio(frame)) => {
113 for (channel, plane) in planes.iter_mut().enumerate() {
114 let bytes = &frame.data[channel];
115 plane.extend(
116 bytes
117 .as_chunks::<4>()
118 .0
119 .iter()
120 .take(frame.samples)
121 .map(|c| f32::from_le_bytes(*c)),
122 );
123 }
124 }
125 Ok(Frame::Video(_)) => unreachable!("Vorbis decodes to audio only"),
126 Err(e) if e.is_need_more() || e.is_eof() => break,
127 Err(e) => panic!("receive_frame: {e}"),
128 }
129 };
130 let base = TimeBase::new(1, 1);
131 for (data, granule) in packets {
132 let mut packet = Packet::new(0, base, data.clone());
133 if let Some(granule) = granule {
134 packet.side_data.push(granule_side_data(*granule));
135 }
136 decoder.send_packet(&packet).expect("send_packet");
137 take(&mut decoder, &mut planes);
138 }
139 decoder.flush().expect("flush");
140 take(&mut decoder, &mut planes);
141 planes
142}
143
144/// Normalised cross-correlation of two signals over their common length.
145fn correlation(a: &[f32], b: &[f32]) -> f64 {
146 let (mut dot, mut na, mut nb) = (0.0f64, 0.0f64, 0.0f64);
147 for (&x, &y) in a.iter().zip(b) {
148 let (x, y) = (f64::from(x), f64::from(y));
149 dot += x * y;
150 na += x * x;
151 nb += y * y;
152 }
153 if na == 0.0 || nb == 0.0 {
154 return if na == nb { 1.0 } else { 0.0 };
155 }
156 dot / (na.sqrt() * nb.sqrt())
157}
158
159fn encoded(name: &str, rate: u32, channels: u32, seconds: f64) -> (PathBuf, usize) {
160 let path = scratch().join(name);
161 let len = encode(&path, rate, channels, seconds);
162 (path, len)
163}
164
165/// Multi-page files: the page granules say where each page ends, and the
166/// decoder's output must be exactly ffmpeg's length, sample for sample.
167#[test]
168fn whole_file_length_and_samples_match_ffmpeg() {
169 let mut failures = Vec::new();
170 for (rate, channels, seconds) in [
171 (44_100u32, 1u32, 1.234f64),
172 (44_100, 2, 2.5),
173 (48_000, 1, 2.5),
174 (48_000, 2, 3.0),
175 (48_000, 1, 1.234),
176 (44_100, 2, 1.234),
177 ] {
178 let name = format!("multi-{rate}-{channels}ch-{seconds}s.ogg");
179 let (path, _) = encoded(&name, rate, channels, seconds);
180 let stream = open(&path);
181 let theirs = ffmpeg_decode(&path, channels as usize);
182 let ours = decode_through_trait(&stream, &stream.packets);
183 if ours[0].len() != theirs[0].len() {
184 failures.push(format!(
185 "{name}: {} frames, ffmpeg {}",
186 ours[0].len(),
187 theirs[0].len()
188 ));
189 continue;
190 }
191 for (channel, (mine, reference)) in ours.iter().zip(theirs.iter()).enumerate() {
192 let corr = correlation(mine, reference);
193 if corr < 0.999 {
194 failures.push(format!("{name}: ch{channel} correlation {corr:.6}"));
195 }
196 }
197 }
198 assert!(failures.is_empty(), "{}", failures.join("\n"));
199}
200
201/// A file whose audio fits on one Ogg page carries only the final granule, so
202/// the decoder has nothing to anchor a head trim on: it emits exactly the
203/// granule's length from sample zero. ffmpeg 8 (libavformat) starts its own
204/// packet timeline 128 samples earlier on such files and decodes 128 fewer
205/// frames. The granule is the stream's own statement of its length, so the
206/// decoder follows it; the test checks that our samples agree with ffmpeg's
207/// where both have them.
208#[test]
209fn single_page_file_ends_at_its_granule() {
210 let mut failures = Vec::new();
211 for (rate, channels) in [(44_100u32, 1usize), (48_000, 2)] {
212 let name = format!("single-{rate}-{channels}ch.ogg");
213 let (path, want) = encoded(&name, rate, channels as u32, 1.0);
214 let stream = open(&path);
215 let theirs = ffmpeg_decode(&path, channels);
216 let ours = decode_through_trait(&stream, &stream.packets);
217 if ours[0].len() != want {
218 failures.push(format!(
219 "{name}: {} frames, granule states {want}",
220 ours[0].len()
221 ));
222 }
223 for (channel, (mine, reference)) in ours.iter().zip(theirs.iter()).enumerate() {
224 let corr = correlation(&mine[..reference.len().min(mine.len())], reference);
225 if corr < 0.999 {
226 failures.push(format!("{name}: ch{channel} correlation {corr:.6}"));
227 }
228 }
229 }
230 assert!(failures.is_empty(), "{}", failures.join("\n"));
231}
232
233/// A granule that lands before the decoded count on the first packet that
234/// produces output is a head trim: the decoder drops the samples before the
235/// stream's start. Built by moving the granule of that packet, so the expected
236/// output is known exactly from an untrimmed decode.
237#[test]
238fn granule_behind_the_first_output_trims_the_head() {
239 const K: i64 = 300;
240 let (path, want) = encoded("head-44100-2ch.ogg", 44_100, 2, 2.5);
241 let stream = open(&path);
242 let mut raw = VorbisDecoder::from_extradata(&stream.extradata).expect("headers");
243 let mut untrimmed = vec![Vec::new(); stream.channels];
244 let mut counts = Vec::new();
245 for (data, _) in &stream.packets {
246 let samples = raw.decode_audio(data).expect("decode");
247 counts.push(samples[0].len() as i64);
248 for (channel, plane) in samples.iter().enumerate() {
249 untrimmed[channel].extend_from_slice(plane);
250 }
251 }
252 // The first packet that produces output (packet 0 produces none).
253 let first_output = counts.iter().position(|&c| c > 0).expect("some output");
254 let decoded_through: i64 = counts[..=first_output].iter().sum();
255 assert!(
256 decoded_through > K,
257 "first output packet too short to trim {K} from"
258 );
259
260 let mut packets = stream.packets.clone();
261 packets[first_output].1 = Some(decoded_through - K);
262 let ours = decode_through_trait(&stream, &packets);
263
264 assert_eq!(ours[0].len(), want, "head trim changed the length");
265 for (channel, plane) in ours.iter().enumerate() {
266 let expect = &untrimmed[channel][K as usize..K as usize + want];
267 assert!(
268 plane == expect,
269 "ch{channel}: output is not the untrimmed decode from sample {K}"
270 );
271 }
272}