diff --git a/Cargo.lock b/Cargo.lock index dca8720c..8475d2cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1240,7 +1240,9 @@ name = "symphonia" version = "0.6.0" dependencies = [ "ec-core", + "ec-ogg", "ec-probe", + "ec-vorbis", "symphonia-codec-aac", "symphonia-core", ] diff --git a/crates/ec-probe/src/decoder.rs b/crates/ec-probe/src/decoder.rs index 33bf624a..c5b149bc 100644 --- a/crates/ec-probe/src/decoder.rs +++ b/crates/ec-probe/src/decoder.rs @@ -31,6 +31,37 @@ pub struct AudioDecoder { codec: CodecId, channels: usize, sample_rate: u32, + /// Raw interleaved frames the decoder has produced so far, before any + /// trim — the running clock the front-offset calculation below measures + /// against. + produced: i64, + /// Frames actually handed out to the caller so far. + emitted: i64, + /// `granule - produced` at the first packet whose granule is known: a + /// Vorbis stream's very first pages account for the encoder's pre-roll in + /// their granule, so this is the one-time head start (or catch-up) the + /// decoder's own count needed to line up with the container's. + /// + /// This is a front offset only. An *interior* page's granule marks where + /// the last packet completed *on that page* ends — not a ceiling every + /// later page's cumulative output must stay under, since packets can span + /// pages and pages can end mid-packet. Only the first granule (front) and + /// the last one (tail, at [`Self::flush`]) are trustworthy trim points. + trim_offset: Option, + /// The last granule [`Self::decode`] saw, carried into [`Self::flush`] + /// for the terminal packet's own trim: the flush call's packet (the + /// reader's synthetic end-of-stream marker) carries no granule of its own. + last_granule: Option, + /// The most recently decoded packet's own audio, held back one call + /// rather than handed to the caller straight away: Vorbis's terminal + /// packet routinely decodes real samples past the container's true final + /// granule (its own block reaches further than the stream actually + /// runs), and so does [`Self::flush`]'s un-overlapped tail on top of it. + /// Once a packet's audio has left this decoder there is nothing left to + /// trim it from, so the last packet's audio waits here — combined with + /// the flush tail — for [`Self::flush`] to cut both down to the file's + /// real length in one go. + held: Vec, } impl std::fmt::Debug for AudioDecoder { @@ -109,6 +140,11 @@ impl AudioDecoder { CodecId::Opus => 48_000, _ => sample_rate, }, + produced: 0, + emitted: 0, + trim_offset: None, + last_granule: None, + held: Vec::new(), }) } @@ -160,9 +196,105 @@ impl AudioDecoder { } Inner::Pcm(codec) => pcm(*codec, &packet.data, out), } + self.trim(ec_ogg::granule_of(packet), out); + // Only Vorbis holds real, un-overlapped state across a packet + // boundary that a stream-final granule can still need to reach into + // (see `held`'s own doc); every other codec here releases its audio + // the moment it is decoded, exactly as before, so a caller that never + // calls `flush` still gets every packet's worth back. + if matches!(self.inner, Inner::Vorbis(_)) { + std::mem::swap(&mut self.held, out); + } + self.emitted += out.len() as i64 / self.channels.max(1) as i64; + Ok(()) + } + + /// The one-off front trim: only the very first packet this decoder ever + /// sees can carry a legitimate pre-roll offset (`granule` at real stream + /// position zero). Most containers' first *audio* packet carries no + /// granule at all — pages tend to end well into the block run — so once + /// any later packet is the first to reveal one, that granule is an + /// interior page mark, not a front offset: subtracting it from what has + /// already been decoded would blame ordinary block-to-block lag on a + /// pre-roll that was never there, and can trim away a whole packet's + /// worth of real audio. Every later packet passes through untouched — an + /// interior page's granule is not a per-page ceiling (see + /// [`Self::trim_offset`]); only [`Self::flush`]'s tail trim cuts again. + fn trim(&mut self, granule: Option, out: &mut Vec) { + let channels = self.channels.max(1) as i64; + let raw_frames = out.len() as i64 / channels; + if let Some(granule) = granule { + self.last_granule = Some(granule); + if self.trim_offset.is_none() { + if self.produced == 0 { + let offset = (granule - raw_frames).max(0); + self.trim_offset = Some(offset); + if offset > 0 { + let drop = (offset.min(raw_frames) * channels) as usize; + out.drain(0..drop); + } + } else { + // Too late for a real front offset: this stream's first + // audio packet already went by with no granule on it. + self.trim_offset = Some(0); + } + } + } + self.produced += raw_frames; + } + + /// Signal end of stream and take whatever the decoder was holding back. + /// + /// Every codec here that overlaps blocks (Vorbis above all: its terminal + /// block's un-overlapped right half is real audio up to the stream's + /// final granule, and is otherwise always exactly one hop short) needs + /// this told to it once the packets have run out, or the last hop never + /// comes out at all. `out` is cleared first, same as [`Self::decode`]. + /// + /// [`Self::held`] (the last packet's own audio, never yet released) is + /// combined with whatever this call's own flush produces, and the pair + /// are cut down together to the stream's real final granule — the last + /// [`Self::decode`] call's packet is routinely the one this trim needs to + /// reach into, and once its audio had left this decoder that was no + /// longer possible. + pub fn flush(&mut self, out: &mut Vec) -> Result<()> { + out.clear(); + match &mut self.inner { + Inner::Flac(d) => flush_drain(d.as_mut(), out)?, + Inner::Mp3(d) => flush_drain(d.as_mut(), out)?, + Inner::Vorbis(d) => flush_drain(d.as_mut(), out)?, + Inner::Ac3(d) => flush_drain(d.as_mut(), out)?, + // AAC, ALAC, Opus and PCM decode a packet at a time with nothing + // held back across the end of the file. + Inner::Aac(_) | Inner::Alac(_) | Inner::Opus(_) | Inner::Pcm(_) => {} + } + let channels = self.channels.max(1) as i64; + self.produced += out.len() as i64 / channels; + let mut combined = std::mem::take(&mut self.held); + combined.append(out); + self.trim_tail(&combined, out); Ok(()) } + /// The terminal trim: the stream's last granule minus the front offset + /// is the file's true total frame count, so whatever `combined` (the + /// held-back last packet plus the flush tail) still has past that is + /// dropped rather than handed to the caller. + fn trim_tail(&mut self, combined: &[f32], out: &mut Vec) { + let channels = self.channels.max(1) as i64; + let raw_frames = combined.len() as i64 / channels; + let keep = match self.last_granule { + Some(granule) => { + let offset = self.trim_offset.unwrap_or(0); + let target = (granule - offset).max(0); + (target - self.emitted).clamp(0, raw_frames) + } + None => raw_frames, + }; + out.extend_from_slice(&combined[..(keep * channels).max(0) as usize]); + self.emitted += keep; + } + /// Drop everything buffered from before a seek. pub fn reset(&mut self) { match &mut self.inner { @@ -175,6 +307,11 @@ impl AudioDecoder { Inner::Opus(d) => d.reset(), Inner::Pcm(_) => {} } + self.held.clear(); + self.produced = 0; + self.emitted = 0; + self.trim_offset = None; + self.last_granule = None; } } @@ -219,6 +356,17 @@ fn is_pcm(codec: CodecId) -> bool { /// yields, converted to interleaved `f32`. fn drain(decoder: &mut dyn Decoder, packet: &Packet, out: &mut Vec) -> Result<()> { decoder.send_packet(packet)?; + drain_frames(decoder, out) +} + +/// [`ec_core::Decoder::flush`], then every frame it releases because of it. +fn flush_drain(decoder: &mut dyn Decoder, out: &mut Vec) -> Result<()> { + decoder.flush()?; + drain_frames(decoder, out) +} + +/// Every frame currently ready, converted to interleaved `f32`. +fn drain_frames(decoder: &mut dyn Decoder, out: &mut Vec) -> Result<()> { loop { match decoder.receive_frame() { Ok(Frame::Audio(frame)) => interleave(&frame, out), diff --git a/shims/symphonia-core/src/packet.rs b/shims/symphonia-core/src/packet.rs index 99fb4142..c15f4ca3 100644 --- a/shims/symphonia-core/src/packet.rs +++ b/shims/symphonia-core/src/packet.rs @@ -13,6 +13,11 @@ pub struct Packet { pub dur: Duration, /// The coded bytes. pub data: Box<[u8]>, + /// The container's own end-of-packet position, in the track's time base, + /// when it states one — an Ogg page's granule above all, which is the + /// only way a Vorbis (or FLAC-in-Ogg) stream's true, un-rounded length + /// ever reaches the decoder: the codec's own bitstream never states it. + pub granule: Option, } impl Packet { @@ -23,6 +28,7 @@ impl Packet { pts, dur, data: data.to_vec().into_boxed_slice(), + granule: None, } } diff --git a/shims/symphonia/Cargo.toml b/shims/symphonia/Cargo.toml index f58bf688..574f67c8 100644 --- a/shims/symphonia/Cargo.toml +++ b/shims/symphonia/Cargo.toml @@ -9,11 +9,13 @@ publish = false [dependencies] ec-core = { path = "../../crates/ec-core", version = "0.1.0" } +ec-ogg = { path = "../../crates/ec-ogg", version = "0.1.0" } ec-probe = { path = "../../crates/ec-probe", version = "0.1.0" } symphonia-core = { path = "../symphonia-core", version = "0.6.0" } [dev-dependencies] symphonia-codec-aac = { path = "../symphonia-codec-aac", version = "0.6.0" } +ec-vorbis = { path = "../../crates/ec-vorbis", version = "0.1.0" } # The incumbent's feature names, every one of them a no-op: a caller selects # codecs and containers there, and here `ec_probe` serves all of them diff --git a/shims/symphonia/src/reader.rs b/shims/symphonia/src/reader.rs index 30c5a60f..a78c78cb 100644 --- a/shims/symphonia/src/reader.rs +++ b/shims/symphonia/src/reader.rs @@ -17,6 +17,11 @@ use ec_core::registry::MediaType; pub struct ProbeReader { inner: ec_probe::Reader, tracks: Vec, + /// Audio track ids still owed their terminal, empty-data packet once the + /// container itself has run out: `None` before that, then the queue, + /// draining to empty rather than back to `None` so a second real EOF read + /// hands out nothing more than once each. + eos_pending: Option>, } impl ProbeReader { @@ -40,7 +45,11 @@ impl ProbeReader { language: s.language.clone(), }) .collect(); - ProbeReader { inner, tracks } + ProbeReader { + inner, + tracks, + eos_pending: None, + } } /// The stream index behind a track id. @@ -106,17 +115,44 @@ impl FormatReader for ProbeReader { } fn next_packet(&mut self) -> Result> { + if let Some(pending) = &mut self.eos_pending { + // Empty data is the flush signal `EcAudioDecoder::decode` reads: + // a real packet is never zero bytes for any codec this family + // decodes. + return Ok(pending + .next() + .map(|id| Packet::new(id, Timestamp::new(0), Duration::new(0), &[]))); + } match self.inner.next_packet() { Ok(packet) => { let id = self.inner.native_id(packet.stream) as u32; - Ok(Some(Packet::new( + let granule = ec_ogg::granule_of(&packet); + let mut out = Packet::new( id, Timestamp::new(packet.pts.unwrap_or(0)), Duration::new(packet.duration.unwrap_or(0).max(0) as u64), &packet.data, - ))) + ); + out.granule = granule; + Ok(Some(out)) + } + Err(e) if e.is_eof() => { + // The container itself is exhausted: give every audio track + // one last, empty packet so its decoder is told to flush the + // hop it has been holding back, then report real EOF. + let ids: Vec = self + .tracks + .iter() + .filter(|t| t.track_type == TrackType::Audio) + .map(|t| t.id) + .collect(); + let mut ids = ids.into_iter(); + let first = ids + .next() + .map(|id| Packet::new(id, Timestamp::new(0), Duration::new(0), &[])); + self.eos_pending = Some(ids); + Ok(first) } - Err(e) if e.is_eof() => Ok(None), Err(e) => Err(e.into()), } } @@ -144,15 +180,25 @@ impl EcAudioDecoder { impl AudioDecoder for EcAudioDecoder { fn decode(&mut self, packet: &Packet) -> Result> { - let rate = self.inner.sample_rate().max(1); - let mut ec = ec_core::Packet::new( - packet.track_id, - ec_core::TimeBase::from_rate(rate), - packet.data.as_ref(), - ); - ec.pts = Some(packet.pts.value()); - ec.duration = Some(packet.dur.value() as i64); - self.inner.decode(&ec, &mut self.out)?; + if packet.data.is_empty() { + // `ProbeReader::next_packet`'s terminal, empty packet: the file + // has run out, and this is the signal to release whatever the + // decoder was holding back rather than decode nothing. + self.inner.flush(&mut self.out)?; + } else { + let rate = self.inner.sample_rate().max(1); + let mut ec = ec_core::Packet::new( + packet.track_id, + ec_core::TimeBase::from_rate(rate), + packet.data.as_ref(), + ); + ec.pts = Some(packet.pts.value()); + ec.duration = Some(packet.dur.value() as i64); + if let Some(granule) = packet.granule { + ec.side_data.push(ec_ogg::granule_side_data(granule)); + } + self.inner.decode(&ec, &mut self.out)?; + } Ok(GenericAudioBufferRef::new( &self.out, self.inner.channels().max(1), diff --git a/shims/symphonia/tests/edith_surface.rs b/shims/symphonia/tests/edith_surface.rs index f1030b9b..b33d07b9 100644 --- a/shims/symphonia/tests/edith_surface.rs +++ b/shims/symphonia/tests/edith_surface.rs @@ -320,6 +320,7 @@ fn cover_art_and_id3v1_tail_do_not_stop_the_probe() { let mut decoder = track.decoder(); let mut out = Vec::new(); let mut decoded_packets = 0; + let mut total_samples = 0; while let Some(packet) = track.reader.next_packet().expect("demux") { if packet.track_id != track.track_id { continue; @@ -328,13 +329,135 @@ fn cover_art_and_id3v1_tail_do_not_stop_the_probe() { .decode(&packet) .expect("decode") .copy_to_vec_interleaved::(&mut out); + // The reader's terminal, empty flush packet legitimately decodes to + // nothing for mp3 (nothing is held back across EOS), and it is always + // the last one seen — `out` alone, checked only after the loop, would + // read that packet's empty result rather than the file's real audio. + total_samples += out.len(); decoded_packets += 1; } assert!(decoded_packets > 0, "no audio packets decoded"); - assert!(!out.is_empty(), "no samples decoded"); + assert!(total_samples > 0, "no samples decoded"); let _ = std::fs::remove_file(&path); } +/// Write `source` (one `Vec` per channel, all the same length) as an Ogg +/// Vorbis file through `ec_vorbis`/`ec_ogg` — the same two crates +/// `edith_replica::export::write_ogg` writes through — at scratch/`name`. +fn encode_ogg(source: &[Vec], rate: u32, path: &Path) { + use ec_core::{ + AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, MediaParameters, Muxer, + Packet, StreamInfo, TimeBase, + }; + use ec_vorbis::{EncoderConfig, VorbisEncoder}; + + let channels = source.len() as u16; + let mut encoder = VorbisEncoder::new(EncoderConfig { + sample_rate: rate, + channels, + bitrate_bps: 128_000, + quality: 0.6, + }) + .expect("vorbis encoder"); + let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect(); + encoder.push_planar(&borrowed).expect("push"); + encoder.finish(); + let mut packets = Vec::new(); + loop { + match encoder.next_packet() { + Ok(p) => packets.push((p.data, p.granule)), + Err(e) if e.is_eof() => break, + Err(e) => panic!("encode: {e}"), + } + } + eprintln!( + "encode_ogg: {} packets, last granule {}", + packets.len(), + packets.last().map_or(0, |(_, g)| *g) + ); + + let base = TimeBase::new(1, i64::from(rate)); + let mut params = CodecParameters::new(CodecId::Vorbis); + params.media = MediaParameters::Audio(AudioParameters { + sample_rate: rate, + layout: ChannelLayout::from_count(usize::from(channels)), + format: None, + bits_per_sample: None, + }); + params.extradata = Some(Buf::from_vec(encoder.extradata())); + let file = File::create(path).expect("create"); + let mut muxer = ec_ogg::OggMuxer::new(file); + muxer + .add_stream(StreamInfo::new(0, base, params)) + .expect("add stream"); + muxer.write_headers().expect("headers"); + for (data, granule) in &packets { + let mut packet = Packet::new(0, base, data.clone()); + packet.side_data.push(ec_ogg::granule_side_data(*granule)); + muxer.write_packet(&packet).expect("packet"); + } + muxer.finish().expect("finish"); +} + +/// The engine's own read door (`SymTrack` above, mirroring +/// `edith_replica::engine::audio::run_sym`): open, decode every packet to +/// EOF, count frames. This is what the export tests' `decode()` helper +/// measures against. +fn decode_all(path: &Path) -> u64 { + let mut track = SymTrack::open(path).expect("track"); + let mut decoder = track.decoder(); + let mut out = Vec::new(); + let mut frames = 0u64; + let mut n = 0; + while let Some(packet) = track.reader.next_packet().expect("demux") { + if packet.track_id != track.track_id { + continue; + } + let before = frames; + decoder + .decode(&packet) + .expect("decode") + .copy_to_vec_interleaved::(&mut out); + frames += (out.len() / usize::from(track.channels)) as u64; + n += 1; + eprintln!( + "packet {n}: {} bytes in, {} frames out (running {frames})", + packet.data.len(), + frames - before + ); + } + frames +} + +/// The exact shape of `audio_export::exports_the_timeline_as_an_ogg_vorbis` +/// and `a_mono_timeline_exports_as_dual_mono_ogg` in `edith_replica`: write N +/// samples through the family's own Ogg Vorbis encoder, read them back +/// through this shim exactly as the engine's `SymTrack`/`run_sym` do, and the +/// count must come back to N — the terminal hop `VorbisDecoder::flush` +/// delivers has to actually reach the reader at EOS. +#[test] +fn ogg_vorbis_round_trip_reads_back_every_sample_written() { + let rate = 44_100u32; + for (name, channels, n) in [ + ("surface-mono-44100.ogg", 2usize, 44_100usize), + ("surface-stereo-264600.ogg", 2, 264_600), + ] { + let source: Vec> = (0..channels) + .map(|_| { + (0..n) + .map(|i| 0.2 * (i as f32 * 0.05).sin()) + .collect::>() + }) + .collect(); + let path = std::env::temp_dir().join(format!("edith-surface-{}-{name}", std::process::id())); + encode_ogg(&source, rate, &path); + let frames = decode_all(&path); + eprintln!("{name}: wrote {n} frames, read back {frames}"); + assert_eq!(frames, n as u64, "{name}: round trip sample count"); + let _ = std::fs::remove_file(&path); + } +} + /// ID3v2's syncsafe integer: 4 bytes, 7 significant bits each (top bit clear), /// big-endian. fn syncsafe(mut n: u32) -> [u8; 4] {