From cc3e0e3930d5919876b7d3ce5a56dc8b03140243 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 20 Aug 2026 17:08:39 +0300 Subject: [PATCH] fix(mp3): propagate real decode errors from Mp3Reader::take, and fix a test comparison that never saw them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 18 ++++++--- crates/ec-probe/tests/library.rs | 69 ++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 5 deletions(-) diff --git a/crates/ec-mp3/src/lib.rs b/crates/ec-mp3/src/lib.rs index fd966553..7a32715a 100644 --- a/crates/ec-mp3/src/lib.rs +++ b/crates/ec-mp3/src/lib.rs @@ -74,8 +74,17 @@ impl Mp3Decoder { }) } - fn take(&mut self) { - while let Ok(frame) = self.reader.next_frame() { + // Drains every complete frame the reservoir will yield. `NeedMore`/`Eof` + // just mean "nothing left to take yet" and end the loop quietly; any + // other error (corrupt CRC, unsupported layer) is real and must reach + // the caller rather than vanish here. + fn take(&mut self) -> Result<()> { + loop { + let frame = match self.reader.next_frame() { + Ok(frame) => frame, + Err(e) if e.is_need_more() || e.is_eof() => return Ok(()), + Err(e) => return Err(e), + }; if frame.samples.is_empty() { continue; } @@ -111,8 +120,7 @@ impl Decoder for Mp3Decoder { fn send_packet(&mut self, packet: &Packet) -> Result<()> { self.reader.push(packet.data.as_ref()); - self.take(); - Ok(()) + self.take() } fn receive_frame(&mut self) -> Result { @@ -127,7 +135,7 @@ impl Decoder for Mp3Decoder { } fn flush(&mut self) -> Result<()> { - self.take(); + self.take()?; self.drained = true; Ok(()) } diff --git a/crates/ec-probe/tests/library.rs b/crates/ec-probe/tests/library.rs index 4337e1d0..b5b5ea12 100644 --- a/crates/ec-probe/tests/library.rs +++ b/crates/ec-probe/tests/library.rs @@ -259,3 +259,72 @@ fn ffprobe_audio_codecs(path: &Path) -> Vec { .map(|l| l.trim().to_string()) .collect() } + +/// Cover-art (`APIC`) ID3v2 tags shipped by real rippers/taggers put a whole +/// image ahead of the first frame; opening must skip the tag by its own +/// syncsafe size and never confuse the codec/window prefixes it hunts for +/// sync in with that image's bytes. Matched against ffmpeg's own decode of +/// the same first second, not just "it opened". +#[test] +fn a_cover_art_tagged_mp3_opens() { + let path = Path::new("/home/user/Music/reeli.mp3"); + if !path.exists() { + eprintln!("file not present, skipping"); + return; + } + let mut reader = Reader::open(path).expect("open"); + let audio = reader + .default_stream(MediaType::Audio) + .cloned() + .expect("audio stream"); + let mut decoder = reader.make_decoder(audio.index).expect("decoder"); + let rate = decoder.sample_rate(); + let channels = decoder.channels().max(1) as u32; + // The raw decoder hands back every sample the bitstream carries, + // including the LAME/Xing encoder's lead-in; `initial_padding` (parsed + // from that header) is how many of them a player is meant to drop + // (ec-core registry.rs: "audible length is duration - initial_padding"). + // ffmpeg does that trim itself before writing PCM, so match it here. + let lead_in = audio.initial_padding * channels; + let mut ours = Vec::new(); + let mut scratch = Vec::new(); + let mut n = 0; + while (ours.len() as u32) < rate + lead_in { + let packet = match reader.next_packet() { + Ok(p) => p, + Err(e) => panic!("next_packet after {n} packets, {} samples: {e}", ours.len()), + }; + n += 1; + if packet.stream != audio.index { + continue; + } + decoder.decode(&packet, &mut scratch).expect("decode 1s"); + ours.extend_from_slice(&scratch); + } + let ours = &ours[lead_in as usize..]; + assert!(ours.len() as u32 >= rate / 2, "decoded too little audio"); + + let out = Command::new("ffmpeg") + .args(["-v", "error", "-t", "1", "-i"]) + .arg(path) + .args(["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .output() + .expect("ffmpeg runs"); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let theirs: Vec = out + .stdout + .chunks_exact(4) + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect(); + + let n = ours.len().min(theirs.len()); + let (mut num, mut a2, mut b2) = (0.0f64, 0.0f64, 0.0f64); + for i in 0..n { + let (a, b) = (ours[i] as f64, theirs[i] as f64); + num += a * b; + a2 += a * a; + b2 += b * b; + } + let corr = num / (a2.sqrt() * b2.sqrt()).max(1e-12); + assert!(corr >= 0.999, "corr vs ffmpeg = {corr}"); +}