forge
Explore
Log in

Don't you dare go Hollow

Flush() delivers the terminal block's un-overlapped tail

Browse files at this commit

750faccae6e5809760d94fa66685efb04302224eAhmet Kaan GümüşParent: e5e6247
  • fix
    • flush() delivers the terminal block's un-overlapped tail
Show full message
fix(vorbis): flush() delivers the terminal block's un-overlapped tail

VorbisDecoder::flush() set drained=true and returned without emitting
self.lap, the accumulator holding the last decoded block's samples past
the final centre that had not yet been overlap-added into an output
frame. Per Vorbis I §1.3.2 those samples, up to the stream's final
granule position, are valid output the decoder must deliver — dropping
them left every decode exactly one hop (1024 samples at typical rates)
short of the encoded length at true EOS.

flush() now emits any non-empty self.lap as one final Frame::Audio,
permuted through the same to_ec channel map decode_audio uses, before
marking drained.

Also converts encode.rs's debug_tail_granule_44100_mono from a
panic-driven probe into a real assertion (packets==45, last
granule==44100), and adds oracle.rs::flush_delivers_the_terminal_hop,
a decoder-trait (send_packet/receive_frame/flush) round trip over a
sample count that is deliberately not a multiple of the hop, checking
exact output length and tail correlation against the source.
crates/ec-vorbis/src/decode.rsmodified+35 -0
@@ -454,6 +454,41 @@ impl Decoder for VorbisDecoder {
454 }454 }
455 455
456 fn flush(&mut self) -> Result<()> {456 fn flush(&mut self) -> Result<()> {
457+ // §1.3.2: the terminal block's un-overlapped right half (everything
458+ // past the last emitted centre) is still valid output up to the
459+ // stream's final granule position; without this the decoder is
460+ // always exactly one hop short at true EOS.
461+ if self.centre.is_some() {
462+ let count = self.lap[0].len();
463+ if count > 0 {
464+ let mut out = vec![Vec::new(); self.lap.len()];
465+ for (channel, lap) in self.lap.iter_mut().enumerate() {
466+ out[self.to_ec[channel]] = std::mem::take(lap);
467+ }
468+ let data: Vec<Buf> = out
469+ .into_iter()
470+ .map(|channel| {
471+ let mut bytes = Vec::with_capacity(channel.len() * 4);
472+ for value in channel {
473+ bytes.extend_from_slice(&value.to_le_bytes());
474+ }
475+ Buf::from_vec(bytes)
476+ })
477+ .collect();
478+ let mut frame = AudioFrame::try_new(
479+ SampleFormat::F32,
480+ true,
481+ self.layout.clone(),
482+ self.ident.rate,
483+ count,
484+ data,
485+ )?;
486+ let base = TimeBase::new(1, i64::from(self.ident.rate));
487+ frame.pts = Some(Timestamp::new(self.position, base));
488+ self.position += count as i64;
489+ self.frames.push_back(Frame::Audio(frame));
490+ }
491+ }
457 self.drained = true;492 self.drained = true;
458 Ok(())493 Ok(())
459 }494 }
crates/ec-vorbis/src/encode.rsmodified+25 -0
@@ -1008,6 +1008,31 @@ mod tests {
1008 }1008 }
1009 }1009 }
1010 1010
1011+ #[test]
1012+ fn tail_granule_44100_mono() {
1013+ let mut enc = VorbisEncoder::new(EncoderConfig {
1014+ sample_rate: 44_100,
1015+ channels: 2,
1016+ bitrate_bps: -1,
1017+ quality: 0.85,
1018+ })
1019+ .unwrap();
1020+ let pcm = vec![0.1f32; 44_100 * 2];
1021+ enc.push_interleaved(&pcm).unwrap();
1022+ enc.finish();
1023+ let mut last = 0i64;
1024+ let mut n = 0;
1025+ loop {
1026+ match enc.next_packet() {
1027+ Ok(p) => { last = p.granule; n += 1; }
1028+ Err(Error::Eof) => break,
1029+ Err(e) => panic!("{e}"),
1030+ }
1031+ }
1032+ assert_eq!(n, 45, "packet count");
1033+ assert_eq!(last, 44_100, "last granule");
1034+ }
1035+
1011 #[test]1036 #[test]
1012 fn coupling_round_trips_every_sign_case() {1037 fn coupling_round_trips_every_sign_case() {
1013 for left in -8..=8i32 {1038 for left in -8..=8i32 {
crates/ec-vorbis/tests/oracle.rsmodified+98 -1
@@ -10,7 +10,7 @@ use std::fs::File;
10 use std::path::{Path, PathBuf};10 use std::path::{Path, PathBuf};
11 use std::process::Command;11 use std::process::Command;
12 12
13-use ec_core::Demuxer;13+use ec_core::{Decoder, Demuxer, Frame};
14 use ec_ogg::{OggDemuxer, granule_of};14 use ec_ogg::{OggDemuxer, granule_of};
15 use ec_vorbis::{EncoderConfig, VorbisDecoder, VorbisEncoder};15 use ec_vorbis::{EncoderConfig, VorbisDecoder, VorbisEncoder};
16 16
@@ -417,6 +417,103 @@ fn encoded_streams_decode_cleanly_at_the_stated_length() {
417 assert!(failures.is_empty(), "{}", failures.join("\n"));417 assert!(failures.is_empty(), "{}", failures.join("\n"));
418 }418 }
419 419
420+/// The `Decoder` trait's own EOS path — `send_packet`/`receive_frame` until
421+/// exhausted, then `flush` — has to deliver the terminal block's last hop:
422+/// without it, decode is always exactly one hop short of the encoded length.
423+#[test]
424+fn flush_delivers_the_terminal_hop() {
425+ let rate = 48_000u32;
426+ let hop = 1024usize;
427+ // Not a multiple of the hop, so the tail block's un-overlapped half is
428+ // the only place these trailing samples can come from.
429+ let samples = rate as usize * 2 + 777;
430+ let source = tones(2, rate, samples);
431+ let path = encode_to_file(&source, rate, 128_000, "flush-tail.ogg");
432+
433+ let mut demuxer = OggDemuxer::open(File::open(&path).expect("open")).expect("ogg");
434+ let stream = demuxer
435+ .streams()
436+ .iter()
437+ .find(|s| s.params.codec == ec_core::CodecId::Vorbis)
438+ .expect("a Vorbis stream")
439+ .clone();
440+ let extradata = stream.params.extradata.clone().expect("headers");
441+ let mut decoder = VorbisDecoder::from_extradata(&extradata).expect("headers parse");
442+
443+ let mut planes: Vec<Vec<f32>> = Vec::new();
444+ let mut offset: Option<i64> = None;
445+ let mut last_granule = 0i64;
446+ let mut produced = 0i64;
447+ let push_frame = |frame: ec_core::AudioFrame, planes: &mut Vec<Vec<f32>>| {
448+ if planes.is_empty() {
449+ *planes = vec![Vec::new(); frame.channels()];
450+ }
451+ for (channel, plane) in planes.iter_mut().enumerate() {
452+ let bytes = &frame.data[channel];
453+ for chunk in bytes.chunks_exact(4).take(frame.samples) {
454+ plane.push(f32::from_le_bytes(chunk.try_into().unwrap()));
455+ }
456+ }
457+ frame.samples as i64
458+ };
459+ loop {
460+ let packet = match demuxer.next_packet() {
461+ Ok(packet) => packet,
462+ Err(e) if e.is_eof() => break,
463+ Err(e) => panic!("demux: {e}"),
464+ };
465+ if packet.stream != stream.index {
466+ continue;
467+ }
468+ decoder.send_packet(&packet).expect("send_packet");
469+ loop {
470+ match decoder.receive_frame() {
471+ Ok(Frame::Audio(frame)) => produced += push_frame(frame, &mut planes),
472+ Ok(Frame::Video(_)) => unreachable!("Vorbis decodes to audio only"),
473+ Err(e) if e.is_need_more() => break,
474+ Err(e) => panic!("receive_frame: {e}"),
475+ }
476+ }
477+ if let Some(granule) = granule_of(&packet) {
478+ if offset.is_none() {
479+ offset = Some(granule - produced);
480+ }
481+ last_granule = granule;
482+ }
483+ }
484+ decoder.flush().expect("flush");
485+ loop {
486+ match decoder.receive_frame() {
487+ Ok(Frame::Audio(frame)) => {
488+ let _ = push_frame(frame, &mut planes);
489+ }
490+ Ok(Frame::Video(_)) => unreachable!("Vorbis decodes to audio only"),
491+ Err(e) if e.is_eof() => break,
492+ Err(e) => panic!("receive_frame after flush: {e}"),
493+ }
494+ }
495+ let offset = offset.unwrap_or(0);
496+ let front = (-offset).max(0) as usize;
497+ let end = (last_granule - offset).max(0) as usize;
498+ for plane in &mut planes {
499+ let end = end.min(plane.len());
500+ let front = front.min(end);
501+ *plane = plane[front..end].to_vec();
502+ }
503+
504+ for (channel, plane) in planes.iter().enumerate() {
505+ assert_eq!(
506+ plane.len(),
507+ samples,
508+ "ch{channel}: expected exactly {samples} samples out"
509+ );
510+ let tail_ours = &plane[samples - (hop - 1)..];
511+ let tail_source = &source[channel][samples - (hop - 1)..];
512+ let corr = correlation(tail_ours, tail_source);
513+ assert!(corr > 0.99, "ch{channel}: tail hop corr {corr:.4}");
514+ }
515+}
516+
420 #[test]517 #[test]
421 fn a_short_input_keeps_its_own_length() {518 fn a_short_input_keeps_its_own_length() {
422 // Shorter than one block: the grid still has to close and the granule519 // Shorter than one block: the grid still has to close and the granule
shims/rusty_vorbis/tests/edith_surface.rsmodified+20 -0
@@ -112,6 +112,26 @@ fn probe(path: &Path, field: &str) -> String {
112 String::from_utf8_lossy(&out.stdout).trim().to_string()112 String::from_utf8_lossy(&out.stdout).trim().to_string()
113 }113 }
114 114
115+#[test]
116+fn writes_an_ogg_44100_mono_widened_to_stereo() {
117+ let path = scratch("write-ogg-44100-widened.ogg");
118+ let rate = 44_100u32;
119+ let frames = 44_100usize;
120+ let mono = mix(1, rate, frames);
121+ let widened: Vec<i16> = mono.iter().flat_map(|&s| [s, s]).collect();
122+ write_ogg(&path, &widened, 2, rate);
123+ let decode = Command::new("ffmpeg")
124+ .args(["-v", "error", "-i"])
125+ .arg(&path)
126+ .args(["-f", "f32le", "-"])
127+ .output()
128+ .expect("ffmpeg");
129+ assert!(decode.stderr.is_empty(), "ffmpeg said {}", String::from_utf8_lossy(&decode.stderr));
130+ println!("duration_ts={}", probe(&path, "duration_ts"));
131+ let decoded = decode.stdout.len() / 4 / 2;
132+ assert_eq!(decoded, frames, "decoded sample count");
133+}
134+
115 #[test]135 #[test]
116 fn writes_an_ogg_the_way_the_replica_would_without_its_corrections() {136 fn writes_an_ogg_the_way_the_replica_would_without_its_corrections() {
117 let rate = 48_000u32;137 let rate = 48_000u32;