diff --git a/Cargo.lock b/Cargo.lock index b35796c04..6e48813da 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]] @@ -6610,6 +6621,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" @@ -10371,6 +10391,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 d132f23da..8798272b3 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -24,13 +24,15 @@ 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. 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"] # The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`. @@ -65,6 +67,9 @@ rayon = { workspace = true, 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"] } +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +vorbis_rs = { version = "0.5", optional = true } + [dev-dependencies] craft-media-testkit = { workspace = true } proptest = { workspace = true } diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 1c6c73dcf..33dcdee3b 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -62,9 +62,12 @@ mod wav; feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", - feature = "eac3-encode" + feature = "eac3-encode", + feature = "vorbis-encode" ))] mod write; +#[cfg(feature = "vorbis-encode")] +pub use write::{OGG_BITRATES, 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 @@ -107,8 +110,6 @@ pub use read::{ pub use read::{RawPcm, aiff_pcm, wav_pcm}; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] pub use track::{LOOKAHEAD_PACKETS, TrackDecoder}; -#[cfg(feature = "pcm-encode")] -pub use write::wav_float_header; #[cfg(any( feature = "pcm-encode", feature = "flac-encode", @@ -118,7 +119,20 @@ pub use write::wav_float_header; feature = "ac3-encode", feature = "eac3-encode" ))] -pub use write::{ENCODE_EXTENSIONS, FileEncoder, encode, encode_format_for}; +pub use write::FileEncoder; +#[cfg(feature = "pcm-encode")] +pub use write::wav_float_header; +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "vorbis-encode" +))] +pub use write::{ENCODE_EXTENSIONS, encode, encode_format_for}; #[cfg(feature = "pcm-encode")] pub use write::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; @@ -256,6 +270,8 @@ pub enum EncodeFormat { Ac3, /// An E-AC-3 stream: up to 7.1 at 32, 44.1 or 48 kHz. Eac3, + /// Ogg Vorbis, whole-buffer encoding only. + Ogg, } impl EncodeFormat { @@ -270,6 +286,7 @@ impl EncodeFormat { EncodeFormat::Mp3, EncodeFormat::Ac3, EncodeFormat::Eac3, + EncodeFormat::Ogg, ]; /// The extension a new file of this format gets, lower case and without the dot: `"wav"`, @@ -284,6 +301,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => "mp3", EncodeFormat::Ac3 => "ac3", EncodeFormat::Eac3 => "eac3", + EncodeFormat::Ogg => "ogg", } } @@ -297,6 +315,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => "audio/mpeg", EncodeFormat::Ac3 => "audio/ac3", EncodeFormat::Eac3 => "audio/eac3", + EncodeFormat::Ogg => "audio/ogg", } } @@ -309,6 +328,7 @@ impl EncodeFormat { EncodeFormat::Aac | EncodeFormat::Alac => Container::Mp4, EncodeFormat::Mp3 => Container::MpegAudio, EncodeFormat::Ac3 | EncodeFormat::Eac3 => Container::Ac3, + EncodeFormat::Ogg => Container::Ogg, } } @@ -322,6 +342,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => CodecId::Mp3, EncodeFormat::Ac3 => CodecId::Ac3, EncodeFormat::Eac3 => CodecId::Eac3, + EncodeFormat::Ogg => CodecId::Vorbis, } } @@ -335,10 +356,11 @@ impl EncodeFormat { EncodeFormat::Mp3 => "mp3-encode", EncodeFormat::Ac3 => "ac3-encode", EncodeFormat::Eac3 => "eac3-encode", + EncodeFormat::Ogg => "vorbis-encode", } } - /// Whether [`encode`] and [`FileEncoder`] write this format in this build (its + /// Whether [`encode`] writes this format in this build (its /// [`feature`](Self::feature) is on): what to filter [`EncodeFormat::ALL`] by for a menu. pub fn is_built(self) -> bool { match self { @@ -349,6 +371,7 @@ impl EncodeFormat { EncodeFormat::Mp3 => cfg!(feature = "mp3-encode"), EncodeFormat::Ac3 => cfg!(feature = "ac3-encode"), EncodeFormat::Eac3 => cfg!(feature = "eac3-encode"), + EncodeFormat::Ogg => cfg!(all(feature = "vorbis-encode", not(target_arch = "wasm32"))), } } @@ -359,7 +382,7 @@ impl EncodeFormat { EncodeFormat::Aac => Some(&[7350, 8000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000, 64_000, 88_200, 96_000]), EncodeFormat::Mp3 => Some(&[16_000, 22_050, 24_000, 32_000, 44_100, 48_000]), EncodeFormat::Ac3 | EncodeFormat::Eac3 => Some(&[32_000, 44_100, 48_000]), - EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac | EncodeFormat::Alac => None, + EncodeFormat::Wav | EncodeFormat::Aiff | EncodeFormat::Flac | EncodeFormat::Alac | EncodeFormat::Ogg => None, } } @@ -371,7 +394,7 @@ impl EncodeFormat { EncodeFormat::Wav | EncodeFormat::Aiff => 32_767, EncodeFormat::Flac | EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Eac3 => 8, EncodeFormat::Ac3 => 6, - EncodeFormat::Mp3 => 2, + EncodeFormat::Mp3 | EncodeFormat::Ogg => 2, } } @@ -385,7 +408,7 @@ impl EncodeFormat { EncodeFormat::Aac => &[&[0x4], &[0x3], &[0x7], &[0x107], &[0x607], &[0x60F], &[0x70F], &[0xFF]], // Apple's layout tags for 1–8 channels, surrounds as back speakers. EncodeFormat::Alac => &[&[0x4], &[0x3], &[0x7], &[0x107], &[0x37], &[0x3F], &[0x13F], &[0xFF]], - EncodeFormat::Mp3 => &[&[0x4], &[0x3]], + EncodeFormat::Mp3 | EncodeFormat::Ogg => &[&[0x4], &[0x3]], // The coding modes 1/0 to 3/2 with and without an LFE, by channel count. EncodeFormat::Ac3 => &[&[0x4], &[0x3, 0xC], &[0x7, 0x103, 0xB], &[0x107, 0x603, 0xF, 0x10B], &[0x607, 0x10F, 0x60B], &[0x60F]], // The same, and 7.1 with backs and sides. @@ -436,7 +459,7 @@ impl EncodeFormat { /// Whether the format loses audio: AAC, MP3, AC-3 and E-AC-3. These take /// [`EncodeOptions::rate_control`] and ignore the bit depth and dither. pub fn is_lossy(self) -> bool { - matches!(self, EncodeFormat::Aac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3) + matches!(self, EncodeFormat::Aac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 | EncodeFormat::Ogg) } } @@ -449,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 0de55c394..ce4b90773 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -9,6 +9,10 @@ mod coded; #[cfg(feature = "flac-encode")] pub(crate) mod flac; mod pcm; +#[cfg(feature = "vorbis-encode")] +mod vorbis; +#[cfg(feature = "vorbis-encode")] +pub use vorbis::{OGG_BITRATES, encode as encode_ogg}; #[cfg(feature = "pcm-encode")] mod raw; #[cfg(feature = "pcm-encode")] @@ -17,6 +21,15 @@ mod wav; use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, Result}; #[cfg(feature = "pcm-encode")] pub use raw::{pcm_aiff_file, pcm_aiff_header, pcm_wav_file, pcm_wav_header}; +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] use std::io::{Seek, Write}; /// Encode `buf` as the file `opts.format` names. Integer depths clamp samples to [-1, 1]; float @@ -51,6 +64,18 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { EncodeFormat::Flac => flac::encode(buf, opts.bit_depth, opts.dither, mask), #[cfg(any(feature = "aac-encode", feature = "alac-encode", feature = "mp3-encode", feature = "ac3-encode", feature = "eac3-encode"))] EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Mp3 | EncodeFormat::Ac3 | EncodeFormat::Eac3 => coded::encode(buf, opts), + #[cfg(feature = "vorbis-encode")] + EncodeFormat::Ogg => { + if opts.layout.is_some_and(|layout| !EncodeFormat::Ogg.supports_layout(&layout)) { + return Err(AudioError::Unsupported("Vorbis requires a mono or stereo speaker layout".into())); + } + let kbps = match opts.rate_control { + None => 192, + Some(crate::RateControl::Bitrate(bps)) => bps / 1000, + Some(crate::RateControl::Quality(_)) => return Err(AudioError::Unsupported("Ogg export takes a target bitrate".into())), + }; + vorbis::encode(buf, kbps) + } #[allow(unreachable_patterns)] f => Err(AudioError::Unsupported(format!("writing {f:?}"))), } @@ -62,8 +87,8 @@ fn check_built(format: EncodeFormat) -> Result<()> { } /// Every extension [`ENCODE_EXTENSIONS`] can list, and how many of them the features built give. -const fn extensions() -> ([&'static str; 12], usize) { - let mut all = [""; 12]; +const fn extensions() -> ([&'static str; 13], usize) { + let mut all = [""; 13]; let mut n = 0; macro_rules! add { ($built:expr, $($extension:literal),+) => { @@ -81,10 +106,11 @@ const fn extensions() -> ([&'static str; 12], usize) { add!(cfg!(feature = "mp3-encode"), "mp3"); add!(cfg!(feature = "ac3-encode"), "ac3"); add!(cfg!(feature = "eac3-encode"), "eac3", "ec3"); + add!(cfg!(all(feature = "vorbis-encode", not(target_arch = "wasm32"))), "ogg"); (all, n) } -const EXTENSIONS: ([&str; 12], usize) = extensions(); +const EXTENSIONS: ([&str; 13], usize) = extensions(); /// The file extensions of the formats [`encode`] can write (those whose features are on). pub const ENCODE_EXTENSIONS: &[&str] = EXTENSIONS.0.split_at(EXTENSIONS.1).0; @@ -99,7 +125,7 @@ pub const ENCODE_EXTENSIONS: &[&str] = EXTENSIONS.0.split_at(EXTENSIONS.1).0; /// use craft_audio::{EncodeFormat, encode_format_for}; /// /// assert_eq!(encode_format_for(".AIFF"), Some(EncodeFormat::Aiff)); -/// assert_eq!(encode_format_for("ogg"), None); +/// assert_eq!(encode_format_for("unknown"), None); /// # } /// ``` pub fn encode_format_for(name: &str) -> Option { @@ -122,6 +148,8 @@ pub fn encode_format_for(name: &str) -> Option { "ac3" => Some(EncodeFormat::Ac3), #[cfg(feature = "eac3-encode")] "eac3" | "ec3" => Some(EncodeFormat::Eac3), + #[cfg(all(feature = "vorbis-encode", not(target_arch = "wasm32")))] + "ogg" => Some(EncodeFormat::Ogg), _ => None, } } @@ -138,6 +166,15 @@ fn wav_mask(layout: &ChannelLayout, channels: usize) -> Result { /// The error a stream encoder returns for every call after one of its writes has failed: the /// sink may already hold a prefix of the failed block, so the encoder's counters can no longer /// describe the bytes on the sink, and later writes or `finish` must not claim success. +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] fn failed_write_error() -> AudioError { AudioError::Encode("the stream encoder already failed on an earlier write; its output is incomplete".into()) } @@ -163,12 +200,30 @@ fn failed_write_error() -> AudioError { /// assert_eq!(&flac[..4], b"fLaC"); /// # } /// ``` +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] pub struct FileEncoder { writer: Writer, format: EncodeFormat, channels: usize, } +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode" +))] impl std::fmt::Debug for FileEncoder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("FileEncoder").field("format", &self.format).finish_non_exhaustive() @@ -177,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), @@ -188,6 +252,15 @@ enum Writer { Coded(Box>), } +#[cfg(any( + feature = "pcm-encode", + feature = "flac-encode", + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-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. @@ -317,9 +390,39 @@ 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()) + #[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 new file mode 100644 index 000000000..f56d01148 --- /dev/null +++ b/crates/audio/src/write/vorbis.rs @@ -0,0 +1,130 @@ +//! 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. +#[cfg(not(target_arch = "wasm32"))] +const BLOCK: usize = 4096; + +#[cfg(not(target_arch = "wasm32"))] +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(); + if !(1..=2).contains(&channels) { + return Err(AudioError::Unsupported("Ogg Vorbis export requires mono or stereo audio".into())); + } + if buf.channels.iter().any(|c| c.len() != buf.frames() || c.iter().any(|s| !s.is_finite())) { + return Err(AudioError::Encode("Vorbis samples must be finite and channels equally long".into())); + } + 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) + }; + + // Convert Rust unwinds to an error. This does not catch native crashes or aborts. + 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}"))), + } +} + +/// 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())) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + #[test] + fn rejects_unsupported_or_malformed_channels_without_dropping_audio() { + for channels in [0, 3, 6] { + assert!(matches!(encode(&AudioBuffer::new(48_000, channels, 16), 192), Err(AudioError::Unsupported(_)))); + } + let ragged = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.0; 16], vec![0.0; 15]] }; + assert!(encode(&ragged, 192).is_err()); + assert!(encode(&AudioBuffer::new(0, 1, 16), 192).is_err()); + let invalid = AudioBuffer { sample_rate: 48_000, channels: vec![vec![f32::NAN]] }; + assert!(encode(&invalid, 192).is_err()); + } + + #[test] + fn generic_and_direct_encoders_write_mono_and_stereo_ogg() { + 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")); + assert_eq!(direct, generic); + #[cfg(feature = "decode")] + { + let (info, decoded) = crate::decode(&generic, Some("ogg")).unwrap(); + assert_eq!(info.channels, channels); + assert_eq!(decoded.num_channels(), channels); + assert_eq!(decoded.frames(), audio.frames()); + } + } + } + #[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()); + } + } + } +} diff --git a/crates/audio/tests/audio/decode_extensions.rs b/crates/audio/tests/audio/decode_extensions.rs index 27a5573de..fc961cc39 100644 --- a/crates/audio/tests/audio/decode_extensions.rs +++ b/crates/audio/tests/audio/decode_extensions.rs @@ -77,6 +77,6 @@ fn every_encode_format_has_an_extension_it_is_written_and_read_under() { assert!(format.mime_type().starts_with("audio/"), "{format:?}"); } let extensions: Vec<_> = EncodeFormat::ALL.iter().map(|f| f.extension()).collect(); - assert_eq!(extensions, ["wav", "aif", "flac", "m4a", "m4a", "mp3", "ac3", "eac3"]); + assert_eq!(extensions, ["wav", "aif", "flac", "m4a", "m4a", "mp3", "ac3", "eac3", "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 7713f37a5..e91f93623 100644 --- a/crates/audio/tests/audio/encode_format.rs +++ b/crates/audio/tests/audio/encode_format.rs @@ -14,7 +14,15 @@ 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 ["ogg", "opus", "aac", "mp4", "xyz", ""] { + for other in ["opus", "aac", "mp4", "xyz", ""] { assert_eq!(encode_format_for(other), None, "{other}"); } } + +#[test] +fn ogg_names_follow_the_native_feature() { + let built = cfg!(all(feature = "vorbis-encode", not(target_arch = "wasm32"))); + assert_eq!(EncodeFormat::Ogg.is_built(), built); + assert_eq!(encode_format_for("ogg"), built.then_some(EncodeFormat::Ogg)); + assert_eq!(craft_audio::ENCODE_EXTENSIONS.contains(&"ogg"), built); +} 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()); +}