forge
Explore
Log in

Don't you dare go Hollow

Propagate real decode errors from Mp3Reader::take, and fix a test comparison that never saw them

Browse files at this commit

cc3e0e3930d5919876b7d3ce5a56dc8b03140243Ahmet Kaan GümüşParent: 03a1069
  • fix
    • propagate real decode errors from Mp3Reader::take, and fix a test comparison that never saw them
Show full message
fix(mp3): propagate real decode errors from Mp3Reader::take, and fix a test comparison that never saw them

Root cause of the "open: NeedMore" symptom on this file was never in
ec-mp3's per-packet frame/reservoir bookkeeping — that already decodes
this cover-art-tagged, CRC-less 192kbps/48kHz stream correctly one
frame per packet, matching ffmpeg sample-for-sample once the LAME
encoder's lead-in is accounted for (measured lag 2210 interleaved
samples = 1105 stereo frames = exactly StreamInfo::initial_padding).

Two real bugs, both now fixed:

- Mp3Decoder::take() used `while let Ok(frame) = self.reader.next_frame()`,
  so any real decode error (corrupt CRC, unsupported layer) — not just
  the expected "nothing more yet" NeedMore/Eof — was silently dropped
  instead of reaching send_packet's caller. take() now returns Result
  and only swallows NeedMore/Eof.

- The new real-file regression test compared decoded audio against
  ffmpeg without accounting for initial_padding: ffmpeg trims the
  LAME/Xing encoder's lead-in from its PCM output; ec-mp3's raw decoder
  intentionally does not (registry.rs: callers must count and drop it
  themselves). The mismatch alone produced corr=0.53; trimming
  `initial_padding * channels` off the front before comparing gets
  corr>0.999.
crates/ec-mp3/src/lib.rsmodified+13 -5
@@ -74,8 +74,17 @@ impl Mp3Decoder {
7474 })
7575 }
7676
77- fn take(&mut self) {
78- while let Ok(frame) = self.reader.next_frame() {
77+ // Drains every complete frame the reservoir will yield. `NeedMore`/`Eof`
78+ // just mean "nothing left to take yet" and end the loop quietly; any
79+ // other error (corrupt CRC, unsupported layer) is real and must reach
80+ // the caller rather than vanish here.
81+ fn take(&mut self) -> Result<()> {
82+ loop {
83+ let frame = match self.reader.next_frame() {
84+ Ok(frame) => frame,
85+ Err(e) if e.is_need_more() || e.is_eof() => return Ok(()),
86+ Err(e) => return Err(e),
87+ };
7988 if frame.samples.is_empty() {
8089 continue;
8190 }
@@ -111,8 +120,7 @@ impl Decoder for Mp3Decoder {
111120
112121 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
113122 self.reader.push(packet.data.as_ref());
114- self.take();
115- Ok(())
123+ self.take()
116124 }
117125
118126 fn receive_frame(&mut self) -> Result<Frame> {
@@ -127,7 +135,7 @@ impl Decoder for Mp3Decoder {
127135 }
128136
129137 fn flush(&mut self) -> Result<()> {
130- self.take();
138+ self.take()?;
131139 self.drained = true;
132140 Ok(())
133141 }
crates/ec-probe/tests/library.rsmodified+69 -0
@@ -259,3 +259,72 @@ fn ffprobe_audio_codecs(path: &Path) -> Vec<String> {
259259 .map(|l| l.trim().to_string())
260260 .collect()
261261 }
262+
263+/// Cover-art (`APIC`) ID3v2 tags shipped by real rippers/taggers put a whole
264+/// image ahead of the first frame; opening must skip the tag by its own
265+/// syncsafe size and never confuse the codec/window prefixes it hunts for
266+/// sync in with that image's bytes. Matched against ffmpeg's own decode of
267+/// the same first second, not just "it opened".
268+#[test]
269+fn a_cover_art_tagged_mp3_opens() {
270+ let path = Path::new("/home/user/Music/reeli.mp3");
271+ if !path.exists() {
272+ eprintln!("file not present, skipping");
273+ return;
274+ }
275+ let mut reader = Reader::open(path).expect("open");
276+ let audio = reader
277+ .default_stream(MediaType::Audio)
278+ .cloned()
279+ .expect("audio stream");
280+ let mut decoder = reader.make_decoder(audio.index).expect("decoder");
281+ let rate = decoder.sample_rate();
282+ let channels = decoder.channels().max(1) as u32;
283+ // The raw decoder hands back every sample the bitstream carries,
284+ // including the LAME/Xing encoder's lead-in; `initial_padding` (parsed
285+ // from that header) is how many of them a player is meant to drop
286+ // (ec-core registry.rs: "audible length is duration - initial_padding").
287+ // ffmpeg does that trim itself before writing PCM, so match it here.
288+ let lead_in = audio.initial_padding * channels;
289+ let mut ours = Vec::new();
290+ let mut scratch = Vec::new();
291+ let mut n = 0;
292+ while (ours.len() as u32) < rate + lead_in {
293+ let packet = match reader.next_packet() {
294+ Ok(p) => p,
295+ Err(e) => panic!("next_packet after {n} packets, {} samples: {e}", ours.len()),
296+ };
297+ n += 1;
298+ if packet.stream != audio.index {
299+ continue;
300+ }
301+ decoder.decode(&packet, &mut scratch).expect("decode 1s");
302+ ours.extend_from_slice(&scratch);
303+ }
304+ let ours = &ours[lead_in as usize..];
305+ assert!(ours.len() as u32 >= rate / 2, "decoded too little audio");
306+
307+ let out = Command::new("ffmpeg")
308+ .args(["-v", "error", "-t", "1", "-i"])
309+ .arg(path)
310+ .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
311+ .output()
312+ .expect("ffmpeg runs");
313+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
314+ let theirs: Vec<f32> = out
315+ .stdout
316+ .chunks_exact(4)
317+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
318+ .collect();
319+
320+ let n = ours.len().min(theirs.len());
321+ let (mut num, mut a2, mut b2) = (0.0f64, 0.0f64, 0.0f64);
322+ for i in 0..n {
323+ let (a, b) = (ours[i] as f64, theirs[i] as f64);
324+ num += a * b;
325+ a2 += a * a;
326+ b2 += b * b;
327+ }
328+ let corr = num / (a2.sqrt() * b2.sqrt()).max(1e-12);
329+ assert!(corr >= 0.999, "corr vs ffmpeg = {corr}");
330+}