diff --git a/crates/ec-vorbis/src/decode.rs b/crates/ec-vorbis/src/decode.rs index 2860173c..29e7ec8c 100644 --- a/crates/ec-vorbis/src/decode.rs +++ b/crates/ec-vorbis/src/decode.rs @@ -454,6 +454,41 @@ impl Decoder for VorbisDecoder { } fn flush(&mut self) -> Result<()> { + // §1.3.2: the terminal block's un-overlapped right half (everything + // past the last emitted centre) is still valid output up to the + // stream's final granule position; without this the decoder is + // always exactly one hop short at true EOS. + if self.centre.is_some() { + let count = self.lap[0].len(); + if count > 0 { + let mut out = vec![Vec::new(); self.lap.len()]; + for (channel, lap) in self.lap.iter_mut().enumerate() { + out[self.to_ec[channel]] = std::mem::take(lap); + } + let data: Vec = out + .into_iter() + .map(|channel| { + let mut bytes = Vec::with_capacity(channel.len() * 4); + for value in channel { + bytes.extend_from_slice(&value.to_le_bytes()); + } + Buf::from_vec(bytes) + }) + .collect(); + let mut frame = AudioFrame::try_new( + SampleFormat::F32, + true, + self.layout.clone(), + self.ident.rate, + count, + data, + )?; + let base = TimeBase::new(1, i64::from(self.ident.rate)); + frame.pts = Some(Timestamp::new(self.position, base)); + self.position += count as i64; + self.frames.push_back(Frame::Audio(frame)); + } + } self.drained = true; Ok(()) } diff --git a/crates/ec-vorbis/src/encode.rs b/crates/ec-vorbis/src/encode.rs index 8d593417..cac5a7ec 100644 --- a/crates/ec-vorbis/src/encode.rs +++ b/crates/ec-vorbis/src/encode.rs @@ -1008,6 +1008,31 @@ mod tests { } } + #[test] + fn tail_granule_44100_mono() { + let mut enc = VorbisEncoder::new(EncoderConfig { + sample_rate: 44_100, + channels: 2, + bitrate_bps: -1, + quality: 0.85, + }) + .unwrap(); + let pcm = vec![0.1f32; 44_100 * 2]; + enc.push_interleaved(&pcm).unwrap(); + enc.finish(); + let mut last = 0i64; + let mut n = 0; + loop { + match enc.next_packet() { + Ok(p) => { last = p.granule; n += 1; } + Err(Error::Eof) => break, + Err(e) => panic!("{e}"), + } + } + assert_eq!(n, 45, "packet count"); + assert_eq!(last, 44_100, "last granule"); + } + #[test] fn coupling_round_trips_every_sign_case() { for left in -8..=8i32 { diff --git a/crates/ec-vorbis/tests/oracle.rs b/crates/ec-vorbis/tests/oracle.rs index 44bb66f4..15610b0a 100644 --- a/crates/ec-vorbis/tests/oracle.rs +++ b/crates/ec-vorbis/tests/oracle.rs @@ -10,7 +10,7 @@ use std::fs::File; use std::path::{Path, PathBuf}; use std::process::Command; -use ec_core::Demuxer; +use ec_core::{Decoder, Demuxer, Frame}; use ec_ogg::{OggDemuxer, granule_of}; use ec_vorbis::{EncoderConfig, VorbisDecoder, VorbisEncoder}; @@ -417,6 +417,103 @@ fn encoded_streams_decode_cleanly_at_the_stated_length() { assert!(failures.is_empty(), "{}", failures.join("\n")); } +/// The `Decoder` trait's own EOS path — `send_packet`/`receive_frame` until +/// exhausted, then `flush` — has to deliver the terminal block's last hop: +/// without it, decode is always exactly one hop short of the encoded length. +#[test] +fn flush_delivers_the_terminal_hop() { + let rate = 48_000u32; + let hop = 1024usize; + // Not a multiple of the hop, so the tail block's un-overlapped half is + // the only place these trailing samples can come from. + let samples = rate as usize * 2 + 777; + let source = tones(2, rate, samples); + let path = encode_to_file(&source, rate, 128_000, "flush-tail.ogg"); + + let mut demuxer = OggDemuxer::open(File::open(&path).expect("open")).expect("ogg"); + let stream = demuxer + .streams() + .iter() + .find(|s| s.params.codec == ec_core::CodecId::Vorbis) + .expect("a Vorbis stream") + .clone(); + let extradata = stream.params.extradata.clone().expect("headers"); + let mut decoder = VorbisDecoder::from_extradata(&extradata).expect("headers parse"); + + let mut planes: Vec> = Vec::new(); + let mut offset: Option = None; + let mut last_granule = 0i64; + let mut produced = 0i64; + let push_frame = |frame: ec_core::AudioFrame, planes: &mut Vec>| { + if planes.is_empty() { + *planes = vec![Vec::new(); frame.channels()]; + } + for (channel, plane) in planes.iter_mut().enumerate() { + let bytes = &frame.data[channel]; + for chunk in bytes.chunks_exact(4).take(frame.samples) { + plane.push(f32::from_le_bytes(chunk.try_into().unwrap())); + } + } + frame.samples as i64 + }; + loop { + let packet = match demuxer.next_packet() { + Ok(packet) => packet, + Err(e) if e.is_eof() => break, + Err(e) => panic!("demux: {e}"), + }; + if packet.stream != stream.index { + continue; + } + decoder.send_packet(&packet).expect("send_packet"); + loop { + match decoder.receive_frame() { + Ok(Frame::Audio(frame)) => produced += push_frame(frame, &mut planes), + Ok(Frame::Video(_)) => unreachable!("Vorbis decodes to audio only"), + Err(e) if e.is_need_more() => break, + Err(e) => panic!("receive_frame: {e}"), + } + } + if let Some(granule) = granule_of(&packet) { + if offset.is_none() { + offset = Some(granule - produced); + } + last_granule = granule; + } + } + decoder.flush().expect("flush"); + loop { + match decoder.receive_frame() { + Ok(Frame::Audio(frame)) => { + let _ = push_frame(frame, &mut planes); + } + Ok(Frame::Video(_)) => unreachable!("Vorbis decodes to audio only"), + Err(e) if e.is_eof() => break, + Err(e) => panic!("receive_frame after flush: {e}"), + } + } + let offset = offset.unwrap_or(0); + let front = (-offset).max(0) as usize; + let end = (last_granule - offset).max(0) as usize; + for plane in &mut planes { + let end = end.min(plane.len()); + let front = front.min(end); + *plane = plane[front..end].to_vec(); + } + + for (channel, plane) in planes.iter().enumerate() { + assert_eq!( + plane.len(), + samples, + "ch{channel}: expected exactly {samples} samples out" + ); + let tail_ours = &plane[samples - (hop - 1)..]; + let tail_source = &source[channel][samples - (hop - 1)..]; + let corr = correlation(tail_ours, tail_source); + assert!(corr > 0.99, "ch{channel}: tail hop corr {corr:.4}"); + } +} + #[test] fn a_short_input_keeps_its_own_length() { // Shorter than one block: the grid still has to close and the granule diff --git a/shims/rusty_vorbis/tests/edith_surface.rs b/shims/rusty_vorbis/tests/edith_surface.rs index 313cb1d9..dda4b081 100644 --- a/shims/rusty_vorbis/tests/edith_surface.rs +++ b/shims/rusty_vorbis/tests/edith_surface.rs @@ -112,6 +112,26 @@ fn probe(path: &Path, field: &str) -> String { String::from_utf8_lossy(&out.stdout).trim().to_string() } +#[test] +fn writes_an_ogg_44100_mono_widened_to_stereo() { + let path = scratch("write-ogg-44100-widened.ogg"); + let rate = 44_100u32; + let frames = 44_100usize; + let mono = mix(1, rate, frames); + let widened: Vec = mono.iter().flat_map(|&s| [s, s]).collect(); + write_ogg(&path, &widened, 2, rate); + let decode = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(&path) + .args(["-f", "f32le", "-"]) + .output() + .expect("ffmpeg"); + assert!(decode.stderr.is_empty(), "ffmpeg said {}", String::from_utf8_lossy(&decode.stderr)); + println!("duration_ts={}", probe(&path, "duration_ts")); + let decoded = decode.stdout.len() / 4 / 2; + assert_eq!(decoded, frames, "decoded sample count"); +} + #[test] fn writes_an_ogg_the_way_the_replica_would_without_its_corrections() { let rate = 48_000u32;