From 1648ef05f5a3062ec5ce42235e6d79b55f452546 Mon Sep 17 00:00:00 2001 From: el-j Date: Sun, 15 Nov 2026 22:15:58 +0100 Subject: [PATCH 01/15] craft-audio: MPEG-1/2 Layer II (MP2) encoder (mpa-encode) Constant bit rate mono and stereo at 16-48 kHz, written from ISO/IEC 11172-3 and 13818-3. Decoded by our decoder and by ffmpeg as an oracle. Closes #1545. --- crates/audio/Cargo.toml | 7 + crates/audio/README.md | 2 + crates/audio/src/lib.rs | 2 +- crates/audio/src/mp3/mod.rs | 4 +- crates/audio/src/mpa/encoder.rs | 493 +++++++++++++++++++++++ crates/audio/src/mpa/mod.rs | 18 + crates/audio/tests/mp2_encoder_oracle.rs | 228 +++++++++++ 7 files changed, 751 insertions(+), 3 deletions(-) create mode 100644 crates/audio/src/mpa/encoder.rs create mode 100644 crates/audio/tests/mp2_encoder_oracle.rs diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 645246130..3584b4f7d 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -55,6 +55,9 @@ ac3-encode = ["craft-media/bitstream"] eac3-encode = ["craft-media/bitstream"] # MPEG-1/2 Layer III (MP3) encoder (`mp3`). mp3-encode = ["craft-media/bitstream"] +# MPEG-1/2 Layer II (MP2) encoder (`mpa::encoder`). It shares the polyphase analysis filter of the +# MP3 encoder and the tables of the MP1/MP2 decoder. +mpa-encode = ["mpa-decode", "mp3-encode"] # Multi-resolution waveform overviews (`peaks`). peaks = [] # Encode AAC channels in parallel (with `aac-encode`). @@ -88,6 +91,10 @@ required-features = ["decode", "lossless-encode", "peaks"] name = "codecs" required-features = ["decode", "encode"] +[[test]] +name = "mp2_encoder_oracle" +required-features = ["mpa-encode"] + [[test]] name = "qoa_oracle" required-features = ["qoa"] diff --git a/crates/audio/README.md b/crates/audio/README.md index 63251db8d..f9ab17529 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -42,6 +42,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | | `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` | | `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` | +| `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` | | `peaks` | `peaks::Peaks` | none | | `rayon` | parallel AAC encoding (with `aac-encode`) | `rayon` | | `serde` | `Serialize`/`Deserialize` on the shared types | `serde` | @@ -538,6 +539,7 @@ Each codec module's rustdoc lists the coding tools it implements. | Opus (`opus`) | RFC 6716, 8251, 7845 | decoder: SILK, hybrid, CELT, all frame sizes, PLC and FEC, multistream (`Decoder`) and single stream (`StreamDecoder`), 8–48 kHz output; encoder (`Encoder`): SILK, hybrid, CELT, 48 kHz, 20 ms frames, mono or stereo | all 36 RFC 8251 conformance cases; encoder output through ffmpeg's two Opus decoders | | AC-3/E-AC-3 (`ac3`) | decoder: ATSC A/52:2012; encoder/programme API: ETSI TS 102 366 V1.4.1 | single-syncframe and complete-programme decoding; packet encoding through discrete 7.1 (see below) | decoder comparisons and encoder output through ffmpeg, CRC/channel/timing/bit-budget regressions; synthetic quality limitations below | | MP1/MP2 (`mpa`) | ISO/IEC 11172-3, 13818-3 | Layer I and II, MPEG-1/2/2.5, 8–48 kHz; also the Layer II rate/mode pairs the spec disallows (ffmpeg's default mono 384 kbit/s); no free format | ffmpeg-encoded streams, 73–84 dB SNR | +| MP2 encoder (`mpa::encoder`) | ISO/IEC 11172-3 (§2.4, Annex B and C), 13818-3 | Layer II, constant bit rate, mono or stereo (no joint stereo), 32/44.1/48 kHz at the spec's rate/mode pairs and 16/22.05/24 kHz at 8–160 kbit/s; no CRC | our decoder and ffmpeg decode the frames; SNR of 20–37 dB on tone mixes, and the 481-sample filter delay matches | | MP3 decoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, MPEG-1/2/2.5, 8–48 kHz, every bit rate, CBR and VBR; mono, stereo, dual channel, joint stereo (mid/side and intensity); long, short and mixed blocks; bit reservoir; CRC read, not checked; Xing / Info / VBRI and LAME tags; no free format (read through symphonia) | ffmpeg's float decoder: 127–131 dB SNR on LAME streams of every sampling frequency (CBR, VBR, CRC, no reservoir, transients with short blocks) and on this crate's encoder's; intensity stereo and mixed blocks through LAME frames edited to use them (112–131 dB) | | MP3 encoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, constant bit rate: 32–320 kbit/s at 32/44.1/48 kHz, 8–160 kbit/s at 16/22.05/24 kHz; mono, stereo, joint stereo (mid/side); bit reservoir; long blocks only; no Xing/Info tag, VBR, CRC or free format | ffmpeg decodes every Huffman code as intended; full encodes at every sampling frequency checked with ffprobe and by SNR of ffmpeg's decode | | ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder, same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index be0678303..669328592 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -26,7 +26,7 @@ //! - [`peaks`] (feature `peaks`): min/max/RMS pyramid for waveform drawing. //! - Codec modules for packet-level use, each with its own features: [`aac`] (`aac-decode`, //! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`, and -//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`), [`mp3`] +//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`] //! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-encode`: the packet encoder), [`qoa`] //! (`qoa-decode`, `qoa-encode`: whole QOA files). //! diff --git a/crates/audio/src/mp3/mod.rs b/crates/audio/src/mp3/mod.rs index d28607110..e273e903c 100644 --- a/crates/audio/src/mp3/mod.rs +++ b/crates/audio/src/mp3/mod.rs @@ -39,13 +39,13 @@ mod decoder; #[cfg(feature = "mp3-encode")] mod encoder; #[cfg(feature = "mp3-encode")] -mod filterbank; +pub(crate) mod filterbank; #[cfg(feature = "mp3-encode")] mod huffman; mod huffman_tables; #[cfg(feature = "mp3-encode")] mod quantize; -mod tables; +pub(crate) mod tables; #[cfg(feature = "mp3-decode")] pub use decoder::{Decoder, InfoTag}; diff --git a/crates/audio/src/mpa/encoder.rs b/crates/audio/src/mpa/encoder.rs new file mode 100644 index 000000000..000f86fe7 --- /dev/null +++ b/crates/audio/src/mpa/encoder.rs @@ -0,0 +1,493 @@ +//! The Layer II encoder; the module docs are in `mpa/mod.rs`. + +// Index loops follow the specification's pseudo-code (FilmCraft allows this lint workspace-wide). +#![allow(clippy::needless_range_loop)] + +use craft_media::bitstream::BitWriter; + +use super::tables::{self, AllocTable, SUBBANDS}; +use crate::mp3::filterbank::Polyphase; +use crate::mp3::tables::ath_db; + +/// Settings an [`Encoder`] refuses. +#[non_exhaustive] +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum EncodeError { + /// A sample rate outside [`SAMPLE_RATES`]. + #[error("MP2: unsupported sample rate {0} Hz (32, 44.1, 48 kHz, or 16, 22.05, 24 kHz)")] + SampleRate(u32), + /// A bit rate that is not one of [`bitrates`] for the sample rate and channel count. + #[error("MP2: unsupported bit rate {kbps} kbit/s at {rate} Hz with {channels} channel(s)")] + Bitrate { + /// The bit rate asked for, kbit/s. + kbps: u32, + /// The sample rate, Hz. + rate: u32, + /// The channel count. + channels: usize, + }, + /// More than two channels, or none. + #[error("MP2: unsupported channel count {0} (1 or 2)")] + Channels(usize), +} + +/// Result with this module's [`EncodeError`]. +pub type EncodeResult = std::result::Result; + +/// Encoder settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Config { + /// One of [`SAMPLE_RATES`]. + pub sample_rate: u32, + /// 1 or 2. Two channels are coded as stereo (`mode` 00), each with its own allocation. + pub channels: usize, + /// One of [`bitrates`] for the sample rate and channel count, kbit/s. + pub bitrate_kbps: u32, +} + +impl Config { + /// `channels` at `sample_rate`, constant `bitrate_kbps`. + pub fn cbr(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Config { + Config { sample_rate, channels, bitrate_kbps } + } +} + +/// The sample rates the encoder accepts. +pub const SAMPLE_RATES: [u32; 6] = [32_000, 44_100, 48_000, 16_000, 22_050, 24_000]; + +/// Samples by which a standard decoder's output lags the input: the polyphase analysis and +/// synthesis filters. +pub const DELAY: u32 = 481; + +/// Samples per channel in a frame. +pub const FRAME_SAMPLES: usize = 1152; + +/// Bit rates ISO/IEC 11172-3 Table 3-B.2 allows for a single channel at 32 / 44.1 / 48 kHz. +const MPEG1_MONO: [u32; 10] = [32, 48, 56, 64, 80, 96, 112, 128, 160, 192]; +/// Bit rates it allows for two channels. +const MPEG1_STEREO: [u32; 10] = [64, 96, 112, 128, 160, 192, 224, 256, 320, 384]; + +/// Whether `rate` is one of the MPEG-2 lower sampling frequencies; `None` if it is unsupported. +fn is_lsf(rate: u32) -> Option { + match rate { + 32_000 | 44_100 | 48_000 => Some(false), + 16_000 | 22_050 | 24_000 => Some(true), + _ => None, + } +} + +/// The bit rates (kbit/s) a Layer II stream can use at `sample_rate` with `channels` channels: +/// at 32 / 44.1 / 48 kHz the combinations ISO/IEC 11172-3 allows (32-192 for one channel, 64-384 +/// for two), at the lower sampling frequencies 8-160 for either. Empty for an unsupported rate. +pub fn bitrates(sample_rate: u32, channels: usize) -> &'static [u32] { + match is_lsf(sample_rate) { + Some(false) if channels == 1 => &MPEG1_MONO, + Some(false) => &MPEG1_STEREO, + Some(true) => &tables::BITRATES_LSF_L23[1..], + None => &[], + } +} + +/// The highest bit rate at `sample_rate` and `channels` not above `kbps` (the lowest one when +/// `kbps` is below all of them); `None` for an unsupported rate. +pub fn nearest_bitrate(sample_rate: u32, channels: usize, kbps: u32) -> Option { + let rates = bitrates(sample_rate, channels); + rates.iter().rev().find(|&&r| r <= kbps).or(rates.first()).copied() +} + +/// SNR-free noise model: the power of the error of rounding a value in ±1 to one of `steps` +/// levels spaced `2 / steps` apart, is `(2 / steps)² / 12`. +fn quantization_noise(steps: u16) -> f32 { + let d = 2.0 / f32::from(steps); + d * d / 12.0 +} + +/// Index of the scalefactor for a peak of `peak` (Table 3-B.1): the smallest scalefactor that is +/// at least `peak`, i.e. the largest index. +fn scalefactor_index(peak: f32) -> u32 { + if peak.is_nan() || peak <= 0.0 { + return 62; + } + let mut i = (3.0 * (1.0 - f64::from(peak).log2())).floor().clamp(0.0, 62.0) as u32; + while i > 0 && tables::scalefactor(i) < peak { + i -= 1; + } + while i < 62 && tables::scalefactor(i + 1) >= peak { + i += 1; + } + i +} + +/// Which scalefactors of a subband's three parts are sent (`scfsi`, §2.4.1.6) and what they are. +fn share(sf: [u32; 3]) -> (u32, [u32; 3]) { + let near = |a: u32, b: u32| a.abs_diff(b) <= 1; + let [a, b, c] = sf; + if near(a, b) && near(b, c) && near(a, c) { + let m = a.min(b).min(c); + (2, [m, m, m]) + } else if near(a, b) { + let m = a.min(b); + (1, [m, m, c]) + } else if near(b, c) { + let m = b.min(c); + (3, [a, m, m]) + } else { + (0, sf) + } +} + +/// Scalefactors sent for an `scfsi` class. +fn scalefactors_sent(scfsi: u32) -> u64 { + match scfsi { + 0 => 3, + 2 => 1, + _ => 2, + } +} + +/// Bits of the 12 granules of samples in a subband with `steps` quantization steps. +fn sample_bits(steps: u16) -> u64 { + 12 * match tables::grouping(steps) { + Some(bits) => u64::from(bits), + None => 3 * u64::from((u32::from(steps) + 1).trailing_zeros()), + } +} + +/// What the encoder decided for one channel of a frame. +#[derive(Clone)] +struct ChannelPlan { + /// The allocation value (index into the table's row) per subband. + alloc: [usize; SUBBANDS], + /// `scfsi` per subband. + scfsi: [u32; SUBBANDS], + /// The scalefactor index of each part of each subband, after sharing. + sf: [[u32; 3]; SUBBANDS], + /// Mean square of each subband's samples. + energy: [f32; SUBBANDS], +} + +/// A Layer II encoder. Feed planar `f32` samples (full scale ±1) to [`Encoder::encode`]; it +/// returns whole frames as they are completed. [`Encoder::flush`] pads the end with silence and +/// returns the rest. +/// +/// ``` +/// use craft_audio::mpa::encoder::{Config, DELAY, Encoder}; +/// +/// let left: Vec = (0..48_000).map(|i| (i as f32 * 0.05).sin() * 0.5).collect(); +/// let right = left.clone(); +/// let mut enc = Encoder::new(Config::cbr(48_000, 2, 192))?; +/// let mut mp2 = enc.encode(&[&left, &right]); // whole frames as they complete +/// mp2.extend(enc.flush()); // pads with silence to the last input sample +/// assert_eq!(mp2.len() % 576, 0); // 192 kbit/s at 48 kHz: 576 bytes per frame +/// assert_eq!(DELAY, 481); // a decoder's output lags the input by this many samples +/// # Ok::<(), craft_audio::mpa::encoder::EncodeError>(()) +/// ``` +pub struct Encoder { + cfg: Config, + lsf: bool, + sr_index: u32, + br_index: u32, + table: AllocTable, + sblimit: usize, + /// The masking offset floor per subband (power), from the threshold in quiet. + ath: [f32; SUBBANDS], + poly: Vec, + /// Buffered input per channel, and how much of it is consumed. + input: Vec>, + consumed: usize, + /// Remainder accumulator for the padding slot (44.1 / 22.05 kHz). + pad_acc: u64, + samples_in: u64, + frames: u64, +} + +impl Encoder { + /// An encoder for `cfg`, or the setting it cannot carry. + pub fn new(cfg: Config) -> EncodeResult { + let lsf = is_lsf(cfg.sample_rate).ok_or(EncodeError::SampleRate(cfg.sample_rate))?; + if !(1..=2).contains(&cfg.channels) { + return Err(EncodeError::Channels(cfg.channels)); + } + let bad = EncodeError::Bitrate { kbps: cfg.bitrate_kbps, rate: cfg.sample_rate, channels: cfg.channels }; + if !bitrates(cfg.sample_rate, cfg.channels).contains(&cfg.bitrate_kbps) { + return Err(bad); + } + let (rates, bitrate_table): (&[u32; 3], &[u32; 15]) = + if lsf { (&[22_050, 24_000, 16_000], &tables::BITRATES_LSF_L23) } else { (&tables::SAMPLE_RATES, &tables::BITRATES_MPEG1_L2) }; + let sr_index = rates.iter().position(|&r| r == cfg.sample_rate).ok_or(EncodeError::SampleRate(cfg.sample_rate))?; + let br_index = bitrate_table.iter().position(|&b| b == cfg.bitrate_kbps).ok_or(bad)?; + let per_channel = cfg.bitrate_kbps / cfg.channels as u32; + let table = AllocTable::select(lsf, cfg.sample_rate, per_channel); + let sblimit = table.sblimit().min(SUBBANDS); + let mut ath = [0f32; SUBBANDS]; + for (sb, a) in ath.iter_mut().enumerate() { + let centre = (sb as f64 + 0.5) * f64::from(cfg.sample_rate) / 64.0; + // a full-scale sine has a mean square of 1/2 and plays back at about 96 dB SPL + *a = (0.5 * 10f64.powf((ath_db(centre) - 96.0) / 10.0)) as f32; + } + Ok(Encoder { + cfg, + lsf, + sr_index: sr_index as u32, + br_index: br_index as u32, + table, + sblimit, + ath, + poly: vec![Polyphase::new(); cfg.channels], + input: vec![Vec::new(); cfg.channels], + consumed: 0, + pad_acc: 0, + samples_in: 0, + frames: 0, + }) + } + + /// The settings. + pub fn config(&self) -> &Config { + &self.cfg + } + + /// Samples per channel in a frame: 1152. + pub fn frame_samples(&self) -> usize { + FRAME_SAMPLES + } + + /// Samples by which a standard decoder's output lags the input. + pub fn delay(&self) -> u32 { + DELAY + } + + /// Frames written so far. + pub fn frames(&self) -> u64 { + self.frames + } + + /// Encode planar samples (one slice per channel; a missing channel is silence, extra ones + /// are ignored, every channel takes the first channel's length). Returns the completed frames. + pub fn encode(&mut self, planar: &[&[f32]]) -> Vec { + let n = planar.first().map_or(0, |p| p.len()); + for (c, buf) in self.input.iter_mut().enumerate() { + let src = planar.get(c).copied().unwrap_or(&[]); + buf.extend((0..n).map(|i| src.get(i).copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-4.0, 4.0))); + } + self.samples_in = self.samples_in.saturating_add(n as u64); + let mut out = Vec::new(); + self.drain(&mut out); + out + } + + /// Encode the buffered rest padded with silence, plus enough silence that a decoder outputs + /// every input sample, and return the remaining frames. + pub fn flush(&mut self) -> Vec { + let fs = FRAME_SAMPLES as u64; + let needed = if self.samples_in == 0 { self.frames } else { self.samples_in.saturating_add(u64::from(DELAY)).div_ceil(fs) }; + let have = self.input.first().map_or(0, |b| b.len().saturating_sub(self.consumed)); + let want = (needed.saturating_sub(self.frames) as usize).saturating_mul(FRAME_SAMPLES); + if want > have { + for buf in &mut self.input { + buf.resize(self.consumed + want, 0.0); + } + } + let mut out = Vec::new(); + self.drain(&mut out); + self.input.iter_mut().for_each(Vec::clear); + self.consumed = 0; + out + } + + /// Encode every whole frame of buffered input. + fn drain(&mut self, out: &mut Vec) { + while self.input.first().is_some_and(|b| b.len() - self.consumed >= FRAME_SAMPLES) { + let mut sub = vec![[[0f32; SUBBANDS]; 36]; self.cfg.channels]; + for (ch, slots) in sub.iter_mut().enumerate() { + let (Some(buf), Some(poly)) = (self.input.get(ch), self.poly.get_mut(ch)) else { continue }; + let frame = buf.get(self.consumed..self.consumed + FRAME_SAMPLES).unwrap_or(&[]); + for (slot, chunk) in slots.iter_mut().zip(frame.as_chunks::<32>().0) { + poly.filter(chunk, slot); + } + } + self.consumed += FRAME_SAMPLES; + self.write_frame(&sub, out); + self.frames += 1; + } + // keep the buffer small + if self.consumed >= 1 << 16 { + for buf in &mut self.input { + buf.drain(..self.consumed); + } + self.consumed = 0; + } + } + + /// The scalefactors and energies of a channel's 36 time slots. + fn analyse(&self, slots: &[[f32; SUBBANDS]; 36]) -> ChannelPlan { + let mut plan = ChannelPlan { alloc: [0; SUBBANDS], scfsi: [0; SUBBANDS], sf: [[62; 3]; SUBBANDS], energy: [0.0; SUBBANDS] }; + for sb in 0..self.sblimit { + let mut sf = [62u32; 3]; + for (part, s) in sf.iter_mut().enumerate() { + let peak = slots[12 * part..12 * part + 12].iter().map(|slot| slot[sb].abs()).fold(0f32, f32::max); + *s = scalefactor_index(peak); + } + (plan.scfsi[sb], plan.sf[sb]) = share(sf); + plan.energy[sb] = slots.iter().map(|slot| slot[sb] * slot[sb]).sum::() / 36.0; + } + plan + } + + /// Choose the allocation of every subband of every channel with the bits the frame has. + fn allocate(&self, plans: &mut [ChannelPlan], mut bits_left: i64) { + let nch = plans.len(); + // power the quantization noise of each subband may have before it is audible: a spread + // of the band energies, never below the threshold in quiet + let mut mask = vec![[0f32; SUBBANDS]; nch]; + for (m, plan) in mask.iter_mut().zip(plans.iter()) { + for sb in 0..self.sblimit { + let mut level = self.ath[sb]; + for j in 0..self.sblimit { + let atten_db = 14.0 + 20.0 * sb.abs_diff(j) as f32; + level = level.max(plan.energy[j] * 10f32.powf(-atten_db / 10.0)); + } + m[sb] = level; + } + } + // the fixed cost: every subband's allocation field + for sb in 0..self.sblimit { + bits_left -= (nch * self.table.row(sb).len().trailing_zeros() as usize) as i64; + } + // the noise a subband has with allocation `a`: dropped, or the mean over its parts + let noise = |plan: &ChannelPlan, sb: usize, a: usize| -> f32 { + let row = self.table.row(sb); + let steps = row.get(a).copied().unwrap_or(0); + if steps == 0 { + return plan.energy[sb]; + } + let mean_sf2 = plan.sf[sb].iter().map(|&i| tables::scalefactor(i).powi(2)).sum::() / 3.0; + (quantization_noise(steps) * mean_sf2).min(plan.energy[sb]) + }; + let cost = |plan: &ChannelPlan, sb: usize, a: usize| -> i64 { + let row = self.table.row(sb); + let step = |a: usize| row.get(a).copied().unwrap_or(0); + let (from, to) = (step(a), step(a + 1)); + let mut bits = sample_bits(to) as i64 - if from == 0 { 0 } else { sample_bits(from) as i64 }; + if from == 0 { + bits += 2 + 6 * scalefactors_sent(plan.scfsi[sb]) as i64; + } + bits + }; + let mut blocked = vec![[false; SUBBANDS]; nch]; + loop { + // the subband whose noise is furthest above its mask + let mut best: Option<(usize, usize, f32)> = None; + for (ch, plan) in plans.iter().enumerate() { + for sb in 0..self.sblimit { + let a = plan.alloc[sb]; + if a + 1 >= self.table.row(sb).len() || blocked[ch][sb] || plan.energy[sb] <= 0.0 { + continue; + } + let ratio = noise(plan, sb, a) / mask[ch][sb].max(1e-20); + if ratio > 1e-3 && best.is_none_or(|(_, _, r)| ratio > r) { + best = Some((ch, sb, ratio)); + } + } + } + let Some((ch, sb, _)) = best else { break }; + let plan = &mut plans[ch]; + let c = cost(plan, sb, plan.alloc[sb]); + if c <= bits_left { + bits_left -= c; + plan.alloc[sb] += 1; + } else { + blocked[ch][sb] = true; + } + } + } + + fn write_frame(&mut self, sub: &[[[f32; SUBBANDS]; 36]], out: &mut Vec) { + let nch = self.cfg.channels; + // frame length: 144 bytes per kbit/s over the sampling rate, plus a slot when the + // remainder has added up to one + let rate = u64::from(self.cfg.sample_rate); + let exact = 144 * u64::from(self.cfg.bitrate_kbps) * 1000; + self.pad_acc += exact % rate; + let pad = self.pad_acc >= rate; + if pad { + self.pad_acc -= rate; + } + let frame_bytes = (exact / rate) as usize + usize::from(pad); + + let mut plans: Vec = sub.iter().map(|s| self.analyse(s)).collect(); + self.allocate(&mut plans, frame_bytes as i64 * 8 - 32); + + let mut w = BitWriter::new(); + w.write_bits(0xFFF, 12); + w.write_bits(u32::from(!self.lsf), 1); + w.write_bits(0b10, 2); // Layer II + w.write_bits(1, 1); // no CRC + w.write_bits(self.br_index, 4); + w.write_bits(self.sr_index, 2); + w.write_bits(u32::from(pad), 1); + w.write_bits(0, 1); // private + w.write_bits(if nch == 1 { 3 } else { 0 }, 2); // mono or stereo + w.write_bits(0, 2); // mode extension + w.write_bits(0, 1); // copyright + w.write_bits(1, 1); // original + w.write_bits(0, 2); // emphasis + for sb in 0..self.sblimit { + let nbal = self.table.row(sb).len().trailing_zeros(); + for plan in &plans { + w.write_bits(plan.alloc[sb] as u32, nbal); + } + } + for sb in 0..self.sblimit { + for plan in &plans { + if plan.alloc[sb] != 0 { + w.write_bits(plan.scfsi[sb], 2); + } + } + } + for sb in 0..self.sblimit { + for plan in &plans { + if plan.alloc[sb] == 0 { + continue; + } + let [a, b, c] = plan.sf[sb]; + match plan.scfsi[sb] { + 0 => [a, b, c].iter().for_each(|&s| w.write_bits(s, 6)), + 1 => [a, c].iter().for_each(|&s| w.write_bits(s, 6)), + 2 => w.write_bits(a, 6), + _ => [a, b].iter().for_each(|&s| w.write_bits(s, 6)), + } + } + } + for gr in 0..12 { + let part = gr / 4; + for sb in 0..self.sblimit { + for (ch, plan) in plans.iter().enumerate() { + let a = plan.alloc[sb]; + let steps = self.table.row(sb).get(a).copied().unwrap_or(0); + if steps == 0 { + continue; + } + let scale = tables::scalefactor(plan.sf[sb][part]); + let n = u32::from(steps); + let code = |k: usize| -> u32 { + let x = (sub[ch][3 * gr + k][sb] / scale).clamp(-1.0, 1.0); + // the reconstruction points are (2v + 1 - n) / n + ((x * n as f32 + n as f32 - 1.0) / 2.0).round().clamp(0.0, (n - 1) as f32) as u32 + }; + let v = [code(0), code(1), code(2)]; + match tables::grouping(steps) { + Some(bits) => w.write_bits(v[0] + n * v[1] + n * n * v[2], bits), + None => { + let nb = (n + 1).trailing_zeros(); + v.iter().for_each(|&x| w.write_bits(x, nb)); + } + } + } + } + } + let mut bytes = w.finish(); + bytes.resize(frame_bytes, 0); + out.extend_from_slice(&bytes); + } +} diff --git a/crates/audio/src/mpa/mod.rs b/crates/audio/src/mpa/mod.rs index f1d5b6378..3db204176 100644 --- a/crates/audio/src/mpa/mod.rs +++ b/crates/audio/src/mpa/mod.rs @@ -13,12 +13,30 @@ //! format (bit rate index 0, whose frame length is only known from the next sync word) and the //! CRC (read, not checked, like most decoders). //! +//! # Encoder (feature `mpa-encode`) +//! +//! [`encoder::Encoder`] writes Layer II streams, written from ISO/IEC 11172-3 (§2.4.1.6 bit stream +//! syntax, Annex B tables, Annex C encoding process) and ISO/IEC 13818-3. +//! +//! - Constant bit rate: 32-192 kbit/s mono and 64-384 kbit/s stereo at 32 / 44.1 / 48 kHz (the +//! rate and mode pairs of Table 3-B.2), 8-160 kbit/s at 16 / 22.05 / 24 kHz. Mono, or stereo with +//! each channel allocated on its own (no joint stereo, no dual channel). +//! - The polyphase analysis filterbank of Annex C.1.3 (shared with the Layer III encoder), a +//! scalefactor per 12 samples with the `scfsi` sharing of §2.4.1.6, and a bit allocation chosen by +//! spending the frame's bits where the quantization noise is furthest above a simple masking +//! estimate (the band energies spread over the neighbouring subbands, never below the threshold +//! in quiet). It is not one of the psychoacoustic models of Annex D. +//! - Output: frames only, no CRC, no ID3 tag. Frames written one after another are a playable +//! `.mp2` file. A decoder's output lags the input by [`encoder::DELAY`] samples. +//! //! From FilmCraft's `filmcraft-mpa` (storytold/filmcraft@8fda2f2). Public items keep their names, so //! FilmCraft can re-export this module. // Index loops follow the specification's pseudo-code (FilmCraft allows this lint workspace-wide). #![allow(clippy::needless_range_loop)] +#[cfg(feature = "mpa-encode")] +pub mod encoder; pub(crate) mod tables; use craft_media::bitstream::BitReader; diff --git a/crates/audio/tests/mp2_encoder_oracle.rs b/crates/audio/tests/mp2_encoder_oracle.rs new file mode 100644 index 000000000..ca4d15bd3 --- /dev/null +++ b/crates/audio/tests/mp2_encoder_oracle.rs @@ -0,0 +1,228 @@ +//! The Layer II encoder (feature `mpa-encode`): every frame has the header and size its settings +//! give and decodes with our decoder; ffmpeg as an external decoder (skipped without ffmpeg, a +//! failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`) decodes the stream without a complaint, to the +//! right length, and its output, aligned by [`DELAY`], matches the input within a signal-to-noise +//! ratio per bit rate. The bounds sit well under what the encoder reaches today; white noise loses +//! the subbands above the table's last one (a sixth of it at 48 kHz), so its bound is low. + +use std::path::Path; +use std::process::{Command, Stdio}; + +use craft_audio::mpa::encoder::{Config, DELAY, EncodeError, Encoder, bitrates, nearest_bitrate}; +use craft_audio::mpa::{Decoder, Mode, Version, parse_header}; + +fn chords(rate: u32, n: usize, detune: f32) -> Vec { + let f = [220.0, 277.18, 329.63, 440.0, 1318.5, 3520.0]; + let a = [0.2, 0.15, 0.12, 0.1, 0.05, 0.02]; + (0..n) + .map(|i| { + let t = i as f32 / rate as f32; + f.iter().zip(a).map(|(f, a)| a * (2.0 * std::f32::consts::PI * f * (1.0 + detune) * t).sin()).sum::() + }) + .collect() +} + +fn noise(n: usize, amp: f32, seed: u64) -> Vec { + let mut s = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + (0..n) + .map(|_| { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + ((s >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * amp + }) + .collect() +} + +fn encode(cfg: Config, input: &[Vec], chunk: usize) -> Vec { + let mut enc = Encoder::new(cfg).expect("encoder"); + let mut out = Vec::new(); + let n = input[0].len(); + let mut pos = 0; + while pos < n { + let end = (pos + chunk).min(n); + let planes: Vec<&[f32]> = input.iter().map(|c| &c[pos..end]).collect(); + out.extend(enc.encode(&planes)); + pos = end; + } + out.extend(enc.flush()); + out +} + +/// Split a stream into frames by its headers; every header must be one the settings give. +fn frames<'a>(bytes: &'a [u8], cfg: &Config) -> Vec<&'a [u8]> { + let mut out = Vec::new(); + let mut pos = 0; + while pos < bytes.len() { + let h = parse_header(&bytes[pos..]).unwrap_or_else(|e| panic!("frame {} at byte {pos}: {e}", out.len())); + assert_eq!(h.layer, 2); + assert_eq!(h.version, if cfg.sample_rate >= 32_000 { Version::Mpeg1 } else { Version::Mpeg2 }); + assert_eq!((h.sample_rate, h.bitrate_kbps), (cfg.sample_rate, cfg.bitrate_kbps)); + assert_eq!(h.mode, if cfg.channels == 1 { Mode::Mono } else { Mode::Stereo }); + assert!(!h.crc); + out.push(&bytes[pos..pos + h.frame_bytes]); + pos += h.frame_bytes; + } + assert_eq!(pos, bytes.len(), "the stream ends on a frame boundary"); + out +} + +fn snr(input: &[f32], dec: &[f32]) -> f64 { + let (mut s, mut n) = (0f64, 0f64); + for (a, b) in input.iter().zip(dec) { + s += f64::from(*a) * f64::from(*a); + n += f64::from(a - b) * f64::from(a - b); + } + 10.0 * (s / n.max(1e-30)).log10() +} + +struct Case { + name: &'static str, + rate: u32, + channels: usize, + kbps: u32, + signal: fn(u32, usize, usize) -> Vec, + min_snr: f64, +} + +fn sig_chords(rate: u32, n: usize, c: usize) -> Vec { + chords(rate, n, 0.003 * c as f32) +} +fn sig_noise(_rate: u32, n: usize, c: usize) -> Vec { + noise(n, 0.25, 11 + c as u64) +} + +const CASES: &[Case] = &[ + Case { name: "chords", rate: 48_000, channels: 2, kbps: 192, signal: sig_chords, min_snr: 30.0 }, + Case { name: "chords", rate: 44_100, channels: 2, kbps: 128, signal: sig_chords, min_snr: 25.0 }, + Case { name: "chords", rate: 44_100, channels: 1, kbps: 64, signal: sig_chords, min_snr: 25.0 }, + Case { name: "chords", rate: 32_000, channels: 2, kbps: 96, signal: sig_chords, min_snr: 20.0 }, + Case { name: "chords", rate: 22_050, channels: 2, kbps: 64, signal: sig_chords, min_snr: 20.0 }, + Case { name: "chords", rate: 24_000, channels: 1, kbps: 32, signal: sig_chords, min_snr: 18.0 }, + Case { name: "noise", rate: 48_000, channels: 2, kbps: 384, signal: sig_noise, min_snr: 4.0 }, + Case { name: "noise", rate: 44_100, channels: 2, kbps: 256, signal: sig_noise, min_snr: 4.0 }, +]; + +fn inputs(c: &Case, n: usize) -> Vec> { + (0..c.channels).map(|ch| (c.signal)(c.rate, n, ch)).collect() +} + +#[test] +fn frames_have_the_size_and_header_their_settings_give_and_decode_with_our_decoder() { + for c in CASES { + let n = c.rate as usize * 2 + 777; + let cfg = Config::cbr(c.rate, c.channels, c.kbps); + let bytes = encode(cfg, &inputs(c, n), 1000); + let frames = frames(&bytes, &cfg); + // every input sample and the filter delay fit in the frames, and no more than one frame more + let covered = frames.len() * 1152; + assert!(covered >= n + DELAY as usize && covered < n + DELAY as usize + 1152, "{}: {} frames for {n} samples", c.name, frames.len()); + // 144 kbit/s-slots per frame, the padding slots adding up to the exact rate + let nominal = f64::from(c.kbps) * 125.0 * covered as f64 / f64::from(c.rate); + assert!((bytes.len() as f64 - nominal).abs() < 1.0 + f64::from(c.rate) / 1000.0, "{}: {} bytes against {nominal}", c.name, bytes.len()); + let mut dec = Decoder::new(); + let mut out = vec![Vec::new(); c.channels]; + for f in frames { + let frame = dec.decode(f).unwrap_or_else(|e| panic!("{}: {e}", c.name)); + for (o, ch) in out.iter_mut().zip(frame.channels) { + o.extend(ch); + } + } + let d = DELAY as usize; + for (ch, input) in inputs(c, n).iter().enumerate() { + let s = snr(input, &out[ch][d..d + n]); + println!("{:<7} {:>5} Hz {}ch {:>3} kbps: SNR {s:.2} dB (our decoder)", c.name, c.rate, c.channels, c.kbps); + assert!(s >= c.min_snr, "{} {} Hz {}ch {} kbps: SNR {s:.2} dB under {}", c.name, c.rate, c.channels, c.kbps, c.min_snr); + } + } +} + +#[test] +fn the_stream_does_not_depend_on_how_the_input_is_chunked() { + let c = &CASES[1]; + let n = 44_100 + 333; + let cfg = Config::cbr(c.rate, c.channels, c.kbps); + let input = inputs(c, n); + let whole = encode(cfg, &input, n); + for chunk in [1, 7, 1152, 5000] { + assert_eq!(encode(cfg, &input, chunk), whole, "chunk {chunk}"); + } +} + +#[test] +fn silence_and_nothing_encode_to_valid_frames() { + let cfg = Config::cbr(48_000, 2, 128); + let silent = vec![vec![0f32; 5000]; 2]; + let bytes = encode(cfg, &silent, 5000); + let fs = frames(&bytes, &cfg); + let mut dec = Decoder::new(); + for f in fs { + let frame = dec.decode(f).expect("decode"); + assert!(frame.channels.iter().flatten().all(|v| v.abs() < 1e-6)); + } + assert!(Encoder::new(cfg).expect("encoder").flush().is_empty(), "no input, no frames"); +} + +#[test] +fn hostile_samples_are_tamed() { + let cfg = Config::cbr(44_100, 2, 192); + let mut x = vec![0f32; 4000]; + for (i, v) in x.iter_mut().enumerate() { + *v = [f32::NAN, f32::INFINITY, -f32::INFINITY, 1e30, -1e30, 3.0, 0.5][i % 7]; + } + let bytes = encode(cfg, &[x.clone(), x], 4000); + let mut dec = Decoder::new(); + for f in frames(&bytes, &cfg) { + dec.decode(f).expect("decode"); + } +} + +#[test] +fn settings_that_cannot_be_carried_are_refused() { + assert_eq!(Encoder::new(Config::cbr(44_000, 2, 128)).err(), Some(EncodeError::SampleRate(44_000))); + assert_eq!(Encoder::new(Config::cbr(44_100, 3, 128)).err(), Some(EncodeError::Channels(3))); + assert_eq!(Encoder::new(Config::cbr(44_100, 0, 128)).err(), Some(EncodeError::Channels(0))); + // ISO/IEC 11172-3 allows neither 32 kbit/s for two channels nor 224 for one + assert!(matches!(Encoder::new(Config::cbr(44_100, 2, 32)), Err(EncodeError::Bitrate { .. }))); + assert!(matches!(Encoder::new(Config::cbr(44_100, 1, 224)), Err(EncodeError::Bitrate { .. }))); + assert!(matches!(Encoder::new(Config::cbr(44_100, 2, 130)), Err(EncodeError::Bitrate { .. }))); + assert_eq!(bitrates(44_100, 1).len(), 10); + assert_eq!(bitrates(22_050, 2).first(), Some(&8)); + assert!(bitrates(8_000, 2).is_empty()); + assert_eq!(nearest_bitrate(44_100, 2, 100), Some(96)); + assert_eq!(nearest_bitrate(44_100, 2, 1), Some(64)); + assert_eq!(nearest_bitrate(8_000, 2, 100), None); +} + +fn ffmpeg_decode(ff: &Path, path: &Path, channels: usize) -> (Vec>, String) { + let out = Command::new(ff) + .args(["-v", "error", "-nostdin", "-i"]) + .arg(path) + .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .stdin(Stdio::null()) + .output() + .expect("run ffmpeg"); + let samples: Vec = out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(); + let planar = (0..channels).map(|c| samples.iter().skip(c).step_by(channels).copied().collect()).collect(); + (planar, String::from_utf8_lossy(&out.stderr).into_owned()) +} + +#[test] +fn ffmpeg_decodes_our_streams_to_the_input() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("mp2enc"); + for c in CASES { + let n = c.rate as usize * 2 + 777; + let input = inputs(c, n); + let bytes = encode(Config::cbr(c.rate, c.channels, c.kbps), &input, 1000); + let path = dir.join(format!("{}_{}_{}ch_{}k.mp2", c.name, c.rate, c.channels, c.kbps)); + std::fs::write(&path, &bytes).expect("write"); + let (dec, err) = ffmpeg_decode(&ff, &path, c.channels); + assert!(err.trim().is_empty(), "{}: ffmpeg reported: {err}", path.display()); + let d = DELAY as usize; + assert!(dec[0].len() >= n + d, "{}: decoded {} samples, need {}", c.name, dec[0].len(), n + d); + let s = (0..c.channels).map(|ch| snr(&input[ch], &dec[ch][d..d + n])).sum::() / c.channels as f64; + println!("{:<7} {:>5} Hz {}ch {:>3} kbps: SNR {s:.2} dB (ffmpeg)", c.name, c.rate, c.channels, c.kbps); + assert!(s >= c.min_snr, "{} {} Hz {}ch {} kbps: SNR {s:.2} dB under {}", c.name, c.rate, c.channels, c.kbps, c.min_snr); + } +} From 6502ca440e6c57875a9727e5995e95cc8eccf08d Mon Sep 17 00:00:00 2001 From: el-j Date: Mon, 16 Nov 2026 02:14:12 +0100 Subject: [PATCH 02/15] craft-audio: ITU-T G.722 wideband speech codec (#1530) --- crates/audio/Cargo.toml | 6 + crates/audio/src/g722.rs | 682 ++++++++++++++++++++++++++++++ crates/audio/src/lib.rs | 2 + crates/audio/tests/g722_oracle.rs | 201 +++++++++ 4 files changed, 891 insertions(+) create mode 100644 crates/audio/src/g722.rs create mode 100644 crates/audio/tests/g722_oracle.rs diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index fe28cec3f..0021aae87 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -45,6 +45,8 @@ opus-decode = [] qoa = ["qoa-decode", "qoa-encode"] qoa-decode = [] qoa-encode = [] +# ITU-T G.722 wideband sub-band ADPCM speech codec (64 kbit/s). +g722 = [] opus-encode = [] ac3-decode = ["craft-media/bitstream"] mpa-decode = ["craft-media/bitstream"] @@ -96,6 +98,10 @@ required-features = ["flac-decode", "flac-encode"] name = "qoa_oracle" required-features = ["qoa"] +[[test]] +name = "g722_oracle" +required-features = ["g722"] + [[example]] name = "info" required-features = ["decode"] diff --git a/crates/audio/src/g722.rs b/crates/audio/src/g722.rs new file mode 100644 index 000000000..ea5766c83 --- /dev/null +++ b/crates/audio/src/g722.rs @@ -0,0 +1,682 @@ +//! ITU-T Recommendation G.722 wideband audio coding (64 kbit/s). +//! +//! Pure safe Rust clean-room implementation of the G.722 sub-band adaptive differential +//! pulse code modulation (SB-ADPCM) speech and audio codec. +//! +//! Input audio is 16 kHz 16-bit linear PCM. An analysis Quadrature Mirror Filter (QMF) splits +//! the 16 kHz audio into a lower sub-band (0–4 kHz) and a higher sub-band (4–8 kHz), each +//! sampled at 8 kHz. The lower sub-band is encoded at 48 kbit/s (6 bits/sample) and the higher +//! sub-band at 16 kbit/s (2 bits/sample), multiplexed into an 8-bit octet per 8 kHz cycle +//! (64 kbit/s total stream rate). +//! +//! On decoding, inverse adaptive quantizers reconstruct each sub-band signal, and a synthesis +//! QMF interpolates and combines them back to 16 kHz 16-bit linear PCM. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +/// Maximum allowed channels for multi-channel processing. +pub const MAX_CHANNELS: usize = 8; + +/// Maximum input byte buffer bound to prevent memory exhaustion on hostile inputs (64 MiB). +pub const MAX_INPUT_BYTES: usize = 64 * 1024 * 1024; + +/// Maximum input sample count bound (128 million samples). +pub const MAX_SAMPLES: usize = 128 * 1024 * 1024; + +/// Error conditions encountered during G.722 encoding or decoding. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum Error { + /// The channel count is invalid. + #[error("invalid channel count: {0} (must be 1..={MAX_CHANNELS})")] + InvalidChannels(usize), + + /// The input size exceeds safety bounds. + #[error("input exceeds maximum size bound")] + InputTooLarge, + + /// Encoding requires an even number of samples per channel (16 kHz sample pairs). + #[error("odd number of samples: {0} (G.722 encodes pairs of 16 kHz samples)")] + OddSampleCount(usize), + + /// System allocation failed when reserving buffer memory. + #[error("allocation failed")] + AllocationFailed, +} + +// --------------------------------------------------------------------------- +// Specification Tables from ITU-T Recommendation G.722 +// --------------------------------------------------------------------------- + +/// 24-tap QMF filter coefficients scaled by 2^13 (Table 11/G.722). +const H: [i16; 24] = [3, -11, -11, 53, 12, -156, 32, 362, -210, -805, 951, 3876, 3876, 951, -805, -210, 362, 32, -156, 12, 53, -11, -11, 3]; + +/// Lower sub-band 60-level inverse quantizer reconstruction table QQ6 (Table 14/G.722). +const QQ6: [i16; 31] = [ + 0, 17, 54, 91, 130, 170, 211, 254, 300, 347, 396, 447, 501, 558, 618, 682, 750, 822, 899, 982, 1072, 1170, 1279, 1399, 1535, 1689, 1873, 2088, + 2376, 2738, 3101, +]; + +/// Lower sub-band quantizer decision levels Q6 (Table 14/G.722). +const Q6: [i16; 30] = [ + 0, 35, 72, 110, 150, 190, 233, 276, 323, 370, 422, 473, 530, 587, 650, 714, 786, 858, 940, 1023, 1121, 1219, 1339, 1458, 1612, 1765, 1980, 2195, + 2557, 2919, +]; + +/// Lower sub-band 15-level inverse quantizer reconstruction table QQ4 (Table 14/G.722). +const QQ4: [i16; 8] = [0, 150, 323, 530, 786, 1121, 1612, 2557]; + +/// Lower sub-band logarithmic scale factor multipliers WL (Table 14/G.722). +const WL: [i16; 8] = [-60, -30, 58, 172, 334, 538, 1198, 3042]; + +/// Higher sub-band 4-level inverse quantizer reconstruction table QQ2 (Table 14/G.722). +const QQ2: [i16; 3] = [0, 202, 926]; + +/// Higher sub-band logarithmic scale factor multipliers WH (Table 14/G.722). +const WH: [i16; 3] = [0, -214, 798]; + +/// 32-entry inverse logarithmic scale table ILB (Table 15/G.722). +const ILB: [i32; 32] = [ + 2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383, 2435, 2489, 2543, 2599, 2656, 2714, 2774, 2834, 2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371, + 3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008, +]; + +/// Table 17/G.722: 4-bit codeword (RIL = IL >> 2) to (SIL, IL4). +const IL4_MAP: [(i16, usize); 16] = + [(0, 0), (-1, 7), (-1, 6), (-1, 5), (-1, 4), (-1, 3), (-1, 2), (-1, 1), (0, 7), (0, 6), (0, 5), (0, 4), (0, 3), (0, 2), (0, 1), (0, 0)]; + +/// Table 21/G.722: 2-bit codeword IH to (SIH, IH2). +const IH2_MAP: [(i16, usize); 4] = [(-1, 2), (-1, 1), (0, 2), (0, 1)]; + +#[inline] +fn mult(a: i16, b: i16) -> i16 { + (((a as i32) * (b as i32)) >> 15) as i16 +} + +#[inline] +fn scalel(nbpl: i32) -> i32 { + let wd1 = ((nbpl >> 6) & 31) as usize; + let wd2 = nbpl >> 11; + let shift = 8 - wd2; + let wd3 = if shift >= 0 { ILB[wd1] >> shift } else { ILB[wd1] << (-shift) }; + wd3 << 2 +} + +#[inline] +fn scaleh(nbph: i32) -> i32 { + let wd1 = ((nbph >> 6) & 31) as usize; + let wd2 = nbph >> 11; + let shift = 10 - wd2; + let wd3 = if shift >= 0 { ILB[wd1] >> shift } else { ILB[wd1] << (-shift) }; + wd3 << 2 +} + +// --------------------------------------------------------------------------- +// Sub-band ADPCM State (Pole/Zero Predictors & Adaptations) +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone)] +struct BandState { + s: i16, + sp: i16, + sz: i16, + d: [i16; 7], + r: [i16; 3], + p: [i16; 3], + a: [i16; 3], + b: [i16; 7], + nb: i32, + det: i32, +} + +impl BandState { + fn new(is_lower: bool) -> Self { + Self { s: 0, sp: 0, sz: 0, d: [0; 7], r: [0; 3], p: [0; 3], a: [0; 3], b: [0; 7], nb: 0, det: if is_lower { 32 } else { 8 } } + } + + fn reset(&mut self, is_lower: bool) { + self.s = 0; + self.sp = 0; + self.sz = 0; + self.d = [0; 7]; + self.r = [0; 3]; + self.p = [0; 3]; + self.a = [0; 3]; + self.b = [0; 7]; + self.nb = 0; + self.det = if is_lower { 32 } else { 8 }; + } + + fn update_predictor(&mut self, d: i16, p_sig: i16, r_sig: i16) { + // UPZERO: update 6th order zero predictor coefficients + let wd1: i16 = if d != 0 { 128 } else { 0 }; + let sg0: i16 = if d < 0 { -1 } else { 0 }; + for i in 1..=6 { + let sgi = if self.d[i] < 0 { -1 } else { 0 }; + let wd2 = if sg0 == sgi { wd1 } else { -wd1 }; + let wd3 = mult(self.b[i], 32640); + self.b[i] = wd2.saturating_add(wd3); + } + + // UPPOL2: update 2nd pole coefficient + let sg0 = if p_sig < 0 { -1 } else { 0 }; + let sg1 = if self.p[1] < 0 { -1 } else { 0 }; + let sg2 = if self.p[2] < 0 { -1 } else { 0 }; + let wd1 = self.a[1].saturating_add(self.a[1]).saturating_add(self.a[1].saturating_add(self.a[1])); + let wd2 = if sg0 == sg1 { -wd1 } else { wd1 } >> 7; + let wd3: i16 = if sg0 == sg2 { 128 } else { -128 }; + let wd4 = wd2.saturating_add(wd3); + let wd5 = mult(self.a[2], 32512); + let apl2 = wd4.saturating_add(wd5).clamp(-12288, 12288); + + // UPPOL1: update 1st pole coefficient + let wd1: i16 = if sg0 == sg1 { 192 } else { -192 }; + let wd2 = mult(self.a[1], 32640); + let apl1 = wd1.saturating_add(wd2); + let wd3 = 15360 - apl2; + let apl1 = apl1.clamp(-wd3, wd3); + + self.a[1] = apl1; + self.a[2] = apl2; + + // Shift history delay lines + for i in (2..=6).rev() { + self.d[i] = self.d[i - 1]; + } + self.d[1] = d; + + self.p[2] = self.p[1]; + self.p[1] = p_sig; + + self.r[2] = self.r[1]; + self.r[1] = r_sig; + + // FILTEZ: compute zero section output + let mut sz: i16 = 0; + for i in (1..=6).rev() { + let part = mult(self.b[i], self.d[i].saturating_add(self.d[i])); + sz = sz.saturating_add(part); + } + self.sz = sz; + + // FILTEP: compute pole section output + let sp1 = mult(self.a[1], self.r[1].saturating_add(self.r[1])); + let sp2 = mult(self.a[2], self.r[2].saturating_add(self.r[2])); + self.sp = sp1.saturating_add(sp2); + + // PREDIC: compute full predictor output value + self.s = self.sp.saturating_add(self.sz); + } +} + +// --------------------------------------------------------------------------- +// Quadrature Mirror Filters (QMF) +// --------------------------------------------------------------------------- + +/// Analysis QMF (transmit filter bank): splits pairs of 16 kHz samples into lower and higher sub-bands. +#[derive(Debug, Clone, Default)] +pub struct QmfTx { + x: [i16; 24], +} + +impl QmfTx { + /// Create a new analysis QMF filter. + pub fn new() -> Self { + Self { x: [0; 24] } + } + + /// Reset filter history. + pub fn reset(&mut self) { + self.x = [0; 24]; + } + + /// Process a pair of 16 kHz input samples `(s0, s1)` into `(xl, xh)`. + pub fn filter(&mut self, s0: i16, s1: i16) -> (i16, i16) { + for i in (2..24).rev() { + self.x[i] = self.x[i - 2]; + } + self.x[0] = s1 >> 1; + self.x[1] = s0 >> 1; + + let mut xa: i32 = 0; + let mut xb: i32 = 0; + for i in 0..12 { + xa = xa.saturating_add((self.x[2 * i] as i32) * (H[2 * i] as i32)); + xb = xb.saturating_add((self.x[2 * i + 1] as i32) * (H[2 * i + 1] as i32)); + } + + let xl = ((xa.saturating_add(xb)) >> 13).clamp(-16384, 16383) as i16; + let xh = ((xa.saturating_sub(xb)) >> 13).clamp(-16384, 16383) as i16; + (xl, xh) + } +} + +/// Synthesis QMF (receive filter bank): synthesizes lower and higher sub-band signals into 16 kHz output. +#[derive(Debug, Clone, Default)] +pub struct QmfRx { + xd: [i16; 12], + xs: [i16; 12], +} + +impl QmfRx { + /// Create a new synthesis QMF filter. + pub fn new() -> Self { + Self { xd: [0; 12], xs: [0; 12] } + } + + /// Reset filter history. + pub fn reset(&mut self) { + self.xd = [0; 12]; + self.xs = [0; 12]; + } + + /// Reconstruct a pair of 16 kHz output samples from sub-band samples `(rl, rh)`. + pub fn filter(&mut self, rl: i16, rh: i16) -> (i16, i16) { + let xd_curr = rl.saturating_sub(rh); + let xs_curr = rl.saturating_add(rh); + + for i in (1..12).rev() { + self.xd[i] = self.xd[i - 1]; + self.xs[i] = self.xs[i - 1]; + } + self.xd[0] = xd_curr; + self.xs[0] = xs_curr; + + let mut wd_c: i32 = 0; + let mut wd_d: i32 = 0; + for i in 0..12 { + wd_c = wd_c.saturating_add((self.xd[i] as i32) * (H[2 * i] as i32)); + wd_d = wd_d.saturating_add((self.xs[i] as i32) * (H[2 * i + 1] as i32)); + } + + let xout1 = (wd_c >> 12).clamp(-16384, 16383); + let xout2 = (wd_d >> 12).clamp(-16384, 16383); + + let s0 = (xout1 << 1).clamp(-32768, 32767) as i16; + let s1 = (xout2 << 1).clamp(-32768, 32767) as i16; + (s0, s1) + } +} + +// --------------------------------------------------------------------------- +// G.722 Decoder & Encoder +// --------------------------------------------------------------------------- + +/// ITU-T G.722 64 kbit/s single-channel decoder. +#[derive(Debug, Clone)] +pub struct Decoder { + band_l: BandState, + band_h: BandState, + qmf: QmfRx, +} + +impl Default for Decoder { + fn default() -> Self { + Self::new() + } +} + +impl Decoder { + /// Create a new G.722 decoder initialized to standard reset state. + pub fn new() -> Self { + Self { band_l: BandState::new(true), band_h: BandState::new(false), qmf: QmfRx::new() } + } + + /// Reset decoder internal state. + pub fn reset(&mut self) { + self.band_l.reset(true); + self.band_h.reset(false); + self.qmf.reset(); + } + + /// Decode a single 8-bit octet into two 16 kHz 16-bit PCM samples. + pub fn decode_octet(&mut self, octet: u8) -> (i16, i16) { + let ih = ((octet >> 6) & 3) as usize; + let il = (octet & 0x3F) as usize; + + // INVQBL: 6-bit lower sub-band inverse quantization + let (sil6, il6) = table18_lookup(il); + let wd1 = (QQ6[il6] as i32) << 3; + let wd2 = if sil6 == 0 { wd1 } else { -wd1 }; + let dl = mult(self.band_l.det as i16, wd2 as i16); + let yl = self.band_l.s.saturating_add(dl); + let rl = yl.clamp(-16384, 16383); + + // INVQAL: lower sub-band predictor update (4-bit feedback path) + let ril = il >> 2; + let (sil4, il4) = IL4_MAP[ril & 0x0F]; + let wd1 = (QQ4[il4] as i32) << 3; + let wd2 = if sil4 == 0 { wd1 } else { -wd1 }; + let dlt = mult(self.band_l.det as i16, wd2 as i16); + let plt = dlt.saturating_add(self.band_l.sz); + let rlt = self.band_l.s.saturating_add(dlt); + + // Lower sub-band scale factor adaptation (LOGSCL) + let wd_scale = mult(self.band_l.nb as i16, 32512); + let nbpl = (wd_scale as i32 + WL[il4] as i32).clamp(0, 18432); + self.band_l.nb = nbpl; + self.band_l.det = scalel(nbpl); + self.band_l.update_predictor(dlt, plt, rlt); + + // INVQAH: higher sub-band inverse quantization + let (sih_dec, ih2) = IH2_MAP[ih & 0x03]; + let wd1 = (QQ2[ih2] as i32) << 3; + let wd2 = if sih_dec == 0 { wd1 } else { -wd1 }; + let dh = mult(self.band_h.det as i16, wd2 as i16); + let yh = self.band_h.s.saturating_add(dh); + let rh = yh.clamp(-16384, 16383); + + // Higher sub-band scale factor adaptation (LOGSCH) + let wd_scale = mult(self.band_h.nb as i16, 32512); + let nbph = (wd_scale as i32 + WH[ih2] as i32).clamp(0, 22528); + self.band_h.nb = nbph; + self.band_h.det = scaleh(nbph); + let ph = dh.saturating_add(self.band_h.sz); + self.band_h.update_predictor(dh, ph, yh); + + // Synthesis QMF + self.qmf.filter(rl, rh) + } + + /// Decode G.722 octets into 16 kHz 16-bit linear PCM samples, appending to `dst`. + pub fn decode(&mut self, src: &[u8], dst: &mut Vec) -> Result<(), Error> { + if src.len() > MAX_INPUT_BYTES { + return Err(Error::InputTooLarge); + } + let needed_samples = src.len().saturating_mul(2); + if needed_samples > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } + dst.try_reserve(needed_samples).map_err(|_| Error::AllocationFailed)?; + for &octet in src { + let (s0, s1) = self.decode_octet(octet); + dst.push(s0); + dst.push(s1); + } + Ok(()) + } +} + +/// ITU-T G.722 64 kbit/s single-channel encoder. +#[derive(Debug, Clone)] +pub struct Encoder { + qmf: QmfTx, + band_l: BandState, + band_h: BandState, +} + +impl Default for Encoder { + fn default() -> Self { + Self::new() + } +} + +impl Encoder { + /// Create a new G.722 encoder initialized to standard reset state. + pub fn new() -> Self { + Self { qmf: QmfTx::new(), band_l: BandState::new(true), band_h: BandState::new(false) } + } + + /// Reset encoder internal state. + pub fn reset(&mut self) { + self.qmf.reset(); + self.band_l.reset(true); + self.band_h.reset(false); + } + + /// Encode a pair of 16 kHz 16-bit PCM samples into one 8-bit G.722 octet. + pub fn encode_sample_pair(&mut self, s0: i16, s1: i16) -> u8 { + // Analysis QMF + let (xl, xh) = self.qmf.filter(s0, s1); + + // Lower sub-band quantizer (QUANTL) + let el = xl.saturating_sub(self.band_l.s); + let sil = if el < 0 { -1 } else { 0 }; + let wd = if sil == 0 { el } else { 32767 - (el & 32767) }; + let mut mil: usize = 30; + for (k, &thresh_q) in Q6.iter().enumerate().skip(1) { + let thresh = (((thresh_q as i32) << 3) * self.band_l.det) >> 15; + if (wd as i32) < thresh { + mil = k; + break; + } + } + + // Table 16 conversion to IL + let il: u8 = if sil == 0 { + (62 - mil) as u8 + } else if mil == 1 { + 63 + } else if mil == 2 { + 62 + } else { + (34 - mil) as u8 + }; + + // Lower sub-band feedback and predictor update (INVQAL) + let ril = (il >> 2) as usize; + let (sil4, il4) = IL4_MAP[ril & 0x0F]; + let wd1 = (QQ4[il4] as i32) << 3; + let wd2 = if sil4 == 0 { wd1 } else { -wd1 }; + let dlt = mult(self.band_l.det as i16, wd2 as i16); + let plt = dlt.saturating_add(self.band_l.sz); + let rlt = self.band_l.s.saturating_add(dlt); + + // Lower sub-band scale factor adaptation (LOGSCL) + let wd_scale = mult(self.band_l.nb as i16, 32512); + let nbpl = (wd_scale as i32 + WL[il4] as i32).clamp(0, 18432); + self.band_l.nb = nbpl; + self.band_l.det = scalel(nbpl); + self.band_l.update_predictor(dlt, plt, rlt); + + // Higher sub-band quantizer (QUANTH) + let eh = xh.saturating_sub(self.band_h.s); + let sih = if eh < 0 { -1 } else { 0 }; + let wd = if sih == 0 { eh } else { 32767 - (eh & 32767) }; + let thresh = ((564 << 3) * self.band_h.det) >> 15; + let mih = if (wd as i32) < thresh { 1 } else { 2 }; + + // Table 20 conversion to IH + let ih: u8 = if sih == -1 { + if mih == 2 { 0 } else { 1 } + } else if mih == 1 { + 3 + } else { + 2 + }; + + // Higher sub-band feedback and predictor update (INVQAH) + let (sih_dec, ih2) = IH2_MAP[ih as usize]; + let wd1 = (QQ2[ih2] as i32) << 3; + let wd2 = if sih_dec == 0 { wd1 } else { -wd1 }; + let dh = mult(self.band_h.det as i16, wd2 as i16); + let yh = self.band_h.s.saturating_add(dh); + + // Higher sub-band scale factor adaptation (LOGSCH) + let wd_scale = mult(self.band_h.nb as i16, 32512); + let nbph = (wd_scale as i32 + WH[ih2] as i32).clamp(0, 22528); + self.band_h.nb = nbph; + self.band_h.det = scaleh(nbph); + let ph = dh.saturating_add(self.band_h.sz); + self.band_h.update_predictor(dh, ph, yh); + + // Multiplexer (MUX) + (ih << 6) | (il & 0x3F) + } + + /// Encode 16 kHz 16-bit linear PCM samples into G.722 octets, appending to `dst`. + pub fn encode(&mut self, src: &[i16], dst: &mut Vec) -> Result<(), Error> { + if !src.len().is_multiple_of(2) { + return Err(Error::OddSampleCount(src.len())); + } + if src.len() > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } + let needed_octets = src.len() / 2; + dst.try_reserve(needed_octets).map_err(|_| Error::AllocationFailed)?; + for &[s0, s1] in src.as_chunks::<2>().0 { + let octet = self.encode_sample_pair(s0, s1); + dst.push(octet); + } + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +#[inline] +fn table18_lookup(il: usize) -> (i16, usize) { + let il = il & 0x3F; + if (4..=31).contains(&il) { + (-1, 34 - il) + } else if il == 62 { + (-1, 2) + } else if il == 63 { + (-1, 1) + } else if (32..=61).contains(&il) { + (0, 62 - il) + } else { + // Transmission error fallbacks (0..=3) + (-1, 1) + } +} + +// --------------------------------------------------------------------------- +// Public Top-Level Functions +// --------------------------------------------------------------------------- + +/// Decode a mono 64 kbit/s G.722 stream into 16 kHz 16-bit linear PCM samples. +pub fn decode(bytes: &[u8]) -> Result, Error> { + let mut decoder = Decoder::new(); + let mut out = Vec::new(); + decoder.decode(bytes, &mut out)?; + Ok(out) +} + +/// Encode mono 16 kHz 16-bit linear PCM samples into a 64 kbit/s G.722 stream. +pub fn encode(samples: &[i16]) -> Result, Error> { + let mut encoder = Encoder::new(); + let mut out = Vec::new(); + encoder.encode(samples, &mut out)?; + Ok(out) +} + +/// Decode an interleaved multi-channel G.722 stream into interleaved 16 kHz 16-bit PCM samples. +pub fn decode_interleaved(bytes: &[u8], channels: usize) -> Result, Error> { + if channels == 0 || channels > MAX_CHANNELS { + return Err(Error::InvalidChannels(channels)); + } + if channels == 1 { + return decode(bytes); + } + if bytes.len() > MAX_INPUT_BYTES { + return Err(Error::InputTooLarge); + } + let frames = bytes.len() / channels; + let mut decoders: Vec = Vec::with_capacity(channels); + for _ in 0..channels { + decoders.push(Decoder::new()); + } + let total_samples = frames.saturating_mul(channels).saturating_mul(2); + let mut out = Vec::new(); + out.try_reserve(total_samples).map_err(|_| Error::AllocationFailed)?; + + // Each frame has `channels` bytes. Decode each byte with its channel's decoder, + // producing sample 0 for each channel, then sample 1 for each channel. + for chunk in bytes.chunks_exact(channels) { + let mut pairs = [(0i16, 0i16); MAX_CHANNELS]; + for (ch, &b) in chunk.iter().enumerate() { + pairs[ch] = decoders[ch].decode_octet(b); + } + for pair in pairs.iter().take(channels) { + out.push(pair.0); + } + for pair in pairs.iter().take(channels) { + out.push(pair.1); + } + } + Ok(out) +} + +/// Encode interleaved 16 kHz 16-bit PCM samples into an interleaved multi-channel G.722 stream. +pub fn encode_interleaved(samples: &[i16], channels: usize) -> Result, Error> { + if channels == 0 || channels > MAX_CHANNELS { + return Err(Error::InvalidChannels(channels)); + } + if channels == 1 { + return encode(samples); + } + let frame_len = channels.saturating_mul(2); + if !samples.len().is_multiple_of(frame_len) { + return Err(Error::OddSampleCount(samples.len())); + } + let frames = samples.len() / frame_len; + let mut encoders: Vec = Vec::with_capacity(channels); + for _ in 0..channels { + encoders.push(Encoder::new()); + } + let total_bytes = frames.saturating_mul(channels); + let mut out = Vec::new(); + out.try_reserve(total_bytes).map_err(|_| Error::AllocationFailed)?; + + for chunk in samples.chunks_exact(frame_len) { + for ch in 0..channels { + let s0 = chunk[ch]; + let s1 = chunk[ch + channels]; + out.push(encoders[ch].encode_sample_pair(s0, s1)); + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reject_invalid_channels() { + assert_eq!(decode_interleaved(&[0; 4], 0), Err(Error::InvalidChannels(0))); + assert_eq!(decode_interleaved(&[0; 4], 9), Err(Error::InvalidChannels(9))); + assert_eq!(encode_interleaved(&[0; 4], 0), Err(Error::InvalidChannels(0))); + assert_eq!(encode_interleaved(&[0; 4], 9), Err(Error::InvalidChannels(9))); + } + + #[test] + fn reject_odd_sample_count() { + assert_eq!(encode(&[0; 3]), Err(Error::OddSampleCount(3))); + assert_eq!(encode_interleaved(&[0; 5], 2), Err(Error::OddSampleCount(5))); + } + + #[test] + fn roundtrip_silence() { + let input = vec![0i16; 320]; + let encoded = encode(&input).expect("encode silence"); + assert_eq!(encoded.len(), 160); + let decoded = decode(&encoded).expect("decode silence"); + assert_eq!(decoded.len(), 320); + for &s in &decoded[40..] { + assert!(s.abs() <= 6, "silence sample too large: {s}"); + } + } + + #[test] + fn multichannel_stereo_roundtrip() { + let mut stereo_pcm = Vec::new(); + for i in 0..400 { + stereo_pcm.push((i * 10) as i16); + stereo_pcm.push((-i * 10) as i16); + } + let enc = encode_interleaved(&stereo_pcm, 2).expect("encode stereo"); + assert_eq!(enc.len(), 400); + let dec = decode_interleaved(&enc, 2).expect("decode stereo"); + assert_eq!(dec.len(), 800); + } + + #[test] + fn hostile_input_does_not_panic() { + let garbage = [0xFF, 0x00, 0x55, 0xAA, 0x12, 0x34, 0x7F, 0x80]; + let dec = decode(&garbage).expect("decode garbage"); + assert_eq!(dec.len(), 16); + } +} diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 93fbec58d..8cd6e5acc 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -41,6 +41,8 @@ pub mod ac3; #[cfg(any(feature = "alac-decode", feature = "alac-encode"))] pub mod alac; mod buffer; +#[cfg(feature = "g722")] +pub mod g722; mod layout; #[cfg(any(feature = "mp3-encode", feature = "mp3-decode"))] pub mod mp3; diff --git a/crates/audio/tests/g722_oracle.rs b/crates/audio/tests/g722_oracle.rs new file mode 100644 index 000000000..3da059011 --- /dev/null +++ b/crates/audio/tests/g722_oracle.rs @@ -0,0 +1,201 @@ +//! ITU-T G.722 SB-ADPCM tests and FFmpeg oracle comparisons. +//! +//! Skipped when FFmpeg is not found, unless `CRAFT_MEDIA_REQUIRE_ORACLES=1` is set. + +use craft_audio::g722::{Decoder, Encoder, Error, decode, decode_interleaved, encode, encode_interleaved}; +use std::process::Command; + +fn generate_signal(samples: usize, freq: f64) -> Vec { + (0..samples) + .map(|i| { + let t = i as f64 / 16000.0; + let val = (2.0 * std::f64::consts::PI * freq * t).sin() * 10000.0; + val as i16 + }) + .collect() +} + +#[test] +fn test_silence_roundtrip() { + let pcm = vec![0i16; 640]; + let encoded = encode(&pcm).expect("encode"); + assert_eq!(encoded.len(), 320); + let decoded = decode(&encoded).expect("decode"); + assert_eq!(decoded.len(), 640); + for &s in &decoded[40..] { + assert!(s.abs() <= 6, "silence sample out of bounds: {s}"); + } +} + +#[test] +fn test_sine_wave_roundtrip_fidelity() { + let pcm = generate_signal(1600, 1000.0); + let encoded = encode(&pcm).expect("encode"); + let decoded = decode(&encoded).expect("decode"); + assert_eq!(decoded.len(), pcm.len()); + + // Compute normalized cross-correlation accounting for filter group delay (approx 22 samples) + let delay = 22; + let mut num = 0.0; + let mut den_orig = 0.0; + let mut den_dec = 0.0; + for i in 0..(pcm.len() - delay) { + let o = pcm[i] as f64; + let d = decoded[i + delay] as f64; + num += o * d; + den_orig += o * o; + den_dec += d * d; + } + let corr = num / (den_orig.sqrt() * den_dec.sqrt()); + assert!(corr > 0.98, "reconstructed sine wave correlation too low: {corr}"); +} + +#[test] +fn test_stereo_multichannel_roundtrip() { + let left = generate_signal(800, 440.0); + let right = generate_signal(800, 880.0); + let mut interleaved = Vec::with_capacity(1600); + for i in 0..800 { + interleaved.push(left[i]); + interleaved.push(right[i]); + } + let encoded = encode_interleaved(&interleaved, 2).expect("encode stereo"); + assert_eq!(encoded.len(), 800); + let decoded = decode_interleaved(&encoded, 2).expect("decode stereo"); + assert_eq!(decoded.len(), 1600); +} + +#[test] +fn test_hostile_inputs_do_not_crash() { + let garbage = [0xFF, 0x00, 0xAA, 0x55, 0x12, 0x34, 0x89, 0xFE]; + let decoded = decode(&garbage).expect("decode garbage"); + assert_eq!(decoded.len(), 16); + + assert_eq!(encode(&[1, 2, 3]), Err(Error::OddSampleCount(3))); + assert_eq!(decode_interleaved(&[0; 8], 0), Err(Error::InvalidChannels(0))); + assert_eq!(decode_interleaved(&[0; 8], 9), Err(Error::InvalidChannels(9))); +} + +#[test] +fn test_encoder_and_decoder_reset() { + let mut enc = Encoder::new(); + let mut dec = Decoder::new(); + let pcm = generate_signal(200, 1000.0); + + let mut out1 = Vec::new(); + enc.encode(&pcm, &mut out1).expect("enc 1"); + let mut dec1 = Vec::new(); + dec.decode(&out1, &mut dec1).expect("dec 1"); + + enc.reset(); + dec.reset(); + + let mut out2 = Vec::new(); + enc.encode(&pcm, &mut out2).expect("enc 2"); + let mut dec2 = Vec::new(); + dec.decode(&out2, &mut dec2).expect("dec 2"); + + assert_eq!(out1, out2); + assert_eq!(dec1, dec2); +} + +#[test] +fn test_ffmpeg_g722_oracle_encoder_and_decoder() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("g722_oracle"); + + // 1. Generate test 1000 Hz tone at 16 kHz mono (800 samples = 0.05s) + let pcm = generate_signal(800, 1000.0); + let pcm_path = dir.join("input.s16le"); + let mut pcm_bytes = Vec::with_capacity(pcm.len() * 2); + for &s in &pcm { + pcm_bytes.extend_from_slice(&s.to_le_bytes()); + } + std::fs::write(&pcm_path, &pcm_bytes).expect("write pcm"); + + // 2. FFmpeg encodes the PCM to G.722 + let ff_g722_path = dir.join("ffmpeg.g722"); + let out = Command::new(&ff) + .args(["-y", "-f", "s16le", "-ar", "16000", "-ac", "1", "-i"]) + .arg(&pcm_path) + .args(["-f", "g722"]) + .arg(&ff_g722_path) + .output() + .expect("ffmpeg encode"); + assert!(out.status.success(), "ffmpeg encode failed: {}", String::from_utf8_lossy(&out.stderr)); + let ff_g722_bytes = std::fs::read(&ff_g722_path).expect("read ff g722"); + + // 3. FFmpeg decodes its own G.722 back to PCM + let ff_pcm_back_path = dir.join("ff_back.s16le"); + let out = Command::new(&ff) + .args(["-y", "-f", "g722", "-i"]) + .arg(&ff_g722_path) + .args(["-f", "s16le", "-ar", "16000", "-ac", "1"]) + .arg(&ff_pcm_back_path) + .output() + .expect("ffmpeg decode"); + assert!(out.status.success(), "ffmpeg decode failed: {}", String::from_utf8_lossy(&out.stderr)); + let ff_back_bytes = std::fs::read(&ff_pcm_back_path).expect("read ff back pcm"); + let ff_back_samples: Vec = ff_back_bytes.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect(); + + // 4. Our decoder decodes FFmpeg's G.722 stream + let our_decoded_from_ff = decode(&ff_g722_bytes).expect("our decode of ff stream"); + assert_eq!(our_decoded_from_ff.len(), ff_back_samples.len()); + + // Verify sample-by-sample match against FFmpeg decoder: within ±1 LSB tolerance + let mut max_diff: i32 = 0; + for (i, (&ours, &theirs)) in our_decoded_from_ff.iter().zip(&ff_back_samples).enumerate() { + let diff = (ours as i32 - theirs as i32).abs(); + if diff > max_diff { + max_diff = diff; + } + assert!(diff <= 1, "sample {i} mismatch between our decoder and FFmpeg decoder: ours {ours}, theirs {theirs}"); + } + assert!(max_diff <= 1, "max diff {max_diff} exceeded tolerance"); + + // 5. Our encoder encodes the PCM to G.722 + let our_encoded_bytes = encode(&pcm).expect("our encode"); + let our_g722_path = dir.join("ours.g722"); + std::fs::write(&our_g722_path, &our_encoded_bytes).expect("write our g722"); + + // 6. FFmpeg decodes our encoded G.722 stream + let our_decoded_by_ff_path = dir.join("our_by_ff.s16le"); + let out = Command::new(&ff) + .args(["-y", "-f", "g722", "-i"]) + .arg(&our_g722_path) + .args(["-f", "s16le", "-ar", "16000", "-ac", "1"]) + .arg(&our_decoded_by_ff_path) + .output() + .expect("ffmpeg decode of our stream"); + assert!(out.status.success(), "ffmpeg decode of our stream failed: {}", String::from_utf8_lossy(&out.stderr)); + let our_by_ff_bytes = std::fs::read(&our_decoded_by_ff_path).expect("read our by ff pcm"); + let our_by_ff_samples: Vec = our_by_ff_bytes.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect(); + + // Verify that our decoder and FFmpeg decoder produce identical samples on our stream + let our_decoded_from_ours = decode(&our_encoded_bytes).expect("our decode of our stream"); + assert_eq!(our_decoded_from_ours.len(), our_by_ff_samples.len()); + let mut max_diff_ours: i32 = 0; + for (i, (&ours, &theirs)) in our_decoded_from_ours.iter().zip(&our_by_ff_samples).enumerate() { + let diff = (ours as i32 - theirs as i32).abs(); + if diff > max_diff_ours { + max_diff_ours = diff; + } + assert!(diff <= 1, "sample {i} on our stream mismatch between our decoder and FFmpeg decoder: ours {ours}, theirs {theirs}"); + } + assert!(max_diff_ours <= 1, "max diff {max_diff_ours} exceeded tolerance"); + + // Also check high fidelity correlation of our stream decoded by FFmpeg to original signal + let delay = 22; + let mut num = 0.0; + let mut den_orig = 0.0; + let mut den_dec = 0.0; + for i in 0..(pcm.len() - delay) { + let o = pcm[i] as f64; + let d = our_by_ff_samples[i + delay] as f64; + num += o * d; + den_orig += o * o; + den_dec += d * d; + } + let corr = num / (den_orig.sqrt() * den_dec.sqrt()); + assert!(corr > 0.98, "correlation of our encoded stream decoded by FFmpeg is too low: {corr}"); +} From d09260a36a63d593c852487bb7dd50669bec0af4 Mon Sep 17 00:00:00 2001 From: el-j Date: Mon, 16 Nov 2026 02:39:51 +0100 Subject: [PATCH 03/15] craft-audio: prevent potential negation overflow and bound multichannel input in G.722 --- crates/audio/src/g722.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/audio/src/g722.rs b/crates/audio/src/g722.rs index ea5766c83..030b87d14 100644 --- a/crates/audio/src/g722.rs +++ b/crates/audio/src/g722.rs @@ -152,7 +152,7 @@ impl BandState { let sg0: i16 = if d < 0 { -1 } else { 0 }; for i in 1..=6 { let sgi = if self.d[i] < 0 { -1 } else { 0 }; - let wd2 = if sg0 == sgi { wd1 } else { -wd1 }; + let wd2 = if sg0 == sgi { wd1 } else { wd1.saturating_neg() }; let wd3 = mult(self.b[i], 32640); self.b[i] = wd2.saturating_add(wd3); } @@ -162,7 +162,7 @@ impl BandState { let sg1 = if self.p[1] < 0 { -1 } else { 0 }; let sg2 = if self.p[2] < 0 { -1 } else { 0 }; let wd1 = self.a[1].saturating_add(self.a[1]).saturating_add(self.a[1].saturating_add(self.a[1])); - let wd2 = if sg0 == sg1 { -wd1 } else { wd1 } >> 7; + let wd2 = if sg0 == sg1 { wd1.saturating_neg() } else { wd1 } >> 7; let wd3: i16 = if sg0 == sg2 { 128 } else { -128 }; let wd4 = wd2.saturating_add(wd3); let wd5 = mult(self.a[2], 32512); @@ -607,6 +607,9 @@ pub fn encode_interleaved(samples: &[i16], channels: usize) -> Result, E if channels == 1 { return encode(samples); } + if samples.len() > MAX_SAMPLES { + return Err(Error::InputTooLarge); + } let frame_len = channels.saturating_mul(2); if !samples.len().is_multiple_of(frame_len) { return Err(Error::OddSampleCount(samples.len())); @@ -679,4 +682,12 @@ mod tests { let dec = decode(&garbage).expect("decode garbage"); assert_eq!(dec.len(), 16); } + + #[test] + fn uppol2_overflow_does_not_panic() { + let mut state = BandState::new(true); + state.a[1] = -8192; + state.p = [0, 0, 0]; + state.update_predictor(0, 0, 0); + } } From 551cb9878667d0f046c0b432793f92fa2587ffe7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 21:15:54 -0500 Subject: [PATCH 04/15] plotter: share the HP-GL byte lexer from VectorCraft Source: storytold/vectorcraft commit 74ea25cd6c4dffa4cd41f6ee9a76f7afd4225622, crates/cad/src/hpgl/lex.rs. Production source unchanged except public visibility; parsing, interpreter and writer policy remain with callers. --- crates/plotter/src/hpgl.rs | 3 + crates/plotter/src/hpgl/lex.rs | 428 +++++++++++++++++++++++++++++++++ 2 files changed, 431 insertions(+) create mode 100644 crates/plotter/src/hpgl/lex.rs diff --git a/crates/plotter/src/hpgl.rs b/crates/plotter/src/hpgl.rs index 728f6b153..5f6759241 100644 --- a/crates/plotter/src/hpgl.rs +++ b/crates/plotter/src/hpgl.rs @@ -7,6 +7,9 @@ //! bottom-left and y points up, so the design is flipped about its bottom edge. Force and speed //! are set on the machine's panel. +/// Byte-oriented HP-GL/2 lexer, including PCL/PJL framing and encoded polylines. +pub mod lex; + use crate::{Command, Error, Framing, Job, Program, y_up}; /// Plotter units per mm (1 plu = 0.025 mm). diff --git a/crates/plotter/src/hpgl/lex.rs b/crates/plotter/src/hpgl/lex.rs new file mode 100644 index 000000000..fbdd39622 --- /dev/null +++ b/crates/plotter/src/hpgl/lex.rs @@ -0,0 +1,428 @@ +//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow +//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the +//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped, +//! with the data their escapes carry. + +/// The end-of-text character, the default label terminator. +pub const ETX: u8 = 3; +const ESC: u8 = 0x1b; + +/// The most digits of a number that count: longer ones are read as their first digits. +const MAX_DIGITS: usize = 18; + +/// What the bytes being read hold. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + /// HP-GL instructions. + Hpgl, + /// PCL or HP RTL: escape sequences and their data, nothing to draw. + Pcl, + /// After a Universal Exit Language: PJL lines until a language starts. + Pjl, +} + +/// One item of a PE (Polyline Encoded) instruction. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PeItem { + /// Select pen. + Pen(i64), + /// Rectangle mode: the following coordinates come in fours. + Rect, + /// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`). + Point { x: f64, y: f64, up: bool, absolute: bool }, +} + +/// The state of one PE instruction being read. +#[derive(Clone, Copy, Debug, Default)] +pub struct Pe { + seven_bit: bool, + fraction_bits: u32, + up: bool, + absolute: bool, +} + +pub struct Lexer<'a> { + b: &'a [u8], + at: usize, + mode: Mode, + /// The file holds HP RTL or PCL raster image data. + pub raster: bool, +} + +/// Is `c` a byte that separates numeric parameters (or white space between instructions)? +fn separator(c: u8) -> bool { + matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0) +} + +impl<'a> Lexer<'a> { + pub fn new(b: &'a [u8]) -> Self { + Self { b, at: 0, mode: Mode::Hpgl, raster: false } + } + + fn peek(&self) -> Option { + self.b.get(self.at).copied() + } + + /// Whether everything has been read. + pub fn done(&self) -> bool { + self.at >= self.b.len() + } + + /// How many bytes have been read. + pub fn pos(&self) -> usize { + self.at + } + + /// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and + /// escape sequences may come before it (anything else gives `None`, as the end does). + pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> { + loop { + let c = self.peek()?; + if c == ESC { + self.escape(); + continue; + } + match self.mode { + Mode::Pcl => { + self.at += 1; + continue; + } + Mode::Pjl => { + if separator(c) { + self.at += 1; + } else if c == b'@' { + self.pjl_line(); + } else { + self.mode = Mode::Hpgl; + } + continue; + } + Mode::Hpgl => {} + } + let next = self.b.get(self.at + 1).copied(); + if c.is_ascii_alphabetic() + && let Some(n) = next.filter(u8::is_ascii_alphabetic) + { + self.at += 2; + return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]); + } + if strict && !(separator(c) || c == b';' || c < 0x20) { + return None; + } + self.at += 1; + } + } + + /// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows. + fn pjl_line(&mut self) { + let rest = &self.b[self.at..]; + let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1); + // A command names its language within its first 256 bytes; longer lines aren't copied. + let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase(); + if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) { + self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl }; + } + self.at += end; + } + + /// An escape sequence at the current byte, with the data it carries. + fn escape(&mut self) { + self.at += 1; + let Some(c) = self.peek() else { return }; + self.at += 1; + match c { + // Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL, + // `ESC%#A` to PCL or HP RTL). + b'%' => { + let (_, end) = self.value(); + match end { + Some(b'X') => self.mode = Mode::Pjl, + Some(b'B') => self.mode = Mode::Hpgl, + Some(b'A') => self.mode = Mode::Pcl, + _ => {} + } + } + // Reset: PCL follows, until a language switch. + b'E' => self.mode = Mode::Pcl, + // HP-GL device control: `ESC.` and a letter, with parameters up to a colon. + b'.' => { + let Some(kind) = self.peek() else { return }; + self.at += 1; + if !b"()YZBEJKLORUX".contains(&kind) { + let rest = &self.b[self.at..self.b.len().min(self.at + 80)]; + if let Some(n) = rest.iter().position(|&c| c == b':') + && rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b',')) + { + self.at += n + 1; + } + } + } + // Parameterized PCL: a group character, then values each ending in a letter (upper case + // ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print + // data) are followed by that many bytes of data. Without a group character (`ESC(8U`, + // `ESC)0N`), one value and the letter ending it. + 0x21..=0x2f => { + let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else { + self.value(); + return; + }; + self.at += 1; + loop { + let (v, end) = self.value(); + let Some(end) = end else { return }; + let upper = end.to_ascii_uppercase(); + if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') { + let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize; + if (c, group) == (b'*', b'b') && n > 0 { + self.raster = true; + } + self.at += n; + } + if (c, group, end) == (b'*', b'r', b'A') { + self.raster = true; + } + if !end.is_ascii_lowercase() { + return; + } + } + } + // A two-character escape. + _ => {} + } + } + + /// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None` + /// when that is not a letter or `@` (which is then left unread). + fn value(&mut self) -> (f64, Option) { + let v = self.number_here().unwrap_or(0.0); + match self.peek() { + Some(c) if c.is_ascii_alphabetic() || c == b'@' => { + self.at += 1; + (v, Some(c)) + } + _ => (v, None), + } + } + + /// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit + /// (its sign and point are read all the same). + fn number_here(&mut self) -> Option { + let mut neg = false; + if let Some(c @ (b'+' | b'-')) = self.peek() { + neg = c == b'-'; + self.at += 1; + } + let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64); + let mut point = false; + while let Some(c) = self.peek() { + if c.is_ascii_digit() { + if digits < MAX_DIGITS { + if point { + scale /= 10.0; + v += f64::from(c - b'0') * scale; + } else { + v = v * 10.0 + f64::from(c - b'0'); + } + } else if !point { + // Past the digits that count, an integer part keeps its size. + v *= 10.0; + } + digits += 1; + } else if c == b'.' && !point { + point = true; + } else { + break; + } + self.at += 1; + } + let v = v.min(f64::MAX); + (digits > 0).then_some(if neg { -v } else { v }) + } + + /// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon + /// ending it is read). + pub fn number(&mut self) -> Option { + loop { + let c = self.peek()?; + if separator(c) { + self.at += 1; + } else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') { + if let Some(v) = self.number_here() { + return Some(v); + } + } else { + if c == b';' { + self.at += 1; + } + return None; + } + } + } + + /// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many. + pub fn numbers(&mut self, out: &mut [f64]) -> usize { + let mut n = 0; + while let Some(v) = self.number() { + if let Some(slot) = out.get_mut(n) { + *slot = v; + } + n += 1; + } + n.min(out.len()) + } + + /// Read and drop the parameters of the instruction being read: numbers and quoted strings. + pub fn params(&mut self) { + loop { + while self.number().is_some() {} + if self.peek() != Some(b'"') { + return; + } + self.quoted(); + } + } + + /// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader + /// doesn't know, written out in full). + pub fn closed_params(&mut self) -> bool { + while self.number().is_some() {} + self.at > 0 && self.b.get(self.at - 1) == Some(&b';') + } + + /// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it + /// is one. + pub fn comment(&mut self) -> bool { + while self.peek().is_some_and(separator) { + self.at += 1; + } + match self.peek() { + Some(b'"') => self.quoted(), + Some(b';') => { + self.at += 1; + true + } + None => true, + Some(_) => false, + } + } + + /// The text of a label, up to and including `terminator` (or the end). + pub fn label(&mut self, terminator: u8) { + let rest = &self.b[self.at..]; + self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1); + } + + /// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether + /// there was one. + pub fn quoted(&mut self) -> bool { + while self.peek().is_some_and(separator) { + self.at += 1; + } + let found = self.peek() == Some(b'"'); + if found { + self.at += 1; + let rest = &self.b[self.at..]; + self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1); + } + if self.peek() == Some(b';') { + self.at += 1; + } + found + } + + /// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end + /// (the semicolon is read). + pub fn char(&mut self) -> Option { + let c = self.peek()?; + self.at += 1; + (c != b';').then_some(c) + } + + /// The next item of a PE instruction, `None` at its end (its semicolon is read). + pub fn pe(&mut self, st: &mut Pe) -> Option { + loop { + let raw = self.peek()?; + let c = raw & 0x7f; + // Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored. + if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 { + self.at += 1; + continue; + } + match c { + b';' => { + self.at += 1; + return None; + } + // Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up). + b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => { + self.at += 1; + match c { + b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()), + b'<' => st.up = true, + b'>' => match self.pe_value(st) { + Some(n) => st.fraction_bits = n.clamp(0, 52) as u32, + None => return self.end_pe(), + }, + b'=' => st.absolute = true, + b'7' => st.seven_bit = true, + _ => return Some(PeItem::Rect), + } + } + _ => { + let scale = 0.5f64.powi(st.fraction_bits as i32); + let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() }; + let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute }; + (st.up, st.absolute) = (false, false); + return Some(item); + } + } + } + } + + /// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`]. + fn end_pe(&mut self) -> Option { + self.skip_pe(); + None + } + + /// The data of a PE instruction, up to and including its semicolon, unread: its data is never + /// read as instructions. + pub fn skip_pe(&mut self) { + let rest = &self.b[self.at..]; + self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1); + } + + /// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no + /// digit comes first, which is read). + fn pe_value(&mut self, st: &Pe) -> Option { + let (base, low, high): (u64, std::ops::RangeInclusive, std::ops::RangeInclusive) = + if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) }; + let (mut v, mut place) = (0u64, 1u64); + loop { + let raw = self.peek()?; + let c = if st.seven_bit { raw & 0x7f } else { raw }; + if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 { + self.at += 1; + continue; + } + if c == b';' { + return None; + } + self.at += 1; + let (digit, last) = if low.contains(&c) { + (u64::from(c - 63), false) + } else if high.contains(&c) { + (u64::from(c - high.start()), true) + } else { + return None; + }; + v = v.saturating_add(digit.saturating_mul(place)); + place = place.saturating_mul(base); + if last { + // The low bit is the sign. + let n = i64::try_from(v >> 1).unwrap_or(i64::MAX); + return Some(if v & 1 == 1 { -n } else { n }); + } + } + } +} From 9101c4fc226f5f111b5a890a6c5c19bf3991fd76 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:16:34 -0500 Subject: [PATCH 05/15] plotter: document lexer provenance and pin framing recovery --- crates/plotter/README.md | 14 ++++++++++++++ crates/plotter/src/hpgl/lex.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/crates/plotter/README.md b/crates/plotter/README.md index 59438d366..d35c2b114 100644 --- a/crates/plotter/README.md +++ b/crates/plotter/README.md @@ -78,3 +78,17 @@ is MIT OR Apache-2.0 like the rest of the repository. Vendor binaries were not d decompiled or debugged. The line-segment overcut is this crate's own geometric rule, not a captured vendor stream. When extending the crate, keep to this: public documentation and observed device behaviour, never GPL driver source. + +## HP-GL byte lexer + +`hpgl::lex` also exposes a borrowing HP-GL/2 lexer with PCL/PJL framing, +label/comment skipping and encoded polyline values. It does not interpret drawing +commands or replace the existing cutter encoder. The caller supplies numeric +storage and controls document/geometry budgets; scanning time is proportional to +input consumed, not capped by this API. PJL language detection copies at most 256 +bytes of a line. Malformed-input recovery retains the original VectorCraft behavior. + +This module comes from dotCooCoo's VectorCraft `crates/cad/src/hpgl/lex.rs`, +commit `74ea25cd6c4dffa4cd41f6ee9a76f7afd4225622` (MIT OR Apache-2.0), +with public visibility for reuse. The drawing interpreter and export policies remain +in VectorCraft. Existing plotter encoders and their device limits are unchanged. diff --git a/crates/plotter/src/hpgl/lex.rs b/crates/plotter/src/hpgl/lex.rs index fbdd39622..e84e8d57b 100644 --- a/crates/plotter/src/hpgl/lex.rs +++ b/crates/plotter/src/hpgl/lex.rs @@ -426,3 +426,33 @@ impl<'a> Lexer<'a> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn framing_labels_and_bounded_numbers() { + let mut lex = Lexer::new(b"\x1b%-12345X@PJL ENTER LANGUAGE=HPGL2\nIN;LBPU999;\x03PA1,2,3,4;SP2;"); + assert_eq!(lex.op(true), Some(*b"IN")); + lex.params(); + assert_eq!(lex.op(true), Some(*b"LB")); + lex.label(ETX); + assert_eq!(lex.op(true), Some(*b"PA")); + let mut values = [0.0; 2]; + assert_eq!(lex.numbers(&mut values), 2); + assert_eq!(values, [1.0, 2.0]); + assert_eq!(lex.op(true), Some(*b"SP")); + assert_eq!(lex.number(), Some(2.0)); + } + + #[test] + fn encoded_flags_and_truncated_pair_recover_at_semicolon() { + let mut lex = Lexer::new(b"PE<=\xc1\xc3\xc5;PU;"); + assert_eq!(lex.op(true), Some(*b"PE")); + let mut state = Pe::default(); + assert_eq!(lex.pe(&mut state), Some(PeItem::Point { x: 1.0, y: 2.0, up: true, absolute: true })); + assert_eq!(lex.pe(&mut state), None); + assert_eq!(lex.op(true), Some(*b"PU")); + } +} From de020ead1b43e2d0788e4ed51e375f97d334e5a4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:51:26 -0500 Subject: [PATCH 06/15] plotter: cover lexer framing and malformed payload branches --- crates/plotter/src/hpgl/lex.rs | 87 ++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/crates/plotter/src/hpgl/lex.rs b/crates/plotter/src/hpgl/lex.rs index e84e8d57b..b64ad0785 100644 --- a/crates/plotter/src/hpgl/lex.rs +++ b/crates/plotter/src/hpgl/lex.rs @@ -456,3 +456,90 @@ mod tests { assert_eq!(lex.op(true), Some(*b"PU")); } } + +#[cfg(test)] +mod recovery_tests { + use super::*; + + #[test] + fn short_encoded_payloads_terminate_with_finite_coordinates() { + for value in 0..=u16::MAX { + let [a, b] = value.to_be_bytes(); + let bytes = [a, b, b';']; + let mut lex = Lexer::new(&bytes); + let mut state = Pe::default(); + let mut ended = false; + for _ in 0..=bytes.len() { + let before = lex.pos(); + let Some(item) = lex.pe(&mut state) else { + ended = true; + break; + }; + assert!(lex.pos() > before); + assert!(lex.pos() <= bytes.len()); + if let PeItem::Point { x, y, .. } = item { + assert!(x.is_finite() && y.is_finite()); + } + } + assert!(ended); + } + } + + #[test] + fn pcl_payloads_are_never_interpreted_as_plot_commands() { + for escape in [b"\x1b*b6W".as_slice(), b"\x1b*b6V", b"\x1b&p6X"] { + let mut bytes = escape.to_vec(); + bytes.extend(b"PD9,9;\x1b%0BIN;"); + let mut lex = Lexer::new(&bytes); + assert_eq!(lex.op(true), Some(*b"IN")); + assert_eq!(lex.raster, escape.starts_with(b"\x1b*b")); + } + for prefix in [ + b"\x1bEgarbage\x1b%0B".as_slice(), + b"\x1b(8U", + b"\x1b.r12,3:", + b"\x1b.Y", + b"\x1b*z1a2B", + b"\x1b0", + b"\x1b%-12345X@PJL ENTER LANGUAGE=PCL\nignored\x1b%0B", + ] { + let mut bytes = prefix.to_vec(); + bytes.extend(b"IN;"); + assert_eq!(Lexer::new(&bytes).op(true), Some(*b"IN")); + } + let mut raster = Lexer::new(b"\x1b*r1AIN;"); + assert_eq!(raster.op(true), Some(*b"IN")); + assert!(raster.raster); + for bytes in [b"\x1b".as_slice(), b"\x1b.", b"\x1b*b", b"\x1b*b999999999999Wshort"] { + let mut lex = Lexer::new(bytes); + assert_eq!(lex.op(false), None); + assert!(lex.done()); + } + } + + #[test] + fn malformed_parameters_comments_and_label_delimiters_preserve_boundaries() { + let mut lex = Lexer::new(b" +-.12,999999999999999999999999999999;PU;"); + assert_eq!(lex.number(), Some(-(0.1 + 0.02))); + assert!(lex.number().is_some_and(f64::is_finite)); + assert_eq!(lex.number(), None); + assert_eq!(lex.op(true), Some(*b"PU")); + for (bytes, closed) in [(b"1,2;".as_slice(), true), (b"1,2PU", false)] { + assert_eq!(Lexer::new(bytes).closed_params(), closed); + } + for (bytes, valid) in [(b" \"PD9,9;\";".as_slice(), true), (b";", true), (b"", true), (b"unquoted", false)] { + assert_eq!(Lexer::new(bytes).comment(), valid); + } + let mut lex = Lexer::new(b"1,2\"label\";SP3;"); + lex.params(); + assert_eq!(lex.op(true), Some(*b"SP")); + assert!(!Lexer::new(b"bad").quoted()); + assert_eq!(Lexer::new(b";").char(), None); + assert_eq!(Lexer::new(b"@").char(), Some(b'@')); + assert_eq!(Lexer::new(b"1IN;").op(true), None); + assert_eq!(Lexer::new(b"1IN;").op(false), Some(*b"IN")); + let mut lex = Lexer::new(b"unterminated"); + lex.label(ETX); + assert!(lex.done()); + } +} From 89deb7fac4d4c9114499574417aa34760277aaef Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 16 Nov 2026 23:21:59 -0500 Subject: [PATCH 07/15] feat(lottie): expose raw gradient wire values without opacity elision --- ATTRIBUTION.md | 4 ++++ crates/lottie/src/gradient.rs | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 9d260300c..21ff5a2f4 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -114,3 +114,7 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper ## GIMP palette reader `crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. + +The raw gradient wire ordering in `craft-lottie::Gradient::flat_values` follows +AniCraft's Lottie exporter by Tanish Manku (`63b39355`, `b9258b7b`), MIT OR Apache-2.0. +Sanitization, animation fitting and numeric output policy remain caller-owned. diff --git a/crates/lottie/src/gradient.rs b/crates/lottie/src/gradient.rs index 7edd60025..afb8495fd 100644 --- a/crates/lottie/src/gradient.rs +++ b/crates/lottie/src/gradient.rs @@ -29,6 +29,17 @@ impl Gradient { Some(Self { colors, opacities }) } + /// Raw color groups (`position, r, g, b`), followed by all opacity pairs + /// (`position, alpha`), in input order. No rounding, clamping, or opacity elision. + /// + /// This allocation-free view lets callers fit or interpolate equal-sized animated + /// values before applying their own numeric policy. In particular, opaque alpha + /// stops remain present so an opaque frame can interpolate to a translucent one. + /// Non-finite values are preserved; callers must sanitize them before JSON output. + pub fn flat_values(&self) -> impl Iterator + '_ { + self.colors.iter().flat_map(|(p, [r, g, b])| [*p, *r, *g, *b]).chain(self.opacities.iter().flat_map(|(p, a)| [*p, *a])) + } + /// The flat list, rounded to six decimals. The alpha pairs are left out when every stop is /// opaque. pub fn to_flat(&self) -> Json { @@ -44,3 +55,4 @@ impl Gradient { json!(out) } } + From c2ae800d87ff5a6266c2e0818ee7a18d72f97e25 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:21:59 -0500 Subject: [PATCH 08/15] test(lottie): preserve raw gradient precision and alpha topology --- crates/lottie/src/gradient.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/lottie/src/gradient.rs b/crates/lottie/src/gradient.rs index afb8495fd..0c9a9608f 100644 --- a/crates/lottie/src/gradient.rs +++ b/crates/lottie/src/gradient.rs @@ -56,3 +56,24 @@ impl Gradient { } } +#[cfg(test)] +mod raw_tests { + use super::*; + + #[test] + fn raw_values_keep_order_precision_and_opaque_alpha() { + let g = Gradient { colors: vec![(0.123456789, [0.2, 0.3, 0.4]), (1.0, [0.5, 0.6, 0.7])], opacities: vec![(0.0, 1.0), (1.0, 1.0)] }; + assert_eq!(g.flat_values().collect::>(), vec![0.123456789, 0.2, 0.3, 0.4, 1.0, 0.5, 0.6, 0.7, 0.0, 1.0, 1.0, 1.0]); + assert_eq!(g.to_flat(), json!([0.123457, 0.2, 0.3, 0.4, 1.0, 0.5, 0.6, 0.7])); + } + + #[test] + fn raw_values_keep_nonfinite_signed_zero_and_unpaired_lists() { + let g = Gradient { colors: vec![], opacities: vec![(-0.0, f64::NAN), (f64::INFINITY, f64::NEG_INFINITY)] }; + let bits: Vec<_> = g.flat_values().map(f64::to_bits).collect(); + assert_eq!(bits, [-0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY].map(f64::to_bits)); + assert_eq!(Gradient::default().flat_values().count(), 0); + let g = Gradient { colors: vec![(1e303, [1.0, 0.0, 0.0])], opacities: vec![] }; + assert_eq!(g.flat_values().collect::>(), [1e303, 1.0, 0.0, 0.0]); + } +} From e66b3a79549bc951f9ebbd2783c2972401de72d7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:23:25 -0500 Subject: [PATCH 09/15] zip: support bounded aligned stored entry options Co-authored-by: bflatastic --- ATTRIBUTION.md | 4 +++ crates/zip/src/write.rs | 21 ++++++++++++- crates/zip/tests/aligned_writer.rs | 49 ++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 crates/zip/tests/aligned_writer.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 9d260300c..d676c47c0 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -114,3 +114,7 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper ## GIMP palette reader `crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes. + +## Aligned stored ZIP entries + +The USDZ alignment requirement and compatibility fixture for `Writer::add_stored_aligned` come from TextureCraft `crates/formats/src/mesh_export/usd.rs`, introduced by bflatastic in `bdbb52c9` and maintained through `9eb20086` (MIT OR Apache-2.0). The shared API and alignment validation are subsequent Dylan M. Taylor work. Scene/material mapping remains in TextureCraft. diff --git a/crates/zip/src/write.rs b/crates/zip/src/write.rs index e1fdfad9e..6e62c6f20 100644 --- a/crates/zip/src/write.rs +++ b/crates/zip/src/write.rs @@ -44,6 +44,24 @@ impl Writer { /// Adds an entry from a byte slice. A name the archive already has is an error. pub fn add(&mut self, name: &str, data: &[u8], compression: Compression) -> Result<(), Error> { + self.add_entry(name, data, compression, 1) + } + + /// Adds a stored entry whose payload starts on an `alignment`-byte boundary. + /// + /// USDZ uses 64. Only powers of two from 1 through 4096 are accepted, bounding + /// per-entry padding. This does not impose a total archive-size budget; callers + /// retain their format-specific size and name policies. Discard the writer after + /// a write error, just as for [`Self::add`]. Invalid alignment is rejected before + /// starting an entry. + pub fn add_stored_aligned(&mut self, name: &str, data: &[u8], alignment: u16) -> Result<(), Error> { + if !alignment.is_power_of_two() || alignment > 4096 { + return Err(Error::Write("alignment must be a power of two between 1 and 4096".into())); + } + self.add_entry(name, data, Compression::Stored, alignment) + } + + fn add_entry(&mut self, name: &str, data: &[u8], compression: Compression, alignment: u16) -> Result<(), Error> { let (method, level) = match compression { Compression::Stored => (zip::CompressionMethod::Stored, None), Compression::Deflated => (zip::CompressionMethod::Deflated, Some(6)), @@ -53,7 +71,8 @@ impl Writer { .compression_method(method) .compression_level(level) .last_modified_time(zip::DateTime::default()) - .large_file(data.len() as u64 >= u64::from(u32::MAX) / 2); + .large_file(data.len() as u64 >= u64::from(u32::MAX) / 2) + .with_alignment(alignment); let fail = |e: &dyn std::fmt::Display| Error::Write(format!("{name}: {e}")); self.zip.start_file(name, options).map_err(|e| fail(&e))?; self.zip.write_all(data).map_err(|e| fail(&e)) diff --git a/crates/zip/tests/aligned_writer.rs b/crates/zip/tests/aligned_writer.rs new file mode 100644 index 000000000..03c664e5b --- /dev/null +++ b/crates/zip/tests/aligned_writer.rs @@ -0,0 +1,49 @@ +use craft_zip::{Compression, Writer}; +use std::io::{Cursor, Read, Write}; + +#[test] +fn aligned_stored_matches_previous_usdz_writer() { + for tail in 0..128 { + let payload = vec![37u8; tail]; + let entries: [(&str, &[u8]); 3] = [("scene.usdc", b"PXR-USDC"), ("textures/synthetic.png", &payload), ("empty", b"")]; + let mut shared = Writer::new(); + let mut previous = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).with_alignment(64); + for (name, data) in entries { + shared.add_stored_aligned(name, data, 64).unwrap(); + previous.start_file(name, options).unwrap(); + previous.write_all(data).unwrap(); + } + let bytes = shared.finish().unwrap(); + assert_eq!(bytes, previous.finish().unwrap().into_inner()); + let mut archive = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap(); + for (i, (name, expected)) in entries.iter().enumerate() { + let mut file = archive.by_index(i).unwrap(); + assert_eq!(file.name().unwrap(), *name); + assert_eq!(file.compression(), zip::CompressionMethod::Stored); + assert_eq!(file.data_start().unwrap() % 64, 0); + let mut actual = Vec::new(); + file.read_to_end(&mut actual).unwrap(); + assert_eq!(actual, *expected); + } + } +} + +#[test] +fn invalid_alignment_does_not_start_entry_and_duplicates_fail() { + let mut writer = Writer::new(); + for alignment in [0, 3, 65, 8192, u16::MAX] { + assert!(writer.add_stored_aligned("layer", b"data", alignment).is_err()); + } + writer.add_stored_aligned("layer", b"data", 64).unwrap(); + assert!(writer.add_stored_aligned("layer", b"again", 64).is_err()); +} + +#[test] +fn alignment_one_retains_ordinary_stored_bytes() { + let mut ordinary = Writer::new(); + ordinary.add("entry", b"data", Compression::Stored).unwrap(); + let mut aligned = Writer::new(); + aligned.add_stored_aligned("entry", b"data", 1).unwrap(); + assert_eq!(ordinary.finish().unwrap(), aligned.finish().unwrap()); +} From 6128eabbfb98e5fe486fa7ee4413724e2a4ca908 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:24:27 -0500 Subject: [PATCH 10/15] Keep aligned stored entry headers compatible with USDZ exporter --- crates/zip/src/write.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/zip/src/write.rs b/crates/zip/src/write.rs index 6e62c6f20..451729759 100644 --- a/crates/zip/src/write.rs +++ b/crates/zip/src/write.rs @@ -44,11 +44,13 @@ impl Writer { /// Adds an entry from a byte slice. A name the archive already has is an error. pub fn add(&mut self, name: &str, data: &[u8], compression: Compression) -> Result<(), Error> { - self.add_entry(name, data, compression, 1) + self.add_entry(name, data, compression, 1, data.len() as u64 >= u64::from(u32::MAX) / 2) } /// Adds a stored entry whose payload starts on an `alignment`-byte boundary. /// + /// Entries use ordinary ZIP headers, matching the USDZ writer this replaces; + /// oversized entries fail rather than opting into ZIP64 headers. /// USDZ uses 64. Only powers of two from 1 through 4096 are accepted, bounding /// per-entry padding. This does not impose a total archive-size budget; callers /// retain their format-specific size and name policies. Discard the writer after @@ -58,10 +60,10 @@ impl Writer { if !alignment.is_power_of_two() || alignment > 4096 { return Err(Error::Write("alignment must be a power of two between 1 and 4096".into())); } - self.add_entry(name, data, Compression::Stored, alignment) + self.add_entry(name, data, Compression::Stored, alignment, false) } - fn add_entry(&mut self, name: &str, data: &[u8], compression: Compression, alignment: u16) -> Result<(), Error> { + fn add_entry(&mut self, name: &str, data: &[u8], compression: Compression, alignment: u16, large_file: bool) -> Result<(), Error> { let (method, level) = match compression { Compression::Stored => (zip::CompressionMethod::Stored, None), Compression::Deflated => (zip::CompressionMethod::Deflated, Some(6)), @@ -71,7 +73,7 @@ impl Writer { .compression_method(method) .compression_level(level) .last_modified_time(zip::DateTime::default()) - .large_file(data.len() as u64 >= u64::from(u32::MAX) / 2) + .large_file(large_file) .with_alignment(alignment); let fail = |e: &dyn std::fmt::Display| Error::Write(format!("{name}: {e}")); self.zip.start_file(name, options).map_err(|e| fail(&e))?; From 6181ae557fdf27cdf63052c6db5d21a7d31a0010 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:26:35 -0500 Subject: [PATCH 11/15] feat(lottie): flatten borrowed gradient stops without temporary buffers --- crates/lottie/src/gradient.rs | 14 +++++++++++++- crates/lottie/src/lib.rs | 2 +- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/lottie/src/gradient.rs b/crates/lottie/src/gradient.rs index 0c9a9608f..a3dff7314 100644 --- a/crates/lottie/src/gradient.rs +++ b/crates/lottie/src/gradient.rs @@ -4,6 +4,18 @@ use serde_json::json; use crate::{Json, nums, round6}; +/// Raw gradient wire values from borrowed or mapped stops, without intermediate allocation. +/// +/// Yields color groups (`position, r, g, b`) then every opacity pair (`position, alpha`). +/// Input order and all values, including non-finite values and opaque alpha, are preserved. +/// Sanitization, rounding, and input/output size budgets remain the caller's responsibility. +pub fn flat_gradient_values( + colors: impl IntoIterator, + opacities: impl IntoIterator, +) -> impl Iterator { + colors.into_iter().flat_map(|(p, [r, g, b])| [p, r, g, b]).chain(opacities.into_iter().flat_map(|(p, a)| [p, a])) +} + /// A gradient: colour stops and opacity stops, each at a position in 0..=1. #[derive(Debug, Clone, Default, PartialEq)] pub struct Gradient { @@ -37,7 +49,7 @@ impl Gradient { /// stops remain present so an opaque frame can interpolate to a translucent one. /// Non-finite values are preserved; callers must sanitize them before JSON output. pub fn flat_values(&self) -> impl Iterator + '_ { - self.colors.iter().flat_map(|(p, [r, g, b])| [*p, *r, *g, *b]).chain(self.opacities.iter().flat_map(|(p, a)| [*p, *a])) + flat_gradient_values(self.colors.iter().copied(), self.opacities.iter().copied()) } /// The flat list, rounded to six decimals. The alpha pairs are left out when every stop is diff --git a/crates/lottie/src/lib.rs b/crates/lottie/src/lib.rs index 16c1c6e07..578939d6b 100644 --- a/crates/lottie/src/lib.rs +++ b/crates/lottie/src/lib.rs @@ -30,7 +30,7 @@ mod prop; mod value; pub mod zip; -pub use gradient::Gradient; +pub use gradient::{Gradient, flat_gradient_values}; pub use model::{Animated, Animation, Layer, LayerContent, Limits, Shape, ShapeKind}; pub use path::Bezier; pub use prop::{Ease, Key, KeyOut, Prop, PropValue, Tangents, is_animated, read_prop, tangent, write_keys, write_prop}; From 763b0f32a14e1db748d55486688d5d285faad4fd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 03:19:11 -0500 Subject: [PATCH 12/15] Only select PJL language for ENTER commands --- crates/plotter/src/hpgl/lex.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/plotter/src/hpgl/lex.rs b/crates/plotter/src/hpgl/lex.rs index b64ad0785..26e97bf08 100644 --- a/crates/plotter/src/hpgl/lex.rs +++ b/crates/plotter/src/hpgl/lex.rs @@ -119,7 +119,11 @@ impl<'a> Lexer<'a> { let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1); // A command names its language within its first 256 bytes; longer lines aren't copied. let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase(); - if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) { + // COMMENT/ECHO text may mention LANGUAGE without changing the printer language. + if let Some((command, language)) = line.split_once("LANGUAGE") + && command.split_ascii_whitespace().eq(["@PJL", "ENTER"]) + { + let lang = language.trim_start_matches([' ', '=']).trim(); self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl }; } self.at += end; @@ -431,6 +435,15 @@ impl<'a> Lexer<'a> { mod tests { use super::*; + #[test] + fn pjl_comments_do_not_select_a_language() { + for command in ["COMMENT LANGUAGE=PCL", "ECHO ENTER LANGUAGE=PCL", "SET LANGUAGE=PCL"] { + let bytes = format!("\x1b%-12345X@PJL {command}\n@PJL ENTER LANGUAGE=HPGL2\nIN;"); + assert_eq!(Lexer::new(bytes.as_bytes()).op(true), Some(*b"IN")); + } + assert_eq!(Lexer::new(b"\x1b%-12345X@pjl\tenter\tlanguage=HPGL2\r\nIN;").op(true), Some(*b"IN")); + } + #[test] fn framing_labels_and_bounded_numbers() { let mut lex = Lexer::new(b"\x1b%-12345X@PJL ENTER LANGUAGE=HPGL2\nIN;LBPU999;\x03PA1,2,3,4;SP2;"); From 1b7ab973faa750b18e528bfa1879b7afb94e65bc Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 03:24:53 -0500 Subject: [PATCH 13/15] Document intentional PJL language recovery correction --- crates/plotter/README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/plotter/README.md b/crates/plotter/README.md index d35c2b114..ecfea2309 100644 --- a/crates/plotter/README.md +++ b/crates/plotter/README.md @@ -86,7 +86,10 @@ label/comment skipping and encoded polyline values. It does not interpret drawin commands or replace the existing cutter encoder. The caller supplies numeric storage and controls document/geometry budgets; scanning time is proportional to input consumed, not capped by this API. PJL language detection copies at most 256 -bytes of a line. Malformed-input recovery retains the original VectorCraft behavior. +bytes of a line. Malformed-input recovery retains the original VectorCraft behavior, +except that only `@PJL ENTER LANGUAGE` selects a language: COMMENT/ECHO/SET text +mentioning LANGUAGE no longer hides subsequent HP-GL commands. This is not a full +PJL validator; the remaining permissive language-value handling is unchanged. This module comes from dotCooCoo's VectorCraft `crates/cad/src/hpgl/lex.rs`, commit `74ea25cd6c4dffa4cd41f6ee9a76f7afd4225622` (MIT OR Apache-2.0), From 20baec266a3e73df5b06a7c65443f9d4cb770ddf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 05:43:28 -0500 Subject: [PATCH 14/15] Accept horizontal tabs around PJL language separator --- crates/plotter/src/hpgl/lex.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/plotter/src/hpgl/lex.rs b/crates/plotter/src/hpgl/lex.rs index 26e97bf08..534ec8ebc 100644 --- a/crates/plotter/src/hpgl/lex.rs +++ b/crates/plotter/src/hpgl/lex.rs @@ -123,7 +123,7 @@ impl<'a> Lexer<'a> { if let Some((command, language)) = line.split_once("LANGUAGE") && command.split_ascii_whitespace().eq(["@PJL", "ENTER"]) { - let lang = language.trim_start_matches([' ', '=']).trim(); + let lang = language.trim_start_matches([' ', '\t', '=']).trim(); self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl }; } self.at += end; @@ -444,6 +444,11 @@ mod tests { assert_eq!(Lexer::new(b"\x1b%-12345X@pjl\tenter\tlanguage=HPGL2\r\nIN;").op(true), Some(*b"IN")); } + #[test] + fn pjl_language_separator_accepts_horizontal_tabs() { + assert_eq!(Lexer::new(b"\x1b%-12345X@PJL ENTER LANGUAGE\t=\tHPGL2\nIN;").op(true), Some(*b"IN")); + } + #[test] fn framing_labels_and_bounded_numbers() { let mut lex = Lexer::new(b"\x1b%-12345X@PJL ENTER LANGUAGE=HPGL2\nIN;LBPU999;\x03PA1,2,3,4;SP2;"); From 64fcd9531ae2f6a8f9498478805cfc7228189a9b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:13:52 -0500 Subject: [PATCH 15/15] Add shared span-preserving JSONC editor (#2030) --- ATTRIBUTION.md | 4 + Cargo.lock | 7 + Cargo.toml | 1 + crates/jsonc/Cargo.toml | 12 + crates/jsonc/src/lib.rs | 619 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 643 insertions(+) create mode 100644 crates/jsonc/Cargo.toml create mode 100644 crates/jsonc/src/lib.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index ab2cf7c6f..4c86afd61 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -128,3 +128,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## Screen Video key frames `crates/video/src/screen_video.rs` extracts AniCraft `crates/xfl/src/video.rs` codec-3 decoding and its synthetic partial-block fixture, introduced by Tanish Manku in `1f3e603b7ff53a3da364e41ec4da8d43dc83aab0` with pixel-loop cleanup `2b7571363b4b647266df758f95b6e397021cfd4d` (MIT OR Apache-2.0). Import commits preserve Tanish as primary author. Caller-owned bounds and neutral RGBA output separate codec work from the consuming app's FLV first-frame/report policy. Boundary tests and integration are subsequent Dylan M. Taylor changes. + +## JSONC span-preserving editing + +`crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported. diff --git a/Cargo.lock b/Cargo.lock index a9290398b..9fa1f4401 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2272,6 +2272,13 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "craft-jsonc" +version = "0.1.0" +dependencies = [ + "serde_json", +] + [[package]] name = "craft-jsonrpc" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index f25abd6d1..50ec3c917 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/craft-libs" [workspace.dependencies] +craft-jsonc = { path = "crates/jsonc" } craft-palette = { path = "crates/palette" } craft-score = { path = "crates/score" } craft-shx = { path = "crates/shx" } diff --git a/crates/jsonc/Cargo.toml b/crates/jsonc/Cargo.toml new file mode 100644 index 000000000..eca4538cf --- /dev/null +++ b/crates/jsonc/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "craft-jsonc" +description = "Span-preserving JSON/JSONC object editor with strict mode and caller-controlled input admission" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +[lints] +workspace = true +[dependencies] +serde_json = { workspace = true } diff --git a/crates/jsonc/src/lib.rs b/crates/jsonc/src/lib.rs new file mode 100644 index 000000000..003b9b02d --- /dev/null +++ b/crates/jsonc/src/lib.rs @@ -0,0 +1,619 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! A small JSON-with-comments editor that changes only the bytes it must. +//! +//! The text is tokenized (comments and trailing commas tolerated), parsed into a tree that keeps +//! every value's byte span, and edits are applied by splicing new text into the original. Comments, +//! formatting and key order elsewhere in the file are untouched. In strict mode comments and +//! trailing commas are rejected (for clients whose own parser is strict JSON). + +use serde_json::{Map, Value}; + +/// Deepest nesting accepted (hostile files must not blow the stack). +const MAX_DEPTH: usize = 128; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Tok { + LBrace, + RBrace, + LBracket, + RBracket, + Colon, + Comma, + Str, + Scalar, +} + +#[derive(Debug, Clone, Copy)] +struct Token { + kind: Tok, + start: usize, + end: usize, +} + +/// A parsed value with its span in the source. +#[derive(Debug, Clone)] +pub struct Node { + pub start: usize, + pub end: usize, + pub kind: NodeKind, +} + +#[derive(Debug, Clone)] +pub enum NodeKind { + Object { members: Vec, trailing_comma: bool }, + Array(Vec), + Scalar(Value), +} + +#[derive(Debug, Clone)] +pub struct Member { + pub key: String, + pub key_start: usize, + pub value: Node, +} + +/// A parsed document: the original text plus the tree. +#[derive(Debug, Clone)] +pub struct Doc { + pub text: String, + /// `None` for an empty (or whitespace/comment-only) file. + pub root: Option, + tokens: Vec, +} + +fn tokenize(text: &str, strict: bool) -> Result, String> { + let b = text.as_bytes(); + let mut i = 0usize; + if text.starts_with('\u{feff}') { + if strict { + return Err("byte-order mark is not allowed".into()); + } + i = 3; + } + let mut out = Vec::new(); + while let Some(&c) = b.get(i) { + match c { + b' ' | b'\t' | b'\r' | b'\n' => i += 1, + b'/' if b.get(i + 1) == Some(&b'/') => { + if strict { + return Err(format!("comment at byte {i} is not allowed in strict JSON")); + } + while let Some(&c) = b.get(i) { + if matches!(c, b'\r' | b'\n') { + break; + } + i += 1; + } + } + b'/' if b.get(i + 1) == Some(&b'*') => { + if strict { + return Err(format!("comment at byte {i} is not allowed in strict JSON")); + } + let start = i; + i += 2; + loop { + match b.get(i) { + None => return Err(format!("unterminated comment starting at byte {start}")), + Some(b'*') if b.get(i + 1) == Some(&b'/') => { + i += 2; + break; + } + Some(_) => i += 1, + } + } + } + b'{' | b'}' | b'[' | b']' | b':' | b',' => { + let kind = match c { + b'{' => Tok::LBrace, + b'}' => Tok::RBrace, + b'[' => Tok::LBracket, + b']' => Tok::RBracket, + b':' => Tok::Colon, + _ => Tok::Comma, + }; + out.push(Token { kind, start: i, end: i + 1 }); + i += 1; + } + b'"' => { + let start = i; + i += 1; + loop { + match b.get(i) { + None => return Err(format!("unterminated string starting at byte {start}")), + Some(b'\\') => i += 2, + Some(b'"') => { + i += 1; + break; + } + Some(b'\n') => return Err(format!("line break inside string at byte {i}")), + Some(_) => i += 1, + } + } + out.push(Token { kind: Tok::Str, start, end: i }); + } + c if c == b'-' || c.is_ascii_alphanumeric() || c == b'.' || c == b'+' => { + let start = i; + while let Some(&c) = b.get(i) { + if c == b'-' || c.is_ascii_alphanumeric() || c == b'.' || c == b'+' { + i += 1; + } else { + break; + } + } + out.push(Token { kind: Tok::Scalar, start, end: i }); + } + _ => return Err(format!("unexpected character at byte {i}")), + } + } + Ok(out) +} + +struct Parser<'a> { + text: &'a str, + toks: &'a [Token], + pos: usize, + strict: bool, +} + +impl Parser<'_> { + fn peek(&self) -> Option { + self.toks.get(self.pos).copied() + } + + fn next(&mut self) -> Result { + let t = self.peek().ok_or_else(|| "unexpected end of file".to_string())?; + self.pos += 1; + Ok(t) + } + + fn slice(&self, t: Token) -> &str { + self.text.get(t.start..t.end).unwrap_or_default() + } + + fn value(&mut self, depth: usize) -> Result { + if depth > MAX_DEPTH { + return Err("nested too deeply".into()); + } + let t = self.next()?; + match t.kind { + Tok::LBrace => { + let mut members = Vec::new(); + let mut trailing_comma = false; + loop { + let n = self.peek().ok_or("unterminated object")?; + if n.kind == Tok::RBrace { + self.pos += 1; + if trailing_comma && self.strict { + return Err(format!("trailing comma before byte {}", n.start)); + } + return Ok(Node { start: t.start, end: n.end, kind: NodeKind::Object { members, trailing_comma } }); + } + if !members.is_empty() && !trailing_comma { + return Err(format!("expected , or }} at byte {}", n.start)); + } + let k = self.next()?; + if k.kind != Tok::Str { + return Err(format!("expected a key at byte {}", k.start)); + } + let key: String = serde_json::from_str(self.slice(k)).map_err(|e| format!("bad key at byte {}: {e}", k.start))?; + let c = self.next()?; + if c.kind != Tok::Colon { + return Err(format!("expected : at byte {}", c.start)); + } + let value = self.value(depth + 1)?; + members.push(Member { key, key_start: k.start, value }); + trailing_comma = false; + if self.peek().is_some_and(|t| t.kind == Tok::Comma) { + self.pos += 1; + trailing_comma = true; + } + } + } + Tok::LBracket => { + let mut items = Vec::new(); + let mut comma = false; + loop { + let n = self.peek().ok_or("unterminated array")?; + if n.kind == Tok::RBracket { + self.pos += 1; + if comma && self.strict { + return Err(format!("trailing comma before byte {}", n.start)); + } + return Ok(Node { start: t.start, end: n.end, kind: NodeKind::Array(items) }); + } + if !items.is_empty() && !comma { + return Err(format!("expected , or ] at byte {}", n.start)); + } + items.push(self.value(depth + 1)?); + comma = false; + if self.peek().is_some_and(|t| t.kind == Tok::Comma) { + self.pos += 1; + comma = true; + } + } + } + Tok::Str | Tok::Scalar => { + let v: Value = serde_json::from_str(self.slice(t)).map_err(|_| format!("bad value at byte {}", t.start))?; + Ok(Node { start: t.start, end: t.end, kind: NodeKind::Scalar(v) }) + } + _ => Err(format!("unexpected token at byte {}", t.start)), + } + } +} + +impl Node { + pub fn to_value(&self) -> Value { + match &self.kind { + NodeKind::Scalar(v) => v.clone(), + NodeKind::Array(items) => Value::Array(items.iter().map(Node::to_value).collect()), + NodeKind::Object { members, .. } => { + let mut m = Map::new(); + for mem in members { + m.insert(mem.key.clone(), mem.value.to_value()); + } + Value::Object(m) + } + } + } + + fn member(&self, key: &str) -> Option<&Member> { + match &self.kind { + NodeKind::Object { members, .. } => members.iter().rev().find(|m| m.key == key), + _ => None, + } + } +} + +/// Parse `text`. `strict` rejects comments, trailing commas and a BOM. +/// +/// Compatibility entry point: no implicit byte cap. Callers must bound input and +/// edit values according to their context. Nesting is capped at 128; token/tree +/// storage scales with input. Use [`parse_bounded`] to reject oversized text +/// before tokenization. This does not impose an edit-output budget. +pub fn parse(text: &str, strict: bool) -> Result { + let tokens = tokenize(text, strict)?; + if tokens.is_empty() { + return Ok(Doc { text: text.to_string(), root: None, tokens }); + } + let mut p = Parser { text, toks: &tokens, pos: 0, strict }; + let root = p.value(0)?; + if p.pos != tokens.len() { + return Err("extra content after the top-level value".into()); + } + if !matches!(root.kind, NodeKind::Object { .. }) { + return Err("the top level must be an object".into()); + } + Ok(Doc { text: text.to_string(), root: Some(root), tokens }) +} + +impl Doc { + pub fn to_value(&self) -> Value { + self.root.as_ref().map(Node::to_value).unwrap_or_else(|| Value::Object(Map::new())) + } + + /// The value at `path` (object keys only). + pub fn get(&self, path: &[&str]) -> Option { + let mut node = self.root.as_ref()?; + for k in path { + node = &node.member(k)?.value; + } + Some(node.to_value()) + } + + fn line_start(&self, pos: usize) -> usize { + self.text.get(..pos).and_then(|s| s.rfind(['\r', '\n'])).map(|i| i + 1).unwrap_or(0) + } + + fn indent_at(&self, pos: usize) -> String { + let ls = self.line_start(pos); + self.text.get(ls..).unwrap_or_default().chars().take_while(|c| *c == ' ' || *c == '\t').collect() + } + + /// True when only whitespace precedes `pos` on its line. + fn first_on_line(&self, pos: usize) -> bool { + let ls = self.line_start(pos); + self.text.get(ls..pos).is_some_and(|s| s.trim().is_empty()) + } + + /// Set `path` to `value`, creating intermediate objects. Returns the new text. + pub fn set(&self, path: &[&str], value: &Value) -> Result { + let Some((last, parents)) = path.split_last() else { return Err("empty path".into()) }; + let Some(root) = &self.root else { + // No object yet: retain comments, whitespace and an optional BOM before the new one. + let mut v = value.clone(); + for k in path.iter().rev() { + let mut m = Map::new(); + m.insert((*k).to_string(), v); + v = Value::Object(m); + } + let mut s = self.text.clone(); + let eol = self.eol(); + if !s.is_empty() && !s.ends_with(['\r', '\n']) { + s.push_str(eol); + } + s.push_str(&render(&v, "", eol)); + s.push_str(eol); + return Ok(s); + }; + // Walk down as far as the path exists. + let mut node = root; + let mut depth = 0; + for k in parents { + match node.member(k) { + Some(m) if matches!(m.value.kind, NodeKind::Object { .. }) => { + node = &m.value; + depth += 1; + } + Some(_) => return Err(format!("\"{k}\" exists but is not an object")), + None => break, + } + } + if depth == parents.len() + && let Some(m) = node.member(last) + { + // Replace the existing value in place. + let indent = self.indent_at(m.key_start); + let rendered = render(value, &indent, self.eol()); + return Ok(splice(&self.text, &[(m.value.start, m.value.end, rendered)])); + } + // Insert a new member (holding the rest of the path) into `node`. + let rest = path.get(depth..).unwrap_or_default(); + let Some((first, tail)) = rest.split_first() else { return Err("empty path".into()) }; + let mut v = value.clone(); + for k in tail.iter().rev() { + let mut m = Map::new(); + m.insert((*k).to_string(), v); + v = Value::Object(m); + } + self.insert_member(node, first, &v) + } + + /// Preserve CRLF and CR-only documents; otherwise use LF. + fn eol(&self) -> &'static str { + if self.text.contains("\r\n") { + "\r\n" + } else if self.text.contains('\r') && !self.text.contains('\n') { + "\r" + } else { + "\n" + } + } + + /// Add `key: value` as the last member of `obj`, indented like the members already there. + fn insert_member(&self, obj: &Node, key: &str, value: &Value) -> Result { + let NodeKind::Object { members, trailing_comma } = &obj.kind else { return Err("not an object".into()) }; + let close = obj.end.saturating_sub(1); + let close_indent = self.indent_at(obj.start); + let indent = match members.first() { + Some(m) if self.first_on_line(m.key_start) => self.indent_at(m.key_start), + _ => format!("{close_indent} "), + }; + let eol = self.eol(); + let key_json = serde_json::to_string(key).map_err(|e| e.to_string())?; + // An object whose members all end in a comma gets a new member that does too. + let comma = if *trailing_comma { "," } else { "" }; + let member = format!("{indent}{key_json}: {}{comma}", render(value, &indent, eol)); + let mut edits = Vec::new(); + if let Some(last) = members.last() + && !trailing_comma + { + edits.push((last.value.end, last.value.end, ",".to_string())); + } + if self.first_on_line(close) && !members.is_empty() { + let ls = self.line_start(close); + edits.push((ls, ls, format!("{member}{eol}"))); + } else { + // `{}` or `{ "a": 1 }` on one line: open it up. + let inner_end = close; + let before = self.text.get(..inner_end).unwrap_or_default(); + let trimmed_end = before.trim_end().len().max(obj.start + 1); + edits.push((trimmed_end, inner_end, format!("{eol}{member}{eol}{close_indent}"))); + } + Ok(splice(&self.text, &edits)) + } + + /// Remove every member at `path`. Returns the new text, or `None` if it was not there. + pub fn remove(&self, path: &[&str]) -> Option { + let (last, parents) = path.split_last()?; + let mut node = self.root.as_ref()?; + for k in parents { + node = &node.member(k)?.value; + } + let NodeKind::Object { members, .. } = &node.kind else { return None }; + let mut edits = Vec::new(); + // Remove members separately so comments between duplicates survive. + // A final run's leading comma is a separate edit for the same reason. + for run in members.split(|m| m.key != *last) { + let Some(first) = run.first() else { continue }; + let before_idx = self.tokens.partition_point(|t| t.end <= first.key_start); + let before = before_idx.checked_sub(1).and_then(|i| self.tokens.get(i)).copied().filter(|t| t.kind == Tok::Comma); + for member in run { + let after_idx = self.tokens.partition_point(|t| t.start < member.value.end); + let after = self.tokens.get(after_idx).copied().filter(|t| t.kind == Tok::Comma); + let with_comma = after.is_none_or(|c| self.text.get(member.value.end..c.start).is_some_and(|gap| gap.trim().is_empty())); + let member_end = if with_comma { after.map(|t| t.end).unwrap_or(member.value.end) } else { member.value.end }; + let rest = self.text.get(member_end..).unwrap_or_default(); + let line_rest = rest.split(['\r', '\n']).next().unwrap_or_default(); + let own_lines = self.first_on_line(member.key_start) && line_rest.trim().is_empty(); + let (start, end) = if own_lines { + let line_end = member_end + line_rest.len(); + let eol_len = + if self.text.get(line_end..).is_some_and(|s| s.starts_with("\r\n")) { 2 } else { usize::from(rest.len() > line_rest.len()) }; + (self.line_start(member.key_start), line_end + eol_len) + } else { + (member.key_start, member_end) + }; + edits.push((start, end, String::new())); + if !with_comma && let Some(c) = after { + edits.push((c.start, c.end, String::new())); + } + // The last member had no comma after it, so the one before it goes: leaving it + // would add a trailing comma the file didn't have, which plain JSON readers refuse. + if after.is_none() + && let Some(c) = before + { + edits.push((c.start, c.end, String::new())); + } + } + } + (!edits.is_empty()).then(|| splice(&self.text, &edits)) + } +} + +/// Pretty-print `value` with continuation lines indented by `indent`. +fn render(value: &Value, indent: &str, eol: &str) -> String { + let s = serde_json::to_string_pretty(value).unwrap_or_else(|_| "null".into()); + let mut out = String::new(); + for (i, line) in s.lines().enumerate() { + if i > 0 { + out.push_str(eol); + out.push_str(indent); + } + out.push_str(line); + } + out +} + +/// Apply non-overlapping edits `(start, end, replacement)`. +fn splice(text: &str, edits: &[(usize, usize, String)]) -> String { + let mut sorted: Vec<&(usize, usize, String)> = edits.iter().collect(); + sorted.sort_by_key(|e| (e.0, e.1)); + let mut out = String::with_capacity(text.len() + 256); + let mut pos = 0; + for (s, e, r) in sorted { + if *s < pos { + continue; + } + out.push_str(text.get(pos..*s).unwrap_or_default()); + out.push_str(r); + pos = *e; + } + out.push_str(text.get(pos..).unwrap_or_default()); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const FIXTURE: &str = r#"// user settings +{ + /* theme */ + "theme": "dark", // trailing note + "mcpServers": { + "other": { "command": "x" }, // keep me + }, +} +"#; + + #[test] + fn set_keeps_crlf_line_endings() { + for src in ["{\r\n \"a\": 1\r\n}\r\n", "{}\r\n"] { + let d = parse(src, true).unwrap(); + let out = d.set(&["z"], &json!({"k": [1]})).unwrap(); + assert_eq!(out.matches('\n').count(), out.matches("\r\n").count(), "mixed line endings: {out:?}"); + assert_eq!(parse(&out, true).unwrap().get(&["z", "k"]), Some(json!([1]))); + } + } + + #[test] + fn a_carriage_return_ends_a_line_comment() { + let text = "// editor settings\r{\r \"keep\": 1, // explanation\r \"port\": 2\r}\r"; + let doc = parse(text, false).unwrap(); + assert_eq!(doc.get(&["keep"]), Some(json!(1))); + let updated = doc.set(&["port"], &json!(3)).unwrap(); + assert_eq!(updated, text.replace('2', "3")); + assert_eq!(parse(&updated, false).unwrap().get(&["port"]), Some(json!(3))); + assert!(parse(text, true).is_err()); + } + + #[test] + fn parses_comments_and_trailing_commas() { + let d = parse(FIXTURE, false).unwrap(); + assert_eq!(d.get(&["mcpServers", "other", "command"]), Some(json!("x"))); + assert!(parse(FIXTURE, true).is_err()); + assert!(parse("{\"a\": 1,}", true).is_err()); + assert!(parse("{\"a\": 1}", true).is_ok()); + assert!(parse("[1]", false).is_err()); + assert!(parse("{", false).is_err()); + assert!(parse("", false).unwrap().root.is_none()); + } + + #[test] + fn insert_keeps_comments_and_reparses() { + let d = parse(FIXTURE, false).unwrap(); + let new = d.set(&["mcpServers", "craft-anything"], &json!({"command": "/x/craft-anything-cli", "args": ["mcp"]})).unwrap(); + assert!(new.contains("// keep me") && new.contains("/* theme */") && new.contains("// user settings")); + let d2 = parse(&new, false).unwrap(); + assert_eq!(d2.get(&["mcpServers", "craft-anything", "args"]), Some(json!(["mcp"]))); + assert_eq!(d2.get(&["mcpServers", "other", "command"]), Some(json!("x"))); + // replace in place + let new2 = d2.set(&["mcpServers", "craft-anything"], &json!({"command": "y"})).unwrap(); + let d3 = parse(&new2, false).unwrap(); + assert_eq!(d3.get(&["mcpServers", "craft-anything"]), Some(json!({"command": "y"}))); + // remove restores the original exactly + assert_eq!(d3.remove(&["mcpServers", "craft-anything"]).unwrap(), FIXTURE); + } + + #[test] + fn creates_missing_tables_and_handles_empty() { + let d = parse("{}", true).unwrap(); + let new = d.set(&["mcp", "servers", "k"], &json!(1)).unwrap(); + assert_eq!(parse(&new, true).unwrap().get(&["mcp", "servers", "k"]), Some(json!(1))); + let d = parse("{\n \"a\": 1\n}\n", true).unwrap(); + let new = d.set(&["s", "k"], &json!(true)).unwrap(); + assert_eq!(new, "{\n \"a\": 1,\n \"s\": {\n \"k\": true\n }\n}\n"); + let empty = parse(" \n", false).unwrap().set(&["s", "k"], &json!(2)).unwrap(); + assert_eq!(parse(&empty, true).unwrap().get(&["s", "k"]), Some(json!(2))); + let one_line = parse(r#"{"a": {"b": 1}}"#, true).unwrap().set(&["a", "c"], &json!(2)).unwrap(); + assert_eq!(parse(&one_line, true).unwrap().to_value(), json!({"a": {"b": 1, "c": 2}})); + } + + #[test] + fn remove_first_middle_last() { + let text = "{\n \"a\": 1,\n \"b\": 2,\n \"c\": 3\n}\n"; + let d = parse(text, true).unwrap(); + for (k, rest) in [("a", json!({"b":2,"c":3})), ("b", json!({"a":1,"c":3})), ("c", json!({"a":1,"b":2}))] { + let t = d.remove(&[k]).unwrap(); + assert_eq!(parse(&t, true).unwrap().to_value(), rest, "{t}"); + } + assert!(d.remove(&["zz"]).is_none()); + let single = parse("{\"a\": 1}", true).unwrap().remove(&["a"]).unwrap(); + assert_eq!(parse(&single, true).unwrap().to_value(), json!({})); + } + + #[test] + fn hostile_input_never_panics() { + for s in ["{\"a\":", "{\"a\" 1}", "{,}", "\"\\", "/*", "{\"a\":[1,,2]}", "{\"a\":1}}", &"[".repeat(1000), "\u{feff}{}"] { + let _ = parse(s, false); + let _ = parse(s, true); + } + assert!(parse("\u{feff}{}", false).is_ok()); + } +} + +/// Reject input larger than `max_bytes` before tokenizing, then use [`parse`]. +/// This bounds admitted input, not allocator overhead or subsequent edit output. +pub fn parse_bounded(text: &str, strict: bool, max_bytes: usize) -> Result { + if text.len() > max_bytes { + return Err(format!("JSONC input exceeds {max_bytes} bytes")); + } + parse(text, strict) +} + +#[cfg(test)] +mod admission_tests { + use super::*; + #[test] + fn byte_limit_is_explicit_and_precedes_syntax_work() { + assert!(parse_bounded("{}", false, 2).is_ok()); + assert_eq!(parse_bounded("{", false, 0).unwrap_err(), "JSONC input exceeds 0 bytes"); + assert!(parse_bounded("", false, 0).is_ok()); + let text = "{\"é\":1}"; + assert!(parse_bounded(text, false, text.len() - 1).is_err()); + assert_eq!(parse_bounded(text, false, text.len()).unwrap().to_value(), parse(text, false).unwrap().to_value()); + } +}