diff --git a/Cargo.lock b/Cargo.lock index b36240d6e..6be032393 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -222,16 +222,6 @@ 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" @@ -1414,7 +1404,6 @@ dependencies = [ "serde_json", "symphonia", "thiserror 2.0.21", - "vorbis_rs", ] [[package]] @@ -2859,6 +2848,14 @@ dependencies = [ "zip", ] +[[package]] +name = "craft-usd" +version = "0.1.0" +dependencies = [ + "lz4_flex", + "thiserror 2.0.21", +] + [[package]] name = "craft-vcard" version = "0.1.0" @@ -6058,6 +6055,12 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "lz4_flex" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" + [[package]] name = "maybe-owned" version = "0.3.4" @@ -6816,15 +6819,6 @@ 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 = "oid-registry" version = "0.8.1" @@ -10643,20 +10637,6 @@ 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/Cargo.toml b/Cargo.toml index 1b409247e..dd5593252 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] craft-http-url = { path = "crates/http-url" } +craft-usd = { path = "crates/usd" } craft-smime = { path = "crates/smime" } craft-ber = { path = "crates/ber" } craft-proto = { path = "crates/proto" } diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 645246130..859ac20bc 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-audio" -description = "Audio file I/O and codecs: WAV/AIFF read and write, FLAC encoder, AAC and ALAC decoders and encoders, AC-3/E-AC-3 decoder and encoder, MP3 decoder and encoder, Opus decoder and encoder, MP1/MP2 decoders." +description = "Audio file I/O and codecs: WAV/AIFF read and write, FLAC encoder, AAC and ALAC decoders and encoders, AC-3/E-AC-3 decoder and encoder, MP3 decoder and encoder, Opus decoder and encoder, Vorbis encoder, MP1/MP2 decoders." version.workspace = true edition.workspace = true license.workspace = true @@ -31,8 +31,9 @@ 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"] +# The pure-Rust Vorbis encoder (`vorbis::encoder`) and Ogg Vorbis files through `encode` and +# `encode_ogg_vorbis`. +vorbis-encode = ["craft-media/ogg"] # 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`. @@ -72,9 +73,6 @@ 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/README.md b/crates/audio/README.md index 63251db8d..a5af4b3f3 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -29,7 +29,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `decode` | `decode`, `probe`, `Decoder`, `tracks`, `TrackDecoder`; every format in [Format support](#format-support) | `decode-native`, `symphonia` | | `decode-native` | the same, native formats only (others are `Unsupported`); `wav_pcm`, `aiff_pcm` (a file's integer PCM bit for bit, as `RawPcm`) | the six decoders below, craft-media `isobmff`/`matroska`/`ogg`, `log` | | `symphonia` | the fallback for formats with no native decoder; turning it on is the same as `decode` | `decode-native`, symphonia | -| `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode` | +| `encode` | every encoder, and every format of `encode` and `FileEncoder` | `lossless-encode`, `aac-encode`, `alac-encode`, `ac3-encode`, `eac3-encode`, `mp3-encode`, `opus-encode`, `vorbis-encode` | | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | | `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | @@ -37,6 +37,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `alac-decode` | `alac::Decoder` | none | | `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` | | `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none | +| `vorbis-encode` | `vorbis::encoder::Encoder` (pure Rust); `encode_ogg_vorbis`, `encode_ogg` and `encode` for Ogg Vorbis files (whole buffer; not `FileEncoder`) | craft-media `ogg` | | `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` | | `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` | | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | @@ -355,8 +356,12 @@ let pre_skip = enc.pre_skip(); // samples the player drops at the start The encoder takes 48 kHz only, and craft-audio has no resampler. -craft-media has no Ogg muxer, so `.opus` files cannot be written yet; Opus goes into -Matroska/WebM or MP4: +Opus goes into Ogg, Matroska/WebM or MP4: + +- **Ogg (`.opus`):** `craft_media::ogg::PageWriter` with `head` and `opus_tags` as the two header + packets, each packet's granule position the samples decoded so far (pre-skip included, as + the input above starts with it), and `finish(Some(pre_skip + length))` to trim the end + (RFC 7845 §4). - **Matroska/WebM:** `head` is the track's `CodecPrivate`, and the pre-skip goes in `TrackSpec::codec_delay_ns` (in nanoseconds at 48 kHz). The Matroska muxer cannot write @@ -368,6 +373,27 @@ Matroska/WebM or MP4: timescale), `segment_duration` the audio's length (movie timescale), `media_rate` `0x0001_0000`. +### Encode Ogg Vorbis + +```rust +use craft_audio::{OggVorbisOptions, encode_ogg_vorbis}; + +// 1–8 channels in Vorbis order (5.1: L C R Ls Rs LFE), any sample rate. +let opts = OggVorbisOptions::new(6.0).with_tag("TITLE", "Take 3").with_tag("ARTIST", "Me"); +let ogg: Vec = encode_ogg_vorbis(&buf, &opts)?; +``` + +The encoder is pure Rust (`vorbis::encoder`, from FilmCraft #4481) and builds for wasm32. Quality +runs from -1 to 10 at a variable bit rate: about 18 kbit/s per channel at -1, 100 at 6 and 140 +at 10 on music. `encode` with `EncodeFormat::Ogg` takes a WAV-order layout and writes it in +Vorbis order; its `RateControl::Bitrate` (64–500 kbit/s) picks the quality whose nominal rate +that is (`quality_for_bitrate`), and `RateControl::Quality` 0.0–1.0 is quality -1 to 10. For +streaming, feed `vorbis::encoder::Encoder` and write its packets with `craft_media::ogg::PageWriter` +(identification, `vorbis_comment`, setup, then the audio with each packet's granule position). + +Not yet: short blocks (transients may pre-echo), channel coupling (stereo costs +about twice mono) and bit-rate management. + ### Waveform overviews ```rust @@ -704,6 +730,7 @@ the full tests with ffmpeg and the vectors required. | MP3 encoder | FilmCraft `filmcraft-mp3enc` [4bec22b](https://github.com/storytold/filmcraft/commit/4bec22bd03bd1d995c9cf72e02a284f96d3d72cd) | | ALAC | Apple's reference implementation [macosforge/alac@c38887c](https://github.com/macosforge/alac/tree/c38887c5c5e64a4b31108733bd79ca9b2496d987/codec), Copyright © 2011 Apple Inc., Apache-2.0; ported to Rust and modified (see the `alac` module docs and [NOTICE](../../NOTICE)) | | Opus encoder | EffectCraft `effectcraft-opusenc` [c618429](https://github.com/storytold/effectcraft/commit/c618429252587525a2a6d4b5bccbe4ec5261e1b9) | +| Vorbis encoder | FilmCraft `filmcraft-vorbis` by @JordyUSA ([storytold/filmcraft#4481](https://github.com/storytold/filmcraft/pull/4481)), with partitions of whole sample frames so libvorbis reads surround | Where apps had overlapping implementations, the one that measured better was kept, with the tests of both: diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index be0678303..8151d4072 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -13,6 +13,8 @@ //! demuxers and [`TrackDecoder`]; everything else (FLAC, Vorbis, CAF, ADPCM, A-law, µ-law) through //! `symphonia`, which is to be replaced by native decoders. Feature `decode-native` is the //! same without symphonia. +//! - [`encode_ogg_vorbis`] and [`vorbis::encoder`] (feature `vorbis-encode`): Ogg Vorbis files +//! and Vorbis packets from a pure-Rust encoder, 1 to 8 channels, quality -1 to 10, with tags. //! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar //! `f32` in WAV channel order. //! - [`encode`], [`FileEncoder`]: WAV/BWF/RF64 and AIFF/AIFF-C (feature `pcm-encode`, which also @@ -56,6 +58,8 @@ pub mod qoa; mod read; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] mod track; +#[cfg(feature = "vorbis-encode")] +pub mod vorbis; #[cfg(any(feature = "decode-native", feature = "pcm-encode"))] mod wav; /// Bounded WAV/RF64 cue, adtl and XMP marker metadata, without audio decoding. @@ -75,7 +79,7 @@ mod write; /// Range-backed PCM WAVE access and a 16-bit PCM writer. pub mod wav_range; #[cfg(feature = "vorbis-encode")] -pub use write::{OGG_BITRATES, encode_ogg}; +pub use write::{OGG_BITRATES, OggVorbisOptions, encode_ogg, encode_ogg_vorbis, quality_for_bitrate}; /// 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 @@ -278,7 +282,9 @@ 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 Vorbis, 1–8 channels at any sample rate, whole-buffer encoding only. Variable bit + /// rate: a [`RateControl::Bitrate`] picks the quality whose nominal rate it is + /// ([`quality_for_bitrate`]), [`RateControl::Quality`] sets it directly. Ogg, } @@ -379,7 +385,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"))), + EncodeFormat::Ogg => cfg!(feature = "vorbis-encode"), } } @@ -400,9 +406,9 @@ impl EncodeFormat { pub fn max_channels(self) -> u16 { match self { EncodeFormat::Wav | EncodeFormat::Aiff => 32_767, - EncodeFormat::Flac | EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Eac3 => 8, + EncodeFormat::Flac | EncodeFormat::Aac | EncodeFormat::Alac | EncodeFormat::Eac3 | EncodeFormat::Ogg => 8, EncodeFormat::Ac3 => 6, - EncodeFormat::Mp3 | EncodeFormat::Ogg => 2, + EncodeFormat::Mp3 => 2, } } @@ -416,7 +422,10 @@ 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 | EncodeFormat::Ogg => &[&[0x4], &[0x3]], + EncodeFormat::Mp3 => &[&[0x4], &[0x3]], + // The Vorbis I §4.3.9 layouts for 1–8 channels (6.1 with a back centre and sides, 7.1 + // with sides and backs), written in Vorbis order. + EncodeFormat::Ogg => &[&[0x4], &[0x3], &[0x7], &[0x33], &[0x37], &[0x3F], &[0x70F], &[0x63F]], // 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. @@ -458,10 +467,10 @@ impl EncodeFormat { } } - /// Whether the format takes [`RateControl::Quality`]: AAC. The other lossy formats are - /// written at a constant bit rate only. + /// Whether the format takes [`RateControl::Quality`]: AAC and Ogg Vorbis. The other lossy + /// formats are written at a constant bit rate only. pub fn supports_quality(self) -> bool { - self == EncodeFormat::Aac + matches!(self, EncodeFormat::Aac | EncodeFormat::Ogg) } /// Whether the format loses audio: AAC, MP3, AC-3 and E-AC-3. These take @@ -480,11 +489,12 @@ 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. 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. + /// codes silence. Vorbis takes 64–500 kbit/s and writes the quality whose nominal rate that is + /// ([`quality_for_bitrate`]); its rate varies with the audio. 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. + /// needs. AAC and Vorbis (0.0 is Vorbis quality -1, 1.0 quality 10); values outside the range + /// are clamped, and NaN is an error. Quality(f32), } diff --git a/crates/audio/src/vorbis/encoder/book.rs b/crates/audio/src/vorbis/encoder/book.rs new file mode 100644 index 000000000..b392cf27c --- /dev/null +++ b/crates/audio/src/vorbis/encoder/book.rs @@ -0,0 +1,287 @@ +//! Bit packing (Vorbis I §2) and codebooks (§3): Huffman lengths, the codeword assignment the +//! decoder derives from them, VQ lattices (lookup type 1) and the header encoding. + +use super::{Error, Result}; + +/// LSB-first bit packer (Vorbis I §2.1.4): bits fill each byte from its least significant end. +#[derive(Clone, Debug, Default)] +pub struct BitWriter { + buf: Vec, + bits: u64, +} + +impl BitWriter { + pub fn new() -> BitWriter { + BitWriter::default() + } + + /// Writes the low `n` bits of `v` (`n` ≤ 32). + pub fn write(&mut self, v: u32, n: u32) { + let n = n.min(32); + for i in 0..n { + let bit = (v >> i) & 1; + let at = (self.bits / 8) as usize; + if at == self.buf.len() { + self.buf.push(0); + } + if bit != 0 + && let Some(b) = self.buf.get_mut(at) + { + *b |= 1 << (self.bits % 8); + } + self.bits += 1; + } + } + + pub fn flag(&mut self, b: bool) { + self.write(b as u32, 1); + } + + /// Writes a codeword MSB first: the decoder walks the tree from its first bit. + fn codeword(&mut self, word: u32, len: u32) { + for i in (0..len).rev() { + self.write((word >> i) & 1, 1); + } + } + + pub fn bytes(&mut self, data: &[u8]) { + for &b in data { + self.write(u32::from(b), 8); + } + } + + pub fn finish(self) -> Vec { + self.buf + } +} + +/// `ilog` of the specification (§9.2.1): the position of the highest set bit, 0 for 0. +pub fn ilog(v: u32) -> u32 { + 32 - v.leading_zeros() +} + +/// The 32-bit float format of codebook headers (§9.2.2), for values it represents exactly. +pub fn float32_pack(v: f64) -> u32 { + if v == 0.0 || !v.is_finite() { + return 0; + } + let sign = if v < 0.0 { 0x8000_0000u32 } else { 0 }; + let mut m = v.abs(); + let mut exp: i32 = 0; + // a 21-bit mantissa: scale into [2^20, 2^21) + while m >= (1 << 21) as f64 { + m /= 2.0; + exp += 1; + } + while m < (1 << 20) as f64 { + m *= 2.0; + exp -= 1; + } + let mant = (m.round() as u32).min((1 << 21) - 1); + let biased = (exp + 788).clamp(0, 1023) as u32; + sign | (biased << 21) | mant +} + +/// Huffman code lengths (1..=`max_len`) for `weights`, every entry coded. +pub fn huffman_lengths(weights: &[f64], max_len: u32) -> Vec { + let n = weights.len(); + if n <= 1 { + return vec![1; n]; + } + let total: f64 = weights.iter().map(|w| if w.is_finite() { w.max(0.0) } else { 0.0 }).sum::().max(1e-300); + let mut floor = 1e-9; + loop { + let w: Vec = weights.iter().map(|&x| (if x.is_finite() { x.max(0.0) } else { 0.0 }) / total + floor).collect(); + let lens = huffman(&w); + if lens.iter().all(|&l| l <= max_len) || floor > 1.0 { + return lens.into_iter().map(|l| l.clamp(1, max_len)).collect(); + } + floor *= 4.0; + } +} + +fn huffman(w: &[f64]) -> Vec { + // nodes: (weight, children) with leaves first + let n = w.len(); + let mut parent = vec![usize::MAX; 2 * n]; + let mut weight: Vec = w.to_vec(); + let mut alive: Vec = (0..n).collect(); + while alive.len() > 1 { + alive.sort_by(|&a, &b| weight[b].partial_cmp(&weight[a]).unwrap_or(std::cmp::Ordering::Equal).then(b.cmp(&a))); + let (Some(a), Some(b)) = (alive.pop(), alive.pop()) else { break }; + let id = weight.len(); + weight.push(weight[a] + weight[b]); + if parent.len() <= id { + parent.resize(id + 1, usize::MAX); + } + parent[a] = id; + parent[b] = id; + alive.push(id); + } + (0..n) + .map(|i| { + let mut d = 0; + let mut x = i; + while let Some(&p) = parent.get(x) { + if p == usize::MAX { + break; + } + d += 1; + x = p; + } + d + }) + .collect() +} + +/// The codewords the decoder assigns to `lengths` (§3.2.1): in entry order, each entry gets the +/// lowest available codeword of its length (no prefix of an assigned codeword, and no assigned +/// codeword a prefix of it). An error when the lengths do not fit a prefix code. +pub fn assign_codewords(lengths: &[u32]) -> Result> { + // A trie of the assigned codewords: `children[node]` (0 = none), `leaf[node]`. + let mut children: Vec<[usize; 2]> = vec![[0, 0]]; + let mut leaf = vec![false]; + let mut words = Vec::with_capacity(lengths.len()); + for &len in lengths { + if len == 0 || len > 32 { + return Err(Error::Internal("codeword length")); + } + let bits = lowest_free(&children, &leaf, 0, len).ok_or(Error::Internal("over-subscribed codebook"))?; + let mut node = 0usize; + let mut word = 0u32; + for &bit in &bits { + word = (word << 1) | bit as u32; + node = match children[node][bit] { + 0 => { + children.push([0, 0]); + leaf.push(false); + let id = children.len() - 1; + children[node][bit] = id; + id + } + c => c, + }; + } + leaf[node] = true; + words.push(word); + } + Ok(words) +} + +/// The leftmost free path of `depth` bits below `node` (depth-first, 0 before 1). +fn lowest_free(children: &[[usize; 2]], leaf: &[bool], node: usize, depth: u32) -> Option> { + if leaf[node] || depth == 0 { + return None; + } + for bit in 0..2 { + let c = children[node][bit]; + if c == 0 { + let mut p = vec![bit]; + p.resize(depth as usize, 0); + return Some(p); + } + if let Some(mut rest) = lowest_free(children, leaf, c, depth - 1) { + rest.insert(0, bit); + return Some(rest); + } + } + None +} + +/// A codebook: entry lengths and codewords, and for VQ books a lattice (lookup type 1). +#[derive(Clone, Debug)] +pub struct Codebook { + pub dimensions: u32, + pub lengths: Vec, + pub words: Vec, + /// Lattice values per dimension (lookup type 1: `values^dimensions == entries`). + pub lattice: Option, +} + +#[derive(Clone, Copy, Debug)] +pub struct Lattice { + pub minimum: f64, + pub delta: f64, + /// Values per dimension. + pub values: u32, +} + +impl Codebook { + /// A scalar book (no lookup) of `weights.len()` entries. + pub fn scalar(dimensions: u32, weights: &[f64]) -> Result { + let lengths = huffman_lengths(weights, 20); + let words = assign_codewords(&lengths)?; + Ok(Codebook { dimensions, lengths, words, lattice: None }) + } + + /// A lattice VQ book: `values` integers per dimension from `minimum` in steps of `delta`; + /// `weight(v)` is the relative probability of one component `v`. + pub fn lattice(dimensions: u32, values: u32, minimum: i32, delta: i32, weight: impl Fn(i32) -> f64) -> Result { + let entries = values.checked_pow(dimensions).ok_or(Error::Internal("codebook size"))?; + let w: Vec = (0..entries) + .map(|e| { + let mut p = 1.0; + let mut rest = e; + for _ in 0..dimensions { + let t = (rest % values) as i32; + rest /= values; + p *= weight(minimum + t * delta); + } + p + }) + .collect(); + let lengths = huffman_lengths(&w, 20); + let words = assign_codewords(&lengths)?; + Ok(Codebook { dimensions, lengths, words, lattice: Some(Lattice { minimum: f64::from(minimum), delta: f64::from(delta), values }) }) + } + + pub fn entries(&self) -> usize { + self.lengths.len() + } + + /// Writes entry `e`. + pub fn put(&self, w: &mut BitWriter, e: usize) { + if let (Some(&word), Some(&len)) = (self.words.get(e), self.lengths.get(e)) { + w.codeword(word, len); + } + } + + /// The entry of the lattice vector `v` (component 0 is the least significant digit, §3.2.1). + pub fn entry_of(&self, v: &[i32]) -> usize { + let Some(l) = self.lattice else { return 0 }; + let mut e = 0usize; + let mut scale = 1usize; + for &x in v.iter().take(self.dimensions as usize) { + let t = ((f64::from(x) - l.minimum) / l.delta).round().clamp(0.0, f64::from(l.values - 1)) as usize; + e += t * scale; + scale *= l.values as usize; + } + e + } + + /// The header encoding (§3.2.1). + pub fn write_header(&self, w: &mut BitWriter) { + w.write(0x56_4342, 24); + w.write(self.dimensions, 16); + w.write(self.entries() as u32, 24); + w.flag(false); // not ordered + w.flag(false); // not sparse + for &l in &self.lengths { + w.write(l - 1, 5); + } + match self.lattice { + None => w.write(0, 4), + Some(l) => { + w.write(1, 4); + w.write(float32_pack(l.minimum), 32); + w.write(float32_pack(l.delta), 32); + let bits = ilog(l.values - 1).max(1); + w.write(bits - 1, 4); + w.flag(false); // sequence_p + for m in 0..l.values { + w.write(m, bits); + } + } + } + } +} diff --git a/crates/audio/src/vorbis/encoder/floor.rs b/crates/audio/src/vorbis/encoder/floor.rs new file mode 100644 index 000000000..503385bd3 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/floor.rs @@ -0,0 +1,207 @@ +//! Floor type 1 (Vorbis I §7): a piecewise-linear spectral envelope in the decoder's dB scale. +//! +//! The encoder picks a target value at each of the floor's X positions, codes it against the +//! decoder's prediction from its neighbours (step 2 of §7.2.4, inverted), and renders the curve +//! exactly as the decoder will (`render_line`, integer arithmetic), so the residue is computed +//! against the very floor the decoder multiplies it by. + +use super::book::{BitWriter, Codebook, ilog}; + +/// `floor1_multiplier`: 2, so values run 0..128 and step two entries of the dB table. +pub const MULTIPLIER: u32 = 2; +/// The value range for [`MULTIPLIER`] 2. +pub const RANGE: i32 = 128; +const RANGE_BITS: u32 = 10; +/// Points per partition, and partitions. +pub const CLASS_DIM: usize = 4; +pub const PARTITIONS: usize = 8; + +/// Step (in dB) between entries of `floor1_inverse_dB_table`: it runs from 1.0649863e-07 to 1 +/// over 256 entries. +fn db_step() -> f64 { + (1.0f64 / 1.064_986_3e-7).ln() / 255.0 +} + +/// `floor1_inverse_dB_table[i]`. +pub fn inverse_db(i: i32) -> f32 { + (f64::from(i.clamp(0, 255) - 255) * db_step()).exp() as f32 +} + +/// The table index whose amplitude is nearest (in dB) to `a`. +pub fn db_index(a: f32) -> i32 { + if !a.is_finite() || a <= 0.0 { + return 0; + } + ((f64::from(a)).ln() / db_step() + 255.0).round().clamp(0.0, 255.0) as i32 +} + +/// A floor 1 configuration for blocks of `n/2 = 2^RANGE_BITS` bins. +#[derive(Clone, Debug)] +pub struct Floor1 { + /// X positions: 0, 1024, then the partitions' points. + pub xs: Vec, + /// Index of the book coding the point values. + pub book: usize, + /// For each point (in coding order) its low and high neighbours. + neighbours: Vec<(usize, usize)>, + /// Point indices sorted by X. + sorted: Vec, +} + +impl Floor1 { + /// Points spaced about evenly in log frequency over 1..1024. + pub fn new(book: usize) -> Floor1 { + let count = CLASS_DIM * PARTITIONS; + let mut xs = vec![0, 1 << RANGE_BITS]; + let mut last = 0; + for i in 1..=count { + // geometric from 2 to ~1000 bins, at least one bin apart + let x = (2.0f64 * (500.0f64).powf((i - 1) as f64 / (count - 1) as f64)).round() as i32; + let x = x.max(last + 1).min((1 << RANGE_BITS) - 1); + xs.push(x); + last = x; + } + let neighbours = (0..xs.len()) + .map(|i| { + if i < 2 { + return (0, 0); + } + let (mut lo, mut hi) = (0usize, 1usize); + for j in 0..i { + if xs[j] < xs[i] && xs[j] > xs[lo] { + lo = j; + } + if xs[j] > xs[i] && xs[j] < xs[hi] { + hi = j; + } + } + (lo, hi) + }) + .collect(); + let mut sorted: Vec = (0..xs.len()).collect(); + sorted.sort_by_key(|&i| xs[i]); + Floor1 { xs, book, neighbours, sorted } + } + + /// The setup-header encoding (§7.2.2): one class of `CLASS_DIM` points, no subclasses. + pub fn write_header(&self, w: &mut BitWriter) { + w.write(PARTITIONS as u32, 5); + for _ in 0..PARTITIONS { + w.write(0, 4); + } + w.write(CLASS_DIM as u32 - 1, 3); + w.write(0, 2); // no subclasses + w.write(self.book as u32 + 1, 8); + w.write(MULTIPLIER - 1, 2); + w.write(RANGE_BITS, 4); + for &x in &self.xs[2..] { + w.write(x as u32, RANGE_BITS); + } + } + + /// Codes the target values `want` (one per point, 0..RANGE) into `w`; returns the floor curve + /// the decoder renders (`n2` amplitudes). + pub fn encode(&self, w: &mut BitWriter, book: &Codebook, want: &[i32], n2: usize) -> Vec { + let n = self.xs.len(); + let want = |i: usize| want.get(i).copied().unwrap_or(0).clamp(0, RANGE - 1); + let mut fin = vec![0i32; n]; + let mut used = vec![false; n]; + let mut coded = vec![0u32; n]; + fin[0] = want(0); + fin[1] = want(1); + used[0] = true; + used[1] = true; + for i in 2..n { + let (lo, hi) = self.neighbours[i]; + let pred = render_point(self.xs[lo], fin[lo], self.xs[hi], fin[hi], self.xs[i]); + let f = want(i); + let (highroom, lowroom) = (RANGE - pred, pred); + let room = 2 * highroom.min(lowroom); + let val = if f == pred { + 0 + } else { + let d = f - pred; + let inside = if d > 0 { 2 * d } else { -2 * d - 1 }; + if inside < room { + inside + } else if highroom > lowroom { + f - pred + lowroom + } else { + pred - f + highroom - 1 + } + }; + coded[i] = val.clamp(0, RANGE - 1) as u32; + if val != 0 { + used[lo] = true; + used[hi] = true; + used[i] = true; + fin[i] = f; + } else { + fin[i] = pred; + } + } + let bits = ilog(RANGE as u32 - 1); + w.write(fin[0] as u32, bits); + w.write(fin[1] as u32, bits); + for &c in &coded[2..] { + book.put(w, c as usize); + } + self.render(&fin, &used, n2) + } + + /// The decoder's curve (§7.2.4 step 2, `render_line`) as amplitudes. + fn render(&self, fin: &[i32], used: &[bool], n2: usize) -> Vec { + let mut v = vec![0i32; n2]; + let m = MULTIPLIER as i32; + let (mut lx, mut ly) = (0i32, fin[self.sorted[0]] * m); + let (mut hx, mut hy) = (0i32, ly); + for &i in &self.sorted[1..] { + if used[i] { + hy = fin[i] * m; + hx = self.xs[i]; + render_line(lx, ly, hx, hy, &mut v); + lx = hx; + ly = hy; + } + } + if (hx as usize) < n2 { + render_line(hx, hy, n2 as i32, hy, &mut v); + } + v.iter().map(|&i| inverse_db(i)).collect() + } +} + +fn render_point(x0: i32, y0: i32, x1: i32, y1: i32, x: i32) -> i32 { + let dy = y1 - y0; + let adx = (x1 - x0).max(1); + let err = dy.abs() * (x - x0); + let off = err / adx; + if dy < 0 { y0 - off } else { y0 + off } +} + +fn render_line(x0: i32, y0: i32, x1: i32, y1: i32, v: &mut [i32]) { + let dy = y1 - y0; + let adx = x1 - x0; + if adx <= 0 { + return; + } + let base = dy / adx; + let sy = if dy < 0 { base - 1 } else { base + 1 }; + let ady = dy.abs() - base.abs() * adx; + let (mut y, mut err) = (y0, 0); + if let Some(s) = v.get_mut(x0 as usize) { + *s = y; + } + for x in x0 + 1..x1 { + err += ady; + if err >= adx { + err -= adx; + y += sy; + } else { + y += base; + } + if let Some(s) = v.get_mut(x as usize) { + *s = y; + } + } +} diff --git a/crates/audio/src/vorbis/encoder/mdct.rs b/crates/audio/src/vorbis/encoder/mdct.rs new file mode 100644 index 000000000..3802a24d6 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/mdct.rs @@ -0,0 +1,134 @@ +//! Forward MDCT of a windowed block of `n` samples to `n/2` coefficients: +//! `X[k] = Σ x[j] cos(2Ï€/n · (j + 1/2 + n/4)(k + 1/2))`, the transform the Vorbis decoder inverts +//! (Vorbis I §1.3.2, §4.3.9). Computed as a DCT-IV of the folded block through an `n/8`-point +//! complex FFT. + +use std::f64::consts::PI; + +#[derive(Clone, Copy, Default, Debug)] +struct Cpx { + re: f64, + im: f64, +} + +impl Cpx { + fn mul(self, o: Cpx) -> Cpx { + Cpx { re: self.re * o.re - self.im * o.im, im: self.re * o.im + self.im * o.re } + } +} + +/// A forward MDCT for one block size (a power of two, at least 16). +#[derive(Clone, Debug)] +pub struct Mdct { + n: usize, + twiddle: Vec, + post: Vec, + fft_tw: Vec, + rev: Vec, +} + +impl Mdct { + pub fn new(n: usize) -> Mdct { + let m = n / 2; // DCT-IV length + let h = m / 2; // FFT length + let twiddle = (0..h).map(|j| cis(-PI * (4.0 * j as f64 + 1.0) / (4.0 * m as f64))).collect(); + let post = (0..h).map(|k| cis(-PI * k as f64 / m as f64)).collect(); + let fft_tw = (0..h / 2).map(|j| cis(-2.0 * PI * j as f64 / h as f64)).collect(); + let bits = h.trailing_zeros(); + let rev = (0..h).map(|i| if bits == 0 { 0 } else { i.reverse_bits() >> (usize::BITS - bits) }).collect(); + Mdct { n, twiddle, post, fft_tw, rev } + } + + /// `x`: `n` windowed samples; `out`: `n/2` coefficients (scaled by `scale`). + pub fn forward(&self, x: &[f32], out: &mut [f32], scale: f64) { + let n = self.n; + let m = n / 2; + let q = n / 4; + let at = |i: usize| f64::from(x.get(i).copied().unwrap_or(0.0)); + // fold (a, b, c, d) to the DCT-IV input (-c_r - d, a - b_r) + let mut v = vec![0f64; m]; + for (i, s) in v.iter_mut().enumerate() { + *s = if i < q { -at(3 * q - 1 - i) - at(3 * q + i) } else { at(i - q) - at(3 * q - 1 - i) }; + } + // DCT-IV through a half-length complex FFT + let h = m / 2; + let mut z: Vec = (0..h).map(|j| Cpx { re: v[2 * j], im: v[m - 1 - 2 * j] }.mul(self.twiddle[j])).collect(); + self.fft(&mut z); + for (k, c) in z.iter().enumerate() { + let d = c.mul(self.post[k]); + if let Some(o) = out.get_mut(2 * k) { + *o = (d.re * scale) as f32; + } + if let Some(o) = out.get_mut(m - 1 - 2 * k) { + *o = (-d.im * scale) as f32; + } + } + } + + /// In-place radix-2 FFT (`e^{-2Ï€i jk/h}`). + fn fft(&self, a: &mut [Cpx]) { + let h = a.len(); + for i in 0..h { + let j = self.rev[i]; + if i < j { + a.swap(i, j); + } + } + let mut len = 2; + while len <= h { + let step = h / len; + for start in (0..h).step_by(len) { + for k in 0..len / 2 { + let w = self.fft_tw[k * step]; + let u = a[start + k]; + let t = a[start + k + len / 2].mul(w); + a[start + k] = Cpx { re: u.re + t.re, im: u.im + t.im }; + a[start + k + len / 2] = Cpx { re: u.re - t.re, im: u.im - t.im }; + } + } + len *= 2; + } + } +} + +fn cis(t: f64) -> Cpx { + Cpx { re: t.cos(), im: t.sin() } +} + +/// The Vorbis window (§4.3.1) for a block of `n` between blocks of the same size. +pub fn window(n: usize) -> Vec { + (0..n) + .map(|i| { + let s = (PI * (i as f64 + 0.5) / n as f64).sin(); + (PI / 2.0 * s * s).sin() as f32 + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn matches_the_direct_formula() { + for n in [16usize, 64, 256, 2048] { + let x: Vec = (0..n).map(|i| ((i * 7919 % 211) as f32 - 105.0) / 50.0).collect(); + let mut fast = vec![0f32; n / 2]; + Mdct::new(n).forward(&x, &mut fast, 1.0); + for k in [0usize, 1, 2, n / 4, n / 2 - 1] { + let direct: f64 = + (0..n).map(|j| f64::from(x[j]) * (2.0 * PI / n as f64 * (j as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos()).sum(); + assert!((direct - f64::from(fast[k])).abs() < 1e-3 * (1.0 + direct.abs()), "n={n} k={k}: {direct} vs {}", fast[k]); + } + } + } + + #[test] + fn the_window_is_power_complementary() { + let w = window(2048); + for i in 0..1024 { + let s = w[i] * w[i] + w[i + 1024] * w[i + 1024]; + assert!((s - 1.0).abs() < 1e-5, "{i}: {s}"); + } + } +} diff --git a/crates/audio/src/vorbis/encoder/mod.rs b/crates/audio/src/vorbis/encoder/mod.rs new file mode 100644 index 000000000..95be88244 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/mod.rs @@ -0,0 +1,494 @@ +//! Pure-Rust Vorbis I encoder, written from the Vorbis I specification (Xiph.Org, 2020-07-04). +//! +//! No `unsafe` and no C code; builds for `wasm32-unknown-unknown`. ffmpeg is used only as an +//! external test oracle. +//! +//! The stream: one mode of 2048-sample blocks; per channel a floor 1 envelope of 34 points; one +//! residue type 2 over the interleaved channels, partitions of 32 values (a multiple of the +//! channel count for 3, 5, 6 and 7 channels) in seven classes (silent, +//! three single-pass lattice books, and two- and three-pass cascades for large values); no channel +//! coupling. Quality (-1 to 10) sets how far the floor sits from the spectral envelope (below it +//! for tonal regions, above it for noise-like ones, from the spectral flatness), and with it the +//! residue's precision: variable bit rate, like other Vorbis encoders. +//! +//! From FilmCraft's `filmcraft-vorbis` by @JordyUSA (storytold/filmcraft#4481). +//! +//! The packets go into Ogg with [`craft_media::ogg::PageWriter`] and a comment header from +//! [`craft_media::ogg::vorbis_comment`]; [`crate::encode_ogg_vorbis`] does all of it for a +//! whole buffer. +//! +//! ``` +//! use craft_audio::vorbis::encoder::{Encoder, EncoderConfig}; +//! +//! let mut enc = Encoder::new(EncoderConfig::new(48_000, 2, 5.0))?; +//! let tone: Vec = (0..4_800).map(|i| (i as f32 * 0.05).sin() * 0.5).collect(); +//! let mut packets = enc.encode(&[&tone, &tone])?; +//! packets.extend(enc.finish()?); +//! // the last granule position is the input's length, so a decoder trims the padding +//! assert_eq!(packets.last().map(|p| p.1), Some(4_800)); +//! assert_eq!(&enc.identification()[1..7], b"vorbis"); +//! # Ok::<(), craft_audio::vorbis::encoder::Error>(()) +//! ``` + +// Index loops follow the specification, as in FilmCraft (which allows this lint workspace-wide). +#![allow(clippy::needless_range_loop)] + +mod book; +mod floor; +mod mdct; + +use book::{BitWriter, Codebook}; +use floor::Floor1; +use mdct::Mdct; + +/// Why an encoder could not be created or input could not be encoded. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// A setting or the input is outside what the encoder takes. + #[error("invalid argument: {0}")] + InvalidArgument(&'static str), + /// An encoder invariant failed (a bug, reported instead of panicking). + #[error("internal error: {0}")] + Internal(&'static str), +} + +/// The encoder's result type. +pub type Result = std::result::Result; + +/// Block size (samples); the short block size of the header is never used. +pub const BLOCK: usize = 2048; +const HOP: usize = BLOCK / 2; +/// Residue values per partition for `channels` channels: 32, or for 3, 5, 6 and 7 channels a +/// multiple of the channel count (48, 40, 48, 56). libvorbis decodes each partition of an +/// interleaved (type 2) residue as if it started on channel 0, so a partition must hold whole +/// sample frames; the size also divides `channels × 1024` and is a multiple of every book's +/// dimension (4). +fn partition_size(channels: usize) -> usize { + match channels { + 3 | 6 => 48, + 5 => 40, + 7 => 56, + _ => 32, + } +} +const CLASSES: usize = 8; +/// Largest residue magnitude the cascade codes: 7·225 + 7·15 + 7. +const MAX_RESIDUE: i32 = 1687; + +/// The quality a NaN or infinite setting reads as. +pub const DEFAULT_QUALITY: f32 = 6.0; + +/// Encoder settings. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EncoderConfig { + /// Samples per second, 1 to 768 000. + pub sample_rate: u32, + /// 1 to 8, in Vorbis channel order (§4.3.9). + pub channels: usize, + /// -1 (smallest) to 10 (best); clamped. + pub quality: f32, +} + +impl EncoderConfig { + /// Settings for `channels` channels (in Vorbis order) at `sample_rate` and `quality`. + pub fn new(sample_rate: u32, channels: usize, quality: f32) -> EncoderConfig { + EncoderConfig { sample_rate, channels, quality } + } +} + +/// Book indices in the setup header. +const BOOK_CLASS: usize = 0; +const BOOK_FLOOR: usize = 1; +const BOOK_A1_SPARSE: usize = 2; +const BOOK_A1: usize = 3; +const BOOK_A2: usize = 4; +const BOOK_A4: usize = 5; +const BOOK_F: usize = 6; +const BOOK_M: usize = 7; +const BOOK_C: usize = 8; + +/// Books per class and pass (`None`: nothing coded in that pass). +const CASCADE: [[Option; 3]; CLASSES] = [ + [None, None, None], + [Some(BOOK_A1_SPARSE), None, None], + [Some(BOOK_A1), None, None], + [Some(BOOK_A2), None, None], + [Some(BOOK_A4), None, None], + [Some(BOOK_F), None, None], + [Some(BOOK_M), Some(BOOK_F), None], + [Some(BOOK_C), Some(BOOK_M), Some(BOOK_F)], +]; + +/// A Vorbis encoder for one stream: planar `f32` in, Vorbis packets with their granule +/// positions out. +pub struct Encoder { + cfg: EncoderConfig, + books: Vec, + floor: Floor1, + mdct: Mdct, + window: Vec, + /// Input not yet past a block, per channel; the next block starts at `start`. + pending: Vec>, + /// Read cursor into `pending`: consumed hops are dropped once per call, not per block. + start: usize, + samples_in: u64, + blocks: u64, + finished: bool, + /// Floor offset below the envelope (dB) for tonal and for noise-like regions. + tonal_db: f32, + noise_db: f32, + /// Residue magnitudes below this quantise to 0. + dead_zone: f32, +} + +impl Encoder { + /// An encoder for `cfg`: 1 to 8 channels, a sample rate of 1 to 768 000; the quality is + /// clamped to -1..=10, and NaN or infinite reads as [`DEFAULT_QUALITY`]. + pub fn new(cfg: EncoderConfig) -> Result { + if !(1..=8).contains(&cfg.channels) { + return Err(Error::InvalidArgument("Vorbis encoder: 1 to 8 channels")); + } + if !(1..=768_000).contains(&cfg.sample_rate) { + return Err(Error::InvalidArgument("Vorbis encoder: sample rate")); + } + let quality = if cfg.quality.is_finite() { cfg.quality.clamp(-1.0, 10.0) } else { DEFAULT_QUALITY }; + let cfg = EncoderConfig { quality, ..cfg }; + let books = vec![ + Codebook::scalar(2, &(0..CLASSES * CLASSES).map(|e| class_weight(e / CLASSES) * class_weight(e % CLASSES)).collect::>())?, + Codebook::scalar(1, &(0..floor::RANGE).map(|v| 1.0 / (1.0 + f64::from(v)).powf(1.6)).collect::>())?, + Codebook::lattice(4, 3, -1, 1, |v| if v == 0 { 0.92 } else { 0.04 })?, + Codebook::lattice(4, 3, -1, 1, |v| if v == 0 { 0.5 } else { 0.25 })?, + Codebook::lattice(2, 5, -2, 1, |v| 0.6f64.powi(v.abs()))?, + Codebook::lattice(2, 9, -4, 1, |v| 0.7f64.powi(v.abs()))?, + Codebook::lattice(2, 15, -7, 1, |v| 0.8f64.powi(v.abs()))?, + Codebook::lattice(2, 15, -105, 15, |v| 0.55f64.powi((v / 15).abs()))?, + Codebook::lattice(2, 15, -1575, 225, |v| 0.4f64.powi((v / 225).abs()))?, + ]; + Ok(Encoder { + cfg, + books, + floor: Floor1::new(BOOK_FLOOR), + mdct: Mdct::new(BLOCK), + window: mdct::window(BLOCK), + // the first block is centred on sample 0: the decoder's first output is input sample 0 + pending: vec![vec![0.0; HOP]; cfg.channels], + start: 0, + samples_in: 0, + blocks: 0, + finished: false, + // tones 4 dB (-1) to 30.4 dB (10) under their envelope; noise 14 dB above it (-1) + // to 4.1 dB (10) + tonal_db: 4.0 + 2.4 * (quality + 1.0), + noise_db: -14.0 + 0.9 * (quality + 1.0), + dead_zone: 0.8 - 0.025 * (quality + 1.0), + }) + } + + /// Channels per sample frame. + pub fn channels(&self) -> usize { + self.cfg.channels + } + + /// The quality in use, after clamping. + pub fn quality(&self) -> f32 { + self.cfg.quality + } + + /// Input samples per channel taken so far. + pub fn samples_in(&self) -> u64 { + self.samples_in + } + + /// The identification header packet (§4.2.2): the first packet of the stream. + pub fn identification(&self) -> Vec { + let mut w = BitWriter::new(); + w.write(1, 8); + w.bytes(b"vorbis"); + w.write(0, 32); + w.write(self.cfg.channels as u32, 8); + w.write(self.cfg.sample_rate, 32); + w.write(0, 32); // bit rates: unset (variable) + w.write(0, 32); + w.write(0, 32); + w.write(8, 4); // 256-sample short blocks (unused) + w.write(11, 4); // 2048-sample long blocks + w.flag(true); + w.finish() + } + + /// The setup header packet (§4.2.4): codebooks, floor, residue, mapping and mode. It follows + /// the comment header. + pub fn setup(&self) -> Vec { + let mut w = BitWriter::new(); + w.write(5, 8); + w.bytes(b"vorbis"); + w.write(self.books.len() as u32 - 1, 8); + for b in &self.books { + b.write_header(&mut w); + } + w.write(0, 6); // one time-domain transform placeholder + w.write(0, 16); + w.write(0, 6); // one floor + w.write(1, 16); + self.floor.write_header(&mut w); + w.write(0, 6); // one residue, type 2 + w.write(2, 16); + let end = (self.cfg.channels * HOP) as u32; + w.write(0, 24); + w.write(end, 24); + w.write(partition_size(self.cfg.channels) as u32 - 1, 24); + w.write(CLASSES as u32 - 1, 6); + w.write(BOOK_CLASS as u32, 8); + for c in &CASCADE { + let bits: u32 = c.iter().enumerate().map(|(j, b)| u32::from(b.is_some()) << j).sum(); + w.write(bits & 7, 3); + w.flag(bits > 7); + if bits > 7 { + w.write(bits >> 3, 5); + } + } + for c in &CASCADE { + for b in c.iter().flatten() { + w.write(*b as u32, 8); + } + } + w.write(0, 6); // one mapping, type 0 + w.write(0, 16); + w.flag(false); // one submap + w.flag(false); // no coupling + w.write(0, 2); + w.write(0, 8); // submap 0: time, floor 0, residue 0 + w.write(0, 8); + w.write(0, 8); + w.write(0, 6); // one mode: long blocks, mapping 0 + w.flag(true); + w.write(0, 16); + w.write(0, 16); + w.write(0, 8); + w.flag(true); + w.finish() + } + + /// Encodes planar samples (one slice per channel, all the same length, nominal range ±1); + /// returns the packets completed with their granule positions. NaN or infinite samples, or a + /// channel count or length mismatch, are an error. + pub fn encode(&mut self, planar: &[&[f32]]) -> Result, i64)>> { + if self.finished { + return Err(Error::InvalidArgument("Vorbis encoder: encode after finish")); + } + if planar.len() != self.cfg.channels { + return Err(Error::InvalidArgument("Vorbis encoder: one slice per channel")); + } + let len = planar.first().map_or(0, |p| p.len()); + if planar.iter().any(|p| p.len() != len) { + return Err(Error::InvalidArgument("Vorbis encoder: channels of different lengths")); + } + if planar.iter().any(|p| p.iter().any(|v| !v.is_finite())) { + return Err(Error::InvalidArgument("Vorbis encoder: NaN or infinite sample")); + } + for (b, p) in self.pending.iter_mut().zip(planar) { + b.extend_from_slice(p); + } + self.samples_in += len as u64; + self.drain() + } + + /// Encodes what remains, padded with silence; the last packet's granule position is the + /// input's length, so the decoder trims the padding (§A.2). + pub fn finish(&mut self) -> Result, i64)>> { + if self.finished { + return Ok(Vec::new()); + } + self.finished = true; + // block k ends output at k·HOP: blocks 0..=ceil(len / HOP) + let blocks = self.samples_in.div_ceil(HOP as u64) + 1; + let missing = blocks.saturating_sub(self.blocks) as usize; + self.compact(); + let need = (missing + 1) * HOP; + for b in self.pending.iter_mut() { + if b.len() < need { + b.resize(need, 0.0); + } + } + let mut out = Vec::new(); + for _ in 0..missing { + out.push(self.block()?); + } + Ok(out) + } + + fn drain(&mut self) -> Result, i64)>> { + let mut out = Vec::new(); + while self.pending.first().is_some_and(|b| b.len().saturating_sub(self.start) >= BLOCK) { + out.push(self.block()?); + } + self.compact(); + Ok(out) + } + + /// Drops the hops already encoded from the front of every channel buffer. + fn compact(&mut self) { + for b in self.pending.iter_mut() { + b.drain(..self.start.min(b.len())); + } + self.start = 0; + } + + /// Encodes the block at `start` in `pending` and advances by a hop. + fn block(&mut self) -> Result<(Vec, i64)> { + let ch = self.cfg.channels; + let mut w = BitWriter::new(); + w.write(0, 1); // audio packet; one mode, so no mode number + w.flag(true); // previous and next windows long + w.flag(true); + let mut residue = vec![0i32; ch * HOP]; + let mut any = false; + let mut x = vec![0f32; BLOCK]; + let mut coeffs = vec![0f32; HOP]; + for c in 0..ch { + let src = self.pending.get(c).and_then(|b| b.get(self.start..)).ok_or(Error::Internal("channel buffer"))?; + for (i, v) in x.iter_mut().enumerate() { + *v = src.get(i).copied().unwrap_or(0.0).clamp(-8.0, 8.0) * self.window[i]; + } + self.mdct.forward(&x, &mut coeffs, 2.0 / HOP as f64); + let peak = coeffs.iter().fold(0f32, |m, v| m.max(v.abs())); + // (a NaN peak cannot happen: samples are finite and clamped) + if peak <= 1e-7 { + w.flag(false); // floor unused: the channel is silent + continue; + } + any = true; + w.flag(true); + let want = self.floor_targets(&coeffs); + let curve = self.floor.encode(&mut w, &self.books[BOOK_FLOOR], &want, HOP); + for (k, (&v, &f)) in coeffs.iter().zip(&curve).enumerate() { + let r = if f > 0.0 { v / f } else { 0.0 }; + // a dead zone: values just past half a step are noise peaks, not worth a ±1 + let q = if r.abs() < self.dead_zone { 0.0 } else { r.round() }; + residue[k * ch + c] = if q.is_finite() { (q as i32).clamp(-MAX_RESIDUE, MAX_RESIDUE) } else { 0 }; + } + } + if any { + self.write_residue(&mut w, &residue); + } + let granule = if self.blocks == 0 { + 0 + } else { + let natural = self.blocks.saturating_mul(HOP as u64); + if self.finished { natural.min(self.samples_in) } else { natural } + }; + self.start += HOP; + self.blocks += 1; + Ok((w.finish(), i64::try_from(granule).unwrap_or(i64::MAX))) + } + + /// Floor values at the floor's points: the spectral envelope (power smoothed over a quarter of + /// the frequency, at least 8 bins, on each side) less an offset that grows with the region's tonality, from its + /// spectral flatness: noise needs a few dB of precision, tones much more. + fn floor_targets(&self, coeffs: &[f32]) -> Vec { + let n = coeffs.len(); + let mut cum = vec![0f64; n + 1]; + let mut cum_ln = vec![0f64; n + 1]; + for (i, &v) in coeffs.iter().enumerate() { + let p = f64::from(v) * f64::from(v); + cum[i + 1] = cum[i] + p; + cum_ln[i + 1] = cum_ln[i] + (p + 1e-30).ln(); + } + self.floor + .xs + .iter() + .map(|&x| { + let k = (x as usize).min(n - 1); + let half = (k / 4).max(8); + let (lo, hi) = (k.saturating_sub(half), (k + half + 1).min(n)); + let len = (hi - lo) as f64; + let am = (cum[hi] - cum[lo]) / len; + let gm = ((cum_ln[hi] - cum_ln[lo]) / len).exp(); + // spectral flatness: about -2.5 dB for noise, far below for a tone + let sfm_db = 10.0 * (gm / am.max(1e-30)).max(1e-30).log10(); + let tonality = ((-sfm_db - 2.5) / 20.0).clamp(0.0, 1.0); + let offset = tonality * f64::from(self.tonal_db) + (1.0 - tonality) * f64::from(self.noise_db); + let amp = (am.sqrt() * 10f64.powf(-offset / 20.0)).max(1e-7) as f32; + (floor::db_index(amp) + 1) / floor::MULTIPLIER as i32 + }) + .collect() + } + + /// Residue type 2 (§8.6.2 with the interleaved vector): classes per partition, then the + /// cascade's passes in the decoder's order. + fn write_residue(&self, w: &mut BitWriter, r: &[i32]) { + let partition = partition_size(self.cfg.channels); + let parts = r.len() / partition; + let classes: Vec = r.chunks(partition).map(class_of).collect(); + let per_word = self.books[BOOK_CLASS].dimensions as usize; + for pass in 0..3 { + let mut pc = 0; + while pc < parts { + if pass == 0 { + let mut e = 0usize; + for i in 0..per_word { + e = e * CLASSES + classes.get(pc + i).copied().unwrap_or(0); + } + self.books[BOOK_CLASS].put(w, e); + } + for _ in 0..per_word { + if pc >= parts { + break; + } + let class = classes[pc]; + if let Some(b) = CASCADE[class][pass] { + let book = &self.books[b]; + let dims = book.dimensions as usize; + let part = &r[pc * partition..(pc + 1) * partition]; + for chunk in part.chunks(dims) { + let v: Vec = chunk.iter().map(|&x| pass_value(x, class, pass)).collect(); + book.put(w, book.entry_of(&v)); + } + } + pc += 1; + } + } + } + } +} + +/// Relative frequency of each residue class (for the class book's code lengths). +fn class_weight(c: usize) -> f64 { + [0.3, 0.2, 0.12, 0.12, 0.1, 0.08, 0.06, 0.02].get(c).copied().unwrap_or(0.01) +} + +/// The part of residue value `v` coded in `pass` for `class`: the passes add up to `v`. +fn pass_value(v: i32, class: usize, pass: usize) -> i32 { + let split = |v: i32, step: i32| -> (i32, i32) { + let a = ((f64::from(v) / f64::from(step)).round() as i32).clamp(-7, 7); + (a * step, v - a * step) + }; + match (class, pass) { + (6, 0) => split(v, 15).0, + (6, _) => split(v, 15).1, + (7, 0) => split(v, 225).0, + (7, 1) => split(split(v, 225).1, 15).0, + (7, _) => split(split(v, 225).1, 15).1, + _ => v, + } +} + +/// The residue class of a partition: silent; ±1 with at most four nonzero values, or more; then +/// by the largest magnitude. +fn class_of(p: &[i32]) -> usize { + let m = p.iter().map(|v| v.abs()).max().unwrap_or(0); + match m { + 0 => 0, + 1 if p.iter().filter(|&&v| v != 0).count() <= 4 => 1, + 1 => 2, + 2 => 3, + 3..=4 => 4, + 5..=7 => 5, + 8..=112 => 6, + _ => 7, + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/audio/src/vorbis/encoder/tests.rs b/crates/audio/src/vorbis/encoder/tests.rs new file mode 100644 index 000000000..b1ae87463 --- /dev/null +++ b/crates/audio/src/vorbis/encoder/tests.rs @@ -0,0 +1,285 @@ +//! Unit tests, and ffmpeg (as an external oracle only) decoding the encoder's streams. + +#![allow(clippy::unwrap_used)] + +use std::path::Path; +use std::process::Command; + +use super::book::{BitWriter, assign_codewords, float32_pack}; +use super::{BLOCK, Encoder, EncoderConfig, HOP, partition_size}; + +#[test] +fn codewords_follow_the_specification_example() { + // Vorbis I §3.2.1: lengths 2 4 4 4 4 2 3 3 + let words = assign_codewords(&[2, 4, 4, 4, 4, 2, 3, 3]).unwrap(); + assert_eq!(words, [0b00, 0b0100, 0b0101, 0b0110, 0b0111, 0b10, 0b110, 0b111]); + assert!(assign_codewords(&[1, 1, 1]).is_err(), "over-subscribed"); +} + +#[test] +fn every_book_is_a_complete_prefix_code() { + let e = Encoder::new(EncoderConfig::new(48_000, 2, 5.0)).unwrap(); + for (i, b) in e.books.iter().enumerate() { + let kraft: f64 = b.lengths.iter().map(|&l| 0.5f64.powi(l as i32)).sum(); + assert!((kraft - 1.0).abs() < 1e-9, "book {i}: Kraft sum {kraft}"); + assert!(b.lengths.iter().all(|&l| (1..=20).contains(&l))); + for (a, (&wa, &la)) in b.words.iter().zip(&b.lengths).enumerate() { + for (c, (&wc, &lc)) in b.words.iter().zip(&b.lengths).enumerate() { + if a != c && la <= lc { + assert_ne!(wc >> (lc - la), wa, "book {i}: codeword {a} is a prefix of {c}"); + } + } + } + } +} + +#[test] +fn float32_pack_is_exact_for_lattice_values() { + let unpack = |x: u32| { + let mant = f64::from(x & 0x1F_FFFF); + let exp = ((x >> 21) & 0x3FF) as i32 - 788; + let v = mant * 2f64.powi(exp); + if x & 0x8000_0000 != 0 { -v } else { v } + }; + for v in [1.0, -1.0, -2.0, -4.0, -7.0, -105.0, 15.0, -1575.0, 225.0, 0.5, 3.0] { + assert_eq!(unpack(float32_pack(v)), v); + } + assert_eq!(float32_pack(0.0), 0); +} + +#[test] +fn bits_are_packed_lsb_first() { + let mut w = BitWriter::new(); + w.write(0b1, 1); + w.write(0b10, 2); + w.write(0x1F, 5); + w.write(0xABC, 12); + assert_eq!(w.finish(), [0b1111_1101, 0xBC, 0x0A]); +} + +#[test] +fn hostile_input_is_an_error_not_a_panic() { + assert!(Encoder::new(EncoderConfig::new(48_000, 0, 3.0)).is_err()); + assert!(Encoder::new(EncoderConfig::new(48_000, 9, 3.0)).is_err()); + assert!(Encoder::new(EncoderConfig::new(0, 2, 3.0)).is_err()); + assert_eq!(Encoder::new(EncoderConfig::new(48_000, 1, f32::NAN)).unwrap().cfg.quality, 6.0, "NaN quality uses the default, as the export does"); + let mut e = Encoder::new(EncoderConfig::new(44_100, 2, 3.0)).unwrap(); + assert!(e.encode(&[&[0.0; 4]]).is_err()); + assert!(e.encode(&[&[0.0; 4], &[0.0; 3]]).is_err()); + assert!(e.encode(&[&[f32::NAN; 4], &[0.0; 4]]).is_err()); + let loud = vec![1e30f32; 5000]; + assert!(!e.encode(&[&loud, &loud]).unwrap().is_empty()); + assert!(!e.finish().unwrap().is_empty()); + assert!(e.finish().unwrap().is_empty()); + assert!(e.encode(&[&[0.0; 4], &[0.0; 4]]).is_err()); +} + +#[test] +fn granules_count_the_samples_and_trim_the_end() { + for len in [0usize, 1, 1023, 1024, 1025, 48_000] { + let mut e = Encoder::new(EncoderConfig::new(48_000, 1, 3.0)).unwrap(); + let x = vec![0.1f32; len]; + let mut packets = e.encode(&[&x]).unwrap(); + packets.extend(e.finish().unwrap()); + assert_eq!(packets.len(), len.div_ceil(HOP) + 1, "len {len}"); + // packet k ends output at k·1024 samples; the last one at the input's length + let want: Vec = (0..packets.len()).map(|k| ((k * HOP) as i64).min(len as i64)).collect(); + let got: Vec = packets.iter().map(|p| p.1).collect(); + assert_eq!(got, want, "len {len}"); + } +} + +// --- ffmpeg oracle --- + +/// An Ogg Vorbis file of the three headers and the audio packets, through craft-media's writer. +fn ogg(packets: &[(Vec, i64)]) -> Vec { + let mut w = craft_media::ogg::PageWriter::new(7); + let mut out = Vec::new(); + for (i, (p, g)) in packets.iter().enumerate() { + out.extend(if i < 3 { w.header(p) } else { w.packet(p, *g) }); + } + out.extend(w.finish(None)); + out +} + +fn comment() -> Vec { + craft_media::ogg::vorbis_comment("test", &[]) +} + +/// Encodes `input` (planar) and decodes it with ffmpeg's `decoder`; returns the planar output. +/// ffmpeg's decoders to check: its own `vorbis` always, and `libvorbis` when ffmpeg has it. +fn decoders(ff: &Path) -> Vec<&'static str> { + let list = + Command::new(ff).args(["-hide_banner", "-decoders"]).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default(); + if list.lines().any(|l| l.split_whitespace().nth(1) == Some("libvorbis")) { + vec!["vorbis", "libvorbis"] + } else { + eprintln!("SKIPPED (libvorbis decoder): this ffmpeg has no libvorbis; checking its own decoder only"); + vec!["vorbis"] + } +} + +fn round_trip(input: &[Vec], rate: u32, quality: f32, decoder: &str, name: &str) -> Option<(Vec>, usize)> { + let ff = craft_media_testkit::ffmpeg_or_skip("vorbis oracle")?; + let mut e = Encoder::new(EncoderConfig::new(rate, input.len(), quality)).unwrap(); + let mut packets = vec![(e.identification(), 0), (comment(), 0), (e.setup(), 0)]; + let n = input[0].len(); + let mut at = 0; + while at < n { + let end = (at + 4410).min(n); + let s: Vec<&[f32]> = input.iter().map(|c| &c[at..end]).collect(); + packets.extend(e.encode(&s).unwrap()); + at = end; + } + packets.extend(e.finish().unwrap()); + let bytes: usize = packets[3..].iter().map(|p| p.0.len()).sum(); + let dir = craft_media_testkit::fixtures_dir("audio/vorbis-encoder"); + let path = dir.join(format!("{name}.ogg")); + std::fs::write(&path, ogg(&packets)).unwrap(); + let out = Command::new(ff) + .args(["-v", "error", "-xerror", "-c:a", decoder, "-i"]) + .arg(&path) + .args(["-f", "f32le", "-c:a", "pcm_f32le", "-"]) + .output() + .unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "{name} {decoder}: {}", String::from_utf8_lossy(&out.stderr)); + let pcm: Vec = out.stdout.as_chunks::<4>().0.iter().map(|&b| f32::from_le_bytes(b)).collect(); + let ch = input.len(); + Some(((0..ch).map(|c| pcm.iter().skip(c).step_by(ch).copied().collect()).collect(), bytes)) +} + +fn snr_db(a: &[f32], b: &[f32]) -> f64 { + let (mut s, mut e) = (0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + s += f64::from(x) * f64::from(x); + e += (f64::from(x) - f64::from(y)).powi(2); + } + 10.0 * (s.max(1e-20) / e.max(1e-20)).log10() +} + +fn music(n: usize, seed: u32) -> Vec { + let mut r = seed; + (0..n) + .map(|i| { + let t = i as f32 / 48_000.0; + r = r.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let noise = (r >> 8) as f32 / 8_388_608.0 - 1.0; + let chord: f32 = [220.0f32, 277.18, 329.63, 440.0] + .iter() + .enumerate() + .map(|(k, f)| (0.2 / (k + 1) as f32) * (2.0 * std::f32::consts::PI * f * t).sin()) + .sum(); + chord + 0.01 * noise + }) + .collect() +} + +/// Harmonic chords changing every half second, with decaying noise bursts (music-like). +fn chords(n: usize, seed: u32) -> Vec { + let mut r = seed; + let notes = [220.0f32, 277.2, 329.6, 440.0, 349.2, 523.3, 392.0, 659.3]; + (0..n) + .map(|i| { + let t = i as f32 / 48_000.0; + let chord = (t * 2.0) as usize; + let mut s = 0.0; + for k in 0..3 { + let f = notes[(chord * 3 + k * 2) % notes.len()]; + for h in 1..6 { + s += (2.0 * std::f32::consts::PI * f * h as f32 * t).sin() * 0.08 / h as f32; + } + } + r = r.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let env = (-(t * 2.0).fract() * 3.0).exp(); + s * (0.5 + 0.5 * env) + 0.02 * ((r >> 8) as f32 / 8_388_608.0 - 1.0) * env + }) + .collect() +} + +/// ffmpeg's own Vorbis decoder and libvorbis read every stream exactly as long as the input, +/// with SNR floors about 6 dB (chords 4 dB) under what the encoder measured when written, and bit +/// rates near libvorbis's for the same quality. +/// A signal, and per quality the SNR floor and the bit-rate range (kbit/s). +type Case = (&'static str, Vec>, [(f32, f64, std::ops::Range); 5]); + +#[test] +fn ffmpeg_decodes_every_quality() { + let Some(ff) = craft_media_testkit::ffmpeg_or_skip("vorbis oracle") else { return }; + let n = 48_000 * 3; + let cases: [Case; 2] = [ + ( + "music", + vec![music(n, 1), music(n, 2).iter().map(|v| v * 0.7).collect()], + [(-1.0, 3.0, 15..90), (0.0, 6.5, 20..110), (3.0, 12.0, 60..180), (6.0, 18.5, 120..280), (10.0, 25.5, 180..400)], + ), + ( + "chords", + vec![chords(n, 1), chords(n, 2).iter().map(|v| v * 0.8).collect()], + [(-1.0, 4.5, 20..90), (0.0, 6.0, 25..110), (3.0, 10.0, 70..200), (6.0, 14.0, 130..300), (10.0, 19.0, 180..420)], + ), + ]; + for (name, input, levels) in &cases { + for (q, floor, kbps) in levels { + for decoder in decoders(&ff) { + let Some((out, bytes)) = round_trip(input, 48_000, *q, decoder, &format!("{name}{q}")) else { return }; + assert!(out.iter().all(|c| c.len() == n), "{name} q{q} {decoder}: length {}", out[0].len()); + let snr = snr_db(&input[0][4096..], &out[0][4096..]); + assert!(snr >= *floor, "{name} q{q} {decoder}: {snr:.2} dB < {floor}"); + let rate = bytes * 8 / 3 / 1000; + assert!(kbps.contains(&rate), "{name} q{q}: {rate} kbit/s outside {kbps:?}"); + } + } + } +} + +/// Mono, 44.1 kHz, 3.0, 5.1 and 6.1 streams decode too, with libvorbis as well (which reads each +/// residue partition from channel 0); a silent channel costs one bit per block. +#[test] +fn channel_counts_and_rates() { + let Some(ff) = craft_media_testkit::ffmpeg_or_skip("vorbis oracle") else { return }; + let n = 44_100; + for (rate, ch) in [(44_100u32, 1usize), (22_050, 2), (48_000, 3), (48_000, 6), (48_000, 7)] { + let mut input: Vec> = (0..ch).map(|c| chords(n, c as u32 + 1).iter().map(|v| v * (1.0 - 0.1 * c as f32)).collect()).collect(); + if ch == 6 { + input[3] = vec![0.0; n]; + } + for decoder in decoders(&ff) { + let Some((mut out, _)) = round_trip(&input, rate, 5.0, decoder, &format!("ch{ch}_{rate}_{decoder}")) else { return }; + if decoder == "vorbis" { + // ffmpeg's decoder gives WAV order (5.1: FL FR FC LFE BL BR); the stream is in Vorbis + // order (L C R Ls Rs LFE), which libvorbis passes through + let wav_to_vorbis: &[usize] = match ch { + 3 => &[0, 2, 1], + 6 => &[0, 2, 1, 4, 5, 3], + 7 => &[0, 2, 1, 5, 6, 4, 3], + _ => &[0, 1], + }; + if ch > 2 { + out = wav_to_vorbis.iter().map(|&i| out[i].clone()).collect(); + } + } + assert_eq!(out.len(), ch); + for (c, (a, b)) in input.iter().zip(&out).enumerate() { + assert_eq!(b.len(), n, "{ch} ch {rate} Hz {decoder}: channel {c} length"); + if a.iter().all(|&v| v == 0.0) { + assert!(b.iter().all(|v| v.abs() < 1e-6), "silent channel {c}"); + } else { + let snr = snr_db(&a[4096..], &b[4096..]); + assert!(snr > 8.0, "{ch} ch {rate} Hz {decoder} channel {c}: {snr:.1} dB"); + } + } + } + } +} + +/// Every partition holds whole sample frames (libvorbis decodes each one from channel 0), splits +/// the interleaved residue evenly and fits every book's dimension. +#[test] +fn partitions_hold_whole_frames() { + for ch in 1..=8 { + let p = partition_size(ch); + assert_eq!(p % ch, 0, "{ch} channels"); + assert_eq!((ch * BLOCK / 2) % p, 0, "{ch} channels"); + assert_eq!(p % 4, 0, "{ch} channels"); + } +} diff --git a/crates/audio/src/vorbis/mod.rs b/crates/audio/src/vorbis/mod.rs new file mode 100644 index 000000000..29c423f1d --- /dev/null +++ b/crates/audio/src/vorbis/mod.rs @@ -0,0 +1,4 @@ +//! Vorbis I (feature `vorbis-encode`): the pure-Rust [`encoder`]. Decoding Vorbis goes through +//! [`crate::decode`]. + +pub mod encoder; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index ce4b90773..a2043d279 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -12,7 +12,7 @@ mod pcm; #[cfg(feature = "vorbis-encode")] mod vorbis; #[cfg(feature = "vorbis-encode")] -pub use vorbis::{OGG_BITRATES, encode as encode_ogg}; +pub use vorbis::{OGG_BITRATES, OggVorbisOptions, encode as encode_ogg, encode_ogg_vorbis, quality_for_bitrate}; #[cfg(feature = "pcm-encode")] mod raw; #[cfg(feature = "pcm-encode")] @@ -66,15 +66,22 @@ pub fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> { 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 count = u16::try_from(buf.channels.len()).unwrap_or(u16::MAX); + let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(count)); + if layout.channels() != count { + return Err(AudioError::Unsupported(format!("a {}-channel layout for {count} channels", layout.channels()))); } - 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())), + let map = vorbis::vorbis_map(&layout)?; + let quality = match opts.rate_control { + None => vorbis::quality_for_bitrate(192, buf.channels.len()), + Some(crate::RateControl::Bitrate(bps)) => { + vorbis::quality_for_bitrate((bps / 1000).clamp(OGG_BITRATES.0, OGG_BITRATES.1), buf.channels.len()) + } + Some(crate::RateControl::Quality(q)) if q.is_nan() => return Err(AudioError::Encode("the Vorbis quality is NaN".into())), + Some(crate::RateControl::Quality(q)) => -1.0 + 11.0 * q.clamp(0.0, 1.0), }; - vorbis::encode(buf, kbps) + let planar: Vec<&[f32]> = map.iter().filter_map(|&i| buf.channels.get(i).map(Vec::as_slice)).collect(); + vorbis::encode_planar(buf.sample_rate, &planar, &OggVorbisOptions::new(quality)) } #[allow(unreachable_patterns)] f => Err(AudioError::Unsupported(format!("writing {f:?}"))), @@ -106,7 +113,7 @@ const fn extensions() -> ([&'static str; 13], 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"); + add!(cfg!(feature = "vorbis-encode"), "ogg"); (all, n) } @@ -148,7 +155,7 @@ 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")))] + #[cfg(feature = "vorbis-encode")] "ogg" => Some(EncodeFormat::Ogg), _ => None, } diff --git a/crates/audio/src/write/vorbis.rs b/crates/audio/src/write/vorbis.rs index f56d01148..6c19ada77 100644 --- a/crates/audio/src/write/vorbis.rs +++ b/crates/audio/src/write/vorbis.rs @@ -1,83 +1,198 @@ -//! 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. +//! Ogg Vorbis files (Vorbis I §A, RFC 5334) from the pure-Rust [`crate::vorbis::encoder`] and +//! craft-media's Ogg page writer: 1 to 8 channels in Vorbis channel order, a quality from -1 to +//! 10 (variable bit rate), and the tags in the comment header. Builds for every target. -use crate::{AudioBuffer, AudioError, Result}; +use craft_media::ogg::{PageWriter, vorbis_comment}; -/// The bitrates an Ogg Vorbis export is asked for, in kbit/s. +use crate::vorbis::encoder::{DEFAULT_QUALITY, Encoder, EncoderConfig, Error as VorbisError}; +use crate::{AudioBuffer, AudioError, ChannelLayout, Result}; + +/// The bit rates [`encode_ogg`](crate::encode_ogg) takes, in kbit/s. Vorbis is variable: the bit rate picks a +/// quality ([`quality_for_bitrate`]), and the file comes out near it for typical music. 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; +/// The serial number of the stream when the options do not set one (`LCRF`): one stream per file, +/// so a constant keeps files byte-for-byte reproducible. +const SERIAL: u32 = 0x4C43_5246; -#[cfg(not(target_arch = "wasm32"))] -fn encode_error(e: vorbis_rs::VorbisError) -> AudioError { - AudioError::Encode(e.to_string()) +/// Samples per channel fed to the encoder at a time. +const CHUNK: usize = 4096; + +/// What [`encode_ogg_vorbis`] writes besides the audio. +/// +/// `#[non_exhaustive]`: build it with `OggVorbisOptions::default()` or +/// [`OggVorbisOptions::new`] and the `with_*` methods. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct OggVorbisOptions { + /// -1 (smallest) to 10 (best); clamped, and NaN or infinite reads as + /// [`DEFAULT_QUALITY`] (6). + pub quality: f32, + /// The comment header's vendor string. + pub vendor: String, + /// `NAME=value` comments (Vorbis I §5), in order. A name that is empty, or holds `=` or a byte + /// outside 0x20–0x7D, is left out. + pub tags: Vec<(String, String)>, + /// The logical stream's serial number. + pub serial: u32, } -/// 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())); +impl Default for OggVorbisOptions { + fn default() -> Self { + OggVorbisOptions { quality: DEFAULT_QUALITY, vendor: "craft-audio".into(), tags: Vec::new(), serial: SERIAL } } - if buf.channels.iter().any(|c| c.len() != buf.frames() || c.iter().any(|s| !s.is_finite())) { +} + +impl OggVorbisOptions { + /// The defaults at `quality`. + pub fn new(quality: f32) -> Self { + OggVorbisOptions { quality, ..Self::default() } + } + + /// Sets [`quality`](Self::quality). + pub fn with_quality(mut self, quality: f32) -> Self { + self.quality = quality; + self + } + + /// Sets [`vendor`](Self::vendor). + pub fn with_vendor(mut self, vendor: impl Into) -> Self { + self.vendor = vendor.into(); + self + } + + /// Adds a comment ([`tags`](Self::tags)). + pub fn with_tag(mut self, name: impl Into, value: impl Into) -> Self { + self.tags.push((name.into(), value.into())); + self + } + + /// Sets [`serial`](Self::serial). + pub fn with_serial(mut self, serial: u32) -> Self { + self.serial = serial; + self + } +} + +fn encode_error(e: VorbisError) -> AudioError { + AudioError::Encode(format!("Vorbis: {e}")) +} + +/// Encode `buf` as an Ogg Vorbis file with `opts`. The channels are in Vorbis channel order +/// (Vorbis I §4.3.9: L C R for three, L C R Ls Rs LFE for 5.1, L C R Ls Rs Rl Rr LFE for 7.1). +/// The last granule position is the buffer's length, so a decoder returns exactly its frames. +/// +/// ``` +/// use craft_audio::{AudioBuffer, OggVorbisOptions, encode_ogg_vorbis}; +/// +/// let buf = AudioBuffer::new(48_000, 6, 4_800); // 0.1 s of 5.1 silence +/// let opts = OggVorbisOptions::new(4.0).with_tag("TITLE", "Silence"); +/// let ogg = encode_ogg_vorbis(&buf, &opts).unwrap(); +/// assert!(ogg.starts_with(b"OggS")); +/// ``` +pub fn encode_ogg_vorbis(buf: &AudioBuffer, opts: &OggVorbisOptions) -> Result> { + let planar: Vec<&[f32]> = buf.channels.iter().map(Vec::as_slice).collect(); + encode_planar(buf.sample_rate, &planar, opts) +} + +/// [`encode_ogg_vorbis`] over channels already in Vorbis order. +pub(crate) fn encode_planar(sample_rate: u32, planar: &[&[f32]], opts: &OggVorbisOptions) -> Result> { + if !(1..=8).contains(&planar.len()) { + return Err(AudioError::Unsupported(format!("Ogg Vorbis holds 1 to 8 channels, not {}", planar.len()))); + } + let frames = planar.first().map_or(0, |c| c.len()); + if planar.iter().any(|c| c.len() != 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 { + if sample_rate == 0 { 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; + } + let mut enc = Encoder::new(EncoderConfig::new(sample_rate, planar.len(), opts.quality)).map_err(encode_error)?; + let mut pages = PageWriter::new(opts.serial); + let tags: Vec<(&str, &str)> = opts.tags.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect(); + let mut out = pages.header(&enc.identification()); + out.extend(pages.header(&vorbis_comment(&opts.vendor, &tags))); + out.extend(pages.header(&enc.setup())); + // The first audio packet (which outputs nothing) gets a page of its own: a stream whose first + // audio page is also its last would leave decoders to choose between start and end trimming + // (Vorbis I §A.2), and ffmpeg then plays the padding. + let mut first = true; + let mut add = |packets: Vec<(Vec, i64)>, out: &mut Vec| { + for (packet, granule) in packets { + out.extend(pages.packet(&packet, granule)); + if std::mem::take(&mut first) { + out.extend(pages.flush()); + } } - encoder.finish().map_err(encode_error) }; + let mut at = 0; + loop { + let end = (at + CHUNK).min(frames); + let chunk: Vec<&[f32]> = planar.iter().map(|c| c.get(at..end).unwrap_or_default()).collect(); + add(enc.encode(&chunk).map_err(encode_error)?, &mut out); + at = end; + if at >= frames { + break; + } + } + add(enc.finish().map_err(encode_error)?, &mut out); + out.extend(pages.finish(None)); + Ok(out) +} - // 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}"))), +/// Nominal kbit/s per channel at each whole quality from -1 to 10: this encoder's rate on +/// music-like test signals at 48 kHz (harmonic chords with noise), averaged. +const KBPS_PER_CHANNEL: [f32; 12] = [18.0, 23.0, 31.0, 43.0, 58.0, 75.0, 89.0, 100.0, 111.0, 121.0, 130.0, 140.0]; + +/// The quality whose nominal bit rate is `kbps` kbit/s for `channels` channels (clamped to -1..=10). +/// Vorbis is variable: the bit rate of a file depends on the audio. +pub fn quality_for_bitrate(kbps: u32, channels: usize) -> f32 { + let per = kbps as f32 / channels.max(1) as f32; + let mut q = -1.0; + for pair in KBPS_PER_CHANNEL.windows(2) { + if let [lo, hi] = *pair + && per <= hi + { + return q + ((per - lo) / (hi - lo)).clamp(0.0, 1.0); + } + q += 1.0; + } + 10.0 +} + +/// Encode `buf` as an Ogg Vorbis stream near `kbps` kbit/s ([`OGG_BITRATES`], clamped): the +/// quality [`quality_for_bitrate`] gives, no tags. 1 to 8 channels in Vorbis channel order. +/// `Err` says why there is nothing. +pub fn encode(buf: &AudioBuffer, kbps: u32) -> Result> { + let kbps = kbps.clamp(OGG_BITRATES.0, OGG_BITRATES.1); + encode_ogg_vorbis(buf, &OggVorbisOptions::new(quality_for_bitrate(kbps, buf.channels.len()))) +} + +/// WAV-order speakers ([`crate::EncodeFormat::layout_masks`]) to Vorbis order, per channel count. +const VORBIS_ORDER: [&[usize]; 8] = + [&[0], &[0, 1], &[0, 2, 1], &[0, 1, 2, 3], &[0, 2, 1, 3, 4], &[0, 2, 1, 4, 5, 3], &[0, 2, 1, 5, 6, 4, 3], &[0, 2, 1, 6, 7, 4, 5, 3]]; + +/// For each Vorbis channel, the channel of audio in `layout` it comes from. +pub(crate) fn vorbis_map(layout: &ChannelLayout) -> Result> { + let n = layout.channels(); + let mask = crate::EncodeFormat::Ogg.layout_masks(n).first().copied(); + let order = usize::from(n).checked_sub(1).and_then(|i| VORBIS_ORDER.get(i)).copied(); + match (mask, order) { + (Some(mask), Some(order)) => crate::layout::channel_map(mask, Some(order), layout) + .ok_or_else(|| AudioError::Unsupported(format!("Vorbis has no layout of {n} channels with these speakers"))), + _ => Err(AudioError::Unsupported(format!("Ogg Vorbis holds 1 to 8 channels, not {n}"))), } } -/// 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")))] +#[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] - use super::*; + use super::{OGG_BITRATES, OggVorbisOptions, encode, encode_ogg_vorbis, quality_for_bitrate, vorbis_map}; + use crate::{AudioBuffer, AudioError, ChannelLayout}; #[test] fn rejects_unsupported_or_malformed_channels_without_dropping_audio() { - for channels in [0, 3, 6] { + for channels in [0, 9] { 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]] }; @@ -85,46 +200,68 @@ mod tests { 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()); + let infinite = AudioBuffer { sample_rate: 48_000, channels: vec![vec![f32::INFINITY]] }; + assert!(encode(&infinite, 192).is_err()); } #[test] - fn generic_and_direct_encoders_write_mono_and_stereo_ogg() { - for channels in [1, 2] { + fn generic_and_direct_encoders_write_one_to_eight_channels() { + for channels in 1..=8 { 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); + // silence: the channel order changes nothing, so the generic path writes the same file + let generic = crate::encode(&audio, &opts.with_bitrate(192_000)).unwrap(); + assert_eq!(direct, generic, "{channels} channels"); #[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()); - } + fn the_quality_follows_the_bit_rate() { + assert_eq!(quality_for_bitrate(0, 2), -1.0); + assert_eq!(quality_for_bitrate(10_000, 2), 10.0); + assert!((quality_for_bitrate(200, 2) - 6.0).abs() < 1e-6); + assert!((quality_for_bitrate(600, 6) - 6.0).abs() < 1e-6); + let mut last = -2.0; + for kbps in OGG_BITRATES.0..=OGG_BITRATES.1 { + let q = quality_for_bitrate(kbps, 2); + assert!(q >= last && (-1.0..=10.0).contains(&q)); + last = q; } + assert!(quality_for_bitrate(192, 0).is_finite()); + } + + #[test] + fn layouts_map_to_vorbis_order() { + // 5.1 in WAV order (L R C LFE Ls Rs) is written L C R Ls Rs LFE + assert_eq!(vorbis_map(&ChannelLayout::SURROUND_5_1).unwrap(), [0, 2, 1, 4, 5, 3]); + assert_eq!(vorbis_map(&ChannelLayout::SURROUND_5_1_SIDE).unwrap(), [0, 2, 1, 4, 5, 3]); + assert_eq!(vorbis_map(&ChannelLayout::from_mask(0x63F)).unwrap(), [0, 2, 1, 6, 7, 4, 5, 3]); + assert_eq!(vorbis_map(&ChannelLayout::from_mask(0x7)).unwrap(), [0, 2, 1]); + assert_eq!(vorbis_map(&ChannelLayout::STEREO).unwrap(), [0, 1]); + assert!(vorbis_map(&ChannelLayout::from_mask(0xC)).is_err()); + assert!(vorbis_map(&ChannelLayout::unordered(9)).is_err()); + assert!(vorbis_map(&ChannelLayout::unordered(0)).is_err()); + } + + #[test] + fn options_build_and_tags_reach_the_comment_header() { + let opts = OggVorbisOptions::default().with_quality(2.0).with_vendor("v").with_tag("TITLE", "t").with_tag("bad=name", "x").with_serial(9); + assert_eq!((opts.quality, opts.vendor.as_str(), opts.serial, opts.tags.len()), (2.0, "v", 9, 2)); + let ogg = encode_ogg_vorbis(&AudioBuffer::new(44_100, 1, 100), &opts).unwrap(); + let file = craft_media::ogg::open(&ogg).unwrap(); + let s = &file.streams[0]; + assert_eq!((s.serial, s.saw_eos, s.headers.len()), (9, true, 3)); + assert_eq!(s.headers[1], craft_media::ogg::vorbis_comment("v", &[("TITLE", "t")])); + assert_eq!(s.last_granule, Some(100)); } } diff --git a/crates/audio/tests/audio/encode_format.rs b/crates/audio/tests/audio/encode_format.rs index e91f93623..72749df04 100644 --- a/crates/audio/tests/audio/encode_format.rs +++ b/crates/audio/tests/audio/encode_format.rs @@ -20,8 +20,8 @@ fn only_formats_the_encoder_writes_are_named() { } #[test] -fn ogg_names_follow_the_native_feature() { - let built = cfg!(all(feature = "vorbis-encode", not(target_arch = "wasm32"))); +fn ogg_names_follow_the_feature() { + let built = cfg!(feature = "vorbis-encode"); 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 84169f665..82edf72aa 100644 --- a/crates/audio/tests/codecs/file_formats.rs +++ b/crates/audio/tests/codecs/file_formats.rs @@ -527,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, 2]); + assert_eq!(most, [32_767, 32_767, 8, 8, 8, 2, 6, 8, 8]); for &format in EncodeFormat::ALL { let most = format.max_channels(); match format.fixed_layouts(most) { diff --git a/crates/audio/tests/codecs/main.rs b/crates/audio/tests/codecs/main.rs index c1c9e2131..41829be5c 100644 --- a/crates/audio/tests/codecs/main.rs +++ b/crates/audio/tests/codecs/main.rs @@ -20,3 +20,5 @@ mod opus; mod opusenc; mod routing_oracle; mod track_decoder; +#[cfg(feature = "vorbis-encode")] +mod vorbis_encoder_oracle; diff --git a/crates/audio/tests/codecs/vorbis_encoder_oracle.rs b/crates/audio/tests/codecs/vorbis_encoder_oracle.rs new file mode 100644 index 000000000..342f4fd9a --- /dev/null +++ b/crates/audio/tests/codecs/vorbis_encoder_oracle.rs @@ -0,0 +1,131 @@ +//! ffmpeg as an external oracle for the pure-Rust Vorbis encoder: both of its decoders (its own +//! and libvorbis) read every file exactly as long as the input, surround comes out on the right +//! speakers, and the tags reach ffprobe. Skipped when ffmpeg is not installed. + +use std::path::Path; +use std::process::Command; + +use craft_audio::{AudioBuffer, ChannelLayout, EncodeFormat, EncodeOptions, OggVorbisOptions, encode, encode_ogg_vorbis}; + +/// A different tone on every channel, so each output channel can be traced to its input. +fn tones(rate: u32, channels: usize, frames: usize) -> AudioBuffer { + let channels = (0..channels) + .map(|c| { + let f = 220.0 * (c + 1) as f32; + (0..frames).map(|i| (std::f32::consts::TAU * f * i as f32 / rate as f32).sin() * 0.3).collect() + }) + .collect(); + AudioBuffer { sample_rate: rate, channels } +} + +/// Decodes `file` with ffmpeg's `decoder`; planar output in ffmpeg's (WAV) channel order. +fn ffmpeg_decode(ff: &Path, decoder: &str, file: &[u8], channels: usize, tag: &str) -> Vec> { + let path = crate::testkit::fixtures_dir("vorbis-encoder").join(format!("{tag}.ogg")); + std::fs::write(&path, file).unwrap(); + let out = Command::new(ff) + .args(["-v", "error", "-xerror", "-c:a", decoder, "-i"]) + .arg(&path) + .args(["-f", "f32le", "-c:a", "pcm_f32le", "-"]) + .output() + .unwrap(); + assert!(out.status.success() && out.stderr.is_empty(), "{tag} {decoder}: {}", String::from_utf8_lossy(&out.stderr)); + let pcm: Vec = out.stdout.as_chunks::<4>().0.iter().map(|&b| f32::from_le_bytes(b)).collect(); + (0..channels).map(|c| pcm.iter().skip(c).step_by(channels).copied().collect()).collect() +} + +/// ffmpeg's decoders to check: its own `vorbis` always, and `libvorbis` when ffmpeg has it. +fn decoders(ff: &Path) -> Vec<&'static str> { + let list = + Command::new(ff).args(["-hide_banner", "-decoders"]).output().map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default(); + if list.lines().any(|l| l.split_whitespace().nth(1) == Some("libvorbis")) { + vec!["vorbis", "libvorbis"] + } else { + eprintln!("SKIPPED (libvorbis decoder): this ffmpeg has no libvorbis; checking its own decoder only"); + vec!["vorbis"] + } +} + +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + ab += f64::from(x) * f64::from(y); + aa += f64::from(x) * f64::from(x); + bb += f64::from(y) * f64::from(y); + } + ab / (aa * bb).sqrt().max(1e-20) +} + +/// Vorbis order (§4.3.9) of the WAV-order layouts the test writes, per channel count. +const VORBIS_ORDER: [&[usize]; 8] = + [&[0], &[0, 1], &[0, 2, 1], &[0, 1, 2, 3], &[0, 2, 1, 3, 4], &[0, 2, 1, 4, 5, 3], &[0, 2, 1, 5, 6, 4, 3], &[0, 2, 1, 6, 7, 4, 5, 3]]; + +/// 1 to 8 channels through `encode` with a WAV-order layout, at exactly the input's length out of +/// both decoders: ffmpeg's own puts every channel back on its WAV speaker, and libvorbis (through +/// ffmpeg, which passes its order through) gives the file's Vorbis order. +#[test] +fn every_channel_count_decodes_on_the_right_speakers() { + let ff = require_ffmpeg!(); + for channels in 1..=8u16 { + let layout = if channels == 7 { ChannelLayout::from_mask(0x70F) } else { ChannelLayout::default_for(channels) }; + let buf = tones(48_000, channels.into(), 24_000 + 77); + let opts = EncodeOptions::new(EncodeFormat::Ogg).with_layout(layout).with_quality(0.6); + let file = encode(&buf, &opts).unwrap(); + for decoder in decoders(&ff) { + let out = ffmpeg_decode(&ff, decoder, &file, channels.into(), &format!("tones{channels}-{decoder}")); + for (j, got) in out.iter().enumerate() { + let c = if decoder == "libvorbis" { VORBIS_ORDER[usize::from(channels) - 1][j] } else { j }; + assert_eq!(got.len(), buf.frames(), "{channels} ch {decoder}: channel {j} length"); + let best = (0..buf.channels.len()).max_by(|&a, &b| { + correlation(&buf.channels[a][2048..], &got[2048..]).total_cmp(&correlation(&buf.channels[b][2048..], &got[2048..])) + }); + assert_eq!(best, Some(c), "{channels} ch {decoder}: output channel {c} carries input {best:?}"); + let r = correlation(&buf.channels[c][2048..], &got[2048..]); + assert!(r > 0.95, "{channels} ch {decoder}: channel {c} correlation {r:.3}"); + } + } + } +} + +/// The comment header's tags, UTF-8 values included, are what ffprobe reports; a name that is not +/// a valid field name is left out. +#[test] +fn tags_reach_ffprobe() { + let Some(probe) = crate::common::tool("ffprobe").or_else(|| crate::common::skip("ffprobe not found")) else { return }; + let opts = OggVorbisOptions::new(3.0) + .with_tag("TITLE", "SmörgÃ¥sbord ✓") + .with_tag("ARTIST", "Craft") + .with_tag("bad=name", "dropped") + .with_vendor("craft-audio test"); + let file = encode_ogg_vorbis(&tones(44_100, 2, 44_100), &opts).unwrap(); + let path = crate::testkit::fixtures_dir("vorbis-encoder").join("tags.ogg"); + std::fs::write(&path, &file).unwrap(); + let out = Command::new(probe).args(["-v", "error", "-of", "json", "-show_streams", "-show_format"]).arg(&path).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let j: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + let s = &j["streams"][0]; + assert_eq!((s["codec_name"].as_str(), s["channels"].as_u64(), s["sample_rate"].as_str()), (Some("vorbis"), Some(2), Some("44100"))); + let tags = &s["tags"]; + assert_eq!((tags["TITLE"].as_str(), tags["ARTIST"].as_str()), (Some("SmörgÃ¥sbord ✓"), Some("Craft"))); + assert!(tags.as_object().unwrap().keys().all(|k| !k.contains("bad")), "{tags}"); + assert_eq!(j["format"]["duration"].as_str().map(|d| d.parse::().unwrap()), Some(1.0)); +} + +/// The lowest and highest qualities and the bit-rate path decode at the exact length, mono at +/// 44.1 kHz and stereo at 22.05 kHz. +#[test] +fn quality_extremes_and_rates_decode_exactly() { + let ff = require_ffmpeg!(); + for (rate, channels, quality) in [(44_100u32, 1usize, -1.0f32), (44_100, 1, 10.0), (22_050, 2, -1.0), (22_050, 2, 10.0), (96_000, 2, 5.0)] { + let buf = tones(rate, channels, rate as usize / 2 + 13); + let file = encode_ogg_vorbis(&buf, &OggVorbisOptions::new(quality)).unwrap(); + for decoder in decoders(&ff) { + let out = ffmpeg_decode(&ff, decoder, &file, channels, &format!("q{quality}-{rate}-{channels}-{decoder}")); + assert!(out.iter().all(|c| c.len() == buf.frames()), "q{quality} {rate} Hz {decoder}: {}", out[0].len()); + let r = correlation(&buf.channels[0][2048..], &out[0][2048..]); + assert!(r > 0.9, "q{quality} {rate} Hz {decoder}: correlation {r:.3}"); + } + } + let low = craft_audio::encode_ogg(&tones(48_000, 2, 48_000), craft_audio::OGG_BITRATES.0).unwrap(); + let high = craft_audio::encode_ogg(&tones(48_000, 2, 48_000), craft_audio::OGG_BITRATES.1).unwrap(); + assert!(low.len() < high.len(), "{} vs {} bytes", low.len(), high.len()); +} diff --git a/crates/cms/src/lib.rs b/crates/cms/src/lib.rs index 5e8a1e268..abd2b2604 100644 --- a/crates/cms/src/lib.rs +++ b/crates/cms/src/lib.rs @@ -34,6 +34,7 @@ pub mod profile; pub mod synth; pub mod transform; mod write; +pub mod write_v2; pub use builtin::Builtin; pub use clut::Clut; diff --git a/crates/cms/src/write_v2.rs b/crates/cms/src/write_v2.rs new file mode 100644 index 000000000..63933c801 --- /dev/null +++ b/crates/cms/src/write_v2.rs @@ -0,0 +1,195 @@ +//! Bounded ICC v2.1 matrix/TRC display-profile writer, extracted from TextureCraft. +//! Colour-space selection and transfer-curve sampling remain caller policy. + +const D50_XYZ: [f64; 3] = [0.9642, 1.0, 0.8249]; + +/// One common red/green/blue transfer curve. +#[derive(Clone, Copy)] +pub enum ToneCurve<'a> { + /// ICC gamma 1.0 (`curv` with one u8Fixed8 entry). + Linear, + /// Already quantized samples, inclusive endpoints, between 2 and 4096 entries. + Samples(&'a [u16]), +} + +/// Parameters for an ICC v2.1 RGB display profile. +pub struct MatrixProfile<'a> { + /// RGB-to-XYZ matrix already adapted to PCS D50, in row-major order. + pub matrix: [[f64; 3]; 3], + /// Common RGB transfer curve; its storage is shared by all three tags. + pub curve: ToneCurve<'a>, + /// ASCII description, at most 1024 bytes with no embedded NUL. + pub description: &'a str, + /// ASCII copyright text, at most 1024 bytes with no embedded NUL. + pub copyright: &'a str, + /// Raw ICC date fields: year, month, day, hour, minute, second. + pub date: [u16; 6], +} + +fn s15f16(v: f64) -> [u8; 4] { + ((v * 65536.0).round().clamp(f64::from(i32::MIN), f64::from(i32::MAX)) as i32).to_be_bytes() +} + +fn xyz_tag(v: [f64; 3]) -> Vec { + let mut b = b"XYZ \0\0\0\0".to_vec(); + for c in v { + b.extend_from_slice(&s15f16(c)); + } + b +} + +fn text_tag(text: &str) -> Vec { + let mut b = b"text\0\0\0\0".to_vec(); + b.extend_from_slice(text.as_bytes()); + b.push(0); + b +} + +/// `textDescriptionType` with the ASCII description only. +fn desc_tag(text: &str) -> Vec { + let mut b = b"desc\0\0\0\0".to_vec(); + b.extend_from_slice(&(text.len() as u32 + 1).to_be_bytes()); + b.extend_from_slice(text.as_bytes()); + b.push(0); + // No Unicode text and no Macintosh ScriptCode text: empty fields and the 67-byte filler. + b.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); + b +} + +fn curve_tag(curve: ToneCurve<'_>) -> Vec { + let mut b = b"curv\0\0\0\0".to_vec(); + match curve { + ToneCurve::Linear => { + b.extend_from_slice(&1u32.to_be_bytes()); + b.extend_from_slice(&0x0100u16.to_be_bytes()); + } + ToneCurve::Samples(samples) => { + b.extend_from_slice(&(samples.len() as u32).to_be_bytes()); + for sample in samples { + b.extend_from_slice(&sample.to_be_bytes()); + } + } + } + b +} + +/// Write a deterministic ICC v2.1 RGB display profile with one shared RGB TRC. +/// +/// Returns `None` for nonfinite matrix values, descriptions longer than 1024 ASCII +/// bytes or containing NUL, or sampled curves outside 2..=4096 entries. These caps +/// bound every allocation independently of caller input. Matrix values outside the +/// signed 15.16 range saturate, matching the legacy exporter. The caller owns colour +/// adaptation, transfer sampling, names and timestamp policy. +pub fn matrix_profile(params: &MatrixProfile<'_>) -> Option> { + let valid_text = |s: &str| s.len() <= 1024 && s.is_ascii() && !s.contains('\0'); + if !valid_text(params.description) + || !valid_text(params.copyright) + || !params.matrix.iter().flatten().all(|v| v.is_finite()) + || matches!(params.curve, ToneCurve::Samples(s) if !(2..=4096).contains(&s.len())) + { + return None; + } + let m = params.matrix; + let column = |c: usize| [m[0][c], m[1][c], m[2][c]]; + let curve = curve_tag(params.curve); + // The green and blue curves are the red one's entry. + let tags: [(&[u8; 4], Vec); 9] = [ + (b"desc", desc_tag(params.description)), + (b"cprt", text_tag(params.copyright)), + (b"wtpt", xyz_tag(D50_XYZ)), + (b"rXYZ", xyz_tag(column(0))), + (b"gXYZ", xyz_tag(column(1))), + (b"bXYZ", xyz_tag(column(2))), + (b"rTRC", curve.clone()), + (b"gTRC", curve.clone()), + (b"bTRC", curve), + ]; + // Header (128) + tag count (4) + 12 per tag, then the tag data, each tag padded to 4 bytes. + let table_end = 128 + 4 + 12 * tags.len(); + let mut offsets = Vec::new(); + let mut data: Vec = Vec::new(); + for (i, (_, bytes)) in tags.iter().enumerate() { + let shared = i >= 7; + let at = if shared { offsets.get(6).copied().unwrap_or(0) } else { table_end + data.len() }; + offsets.push(at); + if !shared { + data.extend_from_slice(bytes); + while !data.len().is_multiple_of(4) { + data.push(0); + } + } + } + let total = table_end + data.len(); + let mut out = vec![0u8; 128]; + out.get_mut(0..4)?.copy_from_slice(&(total as u32).to_be_bytes()); + out.get_mut(8..12)?.copy_from_slice(&[2, 0x10, 0, 0]); // version 2.1.0 + out.get_mut(12..16)?.copy_from_slice(b"mntr"); + out.get_mut(16..20)?.copy_from_slice(b"RGB "); + out.get_mut(20..24)?.copy_from_slice(b"XYZ "); + // Serialize caller-supplied ICC date fields; no calendar arithmetic. + for (i, value) in params.date.iter().enumerate() { + out.get_mut(24 + i * 2..26 + i * 2)?.copy_from_slice(&value.to_be_bytes()); + } + out.get_mut(36..40)?.copy_from_slice(b"acsp"); + for (k, v) in D50_XYZ.iter().enumerate() { + out.get_mut(68 + 4 * k..72 + 4 * k)?.copy_from_slice(&s15f16(*v)); + } + out.extend_from_slice(&(tags.len() as u32).to_be_bytes()); + for ((sig, bytes), at) in tags.iter().zip(&offsets) { + out.extend_from_slice(*sig); + out.extend_from_slice(&(*at as u32).to_be_bytes()); + out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); + } + out.extend_from_slice(&data); + Some(out) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + fn params() -> MatrixProfile<'static> { + MatrixProfile { + matrix: [[0.4361, 0.3851, 0.1431], [0.2225, 0.7169, 0.0606], [0.0139, 0.0971, 0.7141]], + curve: ToneCurve::Linear, + description: "v2", + copyright: "free", + date: [2026, 1, 1, 0, 0, 0], + } + } + + #[test] + fn valid_profile_parses_and_aliases_curves() { + for curve in [ToneCurve::Linear, ToneCurve::Samples(&[0, 32768, 65535])] { + let bytes = matrix_profile(&MatrixProfile { curve, ..params() }).unwrap(); + let p = crate::Profile::parse(&bytes).unwrap(); + assert_eq!(p.version, (2, 0x10)); + assert_eq!(p.description, "v2"); + assert_eq!(&bytes[24..28], &[7, 234, 0, 1]); + assert_eq!(&bytes[208..216], &bytes[220..228]); + assert_eq!(&bytes[208..216], &bytes[232..240]); + assert_eq!(bytes, matrix_profile(&MatrixProfile { curve, ..params() }).unwrap()); + } + } + + #[test] + fn bounded_inputs_reject_before_serializing() { + let long = "x".repeat(1025); + for description in [long.as_str(), "bad\0name", "non-ascii é"] { + assert!(matrix_profile(&MatrixProfile { description, ..params() }).is_none()); + } + for samples in [&[][..], &[0][..], &vec![0; 4097][..]] { + assert!(matrix_profile(&MatrixProfile { curve: ToneCurve::Samples(samples), ..params() }).is_none()); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let mut p = params(); + p.matrix[0][0] = value; + assert!(matrix_profile(&p).is_none()); + } + let samples = vec![0; 4096]; + let name = "x".repeat(1024); + let bytes = matrix_profile(&MatrixProfile { description: &name, copyright: &name, curve: ToneCurve::Samples(&samples), ..params() }).unwrap(); + assert!(bytes.len() < 12 * 1024); + } +} diff --git a/crates/image-codecs/Cargo.toml b/crates/image-codecs/Cargo.toml index a8872c0d3..208ff3ce7 100644 --- a/crates/image-codecs/Cargo.toml +++ b/crates/image-codecs/Cargo.toml @@ -15,6 +15,9 @@ corpus = [] default = [] avif = ["image/avif", "dep:ravif", "dep:rav1e", "dep:avif-serialize"] heif = ["dep:craft-heif"] +# AVIF decode: craft-video's clean-room pure-Rust AV1 decoder. Native targets only (on wasm32 a +# decoder panic aborts instead of becoming an error), so wasm32 builds leave AVIF unreadable. +avif-decode = ["dep:craft-video", "craft-video/av1-decode"] [dependencies] crc32fast = "1.5" @@ -41,6 +44,7 @@ hayro-jpeg2000 = { version = "=0.3.5", default-features = false, features = ["st [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } +craft-video = { workspace = true, optional = true } exr = { version = "1.73", default-features = false, features = ["rayon"] } [dev-dependencies] diff --git a/crates/image-codecs/README.md b/crates/image-codecs/README.md index aa0027666..a0e1afaa4 100644 --- a/crates/image-codecs/README.md +++ b/crates/image-codecs/README.md @@ -1,9 +1,10 @@ # craft-image-codecs Codecs for flat raster image formats, written in pure Rust. This crate defines its own `Image` -type and shares its baseline and extended JPEG decoders through `craft-jpeg`, and its optional -HEIF decoder through `craft-heif`. It builds for `wasm32-unknown-unknown` and does no filesystem -I/O: decoders take `&[u8]` and encoders return `Vec`. +type and shares its baseline and extended JPEG decoders through `craft-jpeg`, its optional HEIF +decoder through `craft-heif`, and its optional AVIF decoder through `craft-video`'s AV1 decoder. +It builds for `wasm32-unknown-unknown` and does no filesystem I/O: decoders take `&[u8]` and +encoders return `Vec`. It follows the "Avoiding GIMP's hole" rules in `docs/architecture.md` §1.1: @@ -57,7 +58,7 @@ craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "< | DICOM | yes | **no** | U8, U16 | Gray, RGB | no | no | no | no | no | no | n/a | built in | | Amiga IFF (ILBM/PBM) | yes | yes (24-bit ILBM) | U8 | RGB, RGBA | yes (1-bit mask plane on write) | no | no | no | no | no | no | built in | | JPEG-LS (`.jls`) | yes (any NEAR; one scan per component) | yes (lossless) | U8, U16 | Gray, RGB | no | no | no | no | no | no | no | built in | -| AVIF | **no** | only with feature `avif` | U8 | RGB, RGBA | yes | no | no | no | no | no | yes | `image` + `ravif` | +| AVIF | with feature `avif-decode` (native only) | only with feature `avif` | U8, U16 (10/12-bit decodes to U16; PQ/HLG to linear F32) | RGB, RGBA | yes (auxiliary alpha) | read (`colr` prof/rICC) | read | read | no | no | yes | `craft-video` AV1 decoder; `image` + `ravif` to write | | HEIF/HEIC | with feature `heif` | **no** | U8, U16 (10/12-bit decodes to U16) | RGB, RGBA | yes (auxiliary alpha) | yes (`colr` prof) | yes | yes | no | no | n/a | `heic-rs` | "Native" means the data is stored and read back without conversion. Anything else is converted by @@ -178,10 +179,20 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them decodes to RGB. Image sequences, overlays and identity derivations, multilayer HEVC and some 4:2:2/4:4:4 streams return `CodecError::Unsupported` or `Malformed`, never wrong pixels. Writing needs an HEVC encoder and every mature one is C, so HEIF is listed in `ASYMMETRIC_EXCEPTIONS`. -* **AVIF.** Encoding uses `ravif`, which is pure Rust. Decoding - needs `dav1d`, which is C. AVIF is therefore read-unsupported, and write support is gated - behind the non-default `avif` feature. In a default build it is neither readable nor writable, - so the symmetric guarantee holds. It is listed in `ASYMMETRIC_EXCEPTIONS`. +* **AVIF.** Encoding uses `ravif`, which is pure Rust, behind the non-default `avif` feature. + Decoding (`codecs::avif_decode`, behind the non-default `avif-decode` feature) reads the HEIF + boxes itself and decodes the AV1 pictures with `craft-video`'s clean-room pure-Rust AV1 decoder: + one `av01` image or a `grid`, 8/10/12-bit, 4:2:0/4:2:2/4:4:4/monochrome, the `nclx` colour (or + the sequence header's) and an ICC profile, an `auxl` alpha plane (`prem` too), the Exif and XMP + items, and `clap`/`irot`/`imir`, which are applied unless `keep_orientation` is set, as for HEIF. + PQ and HLG open as linear light in F32, as HEIF does. Image sequences (animated AVIF), depth and + gain-map auxiliary images and layered progressive images aren't read. It is bounded like the + other decoders: the `Limits` are checked against the declared size before any picture decodes, + against every picture and every output buffer, `max_alloc` caps the AV1 decoder's picture store, + box, item and extent counts are capped, item data can't exceed the file, and a decoder panic is + `CodecError::Malformed`. wasm32 builds leave AVIF unreadable, since a panic there aborts. In a + default build AVIF is neither readable nor writable, so the symmetric guarantee holds; a build + with only one of the two features is listed in `ASYMMETRIC_EXCEPTIONS`. * **Lossy WebP.** Lossless (VP8L, via `image-webp`) is the default. `webp_lossless: false` writes a lossy file with our own clean-room VP8 key-frame encoder (`codecs::vp8`, from RFC 6386; `webp_quality` 0–100 on libwebp's scale sets the quantizer). Alpha travels losslessly diff --git a/crates/image-codecs/fuzz/Cargo.toml b/crates/image-codecs/fuzz/Cargo.toml index 3257a3953..30226c76e 100644 --- a/crates/image-codecs/fuzz/Cargo.toml +++ b/crates/image-codecs/fuzz/Cargo.toml @@ -14,7 +14,7 @@ cargo-fuzz = true [dependencies] libfuzzer-sys = "0.4" -craft-image-codecs = { path = "..", features = ["heif"] } +craft-image-codecs = { path = "..", features = ["heif", "avif-decode"] } # Called directly too: the codec turns its panics into errors (see decode_heif.rs). heic-rs = "=0.1.4" @@ -76,3 +76,10 @@ path = "fuzz_targets/decode_webp.rs" test = false doc = false bench = false + +[[bin]] +name = "decode_avif" +path = "fuzz_targets/decode_avif.rs" +test = false +doc = false +bench = false diff --git a/crates/image-codecs/fuzz/fuzz_targets/decode_avif.rs b/crates/image-codecs/fuzz/fuzz_targets/decode_avif.rs new file mode 100644 index 000000000..9a4b8978d --- /dev/null +++ b/crates/image-codecs/fuzz/fuzz_targets/decode_avif.rs @@ -0,0 +1,14 @@ +#![no_main] + +use libfuzzer_sys::fuzz_target; +use craft_image_codecs::{decode_as_with, probe_size, DecodeOptions, Format, Limits}; + +// The AVIF box reader and craft-video's AV1 decoder parse untrusted files: run with `-timeout=10` +// so a hang is reported, not just a panic. The codec turns an AV1 decoder panic into an error, so +// only the box reader's own panics would reach the fuzzer. Both orientation paths are covered. +fuzz_target!(|data: &[u8]| { + let keep_orientation = data.first().is_some_and(|b| b & 1 == 1); + let limits = Limits { max_width: 4096, max_height: 4096, max_pixels: 1 << 22, max_alloc: 256 << 20 }; + let _ = probe_size(data); + let _ = decode_as_with(Format::Avif, data, &DecodeOptions { limits, keep_orientation }); +}); diff --git a/crates/image-codecs/src/cicp.rs b/crates/image-codecs/src/cicp.rs index 290c82bc3..e6911d1b0 100644 --- a/crates/image-codecs/src/cicp.rs +++ b/crates/image-codecs/src/cicp.rs @@ -99,7 +99,7 @@ pub fn linear_to_pq(linear: f32) -> f32 { /// Relative luminance weights of the RGB primaries `code` (BT.2020's for anything else, the /// space BT.2100 defines HLG in). -fn luma_weights(code: u16) -> [f32; 3] { +pub(crate) fn luma_weights(code: u16) -> [f32; 3] { match code { 1 => [0.2126, 0.7152, 0.0722], 12 => [0.2290, 0.6917, 0.0793], diff --git a/crates/image-codecs/src/codecs.rs b/crates/image-codecs/src/codecs.rs index af91aa536..00b94b7ec 100644 --- a/crates/image-codecs/src/codecs.rs +++ b/crates/image-codecs/src/codecs.rs @@ -1,4 +1,6 @@ pub(crate) mod avif; +#[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))] +pub(crate) mod avif_decode; pub(crate) mod dds; pub(crate) mod dds_bc; pub(crate) mod deep_exr; diff --git a/crates/image-codecs/src/codecs/avif_decode.rs b/crates/image-codecs/src/codecs/avif_decode.rs new file mode 100644 index 000000000..382f6a474 --- /dev/null +++ b/crates/image-codecs/src/codecs/avif_decode.rs @@ -0,0 +1,1350 @@ +//! AVIF (AV1 Image File Format) decoding, behind the non-default `avif-decode` feature, native +//! targets only. +//! +//! The container is HEIF (ISO/IEC 23008-12) over ISO-BMFF. This module reads the boxes itself +//! (`meta`, `pitm`, `iloc`, `iinf`, `iref`, `iprp`/`ipco`/`ipma`, `idat`), and `craft-video`'s +//! clean-room AV1 decoder (`av1-decode`, pure Rust, no `unsafe`) decodes the AV1 still pictures. +//! The container reader, colour conversion and transforms are adapted from @emmertex's LightCraft +//! AVIF importer (storytold/lightcraft#3017). +//! +//! Supported: the primary item as one `av01` image or a `grid` of them; 8-, 10- and 12-bit; +//! 4:2:0, 4:2:2, 4:4:4 and monochrome; full or limited range; the `nclx` colour description (or the +//! AV1 sequence header's) and an ICC profile (`prof` / `rICC`); an alpha auxiliary image (`auxl`, +//! premultiplied with `prem` too); the primary item's Exif and XMP items. `clap`, `irot` and `imir` +//! are applied unless the caller keeps the stored orientation, as for HEIF. PQ and HLG files +//! open as linear light in 32-bit float, as HEIF does. Not read: image sequences (animated AVIF), +//! depth and gain-map auxiliary images, layered (`lsel`/`a1lx`) progressive images. +//! +//! Bounded for hostile input: box nesting, item, property and extent counts are capped; item data +//! can't add up to more than the file; the [`Limits`] are checked against the declared size +//! before any picture is decoded, against every decoded picture and against each output buffer; +//! the AV1 decoder's picture store and the pictures one chunk may show are capped by `max_alloc` +//! too; repeated transforms are refused; and a panic in the decoder is +//! a malformed-file error. wasm32 builds leave AVIF unreadable: a panic there aborts instead of +//! unwinding. +//! +//! Sources: ISO/IEC 23008-12 (HEIF) and the AV1 Image File Format specification v1.1.0 (box +//! layouts), ITU-T H.273 (colour code points). + +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use craft_video::av1::decode as av1; + +use crate::Format; +use crate::cicp::Cicp; +use crate::error::CodecError; +use crate::image::{ChannelLayout, Image, Metadata, SampleType}; +use crate::options::Limits; + +const F: Format = Format::Avif; +/// Deepest box nesting followed (meta → iprp → ipco → property is 4). +const MAX_DEPTH: u32 = 8; +/// Most boxes, items, properties, associations or extents accepted: far above real files. +const MAX_ITEMS: usize = 1 << 16; +/// The AV1 decoder's own picture-store cap (`craft-video`'s default on 64-bit targets). +const AV1_MEMORY_BUDGET: u64 = 4 << 30; +/// The `auxC` types of an alpha plane (AVIF and the older HEVC-in-HEIF spelling). +const ALPHA_URNS: [&[u8]; 2] = [b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha", b"urn:mpeg:hevc:2015:auxid:1"]; + +type Result = std::result::Result; + +fn bad(m: impl std::fmt::Display) -> CodecError { + CodecError::malformed(F, m) +} + +/// A big-endian reader over a byte slice that never panics. +struct Rd<'a> { + b: &'a [u8], + p: usize, +} + +impl<'a> Rd<'a> { + fn new(b: &'a [u8]) -> Self { + Rd { b, p: 0 } + } + fn take(&mut self, n: usize) -> Result<&'a [u8]> { + let end = self.p.checked_add(n).ok_or_else(|| bad("box overflows"))?; + let s = self.b.get(self.p..end).ok_or_else(|| bad("box truncated"))?; + self.p = end; + Ok(s) + } + fn u8(&mut self) -> Result { + Ok(self.take(1)?.first().copied().unwrap_or(0)) + } + fn u16(&mut self) -> Result { + Ok(self.uint(2)? as u16) + } + fn u32(&mut self) -> Result { + Ok(self.uint(4)? as u32) + } + /// An unsigned big-endian number of `n` (0 to 8) bytes. + fn uint(&mut self, n: usize) -> Result { + if n > 8 { + return Err(bad("field too wide")); + } + Ok(self.take(n)?.iter().fold(0u64, |a, &x| (a << 8) | u64::from(x))) + } + /// A full box's version, its flags skipped. + fn version(&mut self) -> Result { + let v = self.u8()?; + self.take(3)?; + Ok(v) + } + /// An item ID: 16 bits in version 0 boxes, 32 bits otherwise. + fn id(&mut self, wide: bool) -> Result { + if wide { self.u32() } else { self.u16().map(u32::from) } + } + fn cstr(&mut self) -> Result<&'a [u8]> { + let rest = self.rest(); + let n = rest.iter().position(|&c| c == 0).unwrap_or(rest.len()); + let s = self.take(n)?; + if self.p < self.b.len() { + self.p += 1; + } + Ok(s) + } + fn rest(&self) -> &'a [u8] { + self.b.get(self.p..).unwrap_or(&[]) + } +} + +/// The child boxes of `b`: (type, payload). +fn boxes(b: &[u8]) -> Result> { + let mut out = Vec::new(); + let mut p = 0usize; + while p < b.len() { + let mut r = Rd::new(b.get(p..).unwrap_or(&[])); + if r.b.len() < 8 { + break; // trailing padding + } + let size32 = r.u32()?; + let t = r.take(4)?; + let ty = [t[0], t[1], t[2], t[3]]; + let (hdr, size) = match size32 { + 0 => (8usize, r.b.len() as u64), + 1 => (16, r.uint(8)?), + s => (8, u64::from(s)), + }; + let size = usize::try_from(size).map_err(|_| bad("box too large"))?; + if size < hdr || size > r.b.len() { + return Err(bad(format!("box {} has a bad size", String::from_utf8_lossy(&ty)))); + } + out.push((ty, r.b.get(hdr..size).unwrap_or(&[]))); + if out.len() > MAX_ITEMS { + return Err(bad("too many boxes")); + } + p = p.checked_add(size).ok_or_else(|| bad("box overflows"))?; + } + Ok(out) +} + +#[derive(Clone, Debug, Default)] +struct Extent { + offset: u64, + length: u64, +} + +#[derive(Clone, Debug, Default)] +struct Loc { + method: u8, + base: u64, + extents: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Transform { + /// Clean aperture: width, height, horizontal and vertical offset of the centre. + Clap { w: f64, h: f64, dx: f64, dy: f64 }, + /// Anticlockwise rotation by `n` × 90°. + Rot(u8), + /// Mirror, as HEIF amendment 2, libheif and libavif read it: 0 = top and bottom exchanged, + /// 1 = left and right exchanged. + Mir(u8), +} + +#[derive(Clone, Debug)] +enum Prop { + Av1c(Vec), + Nclx(Cicp), + Icc(Vec), + Ispe(u32, u32), + AuxC(Vec), + T(Transform), + Other, +} + +struct Item { + id: u32, + kind: [u8; 4], + /// `mime` items: the content type. + content_type: Option>, +} + +#[derive(Default)] +struct Container<'a> { + file: &'a [u8], + primary: u32, + items: Vec, + locs: Vec<(u32, Loc)>, + idat: &'a [u8], + props: Vec, + /// item → 1-based property indices, in order. + assoc: Vec<(u32, Vec)>, + /// (type, from, to…) + refs: Vec<([u8; 4], u32, Vec)>, + /// `iloc` extents read so far, across all items (capped at [`MAX_ITEMS`]). + extents: usize, +} + +fn parse(file: &[u8]) -> Result> { + let top = boxes(file)?; + let meta = top.iter().find(|(t, _)| t == b"meta").map(|(_, b)| *b).ok_or_else(|| { + if top.iter().any(|(t, _)| t == b"moov") { + CodecError::unsupported(F, "AVIF image sequences (animated AVIF) aren't read") + } else { + bad("no meta box") + } + })?; + let mut c = Container { file, ..Default::default() }; + let meta = meta.get(4..).ok_or_else(|| bad("meta box truncated"))?; + for (t, b) in boxes(meta)? { + let mut r = Rd::new(b); + match &t { + b"pitm" => { + let v = r.version()?; + c.primary = r.id(v != 0)?; + } + b"iloc" => parse_iloc(&mut r, &mut c)?, + b"iinf" => parse_iinf(&mut r, &mut c)?, + b"iref" => parse_iref(&mut r, &mut c)?, + b"idat" => c.idat = b, + b"iprp" => parse_iprp(b, &mut c, 0)?, + _ => {} + } + } + if c.primary == 0 { + return Err(bad("no primary item")); + } + Ok(c) +} + +fn parse_iinf(r: &mut Rd, c: &mut Container) -> Result<()> { + let v = r.version()?; + let _count = r.id(v != 0)?; + for (t, b) in boxes(r.rest())? { + if &t != b"infe" { + continue; + } + let mut r = Rd::new(b); + let v = r.version()?; + if v < 2 { + continue; + } + let id = r.id(v != 2)?; + r.u16()?; // protection index + let kind = r.take(4)?; + let kind = [kind[0], kind[1], kind[2], kind[3]]; + let _name = r.cstr()?; + let content_type = (&kind == b"mime").then(|| r.cstr().ok().map(<[u8]>::to_vec)).flatten(); + c.items.push(Item { id, kind, content_type }); + if c.items.len() > MAX_ITEMS { + return Err(bad("too many items")); + } + } + Ok(()) +} + +fn parse_iref(r: &mut Rd, c: &mut Container) -> Result<()> { + let v = r.version()?; + for (t, b) in boxes(r.rest())? { + let mut r = Rd::new(b); + let from = r.id(v != 0)?; + let n = r.u16()?; + let mut to = Vec::with_capacity(usize::from(n).min(r.rest().len() / 2 + 1)); + for _ in 0..n { + to.push(r.id(v != 0)?); + } + c.refs.push((t, from, to)); + if c.refs.len() > MAX_ITEMS { + return Err(bad("too many item references")); + } + } + Ok(()) +} + +fn parse_iloc(r: &mut Rd, c: &mut Container) -> Result<()> { + let v = r.version()?; + if v > 2 { + return Err(CodecError::unsupported(F, "iloc version")); + } + let a = r.u8()?; + let b = r.u8()?; + let (off_size, len_size, base_size) = (usize::from(a >> 4), usize::from(a & 15), usize::from(b >> 4)); + let index_size = if v >= 1 { usize::from(b & 15) } else { 0 }; + let count = if v < 2 { u32::from(r.u16()?) } else { r.u32()? }; + for _ in 0..count { + let id = r.id(v >= 2)?; + let method = if v >= 1 { (r.u16()? & 15) as u8 } else { 0 }; + r.u16()?; // data reference index + let base = r.uint(base_size)?; + let n = r.u16()?; + let mut extents = Vec::with_capacity(usize::from(n).min(64)); + for _ in 0..n { + r.uint(index_size)?; + let offset = r.uint(off_size)?; + let length = r.uint(len_size)?; + extents.push(Extent { offset, length }); + // Zero-width offset and length fields read no bytes, so the file size alone doesn't + // bound this. + c.extents += 1; + if c.extents > MAX_ITEMS { + return Err(bad("too many item extents")); + } + } + c.locs.push((id, Loc { method, base, extents })); + if c.locs.len() > MAX_ITEMS { + return Err(bad("too many items")); + } + } + Ok(()) +} + +fn parse_iprp(b: &[u8], c: &mut Container, depth: u32) -> Result<()> { + if depth > MAX_DEPTH { + return Err(bad("boxes nested too deep")); + } + for (t, b) in boxes(b)? { + match &t { + b"ipco" => { + for (t, b) in boxes(b)? { + c.props.push(parse_prop(&t, b)?); + if c.props.len() > MAX_ITEMS { + return Err(bad("too many properties")); + } + } + } + b"ipma" => parse_ipma(b, c)?, + _ => {} + } + } + Ok(()) +} + +fn parse_ipma(b: &[u8], c: &mut Container) -> Result<()> { + let mut r = Rd::new(b); + let v = r.u8()?; + let flags = r.take(3)?; + let wide = flags.get(2).is_some_and(|f| f & 1 != 0); + let n = r.u32()?; + for _ in 0..n { + let id = r.id(v != 0)?; + let k = r.u8()?; + let mut list = Vec::with_capacity(usize::from(k)); + for _ in 0..k { + let idx = if wide { usize::from(r.u16()? & 0x7fff) } else { usize::from(r.u8()? & 0x7f) }; + list.push(idx); + } + c.assoc.push((id, list)); + if c.assoc.len() > MAX_ITEMS { + return Err(bad("too many property associations")); + } + } + Ok(()) +} + +fn parse_prop(t: &[u8; 4], b: &[u8]) -> Result { + let mut r = Rd::new(b); + Ok(match t { + b"av1C" => Prop::Av1c(b.get(4..).unwrap_or(&[]).to_vec()), + b"colr" => match r.take(4)? { + b"nclx" => Prop::Nclx(Cicp { primaries: r.u16()?, transfer: r.u16()?, matrix: r.u16()?, full_range: r.u8()? & 0x80 != 0 }), + b"prof" | b"rICC" => Prop::Icc(r.rest().to_vec()), + _ => Prop::Other, + }, + b"ispe" => { + r.version()?; + Prop::Ispe(r.u32()?, r.u32()?) + } + b"auxC" => { + r.version()?; + Prop::AuxC(r.cstr()?.to_vec()) + } + b"irot" => Prop::T(Transform::Rot(r.u8()? & 3)), + b"imir" => Prop::T(Transform::Mir(r.u8()? & 1)), + b"clap" => { + // Width and height are unsigned fractions; the centre offsets have signed numerators + // (and unsigned denominators), as libavif and libheif read them. + let mut q = |signed: bool| -> Result { + let raw = r.u32()?; + let n = if signed { f64::from(raw as i32) } else { f64::from(raw) }; + let d = r.u32()?; + if d == 0 { + return Err(bad("clap with a zero denominator")); + } + Ok(n / f64::from(d)) + }; + let (w, h, dx, dy) = (q(false)?, q(false)?, q(true)?, q(true)?); + Prop::T(Transform::Clap { w, h, dx, dy }) + } + _ => Prop::Other, + }) +} + +impl Container<'_> { + fn item_type(&self, id: u32) -> Option<[u8; 4]> { + self.items.iter().find(|t| t.id == id).map(|t| t.kind) + } + fn props_of(&self, id: u32) -> impl Iterator { + self.assoc.iter().filter(move |a| a.0 == id).flat_map(|a| a.1.iter()).filter_map(|&i| i.checked_sub(1).and_then(|i| self.props.get(i))) + } + fn data(&self, id: u32) -> Result> { + let loc = self.locs.iter().find(|l| l.0 == id).map(|l| &l.1).ok_or_else(|| bad(format!("item {id} has no location")))?; + let src = match loc.method { + 0 => self.file, + 1 => self.idat, + _ => return Err(CodecError::unsupported(F, "item data by reference to another item")), + }; + let mut out = Vec::new(); + for e in &loc.extents { + let start = loc.base.checked_add(e.offset).ok_or_else(|| bad("item offset overflows"))?; + let start = usize::try_from(start).map_err(|_| bad("item offset out of range"))?; + let end = if e.length == 0 { + src.len() + } else { + usize::try_from(e.length).ok().and_then(|l| start.checked_add(l)).ok_or_else(|| bad("item length overflows"))? + }; + let chunk = src.get(start..end).ok_or_else(|| bad("item data runs past the end of the file"))?; + // Every byte comes from the file, so a real item is never larger than it; repeated or + // overlapping extents that add up to more are refused before they allocate. + if out.len().saturating_add(chunk.len()) > self.file.len() { + return Err(bad("item data is larger than the file")); + } + out.extend_from_slice(chunk); + } + Ok(out) + } + fn refs_from(&self, kind: &[u8; 4], from: u32) -> Vec { + self.refs.iter().filter(|r| &r.0 == kind && r.1 == from).flat_map(|r| r.2.iter().copied()).collect() + } + /// Items with a `kind` reference to `to`. + fn refs_to(&self, kind: &[u8; 4], to: u32) -> impl Iterator { + self.refs.iter().filter(move |r| &r.0 == kind && r.2.contains(&to)).map(|r| r.1) + } + fn ispe(&self, id: u32) -> Option<(u32, u32)> { + self.props_of(id).find_map(|p| if let Prop::Ispe(w, h) = p { Some((*w, *h)) } else { None }) + } + /// The item's transformative properties in association order. HEIF allows each of `clap`, + /// `irot` and `imir` at most once per item; a file that associates one more often (repeated + /// `ipma` entries could otherwise ask for a quarter of a million full-image rotations) is + /// refused before any pixels are touched. + fn transforms(&self, id: u32) -> Result> { + // Three is the most a valid item has, so a fourth is already a repeat. + let ts: Vec = self.props_of(id).filter_map(|p| if let Prop::T(t) = p { Some(*t) } else { None }).take(4).collect(); + for (i, t) in ts.iter().enumerate() { + if ts[..i].iter().any(|u| std::mem::discriminant(u) == std::mem::discriminant(t)) { + return Err(bad("an image item has a transformative property (clap, irot or imir) more than once")); + } + } + Ok(ts) + } + fn nclx(&self, id: u32) -> Option { + self.props_of(id).find_map(|p| if let Prop::Nclx(n) = p { Some(*n) } else { None }) + } + fn icc(&self, id: u32) -> Option> { + self.props_of(id).find_map(|p| if let Prop::Icc(b) = p { Some(b.clone()) } else { None }) + } + /// The primary item's alpha plane: an auxiliary image (`auxl`) whose `auxC` says alpha. + fn alpha_item(&self) -> Option { + self.refs_to(b"auxl", self.primary).find(|&id| { + matches!(self.item_type(id), Some(t) if &t == b"av01" || &t == b"grid") + && self.props_of(id).any(|p| matches!(p, Prop::AuxC(urn) if ALPHA_URNS.contains(&urn.as_slice()))) + }) + } + /// The primary item's colour is premultiplied by its alpha (`prem` from colour to alpha). + fn premultiplied(&self, alpha: u32) -> bool { + self.refs_from(b"prem", self.primary).contains(&alpha) + } + /// The first item of a metadata kind that describes (`cdsc`) the primary item. + fn metadata_item(&self, is: impl Fn(&Item) -> bool) -> Option { + let described: Vec = self.refs_to(b"cdsc", self.primary).collect(); + self.items.iter().filter(|i| is(i)).map(|i| i.id).find(|id| described.contains(id)) + } +} + +/// The size of an image item (`av01` or `grid`) before its transforms. +fn item_size(c: &Container, id: u32) -> Result<(u32, u32)> { + let kind = c.item_type(id).ok_or_else(|| bad("an image item is not described"))?; + let (w, h) = match (c.ispe(id), &kind) { + (_, b"grid") => grid_header(&c.data(id)?)?.2, + (Some(s), b"av01") => s, + (None, b"av01") => return Err(bad("an AV1 image item has no size (ispe)")), + _ => return Err(CodecError::unsupported(F, "the image item is not an AV1 image or a grid")), + }; + if w == 0 || h == 0 { + return Err(bad("zero dimension")); + } + Ok((w, h)) +} + +/// The size after `clap` / `irot`, from a stored size. +fn displayed(mut w: u32, mut h: u32, ts: &[Transform]) -> (u32, u32) { + for t in ts { + match *t { + Transform::Clap { w: cw, h: ch, .. } if cw >= 1.0 && ch >= 1.0 && cw.is_finite() && ch.is_finite() => { + w = (cw.round() as u32).clamp(1, w); + h = (ch.round() as u32).clamp(1, h); + } + Transform::Rot(n) if n % 2 == 1 => std::mem::swap(&mut w, &mut h), + _ => {} + } + } + (w, h) +} + +/// (rows, columns, output size) of a `grid` item. +fn grid_header(d: &[u8]) -> Result<(u32, u32, (u32, u32))> { + let mut r = Rd::new(d); + r.u8()?; // version + let flags = r.u8()?; + let rows = u32::from(r.u8()?) + 1; + let cols = u32::from(r.u8()?) + 1; + let n = if flags & 1 != 0 { 4 } else { 2 }; + let w = r.uint(n)? as u32; + let h = r.uint(n)? as u32; + Ok((rows, cols, (w, h))) +} + +/// The upright size [`decode`] returns (`keep_orientation` off), from the boxes alone. +pub(crate) fn probe(bytes: &[u8], limits: &Limits) -> Result<(u32, u32)> { + let c = parse(bytes)?; + let (w, h) = item_size(&c, c.primary)?; + limits.check_size(w, h)?; + Ok(displayed(w, h, &c.transforms(c.primary)?)) +} + +/// One decoded AV1 picture. +struct Pic { + w: usize, + h: usize, + bits: u8, + ssx: usize, + ssy: usize, + mono: bool, + planes: [Vec; 3], + cicp: Cicp, +} + +fn av1_error(e: av1::Error) -> CodecError { + match e { + av1::Error::Unsupported(w) => CodecError::unsupported(F, format!("AV1: {w}")), + other => bad(format!("AV1: {other}")), + } +} + +/// Decodes the `av01` item `id`, refusing pictures over `limits`. +fn decode_av1(c: &Container, id: u32, limits: &Limits) -> Result { + if c.item_type(id) != Some(*b"av01") { + return Err(CodecError::unsupported(F, "an image tile is not an AV1 image")); + } + // A tile's declared size counts before its picture is decoded too. + if let Some((w, h)) = c.ispe(id) { + limits.check(w, h, ChannelLayout::Rgb, SampleType::U16)?; + } + let data = c.data(id)?; + let config = c.props_of(id).find_map(|p| if let Prop::Av1c(o) = p { Some(o.clone()) } else { None }); + let mut dec = av1::Decoder::new(); + dec.set_memory_budget(limits.max_alloc.min(AV1_MEMORY_BUDGET)); + // Only the first picture is kept, so the pictures a chunk may show are held to the same budget + // before they are built (the decoder allows up to 1 GiB of them otherwise). + dec.set_shown_budget(limits.max_alloc); + let mut pics = catch_unwind(AssertUnwindSafe(|| -> std::result::Result, av1::Error> { + let mut pics = Vec::new(); + // The sequence header normally travels in the item too; the av1C copy covers files + // where it doesn't. + if let Some(cfg) = config.filter(|o| !o.is_empty()) { + pics.extend(dec.decode(&cfg)?); + } + pics.extend(dec.decode(&data)?); + pics.extend(dec.flush_result()?); + Ok(pics) + })) + .map_err(|_| bad("the AV1 decoder failed on this file"))? + .map_err(av1_error)?; + if pics.is_empty() { + return Err(bad("the AV1 data holds no picture")); + } + let p = pics.swap_remove(0); + limits.check(p.width, p.height, ChannelLayout::Rgb, SampleType::U16)?; + let (w, h) = (p.width as usize, p.height as usize); + let (ssx, ssy) = (usize::from(p.subsampling_x.min(1)), usize::from(p.subsampling_y.min(1))); + let need = w.checked_mul(h).ok_or_else(|| bad("picture too large"))?; + let cneed = ((w + ssx) >> ssx) * ((h + ssy) >> ssy); + if need == 0 || p.planes[0].len() < need || (!p.mono_chrome && (p.planes[1].len() < cneed || p.planes[2].len() < cneed)) { + return Err(bad("AV1 picture planes are short")); + } + let cicp = Cicp { + primaries: u16::from(p.color_primaries), + transfer: u16::from(p.transfer_characteristics), + matrix: u16::from(p.matrix_coefficients), + full_range: p.full_range, + }; + Ok(Pic { w, h, bits: p.bit_depth.clamp(8, 16), ssx, ssy, mono: p.mono_chrome, planes: p.planes, cicp }) +} + +/// Kr, Kb of an H.273 matrix code point; `None` = identity (GBR). +fn coefficients(matrix: u16, primaries: u16) -> Result> { + Ok(match matrix { + 0 => None, + 1 => Some((0.2126, 0.0722)), + 4 => Some((0.30, 0.11)), + 7 => Some((0.212, 0.087)), + // 9 is BT.2020 non-constant luminance; 10 (constant luminance) needs other equations and + // is refused below. + 9 => Some((0.2627, 0.0593)), + // Chromaticity-derived non-constant luminance. + 12 => { + let [kr, _, kb] = crate::cicp::luma_weights(primaries); + Some((kr, kb)) + } + // 2 (unspecified: AVIF readers assume BT.601), 5, 6 (BT.601) and reserved values. + 2 | 5 | 6 | 3 | 15.. => Some((0.299, 0.114)), + _ => return Err(CodecError::unsupported(F, format!("matrix coefficients {matrix} (YCgCo, constant luminance or ICtCp)"))), + }) +} + +/// A chroma sample at luma position (x, y), bilinear between chroma sites centred on their +/// luma pairs. +#[inline] +fn chroma_at(plane: &[u16], cw: usize, ch: usize, ssx: usize, ssy: usize, x: usize, y: usize) -> f32 { + let pos = |v: usize, ss: usize, n: usize| -> (usize, usize, f32) { + if ss == 0 { + return (v.min(n - 1), v.min(n - 1), 0.0); + } + let f = ((v as f32 + 0.5) / 2.0 - 0.5).max(0.0); + let i = f as usize; + (i.min(n - 1), (i + 1).min(n - 1), f - i as f32) + }; + let (x0, x1, fx) = pos(x, ssx, cw); + let (y0, y1, fy) = pos(y, ssy, ch); + let s = |xx: usize, yy: usize| f32::from(plane.get(yy * cw + xx).copied().unwrap_or(0)); + let top = s(x0, y0) * (1.0 - fx) + s(x1, y0) * fx; + let bot = s(x0, y1) * (1.0 - fx) + s(x1, y1) * fx; + top * (1.0 - fy) + bot * fy +} + +/// The sample scaling of a picture: luma offset and range, chroma range and midpoint. +struct Levels { + yoff: f32, + yrange: f32, + crange: f32, + mid: f32, +} + +impl Levels { + fn new(bits: u8, full_range: bool) -> Self { + let max = ((1u32 << bits) - 1) as f32; + let scale = f32::from(1u16 << (bits - 8).min(8)); + let (yoff, yrange, crange) = if full_range { (0.0, max, max) } else { (16.0 * scale, 219.0 * scale, 224.0 * scale) }; + Levels { yoff, yrange, crange, mid: f32::from(1u16 << (bits - 1).min(15)) } + } +} + +fn to_u16(v: f32) -> u16 { + (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16 +} + +/// Where a decoded picture goes: an interleaved 16-bit canvas of `ch` channels. +struct Canvas { + w: usize, + h: usize, + ch: usize, + data: Vec, +} + +impl Canvas { + fn new(w: u32, h: u32, layout: ChannelLayout, limits: &Limits) -> Result { + limits.check(w, h, layout, SampleType::U16)?; + let (w, h, ch) = (w as usize, h as usize, layout.channels()); + let len = w.checked_mul(h).and_then(|n| n.checked_mul(ch)).ok_or_else(|| bad("image too large"))?; + Ok(Canvas { w, h, ch, data: vec![0; len] }) + } + + /// The picture's YCbCr as non-linear R'G'B' into channels 0..3, its top-left at (x0, y0). + fn put_colour(&mut self, p: &Pic, cicp: Cicp, x0: usize, y0: usize) -> Result<()> { + let lv = Levels::new(p.bits, cicp.full_range); + let k = coefficients(cicp.matrix, cicp.primaries)?; + let (cw, chh) = ((p.w + p.ssx) >> p.ssx, (p.h + p.ssy) >> p.ssy); + for y in 0..p.h.min(self.h.saturating_sub(y0)) { + for x in 0..p.w.min(self.w.saturating_sub(x0)) { + let luma = (f32::from(p.planes[0][y * p.w + x]) - lv.yoff) / lv.yrange; + let (cb, cr) = if p.mono { + (lv.mid, lv.mid) + } else { + (chroma_at(&p.planes[1], cw, chh, p.ssx, p.ssy, x, y), chroma_at(&p.planes[2], cw, chh, p.ssx, p.ssy, x, y)) + }; + let rgb = match k { + // Identity (GBR): Y = G, Cb = B, Cr = R, all three at the luma levels. + None => [(cr - lv.yoff) / lv.yrange, luma, (cb - lv.yoff) / lv.yrange], + Some((kr, kb)) => { + let (cb, cr) = ((cb - lv.mid) / lv.crange, (cr - lv.mid) / lv.crange); + let r = luma + 2.0 * (1.0 - kr) * cr; + let b = luma + 2.0 * (1.0 - kb) * cb; + [r, (luma - kr * r - kb * b) / (1.0 - kr - kb), b] + } + }; + let o = ((y0 + y) * self.w + x0 + x) * self.ch; + for (d, v) in self.data[o..o + 3].iter_mut().zip(rgb) { + *d = to_u16(v); + } + } + } + Ok(()) + } + + /// The picture's luma as alpha into channel 3, its top-left at (x0, y0). + fn put_alpha(&mut self, p: &Pic, x0: usize, y0: usize) { + let lv = Levels::new(p.bits, p.cicp.full_range); + for y in 0..p.h.min(self.h.saturating_sub(y0)) { + for x in 0..p.w.min(self.w.saturating_sub(x0)) { + let a = (f32::from(p.planes[0][y * p.w + x]) - lv.yoff) / lv.yrange; + self.data[((y0 + y) * self.w + x0 + x) * self.ch + 3] = to_u16(a); + } + } + } +} + +/// Decodes the image item `id` (one `av01` or a `grid` of them) into `canvas`, through `put`. +/// Returns the first picture's bit depth and colour description. +fn render( + c: &Container, + id: u32, + limits: &Limits, + canvas: &mut Canvas, + put: &mut dyn FnMut(&mut Canvas, &Pic, usize, usize) -> Result<()>, +) -> Result<(u8, Cicp)> { + if c.item_type(id) != Some(*b"grid") { + let p = decode_av1(c, id, limits)?; + if (p.w, p.h) != (canvas.w, canvas.h) { + return Err(bad("the AV1 picture's size differs from its item's")); + } + put(canvas, &p, 0, 0)?; + return Ok((p.bits, p.cicp)); + } + let (rows, cols, _) = grid_header(&c.data(id)?)?; + let tiles = c.refs_from(b"dimg", id); + if tiles.is_empty() || tiles.len() as u64 != u64::from(rows) * u64::from(cols) { + return Err(bad("grid tile count doesn't match its rows and columns")); + } + let mut first: Option<(usize, usize, u8, Cicp)> = None; + for (i, &t) in tiles.iter().enumerate() { + let p = decode_av1(c, t, limits)?; + let (tw, th, ..) = *first.get_or_insert((p.w, p.h, p.bits, p.cicp)); + if (p.w, p.h) != (tw, th) { + return Err(bad("grid tiles differ in size")); + } + if tw.saturating_mul(cols as usize) < canvas.w || th.saturating_mul(rows as usize) < canvas.h { + return Err(bad("grid tiles don't cover the grid")); + } + put(canvas, &p, (i % cols as usize) * tw, (i / cols as usize) * th)?; + } + first.map(|(_, _, bits, cicp)| (bits, cicp)).ok_or_else(|| bad("grid without tiles")) +} + +/// Applies the container's transforms in order to an interleaved canvas. +fn apply_transforms(mut cv: Canvas, ts: &[Transform]) -> Canvas { + for t in ts { + cv = match *t { + Transform::Clap { w, h, dx, dy } => clap(cv, w, h, dx, dy), + Transform::Rot(n) => (0..n).fold(cv, |cv, _| rotate(cv)), + Transform::Mir(axis) => mirror(cv, axis), + }; + } + cv +} + +fn clap(cv: Canvas, cw: f64, chh: f64, dx: f64, dy: f64) -> Canvas { + if !(cw >= 1.0 && chh >= 1.0 && cw.is_finite() && chh.is_finite() && dx.is_finite() && dy.is_finite()) { + return cv; + } + let (w, h, ch) = (cv.w, cv.h, cv.ch); + let nw = (cw.round() as usize).clamp(1, w); + let nh = (chh.round() as usize).clamp(1, h); + // The centre of the aperture is the image centre plus the offset. + let x0 = ((w as f64 - 1.0) / 2.0 + dx - (nw as f64 - 1.0) / 2.0).round().clamp(0.0, (w - nw) as f64) as usize; + let y0 = ((h as f64 - 1.0) / 2.0 + dy - (nh as f64 - 1.0) / 2.0).round().clamp(0.0, (h - nh) as f64) as usize; + let mut data = Vec::with_capacity(nw * nh * ch); + for y in y0..y0 + nh { + data.extend_from_slice(&cv.data[(y * w + x0) * ch..(y * w + x0 + nw) * ch]); + } + Canvas { w: nw, h: nh, ch, data } +} + +/// 90° anticlockwise: (x, y) → (y, w - 1 - x), the new size h × w. +fn rotate(cv: Canvas) -> Canvas { + let (w, h, ch) = (cv.w, cv.h, cv.ch); + let mut data = vec![0u16; cv.data.len()]; + for y in 0..h { + for x in 0..w { + let d = ((w - 1 - x) * h + y) * ch; + let s = (y * w + x) * ch; + data[d..d + ch].copy_from_slice(&cv.data[s..s + ch]); + } + } + Canvas { w: h, h: w, ch, data } +} + +fn mirror(mut cv: Canvas, axis: u8) -> Canvas { + let (w, h, ch) = (cv.w, cv.h, cv.ch); + if axis == 0 { + for y in 0..h / 2 { + let (top, bottom) = cv.data.split_at_mut((h - 1 - y) * w * ch); + top[y * w * ch..(y + 1) * w * ch].swap_with_slice(&mut bottom[..w * ch]); + } + } else { + for row in cv.data.chunks_exact_mut(w * ch) { + for x in 0..w / 2 { + for c in 0..ch { + row.swap(x * ch + c, (w - 1 - x) * ch + c); + } + } + } + } + cv +} + +/// Straight colour from colour premultiplied by alpha. +fn unpremultiply(cv: &mut Canvas) { + for px in cv.data.as_chunks_mut::<4>().0 { + let a = u32::from(px[3]); + if a == 0 { + continue; + } + for v in &mut px[..3] { + *v = (u32::from(*v) * 65535 / a).min(65535) as u16; + } + } +} + +/// The primary item's Exif (TIFF structure, its offset prefix dropped) and XMP. +fn read_metadata(c: &Container) -> (Option>, Option) { + let exif = c.metadata_item(|i| &i.kind == b"Exif").and_then(|id| c.data(id).ok()).and_then(|d| { + let offset = usize::try_from(u32::from_be_bytes(d.get(..4)?.try_into().ok()?)).ok()?; + let tiff = d.get(4usize.checked_add(offset)?..)?; + (tiff.starts_with(b"II*\0") || tiff.starts_with(b"MM\0*")).then(|| tiff.to_vec()) + }); + let xmp = c + .metadata_item(|i| &i.kind == b"mime" && i.content_type.as_deref() == Some(b"application/rdf+xml")) + .and_then(|id| c.data(id).ok()) + .map(|d| String::from_utf8_lossy(&d).trim_end_matches('\0').to_owned()); + (exif, xmp) +} + +/// Decodes the primary image. `keep_orientation` leaves the container's `clap`, `irot` and +/// `imir` unapplied (the stored pixels), as for HEIF. +pub(crate) fn decode(bytes: &[u8], limits: &Limits, keep_orientation: bool) -> Result { + let c = parse(bytes)?; + let id = c.primary; + let (w, h) = item_size(&c, id)?; + let alpha = c.alpha_item().filter(|&a| item_size(&c, a).is_ok_and(|s| s == (w, h))); + let transforms = c.transforms(id)?; + // The alpha plane is composed in stored orientation and turned with the colour, which is right + // when it has no transforms of its own (what encoders write) or the colour's. Others would put + // transparency in the wrong place, so they are refused rather than ignored. + if let Some(a) = alpha { + let own = c.transforms(a)?; + if !own.is_empty() && own != transforms { + return Err(CodecError::unsupported(F, "an alpha plane with transforms (clap, irot, imir) that differ from the image's")); + } + } + let layout = if alpha.is_some() { ChannelLayout::Rgba } else { ChannelLayout::Rgb }; + // The declared size, before any picture is decoded. + let mut canvas = Canvas::new(w, h, layout, limits)?; + let file_cicp = c.nclx(id); + let mut colour = |cv: &mut Canvas, p: &Pic, x: usize, y: usize| cv.put_colour(p, file_cicp.unwrap_or(p.cicp), x, y); + let (bits, stream_cicp) = render(&c, id, limits, &mut canvas, &mut colour)?; + if let Some(a) = alpha { + render(&c, a, limits, &mut canvas, &mut |cv, p, x, y| { + cv.put_alpha(p, x, y); + Ok(()) + })?; + if c.premultiplied(a) { + unpremultiply(&mut canvas); + } + } + if !keep_orientation { + canvas = apply_transforms(canvas, &transforms); + } + let (w, h) = (canvas.w as u32, canvas.h as u32); + let image = Image::from_u16(w, h, layout, &canvas.data)?; + drop(canvas); + let mut img = if bits > 8 { image } else { image.convert(layout, SampleType::U8) }; + let cicp = file_cicp.unwrap_or(stream_cicp); + img.icc = c.icc(id); + img.cicp = Some(cicp); + let (exif, xmp) = read_metadata(&c); + img.meta = Metadata { + exif: exif.map(|e| if keep_orientation { e } else { crate::orientation::upright_exif(&e).into_owned() }), + xmp: xmp.map(|x| if keep_orientation { x } else { crate::orientation::upright_xmp(&x).into_owned() }), + ..Default::default() + }; + // PQ or HLG: linear light in 32-bit float, as for HEIF. + if cicp.is_hdr() { + limits.check(w, h, layout, SampleType::F32)?; + return crate::cicp::linearize(img, cicp); + } + Ok(img) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::DecodeOptions; + + const QUAD_420: &[u8] = include_bytes!("../../tests/fixtures/avif/quad-420-bt709.avif"); + const QUAD_420_DAV1D: &[u8] = include_bytes!("../../tests/fixtures/avif/quad-420-bt709.dav1d.yuv"); + const QUAD_GBR_LOSSLESS: &[u8] = include_bytes!("../../tests/fixtures/avif/quad-444-gbr-lossless.avif"); + const QUAD_SOURCE: &[u8] = include_bytes!("../../tests/fixtures/avif/quad-source.rgb"); + + fn rgb8(img: &Image) -> Vec { + img.to_rgba8().as_chunks::<4>().0.iter().flat_map(|p| [p[0], p[1], p[2]]).collect() + } + + fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { + assert_eq!(a.len(), b.len()); + a.iter().zip(b).map(|(&x, &y)| (f64::from(x) - f64::from(y)).abs()).sum::() / a.len() as f64 + } + + /// A box of type `t` around `body`. + fn bx(t: &[u8; 4], body: &[u8]) -> Vec { + let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec(); + v.extend_from_slice(t); + v.extend_from_slice(body); + v + } + + /// A full box: version 0, no flags. + fn fbx(t: &[u8; 4], body: &[u8]) -> Vec { + let mut b = vec![0, 0, 0, 0]; + b.extend_from_slice(body); + bx(t, &b) + } + + /// An `infe` (version 2) for item `id` of `kind`. + fn infe(id: u16, kind: &[u8; 4]) -> Vec { + let mut b = vec![2, 0, 0, 0]; + b.extend_from_slice(&id.to_be_bytes()); + b.extend_from_slice(&[0, 0]); + b.extend_from_slice(kind); + b.push(0); + bx(b"infe", &b) + } + + fn ispe(w: u32, h: u32) -> Vec { + let mut b = w.to_be_bytes().to_vec(); + b.extend_from_slice(&h.to_be_bytes()); + fbx(b"ispe", &b) + } + + /// The AV1 data and `av1C` of an encoded file's primary item. + fn av1_of(file: &[u8]) -> (Vec, Vec) { + let c = parse(file).unwrap(); + let cfg = c.props_of(c.primary).find_map(|p| if let Prop::Av1c(o) = p { Some(o.clone()) } else { None }).unwrap(); + (c.data(c.primary).unwrap(), cfg) + } + + /// An AVIF of `items` (id, type, data, property indices) with `props`, `refs` and primary 1. + /// All item data sits in `idat` (construction method 1). + /// An item: ID, type, data and 1-based property indices. + type TestItem<'a> = (u16, &'a [u8; 4], &'a [u8], &'a [u8]); + /// An item reference: type, from, to. + type TestRef<'a> = (&'a [u8; 4], u16, &'a [u16]); + + fn build(items: &[TestItem], props: &[Vec], refs: &[TestRef]) -> Vec { + let mut iinf = vec![0, 0, 0, 0]; + iinf.extend_from_slice(&(items.len() as u16).to_be_bytes()); + let mut iloc = vec![1, 0, 0, 0, 0x44, 0x00]; + iloc.extend_from_slice(&(items.len() as u16).to_be_bytes()); + let mut ipma = vec![0, 0, 0, 0]; + ipma.extend_from_slice(&(items.len() as u32).to_be_bytes()); + let mut idat = Vec::new(); + for &(id, kind, data, assoc) in items { + iinf.extend(infe(id, kind)); + iloc.extend_from_slice(&id.to_be_bytes()); + iloc.extend_from_slice(&[0, 1, 0, 0, 0, 1]); // method 1, data ref 0, one extent + iloc.extend_from_slice(&(idat.len() as u32).to_be_bytes()); + iloc.extend_from_slice(&(data.len() as u32).to_be_bytes()); + idat.extend_from_slice(data); + ipma.extend_from_slice(&id.to_be_bytes()); + ipma.push(assoc.len() as u8); + ipma.extend(assoc.iter().map(|&p| p | 0x80)); + } + let mut iref = vec![0, 0, 0, 0]; + for &(kind, from, to) in refs { + let mut b = from.to_be_bytes().to_vec(); + b.extend_from_slice(&(to.len() as u16).to_be_bytes()); + to.iter().for_each(|t| b.extend_from_slice(&t.to_be_bytes())); + iref.extend(bx(kind, &b)); + } + let mut meta = vec![0, 0, 0, 0]; + meta.extend(fbx(b"hdlr", b"\0\0\0\0pict\0\0\0\0\0\0\0\0\0\0\0\0\0")); + meta.extend(fbx(b"pitm", &[0, 1])); + meta.extend(bx(b"iinf", &iinf)); + meta.extend(bx(b"iloc", &iloc)); + meta.extend(bx(b"iref", &iref)); + meta.extend(bx(b"iprp", &[bx(b"ipco", &props.concat()), bx(b"ipma", &ipma)].concat())); + meta.extend(bx(b"idat", &idat)); + let mut file = bx(b"ftyp", b"avif\0\0\0\0avifmif1miaf"); + file.extend(bx(b"meta", &meta)); + file + } + + #[test] + fn libaom_420_limited_range_matches_dav1d() { + let img = crate::decode(QUAD_420).unwrap(); + assert_eq!((img.width(), img.height(), img.layout(), img.sample_type()), (33, 17, ChannelLayout::Rgb, SampleType::U8)); + assert_eq!(img.cicp.map(|c| (c.matrix, c.full_range)), Some((1, false)), "BT.709 matrix, limited range"); + assert_eq!(crate::probe_size(QUAD_420).unwrap(), (33, 17)); + // The AV1 picture is libdav1d's, sample for sample. + let c = parse(QUAD_420).unwrap(); + let p = decode_av1(&c, c.primary, &Limits::default()).unwrap(); + assert_eq!((p.w, p.h, p.bits, p.ssx, p.ssy, p.mono), (33, 17, 8, 1, 1, false)); + let planes: Vec = p.planes.iter().flatten().map(|&v| v as u8).collect(); + assert_eq!(planes, QUAD_420_DAV1D); + let ours = rgb8(&img); + // The quadrant centres are the source's colours, give or take the lossy coding. + for (x, y) in [(5usize, 4usize), (27, 4), (5, 13), (27, 13)] { + let i = (y * 33 + x) * 3; + let d = mean_abs_diff(&ours[i..i + 3], &QUAD_SOURCE[i..i + 3]); + assert!(d < 12.0, "({x}, {y}): {:?} vs {:?}", &ours[i..i + 3], &QUAD_SOURCE[i..i + 3]); + } + } + + #[test] + fn libaom_lossless_identity_matrix_is_exact() { + let img = crate::decode(QUAD_GBR_LOSSLESS).unwrap(); + assert_eq!((img.width(), img.height(), img.sample_type()), (33, 17, SampleType::U8)); + assert_eq!(img.cicp.map(|c| (c.matrix, c.full_range)), Some((0, true))); + assert_eq!(rgb8(&img), QUAD_SOURCE); + } + + #[test] + fn limits_are_checked_before_decoding() { + let tight = |max_pixels, max_alloc| DecodeOptions { limits: Limits { max_pixels, max_alloc, ..Limits::default() }, ..Default::default() }; + assert!(matches!(crate::decode_with(QUAD_420, &tight(33 * 17 - 1, u64::MAX)), Err(CodecError::LimitExceeded(_)))); + // The 16-bit intermediate counts: 33 × 17 RGB at 2 bytes. + assert!(matches!(crate::decode_with(QUAD_420, &tight(u64::MAX, 33 * 17 * 6 - 1)), Err(CodecError::LimitExceeded(_)))); + assert!(crate::decode_with(QUAD_420, &tight(33 * 17, Limits::default().max_alloc)).is_ok()); + // `max_alloc` is the AV1 decoder's picture-store budget too. + assert!(crate::decode_with(QUAD_420, &tight(33 * 17, 33 * 17 * 6)).is_err()); + // A declared size over the limits fails from the boxes alone. + let (av1, cfg) = av1_of(QUAD_420); + let huge = build(&[(1, b"av01", &av1, &[1, 2])], &[ispe(1 << 20, 1 << 20), bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat())], &[]); + assert!(matches!(crate::decode(&huge), Err(CodecError::LimitExceeded(_)))); + assert!(matches!(crate::probe_size(&huge), Err(CodecError::LimitExceeded(_)))); + } + + #[test] + fn a_picture_that_differs_from_its_ispe_is_refused() { + let (av1, cfg) = av1_of(QUAD_420); + let file = build(&[(1, b"av01", &av1, &[1, 2])], &[ispe(32, 17), bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat())], &[]); + assert!(matches!(crate::decode(&file), Err(CodecError::Malformed { .. }))); + } + + #[test] + fn a_grid_is_assembled_from_its_tiles_and_cropped() { + // Two copies of the 33 × 17 picture side by side, cropped to 60 × 15 by the grid. + let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); + let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); + let grid = [0u8, 0, 0, 1, 0, 60, 0, 15]; + let file = build( + &[(1, b"grid", &grid, &[1]), (2, b"av01", &av1, &[2, 3]), (3, b"av01", &av1, &[2, 3])], + &[ispe(60, 15), ispe(33, 17), av1c, fbx(b"pixi", &[3, 8, 8, 8])], + &[(b"dimg", 1, &[2, 3])], + ); + assert_eq!(crate::probe_size(&file).unwrap(), (60, 15)); + let img = crate::decode(&file).unwrap(); + assert_eq!((img.width(), img.height()), (60, 15)); + let got = rgb8(&img); + for y in 0..15 { + for x in 0..60 { + let s = (y * 33 + x % 33) * 3; + assert_eq!(&got[(y * 60 + x) * 3..][..3], &QUAD_SOURCE[s..s + 3], "({x}, {y})"); + } + } + // Tiles that can't cover the grid are refused. + let wide = [0u8, 0, 0, 1, 0, 70, 0, 15]; + let file = build( + &[(1, b"grid", &wide, &[1]), (2, b"av01", &av1, &[2, 3]), (3, b"av01", &av1, &[2, 3])], + &[ispe(70, 15), ispe(33, 17), bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat())], + &[(b"dimg", 1, &[2, 3])], + ); + assert!(matches!(crate::decode(&file), Err(CodecError::Malformed { .. }))); + } + + #[test] + fn container_rotation_and_mirror_are_applied_unless_kept() { + let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); + let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); + let file = build(&[(1, b"av01", &av1, &[1, 2, 3, 4])], &[ispe(33, 17), av1c, bx(b"irot", &[1]), bx(b"imir", &[0])], &[]); + assert_eq!(crate::probe_size(&file).unwrap(), (17, 33)); + let img = crate::decode(&file).unwrap(); + assert_eq!((img.width(), img.height()), (17, 33)); + let got = rgb8(&img); + // Rotated 90° anticlockwise, then top and bottom exchanged: a transpose, (x, y) from (y, x). + for y in 0..33 { + for x in 0..17 { + let s = (x * 33 + y) * 3; + assert_eq!(&got[(y * 17 + x) * 3..][..3], &QUAD_SOURCE[s..s + 3], "({x}, {y})"); + } + } + let kept = crate::decode_with(&file, &DecodeOptions { keep_orientation: true, ..Default::default() }).unwrap(); + assert_eq!((kept.width(), kept.height(), rgb8(&kept)), (33, 17, QUAD_SOURCE.to_vec())); + } + + /// A `clap` box: width, height, horizontal and vertical offset, each numerator then denominator. + fn clap_box(f: [u32; 8]) -> Vec { + bx(b"clap", &f.iter().flat_map(|v| v.to_be_bytes()).collect::>()) + } + + #[test] + fn clean_aperture_sizes_are_unsigned() { + let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); + let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); + // A 2 × 2 aperture with its width written as 0x80000000 / 0x40000000, centred one pixel + // left of the image centre (a signed offset numerator: -1 / 1). + let clap = clap_box([0x8000_0000, 0x4000_0000, 2, 1, (-1i32) as u32, 1, 0, 1]); + let file = build(&[(1, b"av01", &av1, &[1, 2, 3])], &[ispe(33, 17), av1c, clap], &[]); + assert_eq!(crate::probe_size(&file).unwrap(), (2, 2)); + let img = crate::decode(&file).unwrap(); + assert_eq!((img.width(), img.height()), (2, 2)); + // Centre (16, 8) moved to (15, 8): the 2 × 2 crop starts at (15, 8) (rounded from 14.5, 7.5). + let got = rgb8(&img); + let (x0, y0) = ((32.0f64 / 2.0 - 1.0 - 0.5).round() as usize, (16.0f64 / 2.0 - 0.5).round() as usize); + for y in 0..2 { + for x in 0..2 { + let s = ((y0 + y) * 33 + x0 + x) * 3; + assert_eq!(&got[(y * 2 + x) * 3..][..3], &QUAD_SOURCE[s..s + 3], "({x}, {y})"); + } + } + } + + #[test] + fn repeated_transforms_are_refused() { + let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); + let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); + // the same irot associated twice, and through two ipma entries for the item + let twice = build(&[(1, b"av01", &av1, &[1, 2, 3, 3])], &[ispe(33, 17), av1c.clone(), bx(b"irot", &[1])], &[]); + assert!(matches!(crate::probe_size(&twice), Err(CodecError::Malformed { .. }))); + assert!(matches!(crate::decode(&twice), Err(CodecError::Malformed { .. }))); + let mut many = build(&[(1, b"av01", &av1, &[1, 2, 3])], &[ispe(33, 17), av1c.clone(), bx(b"irot", &[1])], &[]); + let c = parse(&many).unwrap(); + assert_eq!(c.transforms(1).unwrap(), vec![Transform::Rot(1)]); + // 1024 more ipma records for item 1, each repeating the irot 255 times + let mut ipma = vec![0, 0, 0, 0]; + ipma.extend_from_slice(&1024u32.to_be_bytes()); + for _ in 0..1024 { + ipma.extend_from_slice(&[0, 1, 255]); + ipma.extend(std::iter::repeat_n(3u8, 255)); + } + many = build(&[(1, b"av01", &av1, &[1, 2])], &[ispe(33, 17), av1c, bx(b"irot", &[1])], &[]); + let mut c = parse(&many).unwrap(); + parse_ipma(&ipma, &mut c).unwrap(); + assert!(matches!(c.transforms(1), Err(CodecError::Malformed { .. }))); + // each kind once is fine, in any order + let ok = build( + &[(1, b"av01", &av1, &[1, 2, 3, 4, 5])], + &[ + ispe(33, 17), + bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()), + clap_box([33, 1, 17, 1, 0, 1, 0, 1]), + bx(b"irot", &[1]), + bx(b"imir", &[0]), + ], + &[], + ); + assert_eq!(crate::probe_size(&ok).unwrap(), (17, 33)); + } + + #[test] + fn alpha_with_transforms_of_its_own_is_refused() { + let (av1, cfg) = av1_of(QUAD_GBR_LOSSLESS); + let av1c = bx(b"av1C", &[&[0x81, 0, 0, 0][..], &cfg].concat()); + let auxc = fbx(b"auxC", b"urn:mpeg:mpegB:cicp:systems:auxiliary:alpha\0"); + let props = [ispe(33, 17), av1c, auxc, bx(b"imir", &[1])]; + let with = |colour: &[u8], alpha: &[u8]| build(&[(1, b"av01", &av1, colour), (2, b"av01", &av1, alpha)], &props, &[(b"auxl", 2, &[1])]); + // no transforms on the alpha plane, or the colour's: composed, then turned together + let plain = crate::decode(&with(&[1, 2], &[1, 2, 3])).unwrap(); + assert_eq!(plain.layout(), ChannelLayout::Rgba); + let both = crate::decode(&with(&[1, 2, 4], &[1, 2, 3, 4])).unwrap(); + let alpha_free = crate::decode(&with(&[1, 2, 4], &[1, 2, 3])).unwrap(); + assert_eq!(both.to_rgba8(), alpha_free.to_rgba8()); + // an alpha-only mirror would put transparency on the wrong side + assert!(matches!(crate::decode(&with(&[1, 2], &[1, 2, 3, 4])), Err(CodecError::Unsupported { .. }))); + } + + #[test] + fn transforms_rotate_mirror_and_crop() { + // 3 × 2, one channel, value = index + let cv = || Canvas { w: 3, h: 2, ch: 1, data: (0..6).collect() }; + let r = apply_transforms(cv(), &[Transform::Rot(1)]); + // anticlockwise: the right column becomes the top row + assert_eq!((r.w, r.h, r.data), (2, 3, vec![2, 5, 1, 4, 0, 3])); + // axis 0 exchanges top and bottom, axis 1 left and right (libheif's and libavif's reading) + assert_eq!(apply_transforms(cv(), &[Transform::Mir(0)]).data, vec![3, 4, 5, 0, 1, 2]); + assert_eq!(apply_transforms(cv(), &[Transform::Mir(1)]).data, vec![2, 1, 0, 5, 4, 3]); + let c = apply_transforms(cv(), &[Transform::Clap { w: 1.0, h: 1.0, dx: 1.0, dy: 0.0 }]); + assert_eq!((c.w, c.h), (1, 1)); + assert!(c.data == [2] || c.data == [5]); + assert_eq!(displayed(3, 2, &[Transform::Rot(3)]), (2, 3)); + // A non-finite or empty aperture is ignored. + assert_eq!(apply_transforms(cv(), &[Transform::Clap { w: f64::NAN, h: 1.0, dx: 0.0, dy: 0.0 }]).data.len(), 6); + } + + #[test] + fn hostile_files_are_errors_not_panics() { + for file in [QUAD_420, QUAD_GBR_LOSSLESS] { + // every truncation + for n in 0..file.len() { + let _ = crate::probe_size(&file[..n]); + let _ = crate::decode(&file[..n]); + } + // byte flips through the container and the AV1 data + for i in 0..file.len() { + for x in [0x01u8, 0x80, 0xff] { + let mut m = file.to_vec(); + m[i] ^= x; + let _ = crate::probe_size(&m); + let _ = crate::decode(&m); + } + } + } + // box sizes that point far outside the file + let mut b = bx(b"ftyp", b"avif\0\0\0\0avif"); + b.extend_from_slice(b"\xff\xff\xff\xffmeta\0\0\0\0"); + assert!(crate::decode(&b).is_err()); + let mut b = bx(b"ftyp", b"avif\0\0\0\0avif"); + b.extend_from_slice(b"\0\0\0\x01meta\xff\xff\xff\xff\xff\xff\xff\xff"); + assert!(crate::probe_size(&b).is_err()); + } + + #[test] + fn an_animated_avif_is_unsupported() { + let mut b = bx(b"ftyp", b"avis\0\0\0\0avis"); + b.extend(bx(b"moov", &[])); + assert!(matches!(crate::decode(&b), Err(CodecError::Unsupported { format: Format::Avif, .. }))); + } + + #[test] + fn zero_width_iloc_extents_are_capped() { + // iloc v2 with zero-byte offset/length/base/index fields: each extent costs no input bytes + let mut iloc = vec![2, 0, 0, 0, 0, 0]; + iloc.extend_from_slice(&3u32.to_be_bytes()); + for id in 1..=3u32 { + iloc.extend_from_slice(&id.to_be_bytes()); + iloc.extend_from_slice(&[0, 0, 0, 0, 0xff, 0xff]); // method, data ref, 65535 extents + } + let mut meta = vec![0, 0, 0, 0]; + meta.extend(bx(b"iloc", &iloc)); + let mut b = bx(b"ftyp", b"avif\0\0\0\0avif"); + b.extend(bx(b"meta", &meta)); + assert!(matches!(crate::decode(&b), Err(CodecError::Malformed { message, .. }) if message.contains("extents"))); + } + + #[test] + fn item_data_larger_than_the_file_is_refused() { + // one item whose 1000 extents each repeat the whole file (length 0 = to the end) + let mut iloc = vec![1, 0, 0, 0, 0x44, 0]; + iloc.extend_from_slice(&1u16.to_be_bytes()); + iloc.extend_from_slice(&[0, 1, 0, 0, 0, 0]); // id 1, method 0, data ref 0 + iloc.extend_from_slice(&1000u16.to_be_bytes()); + for _ in 0..1000 { + iloc.extend_from_slice(&[0; 8]); + } + let mut meta = vec![0, 0, 0, 0]; + meta.extend(fbx(b"pitm", &[0, 1])); + meta.extend(bx(b"iloc", &iloc)); + let mut b = bx(b"ftyp", b"avif\0\0\0\0avif"); + b.extend(bx(b"meta", &meta)); + let c = parse(&b).unwrap(); + assert!(matches!(c.data(1), Err(CodecError::Malformed { message, .. }) if message.contains("larger than the file"))); + } + + #[test] + fn unsupported_matrices_are_errors() { + for m in [8u16, 10, 11, 13, 14] { + assert!(matches!(coefficients(m, 1), Err(CodecError::Unsupported { .. })), "{m}"); + } + assert_eq!(coefficients(0, 1).unwrap(), None); + assert!(coefficients(12, 9).unwrap().is_some()); + } + + #[cfg(feature = "avif")] + mod with_the_encoder { + use super::*; + use crate::codecs::avif::{HdrTransfer, encode_avif_hdr, encode_avif_with_speed}; + + /// A smooth test card with a saturated band. + fn card(w: usize, h: usize, ch: usize) -> Vec { + (0..w * h) + .flat_map(|i| { + let (x, y) = (i % w, i / w); + let px = + [(x * 255 / (w - 1)) as u8, (y * 255 / (h - 1)) as u8, if x < w / 4 { 230 } else { 40 }, (255 - x * 200 / (w - 1)) as u8]; + px.into_iter().take(ch) + }) + .collect() + } + + #[test] + fn ravif_rgb_round_trip_is_10_bit() { + let (w, h) = (48, 32); + let src = Image::from_u8(w as u32, h as u32, ChannelLayout::Rgb, card(w, h, 3)).unwrap(); + let file = encode_avif_with_speed(&src, 95, 10).unwrap(); + let img = crate::decode(&file).unwrap(); + assert_eq!((img.width(), img.height(), img.layout(), img.sample_type()), (48, 32, ChannelLayout::Rgb, SampleType::U16)); + let diff = mean_abs_diff(&rgb8(&img), &card(w, h, 3)); + assert!(diff < 2.5, "mean difference {diff}"); + } + + #[test] + fn ravif_alpha_round_trips() { + let (w, h) = (40, 24); + let src = Image::from_u8(w as u32, h as u32, ChannelLayout::Rgba, card(w, h, 4)).unwrap(); + let file = encode_avif_with_speed(&src, 95, 10).unwrap(); + let img = crate::decode(&file).unwrap(); + assert_eq!(img.layout(), ChannelLayout::Rgba); + let got = img.to_rgba8(); + let want = card(w, h, 4); + let alpha = |v: &[u8]| v.iter().skip(3).step_by(4).copied().collect::>(); + let diff = mean_abs_diff(&alpha(&got), &alpha(&want)); + assert!(diff < 2.0, "alpha mean difference {diff}"); + } + + #[test] + fn exif_is_read_from_its_item() { + let mut src = Image::from_u8(16, 8, ChannelLayout::Rgb, card(16, 8, 3)).unwrap(); + let exif = b"II*\0\x08\0\0\0\0\0\0\0\0\0".to_vec(); + src.meta.exif = Some(exif.clone()); + let file = encode_avif_with_speed(&src, 80, 10).unwrap(); + let img = crate::decode_with(&file, &DecodeOptions { keep_orientation: true, ..Default::default() }).unwrap(); + assert_eq!(img.meta.exif.as_deref(), Some(exif.as_slice())); + } + + #[test] + fn hdr_round_trips_keep_highlights_above_white() { + let (w, h) = (32usize, 16usize); + // linear BT.2020: left half grey 0.18, right half 4 × SDR white + let rgb: Vec = (0..w * h).flat_map(|i| if i % w < w / 2 { [0.18f32; 3] } else { [4.0; 3] }).collect(); + for t in [HdrTransfer::Pq, HdrTransfer::Hlg] { + let file = encode_avif_hdr(w as u32, h as u32, &rgb, 98, 10, None, t).unwrap(); + let img = crate::decode(&file).unwrap(); + assert_eq!(img.sample_type(), SampleType::F32, "{t:?}"); + assert_eq!(img.cicp.map(|c| c.transfer), Some(Cicp::TRANSFER_LINEAR), "{t:?}"); + let v = img.to_f32_samples().unwrap(); + let at = |x: usize| v[(8 * w + x) * 3 + 1]; + assert!((at(4) / 0.18 - 1.0).abs() < 0.08, "{t:?}: grey {}", at(4)); + assert!((at(w - 4) / 4.0 - 1.0).abs() < 0.08, "{t:?}: highlight {}", at(w - 4)); + } + } + } +} diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index 810c1ad48..26696ae2a 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -26,7 +26,8 @@ pub enum Format { OpenExr, /// Radiance RGBE. Hdr, - /// Encode-only behind the `avif` feature; see [`ASYMMETRIC_EXCEPTIONS`]. + /// Encoded behind the `avif` feature and decoded behind `avif-decode` (native targets); see + /// [`ASYMMETRIC_EXCEPTIONS`] for a build with only one of them. Avif, /// HEIF/HEIC (HEVC-coded): read-only; see [`ASYMMETRIC_EXCEPTIONS`]. Heif, @@ -91,8 +92,10 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[ ), ( Format::Avif, - "AVIF encode uses ravif (pure Rust) but decoding requires dav1d (C); read stays unsupported \ - until a pure-Rust AV1 decoder is viable. Only enabled with the non-default `avif` feature.", + "AVIF encode (ravif and rav1e, pure Rust) is behind the non-default `avif` feature and AVIF \ + decode (craft-video's clean-room pure-Rust AV1 decoder) behind the non-default \ + `avif-decode` feature, native targets only (on wasm32 a decoder panic would abort). A build \ + with only one of them reads or writes AVIF, not both.", ), (Format::Jxl, "Lossless JPEG XL export uses the pure-Rust zune-jpegxl encoder; JPEG XL reading is tracked separately and is not yet available."), ( @@ -304,7 +307,9 @@ pub fn caps(format: Format) -> FormatCaps { Format::Qoi => base, Format::OpenExr => FormatCaps { depths: &[S::F16, S::F32], layouts: RGB_GRAY, ..base }, Format::Hdr => FormatCaps { depths: &[S::F32], layouts: &[L::Rgb], alpha: false, lossy: true, ..base }, - Format::Avif => FormatCaps { read: false, write: cfg!(feature = "avif"), lossy: true, ..base }, + Format::Avif => { + FormatCaps { read: cfg!(all(feature = "avif-decode", not(target_arch = "wasm32"))), write: cfg!(feature = "avif"), lossy: true, ..base } + } Format::Heif => { FormatCaps { read: cfg!(feature = "heif"), write: false, depths: &[S::U8, S::U16], icc: true, exif: true, xmp: true, lossy: true, ..base } } diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index 361285b2a..48dee65c8 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -110,7 +110,11 @@ pub fn decode_as_with(format: Format, bytes: &[u8], opts: &DecodeOptions) -> Res Format::Heif => heif::decode(bytes, l, opts.keep_orientation), Format::Jp2 => jp2::decode(bytes, l), Format::Jxl => Err(CodecError::unsupported(format, "JPEG XL reading is not yet available; export is supported")), - Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::decode(format, bytes, l), + #[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))] + Format::Avif => codecs::avif_decode::decode(bytes, l, opts.keep_orientation), + #[cfg(not(all(feature = "avif-decode", not(target_arch = "wasm32"))))] + Format::Avif => via_image::decode(format, bytes, l), + Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr => via_image::decode(format, bytes, l), }?; finish_format(format, bytes, img, opts) } @@ -167,10 +171,11 @@ fn finish_format(format: Format, bytes: &[u8], mut img: Image, opts: &DecodeOpti } // Turn the pixels upright, like Photoshop: a TIFF records it in the decoded page's own // directory, the others in their EXIF block. The metadata is rewritten to Orientation = 1 - // on the way. HEIF keeps it in its container, and its decoder has already applied it. + // on the way. HEIF and AVIF keep it in their container, and their decoders have already + // applied it. let o = match format { Format::Tiff => tiff::orientation(bytes, None), - Format::Heif => 1, + Format::Heif | Format::Avif => 1, Format::Dpx => dpx::orientation(bytes), Format::Cineon => dpx::cineon_orientation(bytes), _ => img.meta.exif.as_deref().map_or(1, exif_orientation), @@ -199,10 +204,11 @@ pub fn decode_png_rows>( } /// The upright pixel size [`decode`] would return, read from the file's header without decoding -/// pixels, for WebP, OpenEXR (flat) and the GIF/BMP/TGA/ICO/QOI/HDR family. It runs the same +/// pixels, for WebP, OpenEXR (flat), AVIF (with `avif-decode`) and the GIF/BMP/TGA/ICO/QOI/HDR family. It runs the same /// header reads and size checks as the decoder (default [`Limits`]) and swaps the size for an -/// EXIF orientation of 5–8, so wherever [`decode`] succeeds the two agree. Other formats (and -/// deep EXR or AVIF) return [`CodecError::Unsupported`]: decode those to learn their size. +/// EXIF orientation of 5–8 (AVIF: its container's `clap` and `irot`), so wherever [`decode`] +/// succeeds the two agree. Other formats (and deep EXR) return [`CodecError::Unsupported`]: decode +/// those to learn their size. pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> { let format = detect(bytes).ok_or(CodecError::UnknownFormat)?; if !caps(format).read { @@ -212,7 +218,11 @@ pub fn probe_size(bytes: &[u8]) -> Result<(u32, u32), CodecError> { let (w, h, exif) = match format { Format::WebP => webp::probe(bytes, l)?, Format::OpenExr => exr::probe(bytes, l).map(|(w, h)| (w, h, None))?, - Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr | Format::Avif => via_image::probe(format, bytes, l)?, + #[cfg(all(feature = "avif-decode", not(target_arch = "wasm32")))] + Format::Avif => codecs::avif_decode::probe(bytes, l).map(|(w, h)| (w, h, None))?, + #[cfg(not(all(feature = "avif-decode", not(target_arch = "wasm32"))))] + Format::Avif => via_image::probe(format, bytes, l)?, + Format::Gif | Format::Bmp | Format::Tga | Format::Ico | Format::Qoi | Format::Hdr => via_image::probe(format, bytes, l)?, _ => return Err(CodecError::unsupported(format, "no header-only size probe")), }; let o = exif.as_deref().map_or(1, exif_orientation); diff --git a/crates/image-codecs/tests/fixtures/avif/README.md b/crates/image-codecs/tests/fixtures/avif/README.md new file mode 100644 index 000000000..b8b3a8c2a --- /dev/null +++ b/crates/image-codecs/tests/fixtures/avif/README.md @@ -0,0 +1,12 @@ +# AVIF decode fixtures + +Small AVIF files from an independent encoder (libaom through FFmpeg 7.1), for `src/codecs/avif_decode.rs`. + +- `quad-source.rgb`: the 33×17 source, raw RGB24 four-colour quadrants (red, green, blue, near-white). +- `quad-420-bt709.avif`: 8-bit 4:2:0, limited range, BT.709 matrix, odd size (FFmpeg leaves the primaries and transfer unspecified): + `ffmpeg -f rawvideo -pix_fmt rgb24 -s 33x17 -i quad-source.rgb -c:v libaom-av1 -crf 12 -still-picture 1 -pix_fmt yuv420p -colorspace bt709 -color_primaries bt709 -color_trc iec61966-2-1 -color_range tv quad-420-bt709.avif` +- `quad-420-bt709.dav1d.yuv`: that file's AV1 picture as libdav1d decodes it, planar 8-bit 4:2:0 (Y, then Cb, then Cr): + `ffmpeg -c:v libdav1d -i quad-420-bt709.avif -f rawvideo -pix_fmt yuv420p quad-420-bt709.dav1d.yuv` +- `quad-444-gbr-lossless.avif`: lossless 8-bit 4:4:4 with the identity (GBR) matrix, full range: + `ffmpeg -f rawvideo -pix_fmt rgb24 -s 33x17 -i quad-source.rgb -c:v libaom-av1 -crf 0 -still-picture 1 -pix_fmt gbrp -colorspace rgb -color_range pc quad-444-gbr-lossless.avif`. + It decodes to `quad-source.rgb` exactly. diff --git a/crates/image-codecs/tests/fixtures/avif/quad-420-bt709.avif b/crates/image-codecs/tests/fixtures/avif/quad-420-bt709.avif new file mode 100644 index 000000000..419196cb1 Binary files /dev/null and b/crates/image-codecs/tests/fixtures/avif/quad-420-bt709.avif differ diff --git a/crates/image-codecs/tests/fixtures/avif/quad-420-bt709.dav1d.yuv b/crates/image-codecs/tests/fixtures/avif/quad-420-bt709.dav1d.yuv new file mode 100644 index 000000000..95e4ac464 --- /dev/null +++ b/crates/image-codecs/tests/fixtures/avif/quad-420-bt709.dav1d.yuv @@ -0,0 +1 @@ +OOOOOOOOOOOOOOOOO’’’’’’’’’’’’’’’’OOOOOOOOOOOOOOOOO’’’’’’’’’’’’’’’’OOOOOOOOOOOOOOOOO’’’’’’’’’’’’’’’’OOOOOOOOOOOOOOOOO’’’’’’’’’’’’’’’’OOOOOOOOOOOOOOOOO’’’’’’’’’’’’’’’’OOOOOOOOOOOOOOOOO’’’’’’’’’’’’’’’’OOOOOOOOOOOOOOOOO’’’’’’’’’’’’’’’’OOOOOOOOOOOOOOOOO’’’’’’’’’’’’’’’’OOOOOOOOOOOOOOOOO’’’’’’’’’’’’’’’’HHHHHHHHHHHHHHHHHÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞHHHHHHHHHHHHHHHHHÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞHHHHHHHHHHHHHHHHHÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞHHHHHHHHHHHHHHHHHÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞHHHHHHHHHHHHHHHHHÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞHHHHHHHHHHHHHHHHHÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞHHHHHHHHHHHHHHHHHÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞHHHHHHHHHHHHHHHHHÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞÞppppppppbUUUUUUUbppppppppbUUUUUUUbppppppppbUUUUUUUbmmmmmmmmbUUUUUUUb……………………r_______ŠÍÍÍÍÍÍÍͦ�������¦ÉÉÉÉÉÉÉɦ�������¦ÉÉÉÉÉÉÉɦ�������¦ÉÉÉÉÉÉÉɦ�������‘×××××××ׇ6666666‡×××××××ׇ6666666‡×××××××ׇ6666666‡ÛÛÛÛÛÛÛÛ‡6666666‡¾¾¾¾¾¾¾¾ƒHHHHHHHghhhhhhhhv�������vllllllllv�������vllllllllv�������vllllllllv�������| \ No newline at end of file diff --git a/crates/image-codecs/tests/fixtures/avif/quad-444-gbr-lossless.avif b/crates/image-codecs/tests/fixtures/avif/quad-444-gbr-lossless.avif new file mode 100644 index 000000000..c3b1f1423 Binary files /dev/null and b/crates/image-codecs/tests/fixtures/avif/quad-444-gbr-lossless.avif differ diff --git a/crates/image-codecs/tests/fixtures/avif/quad-source.rgb b/crates/image-codecs/tests/fixtures/avif/quad-source.rgb new file mode 100644 index 000000000..9e77c1dd1 --- /dev/null +++ b/crates/image-codecs/tests/fixtures/avif/quad-source.rgb @@ -0,0 +1 @@ +æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(æ(È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<È<<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Üðððððððððððððððððððððððððððððððððððððððððððððððð<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Üðððððððððððððððððððððððððððððððððððððððððððððððð<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Üðððððððððððððððððððððððððððððððððððððððððððððððð<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Üðððððððððððððððððððððððððððððððððððððððððððððððð<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Üðððððððððððððððððððððððððððððððððððððððððððððððð<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Üðððððððððððððððððððððððððððððððððððððððððððððððð<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Üðððððððððððððððððððððððððððððððððððððððððððððððð<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Ü<Üðððððððððððððððððððððððððððððððððððððððððððððððð \ No newline at end of file diff --git a/crates/image-codecs/tests/it/detect_caps.rs b/crates/image-codecs/tests/it/detect_caps.rs index 390eaa41f..e4868f97c 100644 --- a/crates/image-codecs/tests/it/detect_caps.rs +++ b/crates/image-codecs/tests/it/detect_caps.rs @@ -70,10 +70,15 @@ fn default_build_formats_all_symmetric() { } #[test] -fn avif_never_readable() { - assert!(!caps(Format::Avif).read); +fn avif_is_readable_only_with_the_decode_feature() { + assert_eq!(caps(Format::Avif).read, cfg!(all(feature = "avif-decode", not(target_arch = "wasm32")))); assert_eq!(caps(Format::Avif).write, cfg!(feature = "avif")); - assert!(matches!(decode_as(Format::Avif, b"\0\0\0\x1cftypavif"), Err(CodecError::Unsupported { .. }))); + let header = decode_as(Format::Avif, b"\0\0\0\x1cftypavif"); + if caps(Format::Avif).read { + assert!(matches!(header, Err(CodecError::Malformed { .. })), "{header:?}"); + } else { + assert!(matches!(header, Err(CodecError::Unsupported { .. })), "{header:?}"); + } } #[test] diff --git a/crates/media/README.md b/crates/media/README.md index 6262976bb..6663da282 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -447,7 +447,13 @@ page yet. Damage recovery may read bytes again up to twice the file's length plu is read at most about three times over; the packets kept and the header packets of a stream are bounded too, with a warning when a bound is reached. `OpusTiming` gives each Opus packet's start, the pre-skip and the end trimming of the final page. -No muxer. + +The muxer side is `PageWriter`, from FilmCraft's `filmcraft-oggmux` by @JordyUSA +(storytold/filmcraft#4481): it laces the packets of one logical stream into pages (continued +packets, granule positions, BOS/EOS, CRC-32), puts each header packet on pages of its own, closes +audio pages at a byte or packet target, and can replace the final granule position for Ogg Opus +end trimming. `opus_tags` and `vorbis_comment` build the comment headers; tag names that are not +valid field names (Vorbis I §5.2.1) are left out. ## `avi` diff --git a/crates/media/src/ogg/mod.rs b/crates/media/src/ogg/mod.rs index 387c3fc71..d487f9224 100644 --- a/crates/media/src/ogg/mod.rs +++ b/crates/media/src/ogg/mod.rs @@ -1,4 +1,4 @@ -//! Clean-room Ogg demuxer, written from RFC 3533 (the Ogg encapsulation format), RFC 7845 (Ogg +//! Clean-room Ogg demuxer and page writer, written from RFC 3533 (the Ogg encapsulation format), RFC 7845 (Ogg //! Opus) and the Vorbis I specification's Ogg mapping (section A). //! //! [`open`] reads every page (capture pattern, header, lacing values, CRC-32 checked; damaged @@ -12,6 +12,9 @@ //! TOC-derived durations, the pre-skip, and end trimming of the final page, so a player can seek //! to any 48 kHz sample. //! +//! [`PageWriter`] writes the pages of a logical bitstream, and [`opus_tags`] and +//! [`vorbis_comment`] build the comment headers of Ogg Opus and Ogg Vorbis. +//! //! Layer L0: no dependencies beyond `std`, no `unsafe`, builds for `wasm32-unknown-unknown`. //! //! From FilmCraft's `filmcraft-ogg` (storytold/filmcraft@8fda2f2). Public items keep their names, so @@ -25,6 +28,9 @@ use std::fmt; use std::io; pub use crate::source::{ByteSource, ReadSeekSource}; +pub use write::{PAGE_TARGET_BYTES, PAGE_TARGET_PACKETS, PageWriter, opus_tags, vorbis_comment}; + +mod write; /// Errors from reading an Ogg file. #[non_exhaustive] @@ -879,3 +885,5 @@ impl VorbisInfo { #[cfg(test)] mod tests; +#[cfg(test)] +mod write_tests; diff --git a/crates/media/src/ogg/write.rs b/crates/media/src/ogg/write.rs new file mode 100644 index 000000000..ff631c650 --- /dev/null +++ b/crates/media/src/ogg/write.rs @@ -0,0 +1,206 @@ +//! Ogg page writer (RFC 3533) and the comment-header packets of Ogg Opus (RFC 7845 §5.2) and Ogg +//! Vorbis (Vorbis I §5). +//! +//! [`PageWriter`] laces packets into pages of one logical bitstream: lacing values of 255 with a +//! shorter last value per packet, at most 255 per page, continued packets flagged on the next +//! page, the granule position of the last packet completed on each page (-1 on a page where no +//! packet completes), page sequence numbers, the CRC-32, and the beginning- and end-of-stream +//! flags. Header packets are flushed to pages of their own, as both mappings require. +//! +//! From FilmCraft's `filmcraft-oggmux` by @JordyUSA (storytold/filmcraft#4481). + +use super::crc32; + +/// Default size at which an audio page is closed before the next packet is added. +pub const PAGE_TARGET_BYTES: usize = 4096; +/// Default number of packets after which an audio page is closed (one second of 20 ms Opus). +pub const PAGE_TARGET_PACKETS: usize = 50; + +/// Writes the pages of one logical bitstream. +#[derive(Clone, Debug)] +pub struct PageWriter { + serial: u32, + seq: u32, + lacing: Vec, + body: Vec, + /// Granule position of the last packet completed on the pending page. + granule: Option, + /// The pending page starts with the continuation of a packet. + continued: bool, + packets: usize, + bos_written: bool, + finished: bool, + target_bytes: usize, + target_packets: usize, +} + +impl PageWriter { + /// A writer for the logical bitstream with serial number `serial`, closing audio pages at + /// [`PAGE_TARGET_BYTES`] or [`PAGE_TARGET_PACKETS`]. + pub fn new(serial: u32) -> PageWriter { + PageWriter { + serial, + seq: 0, + lacing: Vec::with_capacity(255), + body: Vec::new(), + granule: None, + continued: false, + packets: 0, + bos_written: false, + finished: false, + target_bytes: PAGE_TARGET_BYTES, + target_packets: PAGE_TARGET_PACKETS, + } + } + + /// Closes audio pages at `bytes` of payload or `packets` packets, whichever comes first. + pub fn with_page_target(mut self, bytes: usize, packets: usize) -> PageWriter { + self.target_bytes = bytes.max(1); + self.target_packets = packets.max(1); + self + } + + /// Pages written so far. + pub fn pages(&self) -> u32 { + self.seq + } + + /// A header packet on pages of its own (granule position 0); the first one opens the stream. + pub fn header(&mut self, data: &[u8]) -> Vec { + let mut out = self.flush(); + out.extend(self.add(data, 0)); + out.extend(self.flush()); + out + } + + /// Adds an audio packet that ends at granule position `granule`; returns the pages it + /// completed. The pending page is closed first once it is full enough, so the last packet + /// always stays pending for [`Self::finish`] to mark the end of the stream. + pub fn packet(&mut self, data: &[u8], granule: i64) -> Vec { + let mut out = Vec::new(); + if self.body.len() >= self.target_bytes || self.packets >= self.target_packets { + out = self.flush(); + } + out.extend(self.add(data, granule)); + out + } + + /// Closes the pending page now, if there is one. + pub fn flush(&mut self) -> Vec { + let mut out = Vec::new(); + if !self.lacing.is_empty() { + self.emit(&mut out, false); + } + out + } + + /// Ends the stream: the pending page (or an empty page when nothing is pending) with the + /// end-of-stream flag. `last_granule` replaces the granule position of the final page (Ogg + /// Opus end trimming) when a packet is pending; `None` keeps the last packet's. End trimming + /// applies only to packets completed on the last page (RFC 7845 §4.4), so do not + /// [`Self::flush`] the last packet before finishing. + pub fn finish(&mut self, last_granule: Option) -> Vec { + let mut out = Vec::new(); + if self.finished { + return out; + } + if let Some(g) = last_granule + && !self.lacing.is_empty() + { + self.granule = Some(g); + } + self.emit(&mut out, true); + self.finished = true; + out + } + + fn add(&mut self, data: &[u8], granule: i64) -> Vec { + let mut out = Vec::new(); + let mut rest = data; + let mut started = false; + loop { + if self.lacing.len() == 255 { + // A full page: the next one continues this packet, unless it has not begun yet. + self.emit(&mut out, false); + self.continued = started; + } + let n = rest.len().min(255); + self.lacing.push(n as u8); + started = true; + self.body.extend_from_slice(&rest[..n]); + rest = &rest[n..]; + if n < 255 { + break; + } + } + self.granule = Some(granule); + self.packets += 1; + out + } + + fn emit(&mut self, out: &mut Vec, eos: bool) { + let mut flags = 0u8; + if self.continued { + flags |= 0x01; + } + if !self.bos_written { + flags |= 0x02; + self.bos_written = true; + } + if eos { + flags |= 0x04; + } + let start = out.len(); + out.extend_from_slice(b"OggS"); + out.push(0); + out.push(flags); + out.extend_from_slice(&self.granule.unwrap_or(-1).to_le_bytes()); + out.extend_from_slice(&self.serial.to_le_bytes()); + out.extend_from_slice(&self.seq.to_le_bytes()); + out.extend_from_slice(&[0; 4]); + out.push(self.lacing.len() as u8); + out.extend_from_slice(&self.lacing); + out.extend_from_slice(&self.body); + let crc = crc32(&out[start..]); + out[start + 22..start + 26].copy_from_slice(&crc.to_le_bytes()); + self.seq = self.seq.wrapping_add(1); + self.lacing.clear(); + self.body.clear(); + self.granule = None; + self.continued = false; + self.packets = 0; + } +} + +/// A comment header body: vendor string and `KEY=value` comments, little-endian lengths. +fn comments(magic: &[u8], vendor: &str, tags: &[(&str, &str)]) -> Vec { + let mut v = magic.to_vec(); + let len = |n: usize| u32::try_from(n).unwrap_or(u32::MAX).to_le_bytes(); + v.extend(len(vendor.len())); + v.extend_from_slice(vendor.as_bytes()); + let tags: Vec = tags.iter().filter(|(k, _)| valid_key(k)).map(|(k, val)| format!("{k}={val}")).collect(); + v.extend(len(tags.len())); + for t in &tags { + v.extend(len(t.len())); + v.extend_from_slice(t.as_bytes()); + } + v +} + +/// A comment field name: printable ASCII 0x20–0x7D other than `=` (Vorbis I §5.2.1), not empty. +fn valid_key(k: &str) -> bool { + !k.is_empty() && k.bytes().all(|b| (0x20..=0x7D).contains(&b) && b != b'=') +} + +/// The `OpusTags` packet (RFC 7845 §5.2). Comments whose name is not a valid field name are +/// left out. +pub fn opus_tags(vendor: &str, tags: &[(&str, &str)]) -> Vec { + comments(b"OpusTags", vendor, tags) +} + +/// The Vorbis comment header packet (Vorbis I §5: type 3, `vorbis`, comments, framing bit). +pub fn vorbis_comment(vendor: &str, tags: &[(&str, &str)]) -> Vec { + let mut v = comments(b"\x03vorbis", vendor, tags); + v.push(1); + v +} diff --git a/crates/media/src/ogg/write_tests.rs b/crates/media/src/ogg/write_tests.rs new file mode 100644 index 000000000..eebf5732e --- /dev/null +++ b/crates/media/src/ogg/write_tests.rs @@ -0,0 +1,200 @@ +//! The page writer, read back by [`open`]. + +#![allow(clippy::unwrap_used)] + +use super::{Codec, OpusTiming, PageWriter, crc32, open, opus_tags, vorbis_comment}; + +/// A TOC-only 20 ms CELT packet of `len` bytes whose bytes encode `i` (so packets differ). +fn opus_packet(i: usize, len: usize) -> Vec { + let mut p = vec![0xF8u8]; + p.extend((0..len.saturating_sub(1)).map(|k| (i * 31 + k) as u8)); + p +} + +fn opus_head(pre_skip: u16) -> Vec { + let mut h = b"OpusHead".to_vec(); + h.extend([1, 2]); + h.extend(pre_skip.to_le_bytes()); + h.extend(48_000u32.to_le_bytes()); + h.extend([0, 0, 0]); + h +} + +/// An Ogg Opus file of `n` packets of `sizes(i)` bytes, `samples` playable samples after the pre-skip. +fn write_opus(n: usize, sizes: impl Fn(usize) -> usize, pre_skip: u16, samples: i64) -> (Vec, Vec>) { + let mut w = PageWriter::new(0x1234_5678); + let mut f = w.header(&opus_head(pre_skip)); + f.extend(w.header(&opus_tags("FilmCraft", &[("TITLE", "Test"), ("bad=key", "dropped"), ("", "dropped")]))); + let mut packets = Vec::new(); + for i in 0..n { + let p = opus_packet(i, sizes(i)); + f.extend(w.packet(&p, (i as i64 + 1) * 960)); + packets.push(p); + } + f.extend(w.finish(Some(i64::from(pre_skip) + samples))); + (f, packets) +} + +#[test] +fn written_pages_read_back_packet_for_packet() { + let (f, packets) = write_opus(230, |i| 3 + (i * 37) % 400, 120, 230 * 960 - 120 - 500); + let ogg = open(&f).unwrap(); + assert!(ogg.warnings.is_empty(), "{:?}", ogg.warnings); + assert_eq!(ogg.streams.len(), 1); + let s = &ogg.streams[0]; + assert_eq!((s.serial, s.codec, s.saw_eos), (0x1234_5678, Codec::Opus, true)); + assert_eq!(s.headers.len(), 2); + assert_eq!(s.headers[0], opus_head(120)); + assert_eq!(s.headers[1], opus_tags("FilmCraft", &[("TITLE", "Test")])); + assert_eq!(s.packets.len(), packets.len()); + for (k, p) in packets.iter().enumerate() { + assert_eq!(&ogg.read_packet(&f, 0, k).unwrap(), p, "packet {k}"); + } + assert!(s.packets.last().unwrap().eos); + assert_eq!(s.last_granule, Some(120 + 230 * 960 - 120 - 500)); + // RFC 7845 §4: the end trimming of the final page. + let t = OpusTiming::of(s, 120); + assert_eq!(t.total, 230 * 960 - 120 - 500); + assert_eq!(t.starts[0], -120); + assert!(t.durations.iter().all(|&d| d == 960)); +} + +#[test] +fn headers_have_pages_of_their_own_and_only_the_first_page_opens_the_stream() { + let (f, _) = write_opus(3, |_| 10, 0, 3 * 960); + let mut pos = 0; + let mut flags = Vec::new(); + let mut seqs = Vec::new(); + while pos + 27 <= f.len() { + assert_eq!(&f[pos..pos + 4], b"OggS"); + let mut page = f[pos..].to_vec(); + let nseg = page[26] as usize; + let len = 27 + nseg + page[27..27 + nseg].iter().map(|&l| l as usize).sum::(); + page.truncate(len); + let stored = u32::from_le_bytes(page[22..26].try_into().unwrap()); + page[22..26].fill(0); + assert_eq!(crc32(&page), stored, "page CRC"); + flags.push(f[pos + 5]); + seqs.push(u32::from_le_bytes(f[pos + 18..pos + 22].try_into().unwrap())); + pos += len; + } + assert_eq!(pos, f.len()); + assert_eq!(flags, [0x02, 0x00, 0x04], "BOS head page, tags page, one audio page with EOS"); + assert_eq!(seqs, [0, 1, 2]); +} + +#[test] +fn a_packet_longer_than_a_page_continues() { + let big = 2 * 255 * 255 + 7000; // spans three pages: the middle one completes no packet + let (f, packets) = write_opus(4, |i| if i == 1 { big } else { 50 }, 0, 4 * 960); + let ogg = open(&f).unwrap(); + assert!(ogg.warnings.is_empty()); + for (k, p) in packets.iter().enumerate() { + assert_eq!(&ogg.read_packet(&f, 0, k).unwrap(), p, "packet {k}"); + } + // a page on which no packet completes has granule position -1 + let mut pos = 0; + let mut saw_none = false; + while pos + 27 <= f.len() { + let nseg = f[pos + 26] as usize; + let lacing = &f[pos + 27..pos + 27 + nseg]; + let g = i64::from_le_bytes(f[pos + 6..pos + 14].try_into().unwrap()); + if lacing.iter().all(|&l| l == 255) { + assert_eq!(g, -1); + saw_none = true; + } + pos += 27 + nseg + lacing.iter().map(|&l| l as usize).sum::(); + } + assert!(saw_none); +} + +#[test] +fn page_targets_bound_page_size_and_finish_marks_the_end_once() { + let mut w = PageWriter::new(7).with_page_target(1000, 10); + let mut f = w.header(&opus_head(0)); + f.extend(w.header(&opus_tags("v", &[]))); + for i in 0..95 { + f.extend(w.packet(&opus_packet(i, 160), (i as i64 + 1) * 960)); + } + f.extend(w.finish(None)); + assert!(w.finish(None).is_empty()); + let ogg = open(&f).unwrap(); + let s = &ogg.streams[0]; + assert_eq!(s.packets.len(), 95); + assert_eq!(s.pages, 2 + 95_u32.div_ceil(7), "1000-byte pages hold 7 packets of 160 bytes"); + assert_eq!(s.last_granule, Some(95 * 960)); + // An empty stream still ends. + let mut w = PageWriter::new(1); + let mut f = w.header(&opus_head(0)); + f.extend(w.finish(Some(0))); + assert!(open(&f).unwrap().streams[0].saw_eos); + // A flushed last packet cannot be trimmed: the empty end page keeps its granule. + let mut w = PageWriter::new(1); + let mut f = w.header(&opus_head(312)); + f.extend(w.header(&opus_tags("t", &[]))); + f.extend(w.packet(&[0xFC; 40], 960)); + f.extend(w.flush()); + f.extend(w.finish(Some(500))); + let s = &open(&f).unwrap().streams[0]; + assert!(s.saw_eos); + assert_eq!(s.last_granule, Some(960)); +} + +#[test] +fn vorbis_comment_has_the_framing_bit() { + let c = vorbis_comment("FilmCraft", &[("ARTIST", "x")]); + assert_eq!(&c[..7], b"\x03vorbis"); + assert_eq!(*c.last().unwrap(), 1); + assert_eq!(u32::from_le_bytes(c[7..11].try_into().unwrap()), 9); +} + +/// Packets on and around the lacing boundaries (multiples of 255, where a packet ends with a +/// zero lacing value) and an empty packet read back exactly. +#[test] +fn lacing_boundaries_read_back() { + let sizes = [0usize, 1, 254, 255, 256, 509, 510, 511, 765, 65_024, 65_025, 65_026]; + let mut w = PageWriter::new(3); + let mut f = w.header(&opus_head(0)); + f.extend(w.header(&opus_tags("v", &[]))); + let packets: Vec> = sizes.iter().enumerate().map(|(i, &n)| (0..n).map(|k| (i * 7 + k) as u8).collect()).collect(); + for (i, p) in packets.iter().enumerate() { + f.extend(w.packet(p, (i as i64 + 1) * 960)); + } + f.extend(w.finish(None)); + let ogg = open(&f).unwrap(); + assert!(ogg.warnings.is_empty(), "{:?}", ogg.warnings); + assert_eq!(ogg.streams[0].packets.len(), packets.len()); + for (k, p) in packets.iter().enumerate() { + assert_eq!(ogg.read_packet(&f, 0, k).unwrap(), *p, "packet {k} of {} bytes", p.len()); + } +} + +/// A page exactly full of lacing values when a packet starts: the packet begins on the next page, +/// which must not be flagged as continuing one (the reader would drop its first packet). Review +/// of #4481; reachable with page targets larger than the defaults. +#[test] +fn a_packet_after_an_exactly_full_page_is_not_a_continuation() { + let mut w = PageWriter::new(5).with_page_target(1 << 20, 1000); + let mut f = w.header(&opus_head(0)); + f.extend(w.header(&opus_tags("v", &[]))); + let packets: Vec> = (0..300).map(|i| opus_packet(i, 1)).collect(); + for (i, p) in packets.iter().enumerate() { + f.extend(w.packet(p, (i as i64 + 1) * 960)); + } + f.extend(w.finish(None)); + let ogg = open(&f).unwrap(); + assert!(ogg.warnings.is_empty(), "{:?}", ogg.warnings); + assert_eq!(ogg.streams[0].packets.len(), 300, "every packet is read back"); + for (k, p) in packets.iter().enumerate() { + assert_eq!(&ogg.read_packet(&f, 0, k).unwrap(), p, "packet {k}"); + } + // the second audio page starts with packet 255 and is not a continuation + let mut pos = 0; + let mut flags = Vec::new(); + while pos + 27 <= f.len() { + let nseg = f[pos + 26] as usize; + flags.push(f[pos + 5]); + pos += 27 + nseg + f[pos + 27..pos + 27 + nseg].iter().map(|&l| l as usize).sum::(); + } + assert!(flags.iter().all(|&fl| fl & 0x01 == 0), "no page continues a packet: {flags:?}"); +} diff --git a/crates/psd/src/channel_resources.rs b/crates/psd/src/channel_resources.rs new file mode 100644 index 000000000..204d36eb0 --- /dev/null +++ b/crates/psd/src/channel_resources.rs @@ -0,0 +1,111 @@ +//! Raw PSD channel DisplayInfo (1077/1007) and Alternate Spot Colors (1067) records. +//! +//! Ported from PhotoCraft channel_map: Jason D's f7f8fdcd89 DisplayInfo framing and +//! Khawar Zamman Wani's 9a390661b5 alternate-spot reader. Colour interpretation, opacity +//! clamping, channel matching and legacy compatibility decisions belong to the caller. +//! Readers borrow their input and ignore a trailing partial record, preserving the +//! original tolerant import behavior. Version words are framing, not validation here. + +/// One 13-byte DisplayInfo record, without document-specific colour interpretation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct DisplayInfo { + /// PSD colour-space identifier. + pub space: u16, + /// Four raw colour components. + pub components: [u16; 4], + /// Raw opacity (normally 0 through 100). + pub opacity: u16, + /// Raw channel kind (0 selected, 1 masked, 2 spot). + pub kind: u8, +} + +impl DisplayInfo { + /// Encode the version-1 resource's 13-byte record, without clamping fields. + pub fn to_bytes(self) -> [u8; 13] { + let mut out = [0; 13]; + let values = [self.space, self.components[0], self.components[1], self.components[2], self.components[3], self.opacity]; + for (slot, value) in out[..12].as_chunks_mut::<2>().0.iter_mut().zip(values) { + *slot = value.to_be_bytes(); + } + out[12] = self.kind; + out + } +} + +/// Iterate complete DisplayInfo records without allocating. +/// +/// `versioned` selects resource 1077 (skip four version bytes, 13-byte records), +/// otherwise resource 1007 (14-byte records, ignoring each padding byte). A short +/// version header or incomplete final record yields no corresponding record. +pub fn display_info(data: &[u8], versioned: bool) -> impl ExactSizeIterator + '_ { + let (body, size) = if versioned { (data.get(4..).unwrap_or(&[]), 13) } else { (data, 14) }; + body.chunks_exact(size).map(|rec| { + let u = |i: usize| u16::from_be_bytes([rec[i], rec[i + 1]]); + DisplayInfo { space: u(0), components: [u(2), u(4), u(6), u(8)], opacity: u(10), kind: rec[12] } + }) +} + +/// One Alternate Spot Colors record, retaining unknown colour spaces. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AlternateSpotColor { + /// Channel identifier from resource 1053. + pub id: u32, + /// PSD colour-space identifier. + pub space: u16, + /// Four raw colour components. + pub components: [u16; 4], +} + +/// Iterate available complete 14-byte records up to the resource's declared u16 count. +/// +/// Short headers, absent declared records and trailing partial bytes are tolerated exactly +/// as in the original importer. No allocation is derived from an untrusted count. +pub fn alternate_spot_colors(data: &[u8]) -> impl ExactSizeIterator + '_ { + let count = data.get(2..4).map_or(0, |c| usize::from(u16::from_be_bytes([c[0], c[1]]))); + data.get(4..).unwrap_or_default().as_chunks::<14>().0.iter().take(count).map(|rec| { + let u = |i: usize| u16::from_be_bytes([rec[i], rec[i + 1]]); + AlternateSpotColor { id: u32::from_be_bytes([rec[0], rec[1], rec[2], rec[3]]), space: u(4), components: [u(6), u(8), u(10), u(12)] } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn display_round_trip_and_truncation() { + let record = DisplayInfo { space: 0x2331, components: [0, 1, 255, u16::MAX], opacity: 500, kind: 255 }; + let mut modern = 99u32.to_be_bytes().to_vec(); + modern.extend(record.to_bytes()); + assert_eq!(display_info(&modern, true).collect::>(), [record]); + for n in 0..modern.len() { + assert_eq!(display_info(&modern[..n], true).len(), 0); + } + modern.extend([1, 2, 3]); + assert_eq!(display_info(&modern, true).len(), 1); + let mut old = record.to_bytes().to_vec(); + old.push(42); + old.extend(record.to_bytes()); + old.push(99); + assert_eq!(display_info(&old, false).collect::>(), [record, record]); + assert_eq!(display_info(&old[..27], false).len(), 1); + } + + #[test] + fn alternate_count_is_bounded_by_available_records() { + let mut bytes = vec![0, 9, 255, 255]; + bytes.extend(123u32.to_be_bytes()); + for value in [7u16, 10000, 0xffff, 4, 5] { + bytes.extend(value.to_be_bytes()); + } + let want = AlternateSpotColor { id: 123, space: 7, components: [10000, 0xffff, 4, 5] }; + assert_eq!(alternate_spot_colors(&bytes).collect::>(), [want]); + for n in 0..bytes.len() { + assert_eq!(alternate_spot_colors(&bytes[..n]).len(), 0); + } + bytes.extend([1, 2, 3]); + assert_eq!(alternate_spot_colors(&bytes).len(), 1); + bytes[2..4].copy_from_slice(&0u16.to_be_bytes()); + assert_eq!(alternate_spot_colors(&bytes).len(), 0); + } +} diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 27797f1bc..d4db98065 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -60,6 +60,7 @@ pub mod asl; pub mod atn; pub mod blend; pub mod builder; +pub mod channel_resources; mod codepage; pub mod compression; pub mod csh; @@ -102,6 +103,7 @@ pub mod testgen; pub mod text; pub mod tiff; pub mod tree; +pub mod unicode_names; pub use blend::BlendMode; pub use builder::{GroupSpec, LayerSpec, MaskSpec, PixelData, PsdBuilder}; diff --git a/crates/psd/src/unicode_names.rs b/crates/psd/src/unicode_names.rs new file mode 100644 index 000000000..c4547243b --- /dev/null +++ b/crates/psd/src/unicode_names.rs @@ -0,0 +1,54 @@ +//! Counted UTF-16 name records, as used by PSD Unicode Alpha Names (resource 1045). +//! +//! Adapted from PhotoCraft's channel-name reader. Framing is shared; decoding malformed +//! UTF-16, removing terminators and assigning names to document channels remain caller policy. + +/// Iterate complete records as borrowed big-endian UTF-16 byte slices. +/// +/// A record starts with a big-endian `u32` code-unit count. Empty records are retained. +/// An incomplete count, truncated record or arithmetic overflow ends the list, preserving +/// preceding complete records. No allocation is driven by the declared count, and bytes +/// after a malformed record are not interpreted as new records. +pub fn records(mut data: &[u8]) -> impl Iterator { + std::iter::from_fn(move || { + let count = data.get(..4)?; + let count = u32::from_be_bytes([count[0], count[1], count[2], count[3]]); + let input = data; + // On any malformed length the iterator stays exhausted on subsequent calls. + data = &[]; + let len = usize::try_from(count).ok()?.checked_mul(2)?; + let end = 4usize.checked_add(len)?; + let record = input.get(4..end)?; + data = input.get(end..)?; + Some(record) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn borrows_empty_and_uninterpreted_code_units() { + let data = [0, 0, 0, 0, 0, 0, 0, 3, 0xd8, 0, 0, 65, 0, 0]; + let found: Vec<_> = records(&data).collect(); + assert_eq!(found, [&data[4..4], &data[8..14]]); + assert_eq!(found[1].as_ptr(), data[8..].as_ptr()); + } + + #[test] + fn partial_tail_and_hostile_count_stop_without_losing_prefix() { + let first = [0, 0, 0, 1, 0, 65]; + for tail in [&[0][..], &[0, 0, 0], &[0, 0, 0, 2, 0, 66], &[255, 255, 255, 255, 0, 66]] { + let mut bytes = first.to_vec(); + bytes.extend(tail); + let mut it = records(&bytes); + assert_eq!(it.next(), Some(&first[4..])); + assert_eq!(it.next(), None); + assert_eq!(it.next(), None); + } + for end in 0..first.len() { + assert_eq!(records(&first[..end]).count(), 0); + } + } +} diff --git a/crates/raw/src/dngwrite.rs b/crates/raw/src/dngwrite.rs index 8953f94ea..ace0c07f6 100644 --- a/crates/raw/src/dngwrite.rs +++ b/crates/raw/src/dngwrite.rs @@ -13,6 +13,7 @@ pub enum DngCompression { Uncompressed, /// Lossless JPEG tiles of `tile × tile` pixels (`tile` even). CFA tiles are encoded as two interleaved /// components of half the tile width (the common DNG layout), linear data with one component per sample. + /// Edges above 2048 (after even alignment) are rejected before padding the tile. Lj92 { tile: u32, }, @@ -35,6 +36,11 @@ const DEFLATE_LEVEL: u8 = 1; /// above the 256 default and every real tile this writer makes. const MAX_DEFLATE_TILE: u32 = 2048; +// Match the existing padded Deflate edge budget. JPEG's 16-bit dimension limit alone would permit +// a 65534²-sample allocation even for a tiny source image. At most four validated channels make +// this bound at most 32 MiB of u16 padding per tile, before encoder scratch/output. +const MAX_LJ92_TILE: usize = MAX_DEFLATE_TILE as usize; + /// `tile` aligned down to a multiple of 16 and clamped to [`MAX_DEFLATE_TILE`]. fn deflate_tile(tile: u32) -> usize { (tile.max(16) & !15).min(MAX_DEFLATE_TILE) as usize @@ -270,7 +276,7 @@ pub fn write_dng(raw: &RawImage, opts: &DngWriteOptions) -> Result> { } DngCompression::Lj92 { tile } => { let tile = (tile.max(2) & !1) as usize; - if tile > 65534 { + if tile > MAX_LJ92_TILE { return Err(RawError::Limit("tile too large")); } ifd.set(t::COMPRESSION, Value::Short(vec![compression::JPEG])); @@ -432,6 +438,58 @@ mod tests { use super::*; use crate::{BlackLevel, OpcodeLists, RawData, RawFormat, RawImage, Rect}; + fn tiny_raw() -> RawImage { + let (w, h) = (8usize, 8usize); + let full = Rect::new(0, 0, w, h); + RawImage { + format: RawFormat::Dng, + width: w, + height: h, + cpp: 1, + data: RawData::U16((0..64).map(|i| i as u16 * 129).collect()), + cfa: None, + bits: 14, + black: BlackLevel::uniform(0.0), + white: vec![16383.0], + active_area: full, + crop: full, + orientation: crate::Orientation::Normal, + color: crate::ColorData::default(), + wb_multipliers: None, + linearized: false, + pixel_aspect: 1.0, + opcodes: OpcodeLists::default(), + camera: Default::default(), + cinema: Default::default(), + lens_metadata: Default::default(), + level_sources: Default::default(), + notices: crate::RawNotices::default(), + } + } + + #[test] + fn oversized_lj92_padding_is_rejected() { + let raw = tiny_raw(); + // The near-boundary case previously completed with an oversized padded tile; keep it first + // so reverting the guard fails without trying the multi-gigabyte cases. + for tile in [2050, 65534, u32::MAX] { + let opts = DngWriteOptions { compression: DngCompression::Lj92 { tile }, ..Default::default() }; + assert!(matches!(write_dng(&raw, &opts), Err(RawError::Limit("tile too large")))); + } + } + + #[test] + fn default_lj92_tiles_preserve_samples() { + let raw = tiny_raw(); + let bytes = write_dng(&raw, &DngWriteOptions::default()).expect("normal tiles write"); + let back = crate::decode(&bytes).expect("normal tiles decode"); + assert_eq!((back.width, back.height), (raw.width, raw.height)); + match (&back.data, &raw.data) { + (RawData::U16(actual), RawData::U16(expected)) => assert_eq!(actual, expected), + _ => panic!("integer DNG changed sample type"), + } + } + /// Deflate tiles of `tile × tile` pad into a square buffer that grows with the square: a /// caller-supplied edge of `u32::MAX` would make the writer pad an 8 × 8 image into billions of /// edge-replicate iterations and a multi-gigabyte buffer. The clamp keeps the bounded shape — same diff --git a/crates/stream-codecs/Cargo.toml b/crates/stream-codecs/Cargo.toml index 8827f294e..14ce68603 100644 --- a/crates/stream-codecs/Cargo.toml +++ b/crates/stream-codecs/Cargo.toml @@ -15,8 +15,9 @@ workspace = true fax = "0.2.7" # CCITT fax decoding, the decoder the vendored PDF reader uses. MIT OR Apache-2.0. hayro-ccitt = { version = "0.3", default-features = false } -# JBIG2 decoding, the decoder the vendored PDF reader uses (the workspace patches it to `vendor/hayro-jbig2`). -hayro-jbig2 = { version = "=0.3.0", default-features = false, features = ["std"] } +# The bounded JBIG2 API is a local extension: consumers do not inherit workspace patches. +# Keep the vendored dependency explicit so Git consumers retain its work-budget safeguards. +hayro-jbig2 = { path = "../../vendor/hayro-jbig2", version = "=0.3.0", default-features = false, features = ["std"] } thiserror = { workspace = true } [dev-dependencies] diff --git a/crates/stream-codecs/src/jbig2/decode.rs b/crates/stream-codecs/src/jbig2/decode.rs index e5a49d359..0e04bd648 100644 --- a/crates/stream-codecs/src/jbig2/decode.rs +++ b/crates/stream-codecs/src/jbig2/decode.rs @@ -78,6 +78,15 @@ mod tests { use super::*; use crate::{encode_jbig2, encode_jbig2_generic}; + /// A registry fallback lacks the budget APIs and breaks consumers outside this workspace. + #[test] + fn bounded_decoder_dependency_is_explicit_for_external_consumers() { + let manifest = include_str!("../../Cargo.toml"); + let dependency = manifest.lines().find(|line| line.starts_with("hayro-jbig2 =")).unwrap(); + assert!(dependency.contains(r#"path = "../../vendor/hayro-jbig2""#)); + assert!(dependency.contains(r#"version = "=0.3.0""#)); + } + /// [`decode_jbig2_within`] with no limit on the work. fn decode_jbig2(data: &[u8], globals: Option<&[u8]>, columns: u32, rows: u32, max: usize) -> Result, CodecError> { let mut unbounded = u64::MAX; diff --git a/crates/usd/Cargo.toml b/crates/usd/Cargo.toml new file mode 100644 index 000000000..ac1c64d0c --- /dev/null +++ b/crates/usd/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "craft-usd" +description = "Bounded USD Crate wire primitives, independent of scene and material policy" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] } +thiserror.workspace = true diff --git a/crates/usd/README.md b/crates/usd/README.md new file mode 100644 index 000000000..606b5b250 --- /dev/null +++ b/crates/usd/README.md @@ -0,0 +1,7 @@ +# craft-usd + +Bounded wire primitives for USD Crate, independent of application scene and material models. + +Currently provides Crate-framed LZ4 decompression only: a single unprefixed block or up to 127 length-prefixed blocks, under a caller-provided output-byte cap with fallible output allocation. Trailing bytes after counted chunks retain the original reader's ignored-tail policy. This is not a complete USD reader/writer; scene interpretation, integer packing and export remain outside this first extraction. + +Adapted from TextureCraft `crates/formats/src/mesh_import/usd/codec.rs`, introduced by bflatastic in `bdbb52c9b66b221a55b370105b42f485a76e6fc7`. The LZ4 backend is MIT-licensed `lz4_flex`. diff --git a/crates/usd/src/lib.rs b/crates/usd/src/lib.rs new file mode 100644 index 000000000..943bf1d4d --- /dev/null +++ b/crates/usd/src/lib.rs @@ -0,0 +1,95 @@ +//! Bounded USD Crate wire primitives. Not a complete USD scene reader or writer. +//! +//! The framing decoder is adapted from TextureCraft's `usd/codec.rs`, originally +//! bflatastic, commit bdbb52c9b66b221a55b370105b42f485a76e6fc7. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +/// Failure to read a bounded Crate LZ4 frame. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// Invalid or incomplete chunk framing. + #[error("invalid USD Crate LZ4 framing: {0}")] + Framing(&'static str), + /// Invalid compressed data or output exceeding the supplied capacity. + #[error("USD Crate LZ4 data: {0}")] + Lz4(#[from] lz4_flex::block::DecompressError), + /// The bounded output allocation could not be reserved. + #[error("cannot allocate USD Crate LZ4 output")] + Allocation, +} + +/// Decode Crate's chunk-count byte and LZ4 blocks to at most `max_output` bytes. +/// +/// A zero count means a single unprefixed block; 1..=127 means that many blocks, +/// each preceded by a signed little-endian 32-bit length. As in the original reader, +/// bytes following the declared chunks are ignored. The output allocation is fallible +/// and capped by both the caller's budget and the input's maximum LZ4 expansion. +/// This bounds the returned plane, not backend internal scratch memory. +pub fn decompress(input: &[u8], max_output: usize) -> Result, Error> { + let (&chunks, mut rest) = input.split_first().ok_or(Error::Framing("empty block"))?; + if chunks > 127 { + return Err(Error::Framing("chunk count exceeds 127")); + } + let capacity = max_output.min(input.len().saturating_mul(256).saturating_add(64)); + let mut output = Vec::new(); + output.try_reserve_exact(capacity).map_err(|_| Error::Allocation)?; + output.resize(capacity, 0); + let written = if chunks == 0 { + lz4_flex::block::decompress_into(rest, &mut output)? + } else { + let mut total = 0usize; + for _ in 0..chunks { + let length = rest.get(..4).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes).ok_or(Error::Framing("missing chunk length"))?; + let length = usize::try_from(length).map_err(|_| Error::Framing("negative chunk length"))?; + let end = 4usize.checked_add(length).ok_or(Error::Framing("chunk length overflow"))?; + let chunk = rest.get(4..end).ok_or(Error::Framing("truncated chunk"))?; + rest = rest.get(end..).unwrap_or_default(); + let tail = output.get_mut(total..).ok_or(Error::Framing("output offset overflow"))?; + let count = lz4_flex::block::decompress_into(chunk, tail)?; + total = total.checked_add(count).ok_or(Error::Framing("output length overflow"))?; + } + total + }; + output.truncate(written); + Ok(output) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn single_block_matches_original_wire() { + for n in [0, 1, 15, 16, 255, 4096] { + let raw: Vec = (0..n).map(|i| (i % 251) as u8).collect(); + let mut frame = vec![0]; + frame.extend(lz4_flex::block::compress(&raw)); + assert_eq!(decompress(&frame, raw.len()).unwrap(), raw); + if n > 0 { + assert!(decompress(&frame, n - 1).is_err()); + } + } + } + + #[test] + fn counted_blocks_and_trailing_bytes_keep_existing_policy() { + let mut frame = vec![2]; + for raw in [b"first".as_slice(), b"second".as_slice()] { + let block = lz4_flex::block::compress(raw); + frame.extend((block.len() as i32).to_le_bytes()); + frame.extend(block); + } + frame.extend(b"ignored"); + assert_eq!(decompress(&frame, 11).unwrap(), b"firstsecond"); + assert!(decompress(&frame, 10).is_err()); + } + + #[test] + fn malformed_frames_fail_within_budget() { + for data in [vec![], vec![128], vec![1], vec![1, 255, 255, 255, 255], vec![1, 5, 0, 0, 0, 1]] { + assert!(decompress(&data, 32).is_err()); + } + } +} diff --git a/crates/video/src/av1/decode/decoder.rs b/crates/video/src/av1/decode/decoder.rs index 943923a3b..65c3de6ef 100644 --- a/crates/video/src/av1/decode/decoder.rs +++ b/crates/video/src/av1/decode/decoder.rs @@ -239,6 +239,9 @@ pub struct Decoder { /// Bytes of the pictures the chunk being parsed has shown so far, and whether one was refused for size. shown_bytes: usize, shown_overflow: bool, + /// Most bytes of pictures one chunk may show: [`MAX_SHOWN_BYTES_PER_CHUNK`] unless a caller + /// lowered it with [`Decoder::set_shown_budget`]. + shown_budget: usize, lf_deltas: LoopFilterDeltas, seg_features: SegmentationFeatures, prev_gm_params: [[i32; 6]; 8], @@ -301,8 +304,8 @@ fn shown_within_limit(n: usize) -> bool { /// copies of one 4K reference (about 6.4 GB) from a few hundred bytes of show_existing_frame headers. const MAX_SHOWN_BYTES_PER_CHUNK: usize = 1 << 30; -fn shown_bytes_within_limit(bytes: usize) -> bool { - bytes <= MAX_SHOWN_BYTES_PER_CHUNK +fn shown_bytes_within_limit(bytes: usize, budget: usize) -> bool { + bytes <= budget.min(MAX_SHOWN_BYTES_PER_CHUNK) } /// Bytes of the `u16` sample planes of a `w` × `h` picture. @@ -313,14 +316,14 @@ fn picture_bytes(w: usize, h: usize, c: &crate::av1::decode::header::ColorConfig } /// Add a shown picture to a chunk's outputs, refusing the chunk (and dropping everything it showed) -/// before the list can grow past [`MAX_SHOWN_PER_CHUNK`]. -fn push_shown(out: &mut Vec<(Output, usize, u32)>, shown_bytes: &mut usize, item: (Output, usize, u32)) -> Result<()> { +/// before the list can grow past [`MAX_SHOWN_PER_CHUNK`] or its pictures past `budget` bytes. +fn push_shown(out: &mut Vec<(Output, usize, u32)>, shown_bytes: &mut usize, budget: usize, item: (Output, usize, u32)) -> Result<()> { if !shown_within_limit(out.len() + 1) { out.clear(); return Err(Error::Invalid("too many pictures shown by one chunk")); } let bytes = shown_bytes.saturating_add(item.0.bytes()); - if !shown_bytes_within_limit(bytes) { + if !shown_bytes_within_limit(bytes, budget) { out.clear(); return Err(Error::Invalid("pictures shown by one chunk are too large")); } @@ -349,6 +352,14 @@ impl Decoder { self.memory_budget = bytes; } + /// Cap the bytes of the pictures one `decode` call may return together, below the built-in + /// 1 GiB (a larger value keeps that). The pictures are refused before they are built, so a + /// caller that keeps only one of them (an AVIF still) can hold a stream to its own memory + /// budget instead of collecting up to 256 pictures first. + pub fn set_shown_budget(&mut self, bytes: u64) { + self.shown_budget = usize::try_from(bytes).unwrap_or(usize::MAX).min(MAX_SHOWN_BYTES_PER_CHUNK); + } + /// A decoder using all available cores (with the `threads` feature). pub fn new() -> Decoder { Decoder::with_threads(default_threads()) @@ -369,6 +380,7 @@ impl Decoder { ref_color: Default::default(), shown_bytes: 0, shown_overflow: false, + shown_budget: MAX_SHOWN_BYTES_PER_CHUNK, lf_deltas: LoopFilterDeltas::defaults(), seg_features: SegmentationFeatures::default(), prev_gm_params: default_gm_params(), @@ -564,20 +576,20 @@ impl Decoder { let mut r = BitReader::new(payload); let shown = self.frame_header(&mut r, temporal_id, spatial_id)?; if let Some(o) = shown { - push_shown(out, &mut self.shown_bytes, (o, tu, spatial_id))?; + push_shown(out, &mut self.shown_bytes, self.shown_budget, (o, tu, spatial_id))?; continue; } if obu_type == OBU_FRAME_T { r.byte_align(); let rest = payload.get(r.byte_pos()..).ok_or(Error::Truncated)?; if let Some(o) = self.tile_group(rest)? { - push_shown(out, &mut self.shown_bytes, (o, tu, spatial_id))?; + push_shown(out, &mut self.shown_bytes, self.shown_budget, (o, tu, spatial_id))?; } } } OBU_TILE_GROUP_T => { if let Some(o) = self.tile_group(payload)? { - push_shown(out, &mut self.shown_bytes, (o, tu, spatial_id))?; + push_shown(out, &mut self.shown_bytes, self.shown_budget, (o, tu, spatial_id))?; } } OBU_METADATA_T | OBU_TILE_LIST_T => {} @@ -726,7 +738,7 @@ impl Decoder { // A picture past the chunk's byte budget is never built (decoding the frame as a reference // still happens, so the reference slots stay as the stream says), and the chunk is refused. let bytes = picture_bytes(job.fh.upscaled_width as usize, job.fh.frame_height as usize, &job.seq.color); - if job.picture.is_some() && !shown_bytes_within_limit(self.shown_bytes.saturating_add(bytes)) { + if job.picture.is_some() && !shown_bytes_within_limit(self.shown_bytes.saturating_add(bytes), self.shown_budget) { job.picture = None; self.shown_overflow = true; self.submit(job); @@ -1307,18 +1319,33 @@ mod shown_limit_tests { #[test] fn push_shown_refuses_a_chunk_past_either_limit_and_drops_what_it_showed() { let (mut out, mut bytes) = (Vec::new(), 0usize); - push_shown(&mut out, &mut bytes, shown(10)).unwrap(); + push_shown(&mut out, &mut bytes, MAX_SHOWN_BYTES_PER_CHUNK, shown(10)).unwrap(); assert_eq!((out.len(), bytes), (1, 10)); // past the byte budget - assert!(push_shown(&mut out, &mut bytes, shown(MAX_SHOWN_BYTES_PER_CHUNK)).is_err()); + assert!(push_shown(&mut out, &mut bytes, MAX_SHOWN_BYTES_PER_CHUNK, shown(MAX_SHOWN_BYTES_PER_CHUNK)).is_err()); assert!(out.is_empty(), "the refused chunk shows nothing"); // past the count limit let (mut out, mut bytes) = (Vec::new(), 0usize); for _ in 0..MAX_SHOWN_PER_CHUNK { - push_shown(&mut out, &mut bytes, shown(0)).unwrap(); + push_shown(&mut out, &mut bytes, MAX_SHOWN_BYTES_PER_CHUNK, shown(0)).unwrap(); } - assert!(push_shown(&mut out, &mut bytes, shown(0)).is_err()); + assert!(push_shown(&mut out, &mut bytes, MAX_SHOWN_BYTES_PER_CHUNK, shown(0)).is_err()); assert!(out.is_empty()); + // past a caller's lower budget + let (mut out, mut bytes) = (Vec::new(), 0usize); + push_shown(&mut out, &mut bytes, 100, shown(60)).unwrap(); + assert!(push_shown(&mut out, &mut bytes, 100, shown(60)).is_err()); + assert!(out.is_empty()); + } + + #[test] + fn a_shown_budget_can_lower_the_limit_but_not_raise_it() { + let mut d = Decoder::with_threads(1); + assert_eq!(d.shown_budget, MAX_SHOWN_BYTES_PER_CHUNK); + d.set_shown_budget(1 << 20); + assert_eq!(d.shown_budget, 1 << 20); + d.set_shown_budget(u64::MAX); + assert_eq!(d.shown_budget, MAX_SHOWN_BYTES_PER_CHUNK); } #[test] @@ -1333,8 +1360,8 @@ mod shown_limit_tests { // 4K 4:2:0, u16 samples: about 25 MB; 256 of them is far past the limit, a few are fine let one = picture_bytes(3840, 2160, &c); assert_eq!(one, (3840 * 2160 + 2 * 1920 * 1080) * 2); - assert!(shown_bytes_within_limit(4 * one)); - assert!(!shown_bytes_within_limit(MAX_SHOWN_PER_CHUNK * one)); + assert!(shown_bytes_within_limit(4 * one, MAX_SHOWN_BYTES_PER_CHUNK)); + assert!(!shown_bytes_within_limit(MAX_SHOWN_PER_CHUNK * one, MAX_SHOWN_BYTES_PER_CHUNK)); let mono = crate::av1::decode::header::ColorConfig { num_planes: 1, ..Default::default() }; assert_eq!(picture_bytes(10, 5, &mono), 100); assert_eq!(picture_bytes(usize::MAX, 2, &c), usize::MAX);