From b9c1dfa18f42757755f7cc7770255afc5cdefcab Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 08:50:02 -0500 Subject: [PATCH 1/7] feat(audio): migrate Ogg Vorbis encoding to craft-audio (PR #26) - Add vorbis-encode feature with dep:vorbis_rs = "0.5" - Implement encode_ogg() via VorbisEncoderBuilder matching original behavior: - Fixed stream serial 0x4C43_5246, VBR target bitrate (64-500 kbit/s) - 4096-frame blocks, panic catch with QualityVbr fallback (target_quality: 0.6) - Add EncodeFormat::Ogg variant (cfg-gated on vorbis-encode) - Update ENCODE_EXTENSIONS and encode_format_for() to include .ogg --- Cargo.lock | 34 +++++++++++++++++++ crates/audio/Cargo.toml | 3 ++ crates/audio/src/lib.rs | 20 ++++++++++- crates/audio/src/write/mod.rs | 56 ++++++++++++++++++++++++++---- crates/audio/src/write/vorbis.rs | 58 ++++++++++++++++++++++++++++++++ 5 files changed, 164 insertions(+), 7 deletions(-) create mode 100644 crates/audio/src/write/vorbis.rs diff --git a/Cargo.lock b/Cargo.lock index a1b1ccab3..1314c7745 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -222,6 +222,16 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "aotuv_lancer_vorbis_sys" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bc4fd1a61860d2f1198b60bedd30910eaffa978f1ee6214dfb24ac70d589225" +dependencies = [ + "cc", + "ogg_next_sys", +] + [[package]] name = "arbitrary" version = "1.5.0" @@ -1349,6 +1359,7 @@ dependencies = [ "serde_json", "symphonia", "thiserror 2.0.21", + "vorbis_rs", ] [[package]] @@ -6563,6 +6574,15 @@ dependencies = [ "phf 0.11.3", ] +[[package]] +name = "ogg_next_sys" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2d7a48e247c2bb07e633aefb65a38648ea58c7eedd4e4408a5861721ab049b" +dependencies = [ + "cc", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -10279,6 +10299,20 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vorbis_rs" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49c5da94d280f7a27e8c937e9b73df2da3e23a2583f48471fd8fb4c72f9c1933" +dependencies = [ + "aotuv_lancer_vorbis_sys", + "errno", + "getrandom 0.4.3", + "ogg_next_sys", + "thiserror 2.0.21", + "tinyvec", +] + [[package]] name = "wait-timeout" version = "0.2.1" diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 9b6200198..63e55d232 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -30,6 +30,8 @@ lossless-encode = ["pcm-encode", "flac-encode"] pcm-encode = [] # Encode FLAC files. flac-encode = ["craft-media/bitstream"] +# Encode Ogg Vorbis files (desktop only: builds the reference libvorbis from its C sources). +vorbis-encode = ["dep:vorbis_rs"] # Codec modules on their own, for packet-level use. aac-decode = ["craft-media/bitstream"] aac-encode = ["craft-media/bitstream"] @@ -59,6 +61,7 @@ thiserror = { workspace = true } serde = { workspace = true, optional = true } log = { version = "0.4", optional = true } rayon = { workspace = true, optional = true } +vorbis_rs = { version = "0.5", optional = true } # symphonia keeps its AAC decoder for AAC in CAF, a container craft-media does not read. symphonia = { version = "0.6.1", optional = true, default-features = false, features = ["mp3", "flac", "vorbis", "ogg", "wav", "pcm", "aiff", "isomp4", "aac", "alac", "adpcm", "caf", "mkv"] } diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index f8441a51d..04b813c30 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -54,8 +54,12 @@ mod read; mod track; #[cfg(any(feature = "decode-native", feature = "pcm-encode"))] mod wav; -#[cfg(any(feature = "pcm-encode", feature = "flac-encode"))] +#[cfg(any(feature = "pcm-encode", feature = "flac-encode", feature = "vorbis-encode"))] mod write; +#[cfg(feature = "vorbis-encode")] +pub use write::encode_ogg; +#[cfg(feature = "vorbis-encode")] +pub use write::OGG_BITRATES; /// The FLAC packet encoder (RFC 9639), for a caller that muxes FLAC itself (into MP4, Matroska or /// its own `.flac` writer): planar integer samples in, frames out, and the STREAMINFO to patch in @@ -226,12 +230,20 @@ pub enum EncodeFormat { Aiff, /// FLAC (integer depths). Flac, + /// Ogg Vorbis (variable bitrate). Whole-buffer only: use [`encode_ogg`] directly. + #[cfg(feature = "vorbis-encode")] + Ogg, } impl EncodeFormat { /// Every format, in the order menus list them. Whether [`encode`] writes one depends on its /// feature. + #[cfg(not(feature = "vorbis-encode"))] pub const ALL: &[EncodeFormat] = &[EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac]; + /// Every format, in the order menus list them. Whether [`encode`] writes one depends on its + /// feature. + #[cfg(feature = "vorbis-encode")] + pub const ALL: &[EncodeFormat] = &[EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac, EncodeFormat::Ogg]; /// The extension a new file of this format gets, lower case and without the dot: `"wav"`, /// `"aif"`, `"flac"`. [`encode_format_for`] maps it back. @@ -240,6 +252,8 @@ impl EncodeFormat { EncodeFormat::Wav => "wav", EncodeFormat::Aiff => "aif", EncodeFormat::Flac => "flac", + #[cfg(feature = "vorbis-encode")] + EncodeFormat::Ogg => "ogg", } } @@ -249,6 +263,8 @@ impl EncodeFormat { EncodeFormat::Wav => "audio/wav", EncodeFormat::Aiff => "audio/aiff", EncodeFormat::Flac => "audio/flac", + #[cfg(feature = "vorbis-encode")] + EncodeFormat::Ogg => "audio/ogg", } } @@ -258,6 +274,8 @@ impl EncodeFormat { EncodeFormat::Wav => Container::Wav, EncodeFormat::Aiff => Container::Aiff, EncodeFormat::Flac => Container::Flac, + #[cfg(feature = "vorbis-encode")] + EncodeFormat::Ogg => Container::Ogg, } } } diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 2355a7b05..4a82fdcbe 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -10,6 +10,10 @@ mod pcm; mod raw; #[cfg(feature = "pcm-encode")] mod wav; +#[cfg(feature = "vorbis-encode")] +pub(crate) mod vorbis; +#[cfg(feature = "vorbis-encode")] +pub use vorbis::OGG_BITRATES; use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, Result}; #[cfg(feature = "pcm-encode")] @@ -47,20 +51,54 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { /// Refuses a format whose writer is not built, before anything else about the request is checked. fn check_built(format: EncodeFormat) -> Result<()> { - let (built, feature) = - if format == EncodeFormat::Flac { (cfg!(feature = "flac-encode"), "flac-encode") } else { (cfg!(feature = "pcm-encode"), "pcm-encode") }; + let (built, feature) = match format { + EncodeFormat::Flac => (cfg!(feature = "flac-encode"), "flac-encode"), + #[cfg(feature = "vorbis-encode")] + EncodeFormat::Ogg => (cfg!(feature = "vorbis-encode"), "vorbis-encode"), + _ => (cfg!(feature = "pcm-encode"), "pcm-encode"), + }; if built { Ok(()) } else { Err(AudioError::Unsupported(format!("writing {format:?} needs the `{feature}` feature"))) } } /// The file extensions of the formats [`encode`] can write (those whose features are on). -#[cfg(all(feature = "pcm-encode", feature = "flac-encode"))] +#[cfg(all(feature = "pcm-encode", feature = "flac-encode", feature = "vorbis-encode"))] +pub const ENCODE_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "aifc", "flac", "ogg"]; +/// The file extensions of the formats [`encode`] can write (those whose features are on). +#[cfg(all(feature = "pcm-encode", feature = "flac-encode", not(feature = "vorbis-encode")))] pub const ENCODE_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "aifc", "flac"]; /// The file extensions of the formats [`encode`] can write (those whose features are on). -#[cfg(all(feature = "pcm-encode", not(feature = "flac-encode")))] +#[cfg(all(feature = "pcm-encode", feature = "vorbis-encode", not(feature = "flac-encode")))] +pub const ENCODE_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "aifc", "ogg"]; +/// The file extensions of the formats [`encode`] can write (those whose features are on). +#[cfg(all(feature = "pcm-encode", not(feature = "flac-encode"), not(feature = "vorbis-encode")))] pub const ENCODE_EXTENSIONS: &[&str] = &["wav", "wave", "bwf", "aif", "aiff", "aifc"]; /// The file extensions of the formats [`encode`] can write (those whose features are on). -#[cfg(all(feature = "flac-encode", not(feature = "pcm-encode")))] +#[cfg(all(feature = "flac-encode", feature = "vorbis-encode", not(feature = "pcm-encode")))] +pub const ENCODE_EXTENSIONS: &[&str] = &["flac", "ogg"]; +/// The file extensions of the formats [`encode`] can write (those whose features are on). +#[cfg(all(feature = "flac-encode", not(feature = "pcm-encode"), not(feature = "vorbis-encode")))] pub const ENCODE_EXTENSIONS: &[&str] = &["flac"]; +/// The file extensions of the formats [`encode`] can write (those whose features are on). +#[cfg(all(feature = "vorbis-encode", not(feature = "pcm-encode"), not(feature = "flac-encode")))] +pub const ENCODE_EXTENSIONS: &[&str] = &["ogg"]; + +/// Encode `buf` as an Ogg Vorbis stream at about `kbps` (variable, as Vorbis is): stereo, or mono +/// for a mono buffer. A bitrate the encoder has no setup for at that rate and channel count falls +/// back to a quality that suits it. Whole-buffer only: no streaming encoder is provided for Vorbis. +/// +/// ``` +/// # #[cfg(feature = "vorbis-encode")] { +/// use craft_audio::{AudioBuffer, encode_ogg}; +/// +/// let buf = AudioBuffer::new(48_000, 2, 48_000); // one second of stereo silence +/// let ogg = encode_ogg(&buf, 192).unwrap(); +/// assert_eq!(&ogg[..4], b"OggS"); +/// # } +/// ``` +#[cfg(feature = "vorbis-encode")] +pub fn encode_ogg(buf: &AudioBuffer, kbps: u32) -> Result> { + vorbis::encode(buf, kbps) +} /// The format [`encode`] writes for a file extension or format name (`wav`, `aiff`, `flac`, /// case-insensitive, with or without the dot), or `None` when it cannot write it. `aifc` is @@ -82,6 +120,8 @@ pub fn encode_format_for(name: &str) -> Option { "aif" | "aiff" | "aifc" => Some(EncodeFormat::Aiff), #[cfg(feature = "flac-encode")] "flac" => Some(EncodeFormat::Flac), + #[cfg(feature = "vorbis-encode")] + "ogg" => Some(EncodeFormat::Ogg), _ => None, } } @@ -123,11 +163,13 @@ fn failed_write_error() -> AudioError { /// assert_eq!(&flac[..4], b"fLaC"); /// # } /// ``` +#[cfg(any(feature = "pcm-encode", feature = "flac-encode"))] pub struct FileEncoder { writer: Writer, channels: usize, } +#[cfg(any(feature = "pcm-encode", feature = "flac-encode"))] impl std::fmt::Debug for FileEncoder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let format = match &self.writer { @@ -142,6 +184,7 @@ impl std::fmt::Debug for FileEncoder { } } +#[cfg(any(feature = "pcm-encode", feature = "flac-encode"))] enum Writer { #[cfg(feature = "pcm-encode")] Wav(wav::Writer), @@ -151,6 +194,7 @@ enum Writer { Flac(flac::Writer), } +#[cfg(any(feature = "pcm-encode", feature = "flac-encode"))] impl FileEncoder { /// Starts a file of `channels` channels at `sample_rate` at the current position of `out`. /// `opts.layout`, when set, must have `channels` channels. @@ -252,7 +296,7 @@ pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result< // With only one of `pcm-encode` and `flac-encode`, the other's formats are refused, not silently // written as something else. -#[cfg(all(test, not(all(feature = "pcm-encode", feature = "flac-encode"))))] +#[cfg(all(test, any(feature = "pcm-encode", feature = "flac-encode"), not(all(feature = "pcm-encode", feature = "flac-encode"))))] mod tests { use super::*; diff --git a/crates/audio/src/write/vorbis.rs b/crates/audio/src/write/vorbis.rs new file mode 100644 index 000000000..6b33e8981 --- /dev/null +++ b/crates/audio/src/write/vorbis.rs @@ -0,0 +1,58 @@ +//! Ogg Vorbis encoding (RFC 5334): the reference libvorbis encoder, built from its C sources by +//! `vorbis_rs`. Stereo or mono, variable bitrate at the requested kbit/s (64–500), with a +//! fallback to a quality preset when the bitrate is not supported for the rate and channel count. + +use crate::{AudioBuffer, AudioError, Result}; + +/// The bitrates an Ogg Vorbis export is asked for, in kbit/s. +pub const OGG_BITRATES: (u32, u32) = (64, 500); + +/// The block size the encoder processes at a time: small enough that memory stays bounded +/// regardless of file length. +const BLOCK: usize = 4096; + +fn encode_error(e: vorbis_rs::VorbisError) -> AudioError { + AudioError::Encode(e.to_string()) +} + +/// Encode `buf` as an Ogg Vorbis stream at about `kbps` (variable, as Vorbis is): stereo, or mono +/// for a mono buffer. A bitrate the encoder has no setup for at that rate and channel count falls +/// back to a quality that suits it. `Err` says why there is nothing. +#[cfg(not(target_arch = "wasm32"))] +pub fn encode(buf: &AudioBuffer, kbps: u32) -> Result> { + use std::num::{NonZeroU8, NonZeroU32}; + + let channels = buf.channels.len().clamp(1, 2); + let (Some(rate), Some(count)) = (NonZeroU32::new(buf.sample_rate), NonZeroU8::new(channels as u8)) else { + return Err(AudioError::Encode("there is no audio to encode".into())); + }; + let target = NonZeroU32::new(kbps.clamp(OGG_BITRATES.0, OGG_BITRATES.1) * 1000).unwrap_or(NonZeroU32::MIN); + + let encode = |strategy: vorbis_rs::VorbisBitrateManagementStrategy| -> Result> { + let mut encoder = vorbis_rs::VorbisEncoderBuilder::new_with_serial(rate, count, Vec::new(), 0x4C43_5246) + .bitrate_management_strategy(strategy) + .build() + .map_err(encode_error)?; + let frames = buf.frames(); + let mut at = 0usize; + while at < frames { + let end = (at + BLOCK).min(frames); + let block: Vec<&[f32]> = buf.channels.iter().take(channels).map(|side| side.get(at..end).unwrap_or_default()).collect(); + encoder.encode_audio_block(&block).map_err(encode_error)?; + at = end; + } + encoder.finish().map_err(encode_error) + }; + + // The library is C: whatever it does wrong ends here as an error, never as a crash of the app. + let attempt = |strategy| std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| encode(strategy))).unwrap_or_else(|_| Err(AudioError::Encode("the Vorbis encoder failed".into()))); + match attempt(vorbis_rs::VorbisBitrateManagementStrategy::Vbr { target_bitrate: target }) { + Ok(bytes) => Ok(bytes), + Err(_) => attempt(vorbis_rs::VorbisBitrateManagementStrategy::QualityVbr { target_quality: 0.6 }).map_err(|e| AudioError::Encode(format!("the Vorbis encoder refused the audio: {e}"))), + } +} + +#[cfg(target_arch = "wasm32")] +pub fn encode(_buf: &AudioBuffer, _kbps: u32) -> Result> { + Err("Ogg Vorbis files are exported by the desktop app".into()) +} From 630c57078931ceb58f9d3d61281872261d667785 Mon Sep 17 00:00:00 2001 From: Dylan Taylor Date: Sat, 14 Nov 2026 10:16:33 -0500 Subject: [PATCH 2/7] fix: update tests for vorbis-encode feature (ogg support) --- crates/audio/src/lib.rs | 4 ++-- crates/audio/src/write/mod.rs | 4 ++-- crates/audio/src/write/vorbis.rs | 8 ++++++-- crates/audio/tests/audio/decode_extensions.rs | 2 +- crates/audio/tests/audio/encode_format.rs | 2 +- 5 files changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 04b813c30..3c578242f 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -57,9 +57,9 @@ mod wav; #[cfg(any(feature = "pcm-encode", feature = "flac-encode", feature = "vorbis-encode"))] mod write; #[cfg(feature = "vorbis-encode")] -pub use write::encode_ogg; -#[cfg(feature = "vorbis-encode")] pub use write::OGG_BITRATES; +#[cfg(feature = "vorbis-encode")] +pub use write::encode_ogg; /// The FLAC packet encoder (RFC 9639), for a caller that muxes FLAC itself (into MP4, Matroska or /// its own `.flac` writer): planar integer samples in, frames out, and the STREAMINFO to patch in diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 4a82fdcbe..d95b8fe0f 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -8,10 +8,10 @@ pub(crate) mod flac; mod pcm; #[cfg(feature = "pcm-encode")] mod raw; -#[cfg(feature = "pcm-encode")] -mod wav; #[cfg(feature = "vorbis-encode")] pub(crate) mod vorbis; +#[cfg(feature = "pcm-encode")] +mod wav; #[cfg(feature = "vorbis-encode")] pub use vorbis::OGG_BITRATES; diff --git a/crates/audio/src/write/vorbis.rs b/crates/audio/src/write/vorbis.rs index 6b33e8981..5466a5b92 100644 --- a/crates/audio/src/write/vorbis.rs +++ b/crates/audio/src/write/vorbis.rs @@ -45,10 +45,14 @@ pub fn encode(buf: &AudioBuffer, kbps: u32) -> Result> { }; // The library is C: whatever it does wrong ends here as an error, never as a crash of the app. - let attempt = |strategy| std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| encode(strategy))).unwrap_or_else(|_| Err(AudioError::Encode("the Vorbis encoder failed".into()))); + let attempt = |strategy| { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| encode(strategy))) + .unwrap_or_else(|_| Err(AudioError::Encode("the Vorbis encoder failed".into()))) + }; match attempt(vorbis_rs::VorbisBitrateManagementStrategy::Vbr { target_bitrate: target }) { Ok(bytes) => Ok(bytes), - Err(_) => attempt(vorbis_rs::VorbisBitrateManagementStrategy::QualityVbr { target_quality: 0.6 }).map_err(|e| AudioError::Encode(format!("the Vorbis encoder refused the audio: {e}"))), + Err(_) => attempt(vorbis_rs::VorbisBitrateManagementStrategy::QualityVbr { target_quality: 0.6 }) + .map_err(|e| AudioError::Encode(format!("the Vorbis encoder refused the audio: {e}"))), } } diff --git a/crates/audio/tests/audio/decode_extensions.rs b/crates/audio/tests/audio/decode_extensions.rs index e8fe22d58..c7c8615e4 100644 --- a/crates/audio/tests/audio/decode_extensions.rs +++ b/crates/audio/tests/audio/decode_extensions.rs @@ -67,6 +67,6 @@ fn every_encode_format_has_an_extension_it_is_written_and_read_under() { assert!(DECODE_EXTENSIONS.contains(&ext), "{ext}: what is written reads back"); assert!(format.mime_type().starts_with("audio/"), "{format:?}"); } - assert_eq!(EncodeFormat::ALL.iter().map(|f| f.extension()).collect::>(), ["wav", "aif", "flac"]); + assert_eq!(EncodeFormat::ALL.iter().map(|f| f.extension()).collect::>(), ["wav", "aif", "flac", "ogg"]); assert_eq!(EncodeFormat::Aiff.mime_type(), "audio/aiff"); } diff --git a/crates/audio/tests/audio/encode_format.rs b/crates/audio/tests/audio/encode_format.rs index 30b992685..098dc025a 100644 --- a/crates/audio/tests/audio/encode_format.rs +++ b/crates/audio/tests/audio/encode_format.rs @@ -14,7 +14,7 @@ fn only_formats_the_encoder_writes_are_named() { for name in craft_audio::ENCODE_EXTENSIONS { assert!(encode_format_for(name).is_some(), "{name}"); } - for other in ["mp3", "ogg", "m4a", "xyz", ""] { + for other in ["mp3", "m4a", "xyz", ""] { assert_eq!(encode_format_for(other), None, "{other}"); } } From acaa353f29f61e38b782dd90f304ea9387c9da5a Mon Sep 17 00:00:00 2001 From: Dylan Taylor Date: Sat, 14 Nov 2026 15:28:11 -0500 Subject: [PATCH 3/7] chore: trigger CI re-run From 9efb0a1575814ec7e159f332853f547c7a094832 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 18:12:40 -0500 Subject: [PATCH 4/7] Complete standalone Vorbis feature and option validation --- crates/audio/Cargo.toml | 2 +- crates/audio/src/write/mod.rs | 15 +++++++++++++++ crates/audio/src/write/vorbis.rs | 1 + 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 6e673b39d..8798272b3 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -24,7 +24,7 @@ decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa- symphonia = ["decode-native", "dep:symphonia"] # Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders. # All but Opus are also file formats of `encode` and `FileEncoder`. -encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode"] +encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode", "vorbis-encode"] # Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files. lossless-encode = ["pcm-encode", "flac-encode"] # Encode WAV/BWF/RF64 and AIFF/AIFF-C files. diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index b8372be1c..597a02e07 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -232,6 +232,15 @@ impl std::fmt::Debug for FileEncoder { // The writers differ in size with the features built; the coded one is boxed for its encoder. #[allow(clippy::large_enum_variant)] +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] enum Writer { #[cfg(feature = "pcm-encode")] Wav(wav::Writer), @@ -390,6 +399,12 @@ impl EncodeOptions { /// The constant bit rate such a file would be written at ([`FileEncoder::bitrate`]), or the /// error [`EncodeOptions::check`] returns. pub fn bitrate(&self, sample_rate: u32, channels: u16) -> Result> { + #[cfg(feature = "vorbis-encode")] + if self.format == EncodeFormat::Ogg { + // Vorbis is whole-buffer only and VBR has no constant output bitrate. + encode(&AudioBuffer::new(sample_rate, channels, 0), self)?; + return Ok(None); + } // The encoder a file would get, on a sink that is thrown away: what it accepts and the // rate it settles on are then the writer's by construction. Ok(FileEncoder::new(std::io::Cursor::new(Vec::new()), self, sample_rate, channels)?.bitrate()) diff --git a/crates/audio/src/write/vorbis.rs b/crates/audio/src/write/vorbis.rs index c264e1a54..a5e09ad88 100644 --- a/crates/audio/src/write/vorbis.rs +++ b/crates/audio/src/write/vorbis.rs @@ -71,6 +71,7 @@ pub fn encode(_buf: &AudioBuffer, _kbps: u32) -> Result> { #[cfg(all(test, not(target_arch = "wasm32")))] mod tests { + #![allow(clippy::unwrap_used)] use super::*; #[test] From dc2b83d7f426cb3286b3a1fa67229f27c1ca4d40 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 18:13:31 -0500 Subject: [PATCH 5/7] Document Vorbis rate semantics and validate standalone options --- crates/audio/src/lib.rs | 3 ++- crates/audio/src/write/mod.rs | 35 +++++++++++++++++++++++--------- crates/audio/src/write/vorbis.rs | 3 +++ 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 697568201..33dcdee3b 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -472,7 +472,8 @@ pub enum RateControl { /// set of rates (MP3, AC-3) uses the highest one not above it; a rate outside what the /// stream can carry is moved to the nearest one inside. AAC is written at 6 kbit/s or a /// quarter of the sample rate per channel at least: from about half of that down its encoder - /// codes silence. + /// codes silence. Vorbis treats this as a VBR target (64–500 kbit/s), falling back to + /// a quality preset when that target is unsupported; it does not promise a constant bitrate. Bitrate(u32), /// A constant quality from 0.0 (smallest) to 1.0 (best), at whatever bit rate each frame /// needs. AAC only; values outside the range are clamped, and NaN is an error. diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 597a02e07..ce4b90773 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -367,15 +367,6 @@ impl FileEncoder { } } -#[cfg(any( - feature = "pcm-encode", - feature = "flac-encode", - feature = "aac-encode", - feature = "alac-encode", - feature = "mp3-encode", - feature = "ac3-encode", - feature = "eac3-encode" -))] impl EncodeOptions { /// Whether a file of `channels` channels at `sample_rate` can be written with these options: /// `Ok`, or the error [`FileEncoder::new`] and [`encode`] would return, with nothing written. @@ -407,7 +398,31 @@ impl EncodeOptions { } // The encoder a file would get, on a sink that is thrown away: what it accepts and the // rate it settles on are then the writer's by construction. - Ok(FileEncoder::new(std::io::Cursor::new(Vec::new()), self, sample_rate, channels)?.bitrate()) + #[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" + ))] + { + Ok(FileEncoder::new(std::io::Cursor::new(Vec::new()), self, sample_rate, channels)?.bitrate()) + } + #[cfg(not(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" + )))] + { + let _ = (sample_rate, channels); + Err(AudioError::Unsupported("streaming encoders are not built".into())) + } } } diff --git a/crates/audio/src/write/vorbis.rs b/crates/audio/src/write/vorbis.rs index a5e09ad88..f0e267d50 100644 --- a/crates/audio/src/write/vorbis.rs +++ b/crates/audio/src/write/vorbis.rs @@ -64,6 +64,7 @@ pub fn encode(buf: &AudioBuffer, kbps: u32) -> Result> { } } +/// Ogg Vorbis encoding is unavailable on WASM; returns an unsupported-format error. #[cfg(target_arch = "wasm32")] pub fn encode(_buf: &AudioBuffer, _kbps: u32) -> Result> { Err(AudioError::Unsupported("Ogg Vorbis files are exported by the desktop app".into())) @@ -91,6 +92,8 @@ mod tests { for channels in [1, 2] { let audio = AudioBuffer::new(48_000, channels, 512); let opts = crate::EncodeOptions::new(crate::EncodeFormat::Ogg); + assert!(opts.check(48_000, channels).is_ok()); + assert_eq!(opts.bitrate(48_000, channels).unwrap(), None); let direct = encode(&audio, 192).unwrap(); let generic = crate::encode(&audio, &opts).unwrap(); assert!(direct.starts_with(b"OggS")); From 354acd6a54407a449eade4ccde9e58f6518da38b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 18:15:14 -0500 Subject: [PATCH 6/7] Cover Vorbis in format contract tests and assert streaming refusal --- crates/audio/tests/codecs/file_formats.rs | 26 ++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/audio/tests/codecs/file_formats.rs b/crates/audio/tests/codecs/file_formats.rs index 53947df12..84169f665 100644 --- a/crates/audio/tests/codecs/file_formats.rs +++ b/crates/audio/tests/codecs/file_formats.rs @@ -397,12 +397,15 @@ fn the_formats_are_named() { for name in ENCODE_EXTENSIONS { assert!(encode_format_for(name).is_some(), "{name}"); } - assert_eq!(ENCODE_EXTENSIONS.len(), 12); + assert_eq!(ENCODE_EXTENSIONS.len(), 13); for format in CODED { assert!(EncodeFormat::ALL.contains(&format) && format.is_built()); } let features: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.feature()).collect(); - assert_eq!(features, ["pcm-encode", "pcm-encode", "flac-encode", "alac-encode", "aac-encode", "mp3-encode", "ac3-encode", "eac3-encode"]); + assert_eq!( + features, + ["pcm-encode", "pcm-encode", "flac-encode", "alac-encode", "aac-encode", "mp3-encode", "ac3-encode", "eac3-encode", "vorbis-encode"] + ); } /// ffmpeg's decode of `file` as interleaved `f32`, split into `channels` channels. @@ -495,6 +498,10 @@ fn the_format_queries_agree_with_the_writer() { let layouts = masks.iter().map(|&mask| ChannelLayout::from_mask(mask)).chain((1..=9).map(ChannelLayout::unordered)); for layout in layouts { for &format in EncodeFormat::ALL { + // Vorbis is whole-buffer-only; its direct/generic API and options are tested separately. + if format == EncodeFormat::Ogg { + continue; + } // 24 bits is a depth every format has. let opts = EncodeOptions::new(format).with_layout(layout); for &sample_rate in &rates { @@ -520,7 +527,7 @@ fn the_format_queries_agree_with_the_writer() { // The most channels is the most: one more is refused, by the layouts of a format that has // a fixed set and by the writer of one that has not. let most: Vec = EncodeFormat::ALL.iter().map(|f| f.max_channels()).collect(); - assert_eq!(most, [32_767, 32_767, 8, 8, 8, 2, 6, 8]); + assert_eq!(most, [32_767, 32_767, 8, 8, 8, 2, 6, 8, 2]); for &format in EncodeFormat::ALL { let most = format.max_channels(); match format.fixed_layouts(most) { @@ -569,3 +576,16 @@ fn the_bit_rate_used_can_be_asked_for() { assert_eq!(encode(&buf, &opts).unwrap().len() as u32, 43 * 1152 / 8 * opts.bitrate(48_000, 2).unwrap().unwrap() / 48_000); assert!(is_unsupported(EncodeOptions::new(EncodeFormat::Mp3).bitrate(48_000, 6))); } + +#[test] +fn vorbis_is_whole_buffer_only_and_validates_layouts() { + let opts = EncodeOptions::new(EncodeFormat::Ogg).with_layout(ChannelLayout::STEREO); + assert!(opts.check(48_000, 2).is_ok()); + assert_eq!(opts.bitrate(48_000, 2).unwrap(), None); + assert!(FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, 2).is_err()); + let buf = craft_audio::AudioBuffer::new(48_000, 2, 512); + assert!(craft_audio::encode(&buf, &opts).unwrap().starts_with(b"OggS")); + let wrong = opts.with_layout(ChannelLayout::from_mask(0xC)); + assert!(wrong.check(48_000, 2).is_err()); + assert!(craft_audio::encode(&buf, &wrong).is_err()); +} From 92e665a5e8e12576095ca2addb681d2e3a0fac69 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 18:33:24 -0500 Subject: [PATCH 7/7] Exercise Vorbis block boundaries with distinct channel signals --- crates/audio/src/write/vorbis.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/audio/src/write/vorbis.rs b/crates/audio/src/write/vorbis.rs index f0e267d50..f56d01148 100644 --- a/crates/audio/src/write/vorbis.rs +++ b/crates/audio/src/write/vorbis.rs @@ -107,4 +107,24 @@ mod tests { } } } + #[cfg(feature = "decode")] + #[test] + fn distinct_signals_survive_full_and_partial_blocks() { + for frames in [4096, 4097, 8193] { + let channels: Vec> = [440.0f32, 880.0] + .into_iter() + .map(|hz| (0..frames).map(|i| (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin() * 0.4).collect()) + .collect(); + let audio = AudioBuffer { sample_rate: 48_000, channels }; + let bytes = encode(&audio, 192).unwrap(); + let (_, decoded) = crate::decode(&bytes, Some("ogg")).unwrap(); + assert_eq!(decoded.frames(), frames); + assert_eq!(decoded.channels.len(), 2); + for (expected, actual) in audio.channels.iter().zip(&decoded.channels) { + let mse = expected.iter().zip(actual).map(|(a, b)| (a - b).powi(2)).sum::() / frames as f32; + // Vorbis is lossy; this tolerates codec error but rejects silence or swapped channels. + assert!(mse.sqrt() < 0.08, "{frames} frames: RMS error {}", mse.sqrt()); + } + } + } }