From 2127132b8eee396df32844c3b23cba2c62e2c26c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 09:58:10 +0300 Subject: [PATCH] feat(vorbis): rusty_vorbis shim over ec-vorbis Carries the incumbent's name and version, and drops the two behaviours the replica corrects by hand: the pre-roll hop and the stereo-only setup header. --- shims/rusty_vorbis/Cargo.toml | 15 ++ shims/rusty_vorbis/src/lib.rs | 308 ++++++++++++++++++++++ shims/rusty_vorbis/tests/edith_surface.rs | 152 +++++++++++ 3 files changed, 475 insertions(+) create mode 100644 shims/rusty_vorbis/Cargo.toml create mode 100644 shims/rusty_vorbis/src/lib.rs create mode 100644 shims/rusty_vorbis/tests/edith_surface.rs diff --git a/shims/rusty_vorbis/Cargo.toml b/shims/rusty_vorbis/Cargo.toml new file mode 100644 index 00000000..73efe026 --- /dev/null +++ b/shims/rusty_vorbis/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "rusty_vorbis" +description = "Compatibility shim: the rusty_vorbis 0.1.1 surface edith consumes, served by ec-vorbis." +version = "0.1.1" +edition.workspace = true +license.workspace = true +authors.workspace = true +publish = false + +[dependencies] +ec-core = { path = "../../crates/ec-core", version = "0.1.0" } +ec-vorbis = { path = "../../crates/ec-vorbis", version = "0.1.0" } + +[dev-dependencies] +ec-ogg = { path = "../../crates/ec-ogg", version = "0.1.0" } diff --git a/shims/rusty_vorbis/src/lib.rs b/shims/rusty_vorbis/src/lib.rs new file mode 100644 index 00000000..0ff00ccf --- /dev/null +++ b/shims/rusty_vorbis/src/lib.rs @@ -0,0 +1,308 @@ +//! Drop-in replacement for the `rusty_vorbis` 0.1.1 surface the replica +//! consumes, implemented over [`ec_vorbis`]. +//! +//! It carries the incumbent's package name and version so the swap is a +//! `[patch.crates-io]` entry and nothing else. The scope is the API +//! `engine/src/export.rs` calls (`export.rs:2850-2862`): +//! +//! ```no_run +//! let mut encoder = rusty_vorbis::VorbisEncoder::new(rusty_vorbis::VorbisEncoderConfig { +//! bitrate_bps: rusty_vorbis::BITRATE_NOMINAL, +//! quality: 0.85, +//! }); +//! encoder.push_pcm_s16(&[0i16; 2048], 2, 48_000).unwrap(); +//! encoder.finish(); +//! loop { +//! match encoder.next_packet() { +//! Ok(packet) => { let _ = (&packet.data, packet.pts, packet.duration); } +//! Err(rusty_vorbis::Error::Eof) => break, +//! Err(e) => panic!("{e}"), +//! } +//! } +//! ``` +//! +//! Two of the incumbent's behaviours are deliberately *not* reproduced, because +//! they are the defects this replacement exists to remove — both are corrections +//! the replica currently applies by hand at `export.rs:2762-2815` and can delete: +//! +//! * **No pre-roll hop.** The incumbent's first audio packet advanced the +//! granule by a full block hop while decoding to nothing, so every caller had +//! to feed a hop of silence and subtract a hop from every granule. Here the +//! first block is centred on input sample 0 and [`EncodedPacket::pts`] is the +//! true granule, so a caller writes what it is given. +//! * **No stereo-only setup header.** The incumbent shipped one embedded stereo +//! profile and refused mono ("bad coupling channels") and anything wider. Here +//! the setup header is written per stream for whatever channel count is +//! pushed, so mono stays mono and 5.1 stays 5.1. +//! +//! The last packet's `pts` is the input's own sample count, so a file decodes to +//! exactly as many samples as went in; the caller does not have to state the +//! tail granule itself either. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +use ec_core::Error as EcError; +use ec_vorbis::{EncoderConfig, VorbisEncoder as EcEncoder}; + +/// Short block size, as a power of two, that this encoder states. +pub const BS0_LOG2: u8 = 11; +/// Long block size, as a power of two. +pub const BS1_LOG2: u8 = 11; +/// The nominal bitrate the replica asks for. +pub const BITRATE_NOMINAL: i32 = 128_000; + +/// Errors this encoder can answer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// Something is not implemented. + Unimplemented(String), + /// No further packet: the encoder is finished and drained. + Eof, + /// More input is needed before another packet exists. + Again, + /// The input or the state does not make sense. + InvalidData(String), + /// A legal request this encoder does not serve. + Unsupported(String), +} + +impl Error { + /// An [`Error::InvalidData`] with a message. + pub fn invalid(msg: impl Into) -> Self { + Error::InvalidData(msg.into()) + } + + /// An [`Error::Unsupported`] with a message. + pub fn unsupported(msg: impl Into) -> Self { + Error::Unsupported(msg.into()) + } +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Unimplemented(what) => write!(f, "not yet implemented: {what}"), + Error::Eof => write!(f, "end of stream"), + Error::Again => write!(f, "more input required"), + Error::InvalidData(msg) => write!(f, "invalid data: {msg}"), + Error::Unsupported(msg) => write!(f, "unsupported: {msg}"), + } + } +} + +impl std::error::Error for Error {} + +/// This crate's result type. +pub type Result = std::result::Result; + +fn map(error: EcError) -> Error { + match error { + EcError::Eof => Error::Eof, + EcError::NeedMore => Error::Again, + EcError::Unsupported { what, why } => Error::Unsupported(format!("{what} ({why})")), + other => Error::InvalidData(other.to_string()), + } +} + +/// One packet out of the encoder. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EncodedPacket { + /// Packet payload, ready to page. + pub data: Vec, + /// Granule position this packet ends at: the number of input samples that + /// are decodable once it has been decoded. Zero for the three headers and + /// for the first audio packet, which decodes to no samples at all. + pub pts: i64, + /// Samples this packet finalises. + pub duration: i64, +} + +/// How the encoder is set up. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct VorbisEncoderConfig { + /// Target bitrate in bits per second. + pub bitrate_bps: i32, + /// Quality on `[0, 1]`. + pub quality: f32, +} + +impl Default for VorbisEncoderConfig { + fn default() -> VorbisEncoderConfig { + VorbisEncoderConfig { + bitrate_bps: BITRATE_NOMINAL, + quality: 0.5, + } + } +} + +/// The incumbent's `[0, 1]` quality scale from Vorbis's own `-q` scale. +pub fn quality01_from_vorbis_q(q: f64) -> f32 { + (((q + 1.0) / 11.0).clamp(0.0, 1.0)) as f32 +} + +/// Vorbis encoder over [`ec_vorbis`]. +/// +/// Channel count and sample rate arrive with the first push, exactly as they do +/// in the incumbent, so the encoder is built lazily and the setup header is +/// written for the layout that actually turns up. +pub struct VorbisEncoder { + config: VorbisEncoderConfig, + inner: Option, + /// Header packets not yet handed out. + headers: std::collections::VecDeque>, + finished: bool, +} + +impl VorbisEncoder { + /// A new encoder; nothing is written until the first push states a layout. + pub fn new(config: VorbisEncoderConfig) -> Self { + VorbisEncoder { + config, + inner: None, + headers: std::collections::VecDeque::new(), + finished: false, + } + } + + /// Change the quality; takes effect on the next stream. + pub fn set_quality(&mut self, quality: f32) { + self.config.quality = quality; + } + + /// Change the target bitrate; takes effect on the next stream. + pub fn set_bitrate_bps(&mut self, bps: i32) { + self.config.bitrate_bps = bps; + } + + /// The three header packets, once a push has stated the layout. + pub fn headers(&self) -> Vec> { + self.inner + .as_ref() + .map(|encoder| encoder.headers().into_iter().map(<[u8]>::to_vec).collect()) + .unwrap_or_default() + } + + /// The three headers Xiph-laced, the form a container carries them in. + pub fn extradata(&self) -> Vec { + self.inner + .as_ref() + .map(EcEncoder::extradata) + .unwrap_or_default() + } + + /// Push interleaved float samples. + pub fn push_pcm_f32( + &mut self, + interleaved: &[f32], + channels: u16, + sample_rate: u32, + ) -> Result<()> { + self.start(channels, sample_rate)?; + let encoder = self.inner.as_mut().expect("started"); + encoder.push_interleaved(interleaved).map_err(map) + } + + /// Push interleaved 16-bit samples, scaled by 1/32768 as every decoder in + /// this family scales them. + pub fn push_pcm_s16( + &mut self, + interleaved: &[i16], + channels: u16, + sample_rate: u32, + ) -> Result<()> { + let floats: Vec = interleaved + .iter() + .map(|&sample| f32::from(sample) / 32_768.0) + .collect(); + self.push_pcm_f32(&floats, channels, sample_rate) + } + + /// No more input; the tail is encoded and the last granule is the input's + /// own sample count. + pub fn finish(&mut self) { + self.finished = true; + if let Some(encoder) = self.inner.as_mut() { + encoder.finish(); + } + } + + /// Next packet: the three headers first, then audio, then [`Error::Eof`]. + pub fn next_packet(&mut self) -> Result { + if let Some(data) = self.headers.pop_front() { + return Ok(EncodedPacket { + data, + pts: 0, + duration: 0, + }); + } + let Some(encoder) = self.inner.as_mut() else { + return Err(match self.finished { + true => Error::Eof, + false => Error::Again, + }); + }; + let packet = encoder.next_packet().map_err(map)?; + Ok(EncodedPacket { + data: packet.data, + pts: packet.granule, + duration: packet.samples, + }) + } + + /// Build the encoder on the first push and queue its headers. + fn start(&mut self, channels: u16, sample_rate: u32) -> Result<()> { + if self.inner.is_some() { + return Ok(()); + } + if self.finished { + return Err(Error::invalid("push after finish")); + } + let encoder = EcEncoder::new(EncoderConfig { + sample_rate, + channels, + bitrate_bps: self.config.bitrate_bps, + quality: self.config.quality, + }) + .map_err(map)?; + self.headers = encoder.headers().into_iter().map(<[u8]>::to_vec).collect(); + self.inner = Some(encoder); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_incumbents_call_sequence_yields_headers_then_audio() { + let mut encoder = VorbisEncoder::new(VorbisEncoderConfig { + bitrate_bps: BITRATE_NOMINAL, + quality: 0.85, + }); + // Mono, which the incumbent refused outright. + let pcm: Vec = (0..8_000) + .map(|i| ((f64::from(i) * 0.05).sin() * 12_000.0) as i16) + .collect(); + encoder.push_pcm_s16(&pcm, 1, 48_000).unwrap(); + encoder.finish(); + let mut packets = Vec::new(); + loop { + match encoder.next_packet() { + Ok(packet) => packets.push(packet), + Err(Error::Eof) => break, + Err(e) => panic!("{e}"), + } + } + assert!(packets.len() > 4, "{} packets", packets.len()); + assert_eq!(packets[0].data[0], 1, "identification header first"); + assert_eq!(packets[1].data[0], 3, "comment header second"); + assert_eq!(packets[2].data[0], 5, "setup header third"); + // No pre-roll: the first audio packet ends at granule zero, and the + // last states the input's own length. + assert_eq!(packets[3].pts, 0); + assert_eq!(packets.last().unwrap().pts, 8_000); + assert_eq!(quality01_from_vorbis_q(-1.0), 0.0); + } +} diff --git a/shims/rusty_vorbis/tests/edith_surface.rs b/shims/rusty_vorbis/tests/edith_surface.rs new file mode 100644 index 00000000..313cb1d9 --- /dev/null +++ b/shims/rusty_vorbis/tests/edith_surface.rs @@ -0,0 +1,152 @@ +//! The replica's `write_ogg` (`export.rs:2895-2985`) with both of its +//! corrections deleted, run end to end. +//! +//! That deletion *is* the test: no hop of silence in front of the mix, no hop +//! subtracted from every granule, no hand-written tail granule, and a mono mix +//! written as mono rather than widened to dual mono. What comes out has to +//! decode in ffmpeg without a word of complaint and be exactly as long as the +//! timeline it came from — which is the promise the replica makes for every +//! other audio format. + +use std::fs::File; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_core::{ + AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, MediaParameters, Muxer, Packet, + StreamInfo, TimeBase, +}; + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("rusty-vorbis-shim-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("scratch dir"); + dir.join(name) +} + +/// The replica's own mix, as 16-bit samples: a tone per channel so a channel +/// that came out of the wrong hole is visible rather than subtle. +fn mix(channels: u16, rate: u32, frames: usize) -> Vec { + let mut samples = Vec::with_capacity(frames * usize::from(channels)); + for i in 0..frames { + for channel in 0..channels { + let hz = 220.0 * f64::from(channel + 1); + let t = i as f64 / f64::from(rate); + let value = (2.0 * std::f64::consts::PI * hz * t).sin() * 0.6; + samples.push((value * f64::from(i16::MAX)) as i16); + } + } + samples +} + +/// `write_ogg`, shorn of the workarounds. +fn write_ogg(out: &Path, samples: &[i16], channels: u16, rate: u32) { + let mut encoder = rusty_vorbis::VorbisEncoder::new(rusty_vorbis::VorbisEncoderConfig { + bitrate_bps: rusty_vorbis::BITRATE_NOMINAL, + quality: 0.85, + }); + encoder + .push_pcm_s16(samples, channels, rate) + .expect("vorbis encode"); + encoder.finish(); + let mut packets = Vec::new(); + loop { + match encoder.next_packet() { + Ok(packet) => packets.push(packet), + Err(rusty_vorbis::Error::Eof) => break, + Err(e) => panic!("vorbis encode: {e}"), + } + } + assert!( + packets.len() >= 4, + "{} packets is not a stream", + packets.len() + ); + + let extradata = ec_ogg::xiph_lace(&[ + &packets[0].data[..], + &packets[1].data[..], + &packets[2].data[..], + ]) + .expect("the three headers lace"); + + let time_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(extradata)); + let mut muxer = ec_ogg::OggMuxer::new(File::create(out).expect("create")); + muxer + .add_stream(StreamInfo::new(0, time_base, params)) + .expect("stream"); + muxer.write_headers().expect("headers"); + for packet in &packets[3..] { + // The granule the encoder states, written through: no hop subtracted, + // and no special case for the last packet. + let mut out = Packet::new(0, time_base, packet.data.clone()); + out.side_data.push(ec_ogg::granule_side_data(packet.pts)); + out.duration = Some(packet.duration); + muxer.write_packet(&out).expect("packet"); + } + muxer.finish().expect("trailer"); +} + +fn probe(path: &Path, field: &str) -> String { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "a:0", + "-show_entries", + &format!("stream={field}"), + "-of", + "default=noprint_wrappers=1:nokey=1", + ]) + .arg(path) + .output() + .expect("ffprobe"); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} + +#[test] +fn writes_an_ogg_the_way_the_replica_would_without_its_corrections() { + let rate = 48_000u32; + // Deliberately not a whole number of blocks: the grid has to close over it + // and the granule has to trim the overshoot back off. + let frames = 33_333usize; + for channels in [1u16, 2, 6] { + let path = scratch(&format!("write-ogg-{channels}ch.ogg")); + write_ogg(&path, &mix(channels, rate, frames), channels, rate); + + // ffmpeg decodes it silently... + let decode = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(&path) + .args(["-f", "f32le", "-"]) + .output() + .expect("ffmpeg"); + assert!( + decode.stderr.is_empty(), + "{channels} ch: ffmpeg said {}", + String::from_utf8_lossy(&decode.stderr) + ); + // ...for exactly the timeline's own length... + assert_eq!( + probe(&path, "duration_ts"), + frames.to_string(), + "{channels} ch: duration" + ); + // ...at the channel count that was pushed, mono included. + assert_eq!( + probe(&path, "channels"), + channels.to_string(), + "{channels} ch: channel count" + ); + let decoded = decode.stdout.len() / 4 / usize::from(channels); + assert_eq!(decoded, frames, "{channels} ch: decoded sample count"); + } +}