From 4b740e0075e413a7acc91edb52fbf2c5b368aa0b Mon Sep 17 00:00:00 2001 From: alehel Date: Sat, 14 Nov 2026 21:18:45 +0100 Subject: [PATCH 001/130] craft-audio: ALAC shifts off fewer low bytes in quiet 24- and 32-bit packets (#1368) Apple's reference stores 1 (24-bit) or 2 (32-bit) low bytes of every sample uncompressed, so a 4096-frame stereo packet of 24-bit silence was 8224 bytes. Each element now shifts off the fewest bytes that keep its samples one bit narrower than the reference's prediction width. A 32-bit pair keeps at least one byte, since the format allows no wider prediction. Co-Authored-By: Claude Opus 5.5 --- crates/audio/README.md | 2 +- crates/audio/src/alac/encoder.rs | 123 +++++++++++++++++++++++++++--- crates/audio/src/alac/mod.rs | 4 +- crates/audio/tests/codecs/alac.rs | 36 +++++++++ 4 files changed, 153 insertions(+), 12 deletions(-) diff --git a/crates/audio/README.md b/crates/audio/README.md index 5a5df4f2f5..8546bc6a7b 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -540,7 +540,7 @@ Each codec module's rustdoc lists the coding tools it implements. | 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 | | 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 | +| 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 (except 24- and 32-bit packets quiet enough to shift off fewer low bytes, such as silence), same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | ### MP3 encoding diff --git a/crates/audio/src/alac/encoder.rs b/crates/audio/src/alac/encoder.rs index a589a9060a..2c7773e715 100644 --- a/crates/audio/src/alac/encoder.rs +++ b/crates/audio/src/alac/encoder.rs @@ -8,7 +8,11 @@ //! //! The search (stereo matrixing, 4 or 8 predictor coefficients) and the state kept across //! packets (coefficients, the last matrixing, and the buffers the trial runs read stale parts of) -//! follow the reference, so for the same input this writes the same packets as it. +//! follow the reference, so for the same input this writes the same packets as it, with one +//! exception: the shifted-off low bytes. The reference passes 1 (24-bit) or 2 (32-bit) low bytes +//! of every sample through uncompressed, even for silence. Here an element shifts off fewer bytes +//! in a packet whose samples fit well within the width the reference predicts (see +//! [`packet_shift`]), so silence and quiet passages are not padded with a byte or two per sample. use super::ag::{self, AgParams}; use super::bits::{BitCounter, BitSink, BitWriter}; @@ -100,6 +104,25 @@ fn bytes_shifted(bit_depth: u32) -> u32 { } } +/// The bytes an element shifts off in one packet: the fewest, down from the reference's +/// [`bytes_shifted`], that leave every sample at least one bit narrower than the width the +/// reference predicts (`bit_depth − 8 · bytes_shifted`). The predictor then works on values no +/// wider than in the reference, so its arithmetic stays in the same range; only fewer low bytes go +/// out uncompressed. The spare bit is there because at the full width, coding the low byte through +/// the predictor costs about as much as storing it, and for 24-bit mono measured 2% more. +/// A 32-bit pair keeps at least 1: with none, its prediction width (33 bits) exceeds the 32 the +/// format allows. +fn packet_shift(bit_depth: u32, channels: &[&[i32]]) -> u32 { + let reference = bytes_shifted(bit_depth); + let width = bit_depth - reference * 8 - 1; + let floor = u32::from(bit_depth == 32 && channels.len() == 2); + let fits = |bytes: u32| { + let (lo, hi) = (-(1i64 << (width - 1)), (1i64 << (width - 1)) - 1); + channels.iter().flat_map(|c| c.iter()).all(|&x| (lo..=hi).contains(&i64::from(x >> (bytes * 8)))) + }; + (floor..reference).find(|&b| fits(b)).unwrap_or(reference) +} + impl Encoder { /// An encoder for `cfg`. pub fn new(cfg: EncoderConfig) -> Result { @@ -191,11 +214,12 @@ impl Encoder { w.put(cpe_tag, 4); cpe_tag += 1; let (l, r) = (channels[index], channels[index + 1]); + let bs = packet_shift(self.bit_depth, &[l, r]); // as in the reference, fast mode applies to stereo streams only if self.cfg.fast && channels.len() == 2 { - self.encode_stereo_fast(&mut w, index, l, r)?; + self.encode_stereo_fast(&mut w, index, l, r, bs)?; } else { - self.encode_stereo(&mut w, index, l, r)?; + self.encode_stereo(&mut w, index, l, r, bs)?; } index += 2; } @@ -203,7 +227,8 @@ impl Encoder { let tag = if element == ID_LFE { &mut lfe_tag } else { &mut sce_tag }; w.put(*tag, 4); *tag += 1; - self.encode_mono(&mut w, index, channels[index])?; + let bs = packet_shift(self.bit_depth, &[channels[index]]); + self.encode_mono(&mut w, index, channels[index], bs)?; index += 1; } } @@ -231,10 +256,10 @@ impl Encoder { } /// `EncodeStereo`: a channel pair with the matrixing and coefficient search. - fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> { + /// `bs`: the bytes shifted off, from [`packet_shift`]. + fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = l.len(); - let bs = bytes_shifted(self.bit_depth); let chan_bits = self.bit_depth - bs * 8 + 1; let partial = self.partial(n); let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0); @@ -329,10 +354,9 @@ impl Encoder { } /// `EncodeStereoFast`: a channel pair without matrixing or search. - fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> { + fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = l.len(); - let bs = bytes_shifted(self.bit_depth); let chan_bits = self.bit_depth - bs * 8 + 1; let partial = self.partial(n); let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0); @@ -396,10 +420,9 @@ impl Encoder { } /// `EncodeMono`: one channel (SCE or LFE). - fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32]) -> Result<()> { + fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = input.len(); - let bs = bytes_shifted(self.bit_depth); let shift = bs * 8; let chan_bits = self.bit_depth - shift; let partial = self.partial(n); @@ -577,4 +600,84 @@ mod tests { assert!(enc.encode(&[&[40_000], &[0]]).is_err()); assert!(enc.encode(&[&[-32_768], &[32_767]]).is_ok()); } + + /// One packet of `frames` frames per element, encoded and decoded back; its size in bytes. + fn packet_bytes(cfg: EncoderConfig, input: &[Vec]) -> usize { + let mut enc = Encoder::new(cfg).unwrap(); + let chunk: Vec<&[i32]> = input.iter().map(Vec::as_slice).collect(); + let p = enc.encode(&chunk).unwrap(); + let mut dec = Decoder::new(&enc.cookie()).unwrap(); + assert_eq!(dec.decode(&p).unwrap(), input, "{cfg:?}"); + p.len() + } + + /// The reference shifts 1 (24-bit) or 2 (32-bit) low bytes of every sample off and stores them + /// uncompressed, so a 4096-frame stereo packet of 24-bit silence was 8224 bytes (#1368). + #[test] + fn silence_is_a_few_bytes_at_every_depth() { + for bits in [16, 20, 24, 32] { + for ch in [1, 2, 6] { + for fast in [false, true] { + let cfg = EncoderConfig::new(48_000, ch, bits).with_fast(fast); + let bytes = packet_bytes(cfg, &vec![vec![0; 4096]; usize::from(ch)]); + // a 32-bit pair keeps one shifted byte per sample: the format allows no less + let floor = if bits == 32 { 4096 * 2 * (usize::from(ch) / 2) } else { 0 }; + assert!(bytes <= floor + 40 * usize::from(ch), "{bits} bits, {ch} ch, fast {fast}: {bytes} bytes"); + } + } + } + } + + /// Quiet audio (within 12 bits) at 24 and 32 bits shifts nothing off and comes within 10% of + /// the same audio at 16 bits (the wider prediction width makes the coder's escapes longer); + /// the reference stored a byte or two more per sample. Samples at the edges of each width and + /// loud audio decode exactly. + #[test] + fn quiet_packets_compress_like_16_bit_audio_and_loud_ones_round_trip() { + let quiet = signal(4096, 2, 12); + let at16 = packet_bytes(EncoderConfig::new(48_000, 2, 16), &quiet); + let at24 = packet_bytes(EncoderConfig::new(48_000, 2, 24), &quiet); + assert!(at24 * 10 <= at16 * 11, "24-bit {at24} bytes, 16-bit {at16}"); + let mono = vec![quiet[0].clone()]; + let at16 = packet_bytes(EncoderConfig::new(48_000, 1, 16), &mono); + let at32 = packet_bytes(EncoderConfig::new(48_000, 1, 32), &mono); + assert!(at32 * 10 <= at16 * 11, "32-bit mono {at32} bytes, 16-bit {at16}"); + // the samples just past each narrower width, and loud audio, decode exactly + for bits in [24u32, 32] { + for ch in [1u8, 2] { + let edge: Vec> = (0..ch) + .map(|c| { + (0..4096) + .map(|i| match (i + usize::from(c)) % 4 { + 0 => (16_384 << (bits - 24)) - 1, + 1 => -(16_384 << (bits - 24)), + 2 => 16_384 << (bits - 24), + _ => -(16_384 << (bits - 24)) - 1, + }) + .collect() + }) + .collect(); + packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &edge); + packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &signal(4096, usize::from(ch), bits)); + } + } + } + + #[test] + fn the_shift_is_the_fewest_bytes_that_keep_the_reference_width() { + let z = [0i32; 4]; + assert_eq!(packet_shift(16, &[&z]), 0); + assert_eq!(packet_shift(24, &[&z, &z]), 0); + assert_eq!(packet_shift(24, &[&[16_383, -16_384], &z]), 0); + assert_eq!(packet_shift(24, &[&[16_384], &z]), 1); + assert_eq!(packet_shift(24, &[&[-16_385]]), 1); + assert_eq!(packet_shift(24, &[&[32_767]]), 1); + assert_eq!(packet_shift(32, &[&z]), 0); + assert_eq!(packet_shift(32, &[&[16_383]]), 0); + assert_eq!(packet_shift(32, &[&z, &z]), 1); + assert_eq!(packet_shift(32, &[&[1 << 21]]), 1); + assert_eq!(packet_shift(32, &[&[1 << 22]]), 2); + assert_eq!(packet_shift(32, &[&[i32::MIN]]), 2); + assert_eq!(packet_shift(32, &[&[i32::MAX], &z]), 2); + } } diff --git a/crates/audio/src/alac/mod.rs b/crates/audio/src/alac/mod.rs index a797d1ab68..5547cc47ce 100644 --- a/crates/audio/src/alac/mod.rs +++ b/crates/audio/src/alac/mod.rs @@ -23,7 +23,9 @@ //! reference: hostile input returns errors instead of reading or writing out of bounds, integer //! arithmetic wraps where C would overflow, the 4- and 8-tap predictor loops are folded into the //! general one (same values), the sample-width variants of the matrix routines into one routine -//! over `i32`, and the encoder fills in the cookie's average bit rate. +//! over `i32`, the encoder fills in the cookie's average bit rate, and it shifts off fewer low +//! bytes in packets whose samples fit a narrower width (silence and quiet passages at 24 and 32 +//! bits), where the reference always passes them through uncompressed. // The bit I/O, coder, predictor and matrix modules serve both halves; with only one of // `alac-decode` and `alac-encode` built, the other half's routines are unused. diff --git a/crates/audio/tests/codecs/alac.rs b/crates/audio/tests/codecs/alac.rs index 5b42f2e836..a29e898a34 100644 --- a/crates/audio/tests/codecs/alac.rs +++ b/crates/audio/tests/codecs/alac.rs @@ -153,3 +153,39 @@ fn ffmpeg_decodes_our_alac_exactly() { } } } + +/// Quiet and silent passages at 24 and 32 bits, which our encoder codes with fewer shifted-off +/// low bytes than Apple's reference (#1368), decode exactly in ffmpeg. The packets alternate +/// between silence, audio within 12 bits, audio at the narrower widths' edges and full scale, so +/// one stream changes its shift from packet to packet. +#[test] +fn ffmpeg_decodes_our_quiet_alac_exactly() { + let Some(ff) = crate::testkit::ffmpeg_or_skip("alac oracle") else { return }; + for (channels, bits) in [(1, 24), (2, 24), (6, 24), (1, 32), (2, 32)] { + let full = input(channels, bits, 4 * 4096); + let wav: Vec> = full + .iter() + .map(|c| { + c.iter() + .enumerate() + .map(|(i, &x)| match i / 4096 { + 0 => 0, + 1 => x >> (bits - 12), + 2 => (x >> (bits - 15)) << (bits - 24), + _ => x, + }) + .collect() + }) + .collect(); + // ffmpeg does not decode escaped 32-bit stereo frames: keep the full-scale packet for 24 + let wav: Vec> = if bits == 32 { wav.iter().map(|c| c[..3 * 4096].to_vec()).collect() } else { wav }; + let m4a = our_m4a(&wav, bits, 4096); + let path = dir().join(format!("ours_quiet_{channels}ch_{bits}.m4a")); + std::fs::write(&path, &m4a).unwrap(); + let theirs = ffmpeg_decode(&ff, &path, channels, bits); + assert!(theirs == wav, "{channels} ch, {bits} bits: ffmpeg's decode differs from the input"); + if bits <= 24 { + assert!(our_decode(&m4a, bits) == wav, "{channels} ch, {bits} bits: our decode differs"); + } + } +} From 6c7f2159ac37478fae0b88cc55f5e24262d46cbc Mon Sep 17 00:00:00 2001 From: alehel Date: Sat, 14 Nov 2026 21:59:14 +0100 Subject: [PATCH 002/130] craft-audio: PacketEncoder, one packet interface over the encoders PacketEncoder::new(codec, &EncodeOptions, sample_rate, channels) covers AAC-LC, ALAC, MP3, AC-3, E-AC-3 and Opus, each behind its feature. It takes planar f32 in WAV channel order, maps the channels onto the codec's order (quantizing for ALAC at the configured depth), and returns EncodedPacket { data, pts, duration }; finish() drains the rest. The encoder reports codec_params() (codec, rate, channels, extradata), layout(), priming(), padding(), bitrate() and bit_depth() for a muxer. FileEncoder's coded formats now go through it: the codec dispatch, channel maps and rate selection moved from write/coded.rs to packet.rs, and coded.rs keeps only the M4A and raw sinks. The files written are byte-identical to before. Refs #1230 (point 3). Co-Authored-By: Claude Opus 5.5 --- crates/audio/Cargo.toml | 3 +- crates/audio/README.md | 76 +- crates/audio/src/lib.rs | 21 + crates/audio/src/packet.rs | 683 ++++++++++++++++++ .../src/{write/coded => packet}/tests.rs | 24 +- crates/audio/src/write/coded.rs | 411 ++--------- crates/audio/src/write/mod.rs | 2 +- crates/audio/tests/codecs/main.rs | 1 + crates/audio/tests/codecs/packet_encoder.rs | 239 ++++++ 9 files changed, 1098 insertions(+), 362 deletions(-) create mode 100644 crates/audio/src/packet.rs rename crates/audio/src/{write/coded => packet}/tests.rs (90%) create mode 100644 crates/audio/tests/codecs/packet_encoder.rs diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index d132f23da2..38781ec845 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -23,7 +23,7 @@ decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa- # The symphonia fallback for the formats with no native decoder yet. symphonia = ["decode-native", "dep:symphonia"] # Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders. -# All but Opus are also file formats of `encode` and `FileEncoder`. +# All but Opus are also file formats of `encode` and `FileEncoder`; all are codecs of `PacketEncoder`. encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode"] # Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files. lossless-encode = ["pcm-encode", "flac-encode"] @@ -36,6 +36,7 @@ aac-decode = ["craft-media/bitstream"] # The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`. aac-encode = ["craft-media/bitstream", "craft-media/isobmff"] opus-decode = [] +# The Opus encoder (`opus::encoder`), and Opus through `PacketEncoder`. opus-encode = [] ac3-decode = ["craft-media/bitstream"] mpa-decode = ["craft-media/bitstream"] diff --git a/crates/audio/README.md b/crates/audio/README.md index 5a5df4f2f5..5e5922ebdc 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -33,15 +33,15 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | | `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | -| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` | +| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` | | `alac-decode` | `alac::Decoder` | none | -| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` | -| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none | +| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A; `PacketEncoder` for ALAC | craft-media `isobmff` | +| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder`; with `opus-encode`, `PacketEncoder` for Opus | none | | `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` | -| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` | +| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams; `PacketEncoder` for them | craft-media `bitstream` | | `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` | +| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3; `PacketEncoder` for MP3 | craft-media `bitstream` | | `peaks` | `peaks::Peaks` | none | | `rayon` | parallel AAC encoding (with `aac-encode`) | `rayon` | | `serde` | `Serialize`/`Deserialize` on the shared types | `serde` | @@ -304,12 +304,72 @@ file needs that step before it is written again. An M4A's edit list skips the AAC encoder's priming (1024 frames) and ends at the last frame written, so the file decodes to the length that went in. An MP3, AC-3 or E-AC-3 stream has no -place for that (see [Limits](#limits)). For a container of your own, use the codec modules below. +place for that (see [Limits](#limits)). For a container of your own, use `PacketEncoder` below. + +### Encode packets for your own container + +`PacketEncoder` is the encode-side counterpart of `TrackDecoder`: one interface over the AAC-LC, +ALAC, MP3, AC-3, E-AC-3 and Opus encoders for an app that muxes the audio itself (a video export +to MP4, Matroska or MXF). It returns packets and writes no file; `FileEncoder` writes its coded +formats through it. + +```rust +use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder}; + +let opts = EncodeOptions::new(EncodeFormat::Aac).with_layout(info.layout).with_bitrate(384_000); +let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 6)?; +for block in blocks { // planar f32 in WAV order, any length + for p in enc.encode(&block.channels, block.frames())? { + mux.write(p.pts, p.duration, &p.data)?; // pts and duration in samples at the rate + } +} +for p in enc.finish()? { + mux.write(p.pts, p.duration, &p.data)?; +} +let params = enc.codec_params(); // codec, rate, channels, extradata: what TrackDecoder::new takes +let priming = enc.priming(); // decoded samples before the first input frame +let padding = enc.padding(); // decoded samples after the last one +``` + +It takes the `EncodeOptions` of `FileEncoder` and reads `rate_control`, `layout`, and for ALAC +`bit_depth` and `dither`; `format` is ignored, so `EncodeOptions::default()` with a bit rate will +do for any codec. Input is planar `f32` in WAV channel order. `layout` names the speakers, the +channels are reordered into the codec's order, and ALAC's samples are quantized to the bit depth. +`layout()` reports the speakers the stream carries, in WAV order: the codec's layout for the count +(AAC's 5.1 has side surrounds, ALAC's back surrounds), or the AC-3 coding mode the layout chose. + +| `CodecId` | Feature | Frames per packet | `extradata()` | `priming()` | +|---|---|---|---|---| +| `Aac` (LC) | `aac-encode` | 1024 | `AudioSpecificConfig` | 1024 | +| `Alac` | `alac-encode` | 4096, the last one shorter | `alac` box payload / CodecPrivate | 0 | +| `Mp3` | `mp3-encode` | 1152 (576 below 32 kHz), one frame per packet | empty | 1057 | +| `Ac3`, `Eac3` | `ac3-encode`, `eac3-encode` | 1536 | empty | 256 | +| `Opus` | `opus-encode` | 960 (20 ms) | `OpusHead` | the pre-skip | + +The sample rates, channel counts and layouts are those of the `EncodeFormat` of the same name; +Opus takes 48 kHz mono or stereo at a constant bit rate, 64 kbit/s per channel by default. A codec +with no encoder here, and one whose feature is off, are `Unsupported`; settings a codec cannot take +get the error `EncodeOptions::check` gives for the format. + +Timing: a packet's `pts` is where its decoded audio starts, counted from the first decoded sample, +so input frame `n` is at `n + priming()`. `finish` pads the end with silence until a decoder +returns every input frame, and the durations add up to `priming() + frames() + padding()`. A muxer +skips the priming (MP4: `TrackConfig::media_start` or an edit list; Matroska: `CodecDelay`; Opus: +the pre-skip, which `OpusHead` already holds) and trims the padding (the end of an MP4 edit, +Matroska's `DiscardPadding`). ALAC's `extradata` records the largest packet and the average bit +rate, so read it after `finish`. `bitrate()` is the constant rate used (`None` for ALAC and AAC by +quality); `bit_depth()` is ALAC's. + +`encode` refuses a block without one slice per channel, or with a slice shorter than `frames`, +and encodes nothing. After `finish`, or after an encode that failed, every call returns an error. +E-AC-3 7.1 is encoded as 7.1, and this crate's `TrackDecoder` plays its 5.1 substream (see +[Limits](#limits)). ### Encode AAC packets -For an `.m4a` file, use `EncodeFormat::Aac` above. `aac::Encoder` is the packet encoder behind it, -for muxing into a container of your own: +For an `.m4a` file, use `EncodeFormat::Aac` above, and for packets in WAV channel order, +`PacketEncoder`. `aac::Encoder` is the codec's own encoder behind both, with the settings +`EncodeOptions` does not have (bandwidth, TNS, M/S stereo, window shape, ADTS): ```rust use craft_audio::AudioError; diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 1c6c73dcfe..64a94995b4 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -20,6 +20,9 @@ //! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`, //! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature //! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder. +//! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`, +//! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC, +//! MP3, AC-3, E-AC-3 or Opus, with their timing and codec configuration, for an app's own muxer. //! - [`wav_pcm`], [`aiff_pcm`] (feature `decode-native`) and [`pcm_wav_file`], [`pcm_wav_header`], //! [`pcm_aiff_file`], [`pcm_aiff_header`] (feature `pcm-encode`): the integer PCM of a WAV or AIFF //! file bit for bit, and minimal files around such PCM, for essence embedded in other containers. @@ -45,6 +48,15 @@ pub mod mp3; pub mod mpa; #[cfg(any(feature = "opus-decode", feature = "opus-encode"))] pub mod opus; +#[cfg(any( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" +))] +mod packet; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] mod pcm; #[cfg(feature = "peaks")] @@ -96,6 +108,15 @@ pub use buffer::AudioBuffer; pub use craft_media; pub use craft_media::{ByteSource, CodecId, CodecParams, Container, PcmFormat, ReadSeekSource}; pub use layout::{ChannelLayout, Speaker}; +#[cfg(any( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" +))] +pub use packet::{EncodedPacket, PacketEncoder}; #[cfg(feature = "decode-native")] pub use read::SharedSource; #[cfg(feature = "decode-native")] diff --git a/crates/audio/src/packet.rs b/crates/audio/src/packet.rs new file mode 100644 index 0000000000..4f2d6cb8c4 --- /dev/null +++ b/crates/audio/src/packet.rs @@ -0,0 +1,683 @@ +//! [`PacketEncoder`]: one interface over the AAC-LC, ALAC, MP3, AC-3, E-AC-3 and Opus encoders, for +//! a caller that puts the packets in its own container. It takes planar `f32` in WAV channel order, +//! maps the channels onto the codec's order, and returns packets with their timing; the coded +//! formats of [`FileEncoder`](crate::FileEncoder) are written through it. + +// Each codec is its own feature: with only some of them built, the other halves of the shared +// code are unused. +#![cfg_attr( + not(all( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" + )), + allow(dead_code, unused_imports, unused_variables, unused_mut) +)] + +use crate::layout::channel_map; +use crate::{AudioError, ChannelLayout, CodecId, CodecParams, EncodeFormat, EncodeOptions, RateControl, Result}; + +/// Frames handed to a codec at a time, so its buffers and the packets returned for one call stay +/// small however long a block is. Also the frames of an ALAC packet. +pub(crate) const CHUNK: usize = 4096; + +/// Bits per second per channel when no rate is asked for: AAC and Opus. +const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; +const OPUS_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; +/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per +/// full-bandwidth channel). +const DEFAULT_KBPS_PER_CHANNEL: u32 = 96; + +/// Opus's layouts by channel count: RFC 7845 mapping family 0 (mono, and stereo as L R). +const OPUS_LAYOUT_MASKS: [&[u32]; 2] = [&[0x4], &[0x3]]; + +/// One packet from a [`PacketEncoder`]. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EncodedPacket { + /// The coded bytes: an AAC raw data block (no ADTS header), an ALAC packet, one MP3 frame, + /// one AC-3 syncframe or an E-AC-3 access unit, one Opus packet. + pub data: Vec, + /// Where the packet's decoded audio starts, in samples at the sample rate from the first + /// decoded sample of the stream. The encoder's [priming](PacketEncoder::priming) comes first, + /// so input frame `n` is at `n + priming`. + pub pts: u64, + /// The samples per channel the packet decodes to, the last packet's padding included. + pub duration: u32, +} + +/// Encodes audio to packets of one codec, for a muxer of the caller's own: the encode-side +/// counterpart of [`TrackDecoder`](crate::TrackDecoder). Built from a [`CodecId`] and the +/// [`EncodeOptions`] of [`FileEncoder`](crate::FileEncoder), of which it reads the rate control, +/// the layout, and for ALAC the bit depth and dither. +/// +/// Input is planar `f32` in WAV channel order, one slice per channel, at any block size; packets +/// come out as they are completed, and [`finish`](Self::finish) returns the rest. What a container +/// needs to describe the track is on the encoder: [`codec_params`](Self::codec_params) (codec, +/// rate, channels and [`extradata`](Self::extradata)), [`layout`](Self::layout), +/// [`priming`](Self::priming), and after `finish` [`padding`](Self::padding). +/// +/// | Codec | Feature | Packet | `extradata` | Priming | +/// |---|---|---|---|---| +/// | [`CodecId::Aac`] (LC) | `aac-encode` | 1024 frames | `AudioSpecificConfig` | 1024 | +/// | [`CodecId::Alac`] | `alac-encode` | 4096 frames | the `alac` box / CodecPrivate | 0 | +/// | [`CodecId::Mp3`] | `mp3-encode` | 1152 frames (576 below 32 kHz) | none | 1057 | +/// | [`CodecId::Ac3`], [`CodecId::Eac3`] | `ac3-encode`, `eac3-encode` | 1536 frames | none | 256 | +/// | [`CodecId::Opus`] | `opus-encode` | 960 frames (20 ms) | `OpusHead` | the pre-skip | +/// +/// ``` +/// # #[cfg(all(feature = "aac-encode", feature = "aac-decode"))] { +/// use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder, TrackDecoder}; +/// +/// let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128_000); +/// let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 2)?; +/// let block = [vec![0.25f32; 4800], vec![-0.25f32; 4800]]; // 0.1 s, one Vec per channel +/// let mut packets = enc.encode(&block, 4800)?; +/// packets.extend(enc.finish()?); +/// assert_eq!(enc.priming(), 1024); +/// assert_eq!(packets.iter().map(|p| u64::from(p.duration)).sum::(), 1024 + 4800 + enc.padding()); +/// +/// // The description a muxer writes is what a decoder reads. +/// let mut dec = TrackDecoder::new(&enc.codec_params(), &[])?; +/// assert_eq!(dec.decode(&packets[0].data)?.frames(), 1024); +/// # } +/// # Ok::<(), craft_audio::AudioError>(()) +/// ``` +pub struct PacketEncoder { + codec: CodecId, + inner: Inner, + sample_rate: u32, + /// The speakers of the channels encoded, in WAV order. + layout: ChannelLayout, + /// For each codec channel, the caller's channel that feeds it. + map: Vec, + bitrate: Option, + /// The integer depth of a lossless codec. + bit_depth: Option, + /// Where the next packet starts. + pts: u64, + /// Frames of input taken. + frames: u64, + finished: bool, + /// Set when a call failed: the packets of that block are lost, so the stream has a gap and + /// every later call is refused. + failed: bool, +} + +impl std::fmt::Debug for PacketEncoder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PacketEncoder") + .field("codec", &self.codec) + .field("sample_rate", &self.sample_rate) + .field("layout", &self.layout) + .field("frames", &self.frames) + .finish_non_exhaustive() + } +} + +/// A packet encoder of one of the codecs, taking planar `f32` in its own channel order. +enum Inner { + #[cfg(feature = "aac-encode")] + Aac(Box), + #[cfg(feature = "alac-encode")] + Alac { + enc: Box, + quantizers: Vec, + /// Quantized samples of the packet being filled, per channel. + pending: Vec>, + }, + #[cfg(feature = "mp3-encode")] + Mp3 { + enc: Box, + /// Bytes the encoder returned that do not yet make a whole frame. + bytes: Vec, + }, + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Ac3 { + enc: Box, + /// The block with every sample finite and within ±1, as the encoder requires. + planes: Vec>, + }, + #[cfg(feature = "opus-encode")] + Opus { + enc: Box, + /// Interleaved samples of the frame being filled. + pending: Vec, + /// Frames of the decoded stream the packets so far cover. + coded: u64, + }, +} + +/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`. +fn labels(mask: u32) -> String { + ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::>().join(" ") +} + +/// The speakers of the caller's layout, for an error message. +fn given(layout: &ChannelLayout) -> String { + layout.mask().map_or_else(|| "without speaker assignment".into(), labels) +} + +/// [`channel_map`] for a codec with one layout per channel count (the first of `masks`), and +/// that layout; or why the audio does not fit. +fn fixed_map(masks: &[u32], name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result<(Vec, ChannelLayout)> { + let Some(&mask) = masks.first() else { + return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels()))); + }; + let map = channel_map(mask, order, layout).ok_or_else(|| { + AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout))) + })?; + Ok((map, ChannelLayout::from_mask(mask))) +} + +/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for +/// 8 channels configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc. +#[cfg(feature = "aac-encode")] +pub(super) fn aac_order(channels: usize) -> Option<&'static [usize]> { + if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) } +} + +/// The lowest AAC bit rate used, per channel: 6 kbit/s, and a quarter of the sample rate (256 +/// bits a frame). The encoder accepts less, and from about half of this down codes silence; a +/// stream of silence is no answer to a low bit rate (or to kbit/s given as bit/s). +#[cfg(feature = "aac-encode")] +fn aac_floor_per_channel(sample_rate: u32) -> u32 { + (sample_rate / 4).max(6000) +} + +/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a +/// quality of 0–1 spans the encoder's VBR range. +#[cfg(feature = "aac-encode")] +pub(super) fn aac_mode(rate: Option, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode { + use crate::aac::BitrateMode; + let (lo, hi) = crate::aac::cbr_range(sample_rate, channels); + let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo)); + // An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone. + let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps }; + match rate { + None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))), + Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)), + // NaN stays NaN, which the encoder refuses. + Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)), + } +} + +/// The bit rate in bits per second for a codec with constant bit rates only. +fn constant_bps(name: &str, rate: Option, default: u32) -> Result { + match rate { + None => Ok(default), + Some(RateControl::Bitrate(bps)) => Ok(bps), + Some(RateControl::Quality(_)) => { + Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality"))) + } + } +} + +/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding +/// mode whose speakers the layout names, at the nearest bit rate the stream can carry. +#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] +pub(super) fn ac3_config( + codec: crate::ac3::encoder::Codec, + sample_rate: u32, + layout: &ChannelLayout, + rate: Option, +) -> Result<(crate::ac3::encoder::Config, Vec)> { + use crate::ac3::encoder::{Codec, CodingMode, Config}; + use CodingMode::*; + let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" }; + let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; + let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| { + // 7.1 is an E-AC-3 programme with an LFE; the encoder has no other. + if mode == Surround71 && (codec != Codec::Eac3 || !lfe) { + return None; + } + let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe }; + let map = channel_map(config.channel_layout().mask()?, None, layout)?; + Some((config, map)) + }); + let Some((mut config, map)) = found else { + return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout)))); + }; + let full = config.mode.channels() as u32; + let want = constant_bps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full * 1000)? / 1000; + // What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of + // the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold. + let least = if config.mode == Surround71 { 384 } else { 32 * full }; + config.bitrate_kbps = match codec { + Codec::Ac3 => { + let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least); + crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor) + } + Codec::Eac3 => { + let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 }; + want.clamp(least, most.max(least)) + } + }; + Ok((config, map)) +} + +/// The feature a codec's encoder is built with, or `None` for a codec with no encoder here. +fn feature(codec: CodecId) -> Option<&'static str> { + Some(match codec { + CodecId::Aac => "aac-encode", + CodecId::Alac => "alac-encode", + CodecId::Mp3 => "mp3-encode", + CodecId::Ac3 => "ac3-encode", + CodecId::Eac3 => "eac3-encode", + CodecId::Opus => "opus-encode", + _ => return None, + }) +} + +impl PacketEncoder { + /// An encoder of `codec` for `channels` channels at `sample_rate`. Of `opts` it reads + /// `rate_control` and `layout` (as [`FileEncoder`](crate::FileEncoder) does: the speakers of + /// the caller's channels, mapped onto the codec's layout), and for ALAC `bit_depth` and + /// `dither`; `format`, `bwf` and `force_rf64` are for files and ignored. + /// + /// Opus takes 48 kHz mono or stereo at a constant bit rate (64 kbit/s per channel when none + /// is asked for); the others take what their [`EncodeFormat`] lists. A codec this crate has + /// no encoder for, and one whose feature is not built, are [`AudioError::Unsupported`]. A + /// rate, channel count, layout or rate control the codec cannot take is refused with the error + /// [`EncodeOptions::check`] gives for the format (`Unsupported` for a layout or rate control). + pub fn new(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, channels: u16) -> Result { + let Some(feature) = feature(codec) else { + return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))); + }; + let built = [ + (CodecId::Aac, cfg!(feature = "aac-encode")), + (CodecId::Alac, cfg!(feature = "alac-encode")), + (CodecId::Mp3, cfg!(feature = "mp3-encode")), + (CodecId::Ac3, cfg!(feature = "ac3-encode")), + (CodecId::Eac3, cfg!(feature = "eac3-encode")), + (CodecId::Opus, cfg!(feature = "opus-encode")), + ]; + if !built.contains(&(codec, true)) { + return Err(AudioError::Unsupported(format!("encoding {} needs the `{feature}` feature", codec.name()))); + } + let n = usize::from(channels); + // As the file writers word it. + if channels == 0 { + return Err(AudioError::Encode("buffer has no channels".into())); + } + if sample_rate == 0 { + return Err(AudioError::Encode("sample rate is 0".into())); + } + if let Some(layout) = &opts.layout + && layout.channels() != channels + { + return Err(AudioError::Encode(format!("a {}-channel layout for {channels} channels", layout.channels()))); + } + let given = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels)); + let (inner, map, layout, bitrate, bit_depth) = match codec { + #[cfg(feature = "aac-encode")] + CodecId::Aac => { + let (map, layout) = fixed_map(EncodeFormat::Aac.layout_masks(channels), "AAC", aac_order(n), &given)?; + let mode = aac_mode(opts.rate_control, sample_rate, n); + let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, n, 0) }; + let bitrate = match mode { + crate::aac::BitrateMode::Cbr(bps) => Some(bps), + crate::aac::BitrateMode::Vbr(_) => None, + }; + (Inner::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, layout, bitrate, None) + } + #[cfg(feature = "alac-encode")] + CodecId::Alac => { + let count = u8::try_from(channels).unwrap_or(u8::MAX); + let (map, layout) = fixed_map(EncodeFormat::Alac.layout_masks(channels), "ALAC", crate::alac::alac_order(count), &given)?; + let bits = match opts.bit_depth { + crate::BitDepth::Int16 => 16, + crate::BitDepth::Int24 => 24, + crate::BitDepth::Int32 => 32, + crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())), + }; + let config = crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32); + let enc = crate::alac::Encoder::new(config)?; + let quantizers = crate::write::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, n); + (Inner::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); n] }, map, layout, None, Some(bits)) + } + #[cfg(feature = "mp3-encode")] + CodecId::Mp3 => { + let (map, layout) = fixed_map(EncodeFormat::Mp3.layout_masks(channels), "MP3", None, &given)?; + let want = constant_bps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * u32::from(channels) * 1000)? / 1000; + // A sample rate MP3 has not is the encoder's to refuse. + let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want); + let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, n, kbps))?; + (Inner::Mp3 { enc: Box::new(enc), bytes: Vec::new() }, map, layout, Some(kbps.saturating_mul(1000)), None) + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + CodecId::Ac3 | CodecId::Eac3 => { + let which = if codec == CodecId::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 }; + let (config, map) = ac3_config(which, sample_rate, &given, opts.rate_control)?; + let enc = crate::ac3::encoder::Encoder::new(config)?; + let layout = enc.channel_layout(); + let bitrate = Some(config.bitrate_kbps.saturating_mul(1000)); + (Inner::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); n] }, map, layout, bitrate, None) + } + #[cfg(feature = "opus-encode")] + CodecId::Opus => { + let masks = n.checked_sub(1).and_then(|i| OPUS_LAYOUT_MASKS.get(i)).copied().unwrap_or_default(); + let (map, layout) = fixed_map(masks, "Opus", None, &given)?; + if sample_rate != 48_000 { + return Err(AudioError::Unsupported(format!("Opus is encoded at 48000 Hz, not {sample_rate} Hz"))); + } + let bps = constant_bps("Opus", opts.rate_control, OPUS_DEFAULT_BPS_PER_CHANNEL * u32::from(channels))?; + let enc = crate::opus::encoder::Encoder::new(channels as u8, bps)?; + let bitrate = Some(enc.bitrate()); + (Inner::Opus { enc: Box::new(enc), pending: Vec::new(), coded: 0 }, map, layout, bitrate, None) + } + #[allow(unreachable_patterns)] + _ => return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))), + }; + Ok(PacketEncoder { codec, inner, sample_rate, layout, map, bitrate, bit_depth, pts: 0, frames: 0, finished: false, failed: false }) + } + + /// The codec of the packets. + pub fn codec(&self) -> CodecId { + self.codec + } + + /// The sample rate of the audio and of the packets' timing. + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + /// The number of channels. + pub fn channels(&self) -> u16 { + self.layout.channels() + } + + /// The speakers of the channels encoded, in WAV order: the codec's layout for the channel + /// count (for AC-3 and E-AC-3, the coding mode's), which is what a decoder reports. Where the + /// codec has one surround pair, it is the codec's (AAC's 5.1 has side surrounds, ALAC's back + /// ones), whichever pair the caller's layout named. + pub fn layout(&self) -> ChannelLayout { + self.layout + } + + /// The constant bit rate in bits per second for all channels together, as + /// [`RateControl::Bitrate`] describes the rate the stream settles on; `None` for ALAC and + /// for AAC at a constant quality. + pub fn bitrate(&self) -> Option { + self.bitrate + } + + /// The bits per sample of a lossless codec (ALAC), `None` for the lossy ones. + pub fn bit_depth(&self) -> Option { + self.bit_depth + } + + /// The codec configuration a container stores: AAC's `AudioSpecificConfig` (MP4 `esds` + /// decoder-specific info, Matroska CodecPrivate), ALAC's configuration as MP4's `alac` box + /// and Matroska's CodecPrivate hold it, Opus's `OpusHead`; empty for MP3, AC-3 and E-AC-3. + /// ALAC's records the largest packet and the average bit rate so far, so read it after + /// [`finish`](Self::finish). + pub fn extradata(&self) -> Vec { + match &self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => enc.audio_specific_config(), + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, .. } => enc.cookie(), + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, .. } => enc.opus_head(), + #[allow(unreachable_patterns)] + _ => Vec::new(), + } + } + + /// The codec, sample rate, channels and [`extradata`](Self::extradata): the description + /// [`TrackDecoder::new`](crate::TrackDecoder::new) takes, and what a muxer's track needs. + pub fn codec_params(&self) -> CodecParams { + CodecParams::new(self.codec).with_sample_rate(self.sample_rate).with_channels(self.channels()).with_extradata(self.extradata()) + } + + /// Decoded samples before the first input frame: the encoder's delay, which a container + /// skips (an MP4 edit list's media time, Matroska's CodecDelay, Opus's pre-skip, which + /// `OpusHead` already holds). 0 for ALAC. + pub fn priming(&self) -> u32 { + match &self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => enc.priming_samples(), + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, .. } => enc.delay(), + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, .. } => enc.priming_samples(), + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, .. } => u32::from(enc.pre_skip()), + #[allow(unreachable_patterns)] + _ => 0, + } + } + + /// Frames of input taken so far. + pub fn frames(&self) -> u64 { + self.frames + } + + /// Decoded samples after the last input frame, which a container trims (the end of an MP4 + /// edit, Matroska's DiscardPadding): the packets' durations add up to + /// [`priming`](Self::priming) + [`frames`](Self::frames) + this. Complete after + /// [`finish`](Self::finish). + pub fn padding(&self) -> u64 { + self.pts.saturating_sub(u64::from(self.priming()).saturating_add(self.frames)) + } + + /// Encodes the first `frames` frames of `block`, one slice per channel in WAV order + /// (`&[Vec]`, `&[&[f32]]`, …), and returns the packets completed. Samples are full scale + /// at ±1; NaN is taken as 0, and what a codec cannot carry above full scale is clipped. + /// + /// `block` must have one slice per channel, each at least `frames` long; otherwise nothing is + /// encoded and the error is [`AudioError::Encode`]. A call after [`finish`](Self::finish) is + /// an error too. When encoding itself fails, the packets of the block are lost, and every + /// later call fails rather than return a stream with a gap. + pub fn encode>(&mut self, block: &[C], frames: usize) -> Result> { + self.usable()?; + let channels = usize::from(self.channels()); + if block.len() != channels { + return Err(AudioError::Encode(format!("a block of {} channels for a {channels}-channel stream", block.len()))); + } + if let Some(short) = block.iter().map(|c| c.as_ref().len()).filter(|&n| n < frames).min() { + return Err(AudioError::Encode(format!("{frames} frames asked for, but a channel holds {short}"))); + } + let mut out = Vec::new(); + for at in (0..frames).step_by(CHUNK) { + let end = frames.min(at + CHUNK); + let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect(); + if let Err(e) = self.push(&planes, &mut out) { + self.failed = true; + return Err(e); + } + self.frames = self.frames.saturating_add((end - at) as u64); + } + Ok(out) + } + + /// Encodes what the encoder still holds, padded with silence to whole packets and as far as + /// a decoder needs to return every input frame after the priming, and returns the last + /// packets. Later calls of [`encode`](Self::encode) and `finish` are errors; the description + /// ([`extradata`](Self::extradata), [`padding`](Self::padding)) stays readable. + pub fn finish(&mut self) -> Result> { + self.usable()?; + self.finished = true; + let mut out = Vec::new(); + let done = self.drain(&mut out); + if done.is_err() { + self.failed = true; + } + done.map(|()| out) + } + + fn usable(&self) -> Result<()> { + if self.failed { + Err(AudioError::Encode("the packet encoder already failed; its stream is incomplete".into())) + } else if self.finished { + Err(AudioError::Encode("the packet encoder is finished".into())) + } else { + Ok(()) + } + } + + /// Appends a packet of `duration` decoded samples at the current position. + fn emit(pts: &mut u64, out: &mut Vec, data: Vec, duration: u32) { + out.push(EncodedPacket { data, pts: *pts, duration }); + *pts = pts.saturating_add(u64::from(duration)); + } + + /// Encodes `planes` (one slice per codec channel, equally long, at most [`CHUNK`] frames) + /// and appends the packets completed. + fn push(&mut self, planes: &[&[f32]], out: &mut Vec) -> Result<()> { + let pts = &mut self.pts; + match &mut self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => { + for data in enc.encode(planes) { + Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32); + } + } + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, quantizers, pending } => { + let frames = planes.first().map_or(0, |p| p.len()); + let mut at = 0; + while at < frames { + let filled = pending.first().map_or(0, Vec::len); + let end = frames.min(at + CHUNK.saturating_sub(filled).max(1)); + for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) { + dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s))); + } + at = end; + if pending.first().is_some_and(|p| p.len() >= CHUNK) { + alac_packet(enc, pending, pts, out)?; + } + } + } + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, bytes } => { + bytes.extend(enc.encode(planes)); + mp3_frames(enc, bytes, pts, out)?; + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, planes: clean } => { + for (dst, src) in clean.iter_mut().zip(planes) { + dst.clear(); + dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })); + } + let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect(); + for p in enc.push(&refs)? { + Self::emit(pts, out, p.data, p.samples); + } + } + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, pending, coded } => { + let frames = planes.first().map_or(0, |p| p.len()); + for i in 0..frames { + pending.extend(planes.iter().map(|p| p.get(i).copied().map_or(0.0, |s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) }))); + if pending.len() == crate::opus::encoder::Encoder::FRAME_SIZE * planes.len() { + opus_packet(enc, pending, coded, pts, out)?; + } + } + } + } + Ok(()) + } + + /// Encodes what the codec still holds and appends the last packets. + fn drain(&mut self, out: &mut Vec) -> Result<()> { + let pts = &mut self.pts; + match &mut self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => { + for data in enc.flush() { + Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32); + } + } + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, pending, .. } => { + if pending.first().is_some_and(|p| !p.is_empty()) { + alac_packet(enc, pending, pts, out)?; + } + } + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, bytes } => { + bytes.extend(enc.flush()); + mp3_frames(enc, bytes, pts, out)?; + if !bytes.is_empty() { + return Err(AudioError::Encode(format!("the MP3 encoder ended with {} bytes that are not a whole frame", bytes.len()))); + } + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, .. } => { + for p in enc.finish()?.packets { + Self::emit(pts, out, p.data, p.samples); + } + } + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, pending, coded } => { + // Every input frame decodes after the pre-skip: as many packets as that takes. + let size = crate::opus::encoder::Encoder::FRAME_SIZE as u64; + let needed = if self.frames == 0 { 0 } else { (self.frames + u64::from(enc.pre_skip())).div_ceil(size) * size }; + let width = usize::from(enc.channels()); + while *coded < needed { + pending.resize(crate::opus::encoder::Encoder::FRAME_SIZE * width, 0.0); + opus_packet(enc, pending, coded, pts, out)?; + } + } + } + Ok(()) + } +} + +/// Encodes the pending samples as one ALAC packet and empties them. +#[cfg(feature = "alac-encode")] +fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec], pts: &mut u64, out: &mut Vec) -> Result<()> { + let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect(); + let frames = refs.first().map_or(0, |p| p.len()) as u32; + let data = enc.encode(&refs)?; + pending.iter_mut().for_each(Vec::clear); + PacketEncoder::emit(pts, out, data, frames); + Ok(()) +} + +/// Encodes one full frame of pending interleaved samples as an Opus packet and empties them. +#[cfg(feature = "opus-encode")] +fn opus_packet( + enc: &mut crate::opus::encoder::Encoder, + pending: &mut Vec, + coded: &mut u64, + pts: &mut u64, + out: &mut Vec, +) -> Result<()> { + let data = enc.encode_float(pending)?; + pending.clear(); + let size = crate::opus::encoder::Encoder::FRAME_SIZE as u32; + *coded += u64::from(size); + PacketEncoder::emit(pts, out, data, size); + Ok(()) +} + +/// Splits the whole MP3 frames off the front of `bytes`. The encoder writes constant-rate frames +/// back to back, so each one's length follows from its header's padding bit. +#[cfg(feature = "mp3-encode")] +fn mp3_frames(enc: &crate::mp3::Encoder, bytes: &mut Vec, pts: &mut u64, out: &mut Vec) -> Result<()> { + let samples = enc.frame_samples(); + let config = enc.config(); + // Bytes per frame: samples / 8 × bit rate / sample rate, plus the padding slot. + let base = (samples as u64 / 8 * u64::from(config.bitrate_kbps) * 1000 / u64::from(config.sample_rate.max(1))) as usize; + let mut at = 0; + while let Some(header) = bytes.get(at..at + 4) { + if header[0] != 0xFF || header[1] & 0xE0 != 0xE0 { + return Err(AudioError::Encode("the MP3 encoder returned bytes that are not a frame".into())); + } + let len = base + usize::from((header[2] >> 1) & 1); + let Some(frame) = bytes.get(at..at + len).filter(|_| len > 4) else { break }; + PacketEncoder::emit(pts, out, frame.to_vec(), samples as u32); + at += len; + } + bytes.drain(..at); + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/audio/src/write/coded/tests.rs b/crates/audio/src/packet/tests.rs similarity index 90% rename from crates/audio/src/write/coded/tests.rs rename to crates/audio/src/packet/tests.rs index cbdbd3375b..0056a6b162 100644 --- a/crates/audio/src/write/coded/tests.rs +++ b/crates/audio/src/packet/tests.rs @@ -1,6 +1,6 @@ use super::*; -use crate::Speaker; +use crate::{CodecId, Speaker}; fn map(mask: u32, order: Option<&[usize]>, layout: u32) -> Option> { channel_map(mask, order, &ChannelLayout::from_mask(layout)) @@ -165,3 +165,25 @@ fn the_listed_sample_rates_are_the_encoders() { assert_eq!(EncodeFormat::Aac.sample_rates().unwrap(), sorted(&crate::aac::SAMPLE_RATES)); assert_eq!(EncodeFormat::Mp3.sample_rates().unwrap(), sorted(&crate::mp3::SAMPLE_RATES)); } + +/// A codec whose feature is not built is refused, as `EncodeOptions::check` refuses its format. +#[test] +fn unbuilt_codecs_are_unsupported() { + let built = [ + (CodecId::Aac, cfg!(feature = "aac-encode")), + (CodecId::Alac, cfg!(feature = "alac-encode")), + (CodecId::Mp3, cfg!(feature = "mp3-encode")), + (CodecId::Ac3, cfg!(feature = "ac3-encode")), + (CodecId::Eac3, cfg!(feature = "eac3-encode")), + (CodecId::Opus, cfg!(feature = "opus-encode")), + ]; + let opts = EncodeOptions::default().with_bit_depth(crate::BitDepth::Int16); + for (codec, built) in built { + let made = PacketEncoder::new(codec, &opts, 48_000, 2); + if built { + assert!(made.is_ok(), "{codec:?}: {made:?}"); + } else { + assert!(matches!(&made, Err(AudioError::Unsupported(m)) if m.contains("feature")), "{codec:?}: {made:?}"); + } + } +} diff --git a/crates/audio/src/write/coded.rs b/crates/audio/src/write/coded.rs index 0d0dd626f4..040d590d0d 100644 --- a/crates/audio/src/write/coded.rs +++ b/crates/audio/src/write/coded.rs @@ -1,7 +1,7 @@ //! The coded formats of [`FileEncoder`](crate::FileEncoder): AAC-LC and ALAC in M4A (through -//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] maps the caller's -//! WAV-order channels onto the encoder's order, drives the packet encoder, and for M4A records the -//! encoder's priming and the exact length in the edit list. +//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] drives a +//! [`PacketEncoder`], which maps the caller's WAV-order channels onto the codec's order, and for +//! M4A records the encoder's priming and the exact length in the edit list. // Each codec is its own feature, and so are the two sinks: with only some of them built, the // other halves of the shared code are unused. @@ -11,271 +11,10 @@ )] use super::failed_write_error; -use super::pcm::validate_layout; -use crate::layout::channel_map; -use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, RateControl, Result}; +use crate::packet::{EncodedPacket, PacketEncoder}; +use crate::{AudioBuffer, AudioError, CodecId, EncodeFormat, EncodeOptions, Result}; use std::io::{Cursor, Seek, Write}; -/// Frames handed to the encoder at a time, so its buffers and the packets waiting to be written -/// stay small however long a block is. Also the frames of an ALAC packet. -const CHUNK: usize = 4096; - -/// Bits per second per channel when no rate is asked for: AAC. -const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; -/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per -/// full-bandwidth channel). -const DEFAULT_KBPS_PER_CHANNEL: u32 = 96; - -/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`. -fn labels(mask: u32) -> String { - ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::>().join(" ") -} - -/// [`channel_map`] for a format with one layout per channel count ([`EncodeFormat::layout_masks`]), -/// or why the audio does not fit. -fn fixed_map(format: EncodeFormat, name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result> { - let Some(&mask) = format.layout_masks(layout.channels()).first() else { - return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels()))); - }; - channel_map(mask, order, layout).ok_or_else(|| { - AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout))) - }) -} - -/// The speakers of the caller's layout, for an error message. -fn given(layout: &ChannelLayout) -> String { - layout.mask().map_or_else(|| "without speaker assignment".into(), labels) -} - -/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for 8 channels -/// configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc. -#[cfg(feature = "aac-encode")] -fn aac_order(channels: usize) -> Option<&'static [usize]> { - if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) } -} - -/// The lowest AAC bit rate the writer uses, per channel: 6 kbit/s, and a quarter of the sample -/// rate (256 bits a frame). The encoder accepts less, and from about half of this down codes -/// silence; a file of silence is no answer to a low bit rate (or to kbit/s given as bit/s). -#[cfg(feature = "aac-encode")] -fn aac_floor_per_channel(sample_rate: u32) -> u32 { - (sample_rate / 4).max(6000) -} - -/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a -/// quality of 0–1 spans the encoder's VBR range. -#[cfg(feature = "aac-encode")] -fn aac_mode(rate: Option, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode { - use crate::aac::BitrateMode; - let (lo, hi) = crate::aac::cbr_range(sample_rate, channels); - let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo)); - // An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone. - let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps }; - match rate { - None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))), - Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)), - // NaN stays NaN, which the encoder refuses. - Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)), - } -} - -/// The bit rate in kbit/s for a codec with constant bit rates only. -fn constant_kbps(name: &str, rate: Option, default: u32) -> Result { - match rate { - None => Ok(default), - Some(RateControl::Bitrate(bps)) => Ok(bps / 1000), - Some(RateControl::Quality(_)) => { - Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality"))) - } - } -} - -/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding -/// mode whose speakers the layout names, at the nearest bit rate the stream can carry. -#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] -fn ac3_config( - codec: crate::ac3::encoder::Codec, - sample_rate: u32, - layout: &ChannelLayout, - rate: Option, -) -> Result<(crate::ac3::encoder::Config, Vec)> { - use crate::ac3::encoder::{Codec, CodingMode, Config}; - use CodingMode::*; - let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" }; - let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; - let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| { - // 7.1 is an E-AC-3 programme with an LFE; the encoder has no other. - if mode == Surround71 && (codec != Codec::Eac3 || !lfe) { - return None; - } - let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe }; - let map = channel_map(config.channel_layout().mask()?, None, layout)?; - Some((config, map)) - }); - let Some((mut config, map)) = found else { - return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout)))); - }; - let full = config.mode.channels() as u32; - let want = constant_kbps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full)?; - // What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of - // the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold. - let least = if config.mode == Surround71 { 384 } else { 32 * full }; - config.bitrate_kbps = match codec { - Codec::Ac3 => { - let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least); - crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor) - } - Codec::Eac3 => { - let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 }; - want.clamp(least, most.max(least)) - } - }; - Ok((config, map)) -} - -/// One encoded packet and the frames it decodes to. -struct Packet { - data: Vec, - frames: u32, -} - -/// A packet encoder of any of the codecs, taking planar `f32` in its own channel order. -enum Codec { - #[cfg(feature = "aac-encode")] - Aac(Box), - #[cfg(feature = "alac-encode")] - Alac { - enc: Box, - quantizers: Vec, - /// Quantized samples of the packet being filled, per channel. - pending: Vec>, - }, - #[cfg(feature = "mp3-encode")] - Mp3(Box), - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Ac3 { - enc: Box, - /// The block with every sample finite and within ±1, as the encoder requires. - planes: Vec>, - }, -} - -impl Codec { - /// Encodes `planes` (one slice per encoder channel, equally long, at most [`CHUNK`] frames) - /// and appends the packets completed. - fn push(&mut self, planes: &[&[f32]], out: &mut Vec) -> Result<()> { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => out.extend(enc.encode(planes).into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })), - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, quantizers, pending } => { - let frames = planes.first().map_or(0, |p| p.len()); - let mut at = 0; - while at < frames { - let filled = pending.first().map_or(0, Vec::len); - let end = frames.min(at + CHUNK.saturating_sub(filled).max(1)); - for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) { - dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s))); - } - at = end; - if pending.first().is_some_and(|p| p.len() >= CHUNK) { - alac_packet(enc, pending, out)?; - } - } - } - #[cfg(feature = "mp3-encode")] - Codec::Mp3(enc) => { - let data = enc.encode(planes); - if !data.is_empty() { - out.push(Packet { data, frames: 0 }); - } - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Codec::Ac3 { enc, planes: clean } => { - for (dst, src) in clean.iter_mut().zip(planes) { - dst.clear(); - dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })); - } - let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect(); - out.extend(enc.push(&refs)?.into_iter().map(|p| Packet { data: p.data, frames: p.samples })); - } - } - Ok(()) - } - - /// Encodes what the encoder still holds and appends the last packets. - fn finish(&mut self, out: &mut Vec) -> Result<()> { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => out.extend(enc.flush().into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })), - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, pending, .. } => { - if pending.first().is_some_and(|p| !p.is_empty()) { - alac_packet(enc, pending, out)?; - } - } - #[cfg(feature = "mp3-encode")] - Codec::Mp3(enc) => { - let data = enc.flush(); - if !data.is_empty() { - out.push(Packet { data, frames: 0 }); - } - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Codec::Ac3 { enc, .. } => out.extend(enc.finish()?.packets.into_iter().map(|p| Packet { data: p.data, frames: p.samples })), - } - Ok(()) - } - - /// Decoded frames before the first frame of the audio. - fn priming(&self) -> u32 { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => enc.priming_samples(), - #[allow(unreachable_patterns)] - _ => 0, - } - } - - /// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` - /// frames in all): the configuration a decoder needs, with the average bit rate. - #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - fn sample_entry(&self, sample_rate: u32, channels: u32, bytes: u64, frames: u64) -> Option { - use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry}; - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => { - let mut entry = SampleEntry::aac(enc.audio_specific_config(), channels, sample_rate); - if let CodecConfig::Aac(config) = &mut entry.codec - && frames > 0 - { - let bps = u128::from(bytes) * 8 * u128::from(sample_rate) / u128::from(frames); - config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX); - } - Some(entry) - } - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, .. } => { - let bits = u16::from(enc.encoder_config().bit_depth); - Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.cookie() }, channels, f64::from(sample_rate), bits)) - } - #[allow(unreachable_patterns)] - _ => None, - } - } -} - -/// Encodes the pending samples as one ALAC packet and empties them. -#[cfg(feature = "alac-encode")] -fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec], out: &mut Vec) -> Result<()> { - let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect(); - let frames = refs.first().map_or(0, |p| p.len()) as u32; - let data = enc.encode(&refs)?; - pending.iter_mut().for_each(Vec::clear); - out.push(Packet { data, frames }); - Ok(()) -} - /// A muxer's error as this crate's: a failed write stays an I/O error. #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] fn mux_error(e: craft_media::isobmff::Error) -> AudioError { @@ -285,6 +24,31 @@ fn mux_error(e: craft_media::isobmff::Error) -> AudioError { } } +/// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` frames in +/// all): the configuration a decoder needs, with the average bit rate. +#[cfg(any(feature = "aac-encode", feature = "alac-encode"))] +fn sample_entry(enc: &PacketEncoder, bytes: u64, frames: u64) -> Option { + use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry}; + let (rate, channels) = (enc.sample_rate(), u32::from(enc.channels())); + match enc.codec() { + CodecId::Aac => { + let mut entry = SampleEntry::aac(enc.extradata(), channels, rate); + if let CodecConfig::Aac(config) = &mut entry.codec + && frames > 0 + { + let bps = u128::from(bytes) * 8 * u128::from(rate) / u128::from(frames); + config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX); + } + Some(entry) + } + CodecId::Alac => { + let bits = u16::from(enc.bit_depth().unwrap_or(16)); + Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.extradata() }, channels, f64::from(rate), bits)) + } + _ => None, + } +} + /// An M4A file being written: one audio track whose samples are the packets. /// /// The last packet is held back until the length is known: its duration is cut to the audio's @@ -298,9 +62,8 @@ struct M4a { track: Option, entry: craft_media::isobmff::SampleEntry, sample_rate: u32, - channels: u32, priming: u32, - held: Option, + held: Option, /// Frames and bytes of the packets written, the held one not counted. frames: u64, bytes: u64, @@ -308,13 +71,14 @@ struct M4a { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] impl M4a { - fn new(out: W, codec: &Codec, sample_rate: u32, channels: u32) -> Result { + fn new(out: W, enc: &PacketEncoder) -> Result { use craft_media::isobmff::{Brand, Mp4Writer, WriterOptions}; - let entry = codec.sample_entry(sample_rate, channels, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?; + let entry = sample_entry(enc, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?; + let sample_rate = enc.sample_rate(); let mut options = WriterOptions::new(Brand::Mp4); options.movie_timescale = sample_rate; let mux = Mp4Writer::new(out, options).map_err(mux_error)?; - Ok(M4a { mux, track: None, entry, sample_rate, channels, priming: codec.priming(), held: None, frames: 0, bytes: 0 }) + Ok(M4a { mux, track: None, entry, sample_rate, priming: enc.priming(), held: None, frames: 0, bytes: 0 }) } fn track(&mut self, has_audio: bool) -> Result { @@ -333,7 +97,7 @@ impl M4a { Ok(track) } - fn sample(&mut self, packet: &Packet, duration: u32) -> Result<()> { + fn sample(&mut self, packet: &EncodedPacket, duration: u32) -> Result<()> { let track = self.track(true)?; let sample = craft_media::isobmff::WriteSample { data: &packet.data, duration, composition_offset: 0, is_sync: true }; self.mux.write_sample(track, sample).map_err(mux_error)?; @@ -342,22 +106,22 @@ impl M4a { Ok(()) } - fn write(&mut self, packet: Packet) -> Result<()> { + fn write(&mut self, packet: EncodedPacket) -> Result<()> { if let Some(held) = self.held.replace(packet) { - self.sample(&held, held.frames)?; + self.sample(&held, held.duration)?; } Ok(()) } - /// Writes the last packet, cut to the end of `audio_frames` frames of audio, and the `moov`. - fn finish(mut self, codec: &Codec, audio_frames: u64) -> Result { + /// Writes the last packet, cut to the end of the audio the encoder took, and the `moov`. + fn finish(mut self, enc: &PacketEncoder) -> Result { if let Some(held) = self.held.take() { - let rest = (u64::from(self.priming) + audio_frames).saturating_sub(self.frames); - self.sample(&held, rest.min(u64::from(held.frames)) as u32)?; + let rest = (u64::from(self.priming) + enc.frames()).saturating_sub(self.frames); + self.sample(&held, rest.min(u64::from(held.duration)) as u32)?; } let track = self.track(false)?; // The configuration is complete only now: the bit rate, and ALAC's largest packet. - if let Some(entry) = codec.sample_entry(self.sample_rate, self.channels, self.bytes, self.frames) { + if let Some(entry) = sample_entry(enc, self.bytes, self.frames) { self.mux.set_sample_entry(track, entry).map_err(mux_error)?; } self.mux.finish().map_err(mux_error) @@ -374,15 +138,8 @@ enum Sink { /// A file of one of the coded formats written block by block. pub(crate) struct Writer { - codec: Codec, + enc: PacketEncoder, sink: Sink, - /// For each encoder channel, the caller's channel that feeds it. - map: Vec, - /// The constant bit rate the encoder was set to, bits per second; `None` for ALAC and for - /// AAC at a constant quality. - bitrate: Option, - frames: u64, - packets: Vec, /// Set when a write has failed: the encoder and the sink no longer agree, so the writer /// refuses every later call. failed: bool, @@ -390,68 +147,23 @@ pub(crate) struct Writer { impl Writer { pub(crate) fn new(out: W, opts: &EncodeOptions, sample_rate: u32, channels: usize) -> Result { - validate_layout(channels, sample_rate)?; - let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels as u16)); - let (codec, map, bitrate) = match opts.format { - #[cfg(feature = "aac-encode")] - EncodeFormat::Aac => { - let map = fixed_map(EncodeFormat::Aac, "AAC", aac_order(channels), &layout)?; - let mode = aac_mode(opts.rate_control, sample_rate, channels); - let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, channels, 0) }; - let bitrate = match mode { - crate::aac::BitrateMode::Cbr(bps) => Some(bps), - crate::aac::BitrateMode::Vbr(_) => None, - }; - (Codec::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, bitrate) - } - #[cfg(feature = "alac-encode")] - EncodeFormat::Alac => { - let count = u8::try_from(channels).unwrap_or(u8::MAX); - let map = fixed_map(EncodeFormat::Alac, "ALAC", crate::alac::alac_order(count), &layout)?; - let bits = match opts.bit_depth { - crate::BitDepth::Int16 => 16, - crate::BitDepth::Int24 => 24, - crate::BitDepth::Int32 => 32, - crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())), - }; - let enc = crate::alac::Encoder::new(crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32))?; - let quantizers = super::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, channels); - (Codec::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); channels] }, map, None) - } - #[cfg(feature = "mp3-encode")] - EncodeFormat::Mp3 => { - let map = fixed_map(EncodeFormat::Mp3, "MP3", None, &layout)?; - let want = constant_kbps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * channels as u32)?; - // A sample rate MP3 has not is the encoder's to refuse. - let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want); - let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, channels, kbps))?; - (Codec::Mp3(Box::new(enc)), map, Some(kbps.saturating_mul(1000))) - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - EncodeFormat::Ac3 | EncodeFormat::Eac3 => { - let codec = if opts.format == EncodeFormat::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 }; - let (config, map) = ac3_config(codec, sample_rate, &layout, opts.rate_control)?; - let enc = crate::ac3::encoder::Encoder::new(config)?; - (Codec::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); channels] }, map, Some(config.bitrate_kbps.saturating_mul(1000))) - } - #[allow(unreachable_patterns)] - f => return Err(AudioError::Unsupported(format!("writing {f:?}"))), - }; + let channels = u16::try_from(channels).map_err(|_| AudioError::Encode("too many channels".into()))?; + let enc = PacketEncoder::new(opts.format.codec(), opts, sample_rate, channels)?; let sink = match opts.format { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &codec, sample_rate, channels as u32)?)), + EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &enc)?)), _ => Sink::Raw(out), }; - Ok(Writer { codec, sink, map, bitrate, frames: 0, packets: Vec::new(), failed: false }) + Ok(Writer { enc, sink, failed: false }) } pub(crate) fn bitrate(&self) -> Option { - self.bitrate + self.enc.bitrate() } - /// Hands the packets waiting to the sink. - fn drain(&mut self) -> Result<()> { - for packet in self.packets.drain(..) { + /// Hands `packets` to the sink. + fn drain(&mut self, packets: Vec) -> Result<()> { + for packet in packets { match &mut self.sink { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] Sink::M4a(m4a) => m4a.write(packet)?, @@ -466,16 +178,16 @@ impl Writer { if self.failed { return Err(failed_write_error()); } - for at in (0..frames).step_by(CHUNK) { - let end = frames.min(at + CHUNK); - let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect(); - let written = self.codec.push(&planes, &mut self.packets).and_then(|()| self.drain()); + // A block at a time, so the packets waiting for the sink stay few however long it is. + for at in (0..frames).step_by(crate::packet::CHUNK) { + let end = frames.min(at + crate::packet::CHUNK); + let part: Vec<&[f32]> = block.iter().map(|c| c.as_ref().get(at..end).unwrap_or_default()).collect(); + let written = self.enc.encode(&part, end - at).and_then(|packets| self.drain(packets)); if let Err(e) = written { self.failed = true; return Err(e); } } - self.frames = self.frames.saturating_add(frames as u64); Ok(()) } @@ -483,11 +195,11 @@ impl Writer { if self.failed { return Err(failed_write_error()); } - self.codec.finish(&mut self.packets)?; - self.drain()?; + let last = self.enc.finish()?; + self.drain(last)?; match self.sink { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - Sink::M4a(m4a) => m4a.finish(&self.codec, self.frames), + Sink::M4a(m4a) => m4a.finish(&self.enc), Sink::Raw(mut out) => { out.flush()?; Ok(out) @@ -501,6 +213,3 @@ pub(crate) fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> w.write(&buf.channels, buf.frames())?; Ok(w.finish()?.into_inner()) } - -#[cfg(test)] -mod tests; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 0de55c394b..b5e3d64e4c 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -8,7 +8,7 @@ mod aiff; mod coded; #[cfg(feature = "flac-encode")] pub(crate) mod flac; -mod pcm; +pub(crate) mod pcm; #[cfg(feature = "pcm-encode")] mod raw; #[cfg(feature = "pcm-encode")] diff --git a/crates/audio/tests/codecs/main.rs b/crates/audio/tests/codecs/main.rs index c1c9e2131b..a2e865fe24 100644 --- a/crates/audio/tests/codecs/main.rs +++ b/crates/audio/tests/codecs/main.rs @@ -18,5 +18,6 @@ mod mp3_encoder_oracle; mod mpa_oracle; mod opus; mod opusenc; +mod packet_encoder; mod routing_oracle; mod track_decoder; diff --git a/crates/audio/tests/codecs/packet_encoder.rs b/crates/audio/tests/codecs/packet_encoder.rs new file mode 100644 index 0000000000..0933443699 --- /dev/null +++ b/crates/audio/tests/codecs/packet_encoder.rs @@ -0,0 +1,239 @@ +//! `PacketEncoder`: every codec round-trips through `TrackDecoder` from the description the +//! encoder gives, at the length that was encoded and with each channel on its speaker. + +use std::io::Cursor; + +use craft_audio::{ + AudioError, BitDepth, ChannelLayout, CodecId, EncodeFormat, EncodeOptions, EncodedPacket, FileEncoder, PacketEncoder, TrackDecoder, +}; + +/// `channels` channels of `frames` frames, each a tone of its own frequency low enough for an LFE. +fn tones(sample_rate: u32, channels: usize, frames: usize) -> Vec> { + (0..channels) + .map(|c| { + let step = (40.0 + 9.0 * c as f32) * std::f32::consts::TAU / sample_rate as f32; + (0..frames).map(|i| ((i as f32 * step).sin() * 0.4 * 32768.0).round() / 32768.0).collect() + }) + .collect() +} + +/// Normalised correlation of two signals over the samples both have. +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + let (x, y) = (f64::from(x), f64::from(y)); + ab += x * y; + aa += x * x; + bb += y * y; + } + ab / (aa * bb).sqrt().max(1e-30) +} + +/// Encodes `input` in uneven blocks and returns the packets. +fn encode(enc: &mut PacketEncoder, input: &[Vec]) -> Vec { + let frames = input[0].len(); + let mut packets = Vec::new(); + let mut at = 0; + for n in [1, 999, 4096, 10_000, 7, usize::MAX].into_iter().cycle() { + let n = n.min(frames - at); + let block: Vec<&[f32]> = input.iter().map(|c| &c[at..at + n]).collect(); + packets.extend(enc.encode(&block, n).unwrap()); + at += n; + if at == frames { + break; + } + } + packets.extend(enc.finish().unwrap()); + packets +} + +/// Encodes, checks the timing the packets carry, decodes them from the encoder's description, and +/// returns the decoded audio from the first input frame on, cut to the input's length, and the +/// layout the decoder reports. +fn decode_back(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec]) -> (PacketEncoder, Vec>, ChannelLayout) { + let frames = input[0].len(); + let mut enc = PacketEncoder::new(codec, opts, sample_rate, input.len() as u16).unwrap(); + let packets = encode(&mut enc, input); + assert_eq!(enc.frames(), frames as u64); + // The packets follow one another, and add up to the priming, the audio and the padding. + let mut pts = 0; + for p in &packets { + assert_eq!(p.pts, pts, "{codec:?}"); + pts += u64::from(p.duration); + } + assert_eq!(pts, u64::from(enc.priming()) + frames as u64 + enc.padding(), "{codec:?}"); + let last = packets.last().map_or(0, |p| u64::from(p.duration)); + assert!(enc.padding() < last, "{codec:?}: {} samples of padding after a packet of {last}", enc.padding()); + + let lookahead: Vec<&[u8]> = packets.iter().take(craft_audio::LOOKAHEAD_PACKETS).map(|p| p.data.as_slice()).collect(); + let mut dec = TrackDecoder::new(&enc.codec_params(), &lookahead).unwrap(); + assert_eq!((dec.codec(), dec.sample_rate()), (codec, sample_rate), "{codec:?}"); + let mut out = vec![Vec::new(); usize::from(dec.channels())]; + for p in &packets { + let block = dec.decode(&p.data).unwrap(); + assert_eq!(block.frames(), p.duration as usize, "{codec:?}: a packet's duration is what it decodes to"); + for (o, c) in out.iter_mut().zip(block.channels) { + o.extend(c); + } + } + let skip = enc.priming() as usize; + let out = out.into_iter().map(|c| c[skip..skip + frames].to_vec()).collect(); + (enc, out, dec.layout()) +} + +/// [`decode_back`] for a codec whose decoder returns every channel: on the speakers encoded. +fn round_trip(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec]) -> (PacketEncoder, Vec>) { + let (enc, out, layout) = decode_back(codec, opts, sample_rate, input); + assert_eq!(layout, enc.layout(), "{codec:?}"); + (enc, out) +} + +/// Each decoded channel is its input channel, in place: it matches that channel and no other. The +/// AC-3 encoders low-pass the LFE, which shifts its phase, so the match is by magnitude. +fn assert_in_place(codec: CodecId, input: &[Vec], output: &[Vec], least: f64) { + for (c, got) in output.iter().enumerate() { + let scores: Vec = input.iter().map(|want| correlation(want, got).abs()).collect(); + let least = if matches!(codec, CodecId::Ac3 | CodecId::Eac3) && c == 3 { 0.5 } else { least }; + assert!(scores[c] > least, "{codec:?} channel {c}: {scores:?}"); + for (other, &score) in scores.iter().enumerate().filter(|&(o, _)| o != c) { + assert!(score < scores[c] - 0.3, "{codec:?} channel {c} matches channel {other}: {scores:?}"); + } + } +} + +#[test] +fn aac_round_trips_in_place() { + let input = tones(48_000, 6, 30_001); + let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(384_000); + let (enc, out) = round_trip(CodecId::Aac, &opts, 48_000, &input); + assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (1024, ChannelLayout::SURROUND_5_1_SIDE, Some(384_000))); + assert_eq!(enc.extradata().len(), 2, "an AudioSpecificConfig for channel configuration 6"); + assert_in_place(CodecId::Aac, &input, &out, 0.95); +} + +/// 16-bit ALAC is lossless: the input comes back bit for bit. +#[test] +fn alac_round_trips_exactly() { + let input = tones(44_100, 6, 10_000); + let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(ChannelLayout::SURROUND_5_1); + let (enc, out) = round_trip(CodecId::Alac, &opts, 44_100, &input); + assert_eq!((enc.priming(), enc.padding(), enc.bit_depth(), enc.layout()), (0, 0, Some(16), ChannelLayout::SURROUND_5_1)); + assert_eq!(out, input); +} + +#[test] +fn mp3_round_trips_in_place() { + for (rate, frame) in [(48_000, 1152), (44_100, 1152), (24_000, 576)] { + let input = tones(rate, 2, 20_000); + let opts = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(192_000); + let mut enc = PacketEncoder::new(CodecId::Mp3, &opts, rate, 2).unwrap(); + let packets = encode(&mut enc, &input); + assert!(packets.iter().all(|p| p.duration == frame && p.data[0] == 0xFF), "{rate} Hz"); + let (enc, out) = round_trip(CodecId::Mp3, &opts, rate, &input); + assert_eq!((enc.priming(), enc.extradata()), (1057, vec![])); + assert_in_place(CodecId::Mp3, &input, &out, 0.95); + } +} + +#[test] +fn ac3_round_trips_in_place() { + let input = tones(48_000, 6, 20_000); + let (enc, out) = round_trip(CodecId::Ac3, &EncodeOptions::new(EncodeFormat::Ac3), 48_000, &input); + assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (256, ChannelLayout::SURROUND_5_1_SIDE, Some(448_000))); + assert_in_place(CodecId::Ac3, &input, &out, 0.9); +} + +#[test] +fn eac3_round_trips_in_place() { + let input = tones(48_000, 6, 20_000); + let (enc, out) = round_trip(CodecId::Eac3, &EncodeOptions::new(EncodeFormat::Eac3), 48_000, &input); + assert_eq!((enc.priming(), enc.layout()), (256, ChannelLayout::SURROUND_5_1_SIDE)); + assert_in_place(CodecId::Eac3, &input, &out, 0.9); +} + +/// 7.1 E-AC-3 is encoded as 7.1; `TrackDecoder` plays its 5.1 independent substream (see the +/// README), at the same length. +#[test] +fn eac3_7_1_decodes_as_its_5_1_substream() { + let input = tones(48_000, 8, 20_000); + let opts = EncodeOptions::new(EncodeFormat::Eac3).with_layout(ChannelLayout::SURROUND_7_1); + let (enc, out, layout) = decode_back(CodecId::Eac3, &opts, 48_000, &input); + assert_eq!((enc.layout(), enc.channels(), layout), (ChannelLayout::SURROUND_7_1, 8, ChannelLayout::SURROUND_5_1_SIDE)); + assert!(out.iter().all(|c| c.len() == 20_000)); +} + +#[test] +fn opus_round_trips_in_place() { + for channels in [1, 2] { + let input = tones(48_000, channels, 20_000); + let opts = EncodeOptions::default().with_bitrate(128_000); + let (enc, out) = round_trip(CodecId::Opus, &opts, 48_000, &input); + let head = enc.extradata(); + assert_eq!((&head[..8], head[9], u32::from(u16::from_le_bytes([head[10], head[11]]))), (&b"OpusHead"[..], channels as u8, enc.priming())); + assert_in_place(CodecId::Opus, &input, &out, 0.9); + } +} + +/// The raw streams `FileEncoder` writes are the packets in a row. +#[test] +fn file_encoder_writes_the_packets() { + for (format, layout) in [(EncodeFormat::Mp3, ChannelLayout::STEREO), (EncodeFormat::Ac3, ChannelLayout::SURROUND_5_1)] { + let input = tones(48_000, usize::from(layout.channels()), 12_345); + let opts = EncodeOptions::new(format).with_layout(layout); + let mut file = FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, layout.channels()).unwrap(); + file.write(&input, 12_345).unwrap(); + let file = file.finish().unwrap().into_inner(); + let mut enc = PacketEncoder::new(format.codec(), &opts, 48_000, layout.channels()).unwrap(); + let packets: Vec = encode(&mut enc, &input).into_iter().flat_map(|p| p.data).collect(); + assert_eq!(file, packets, "{format:?}"); + } +} + +/// What a codec cannot take is refused, and as `EncodeOptions::check` refuses it for the format. +#[test] +fn unsupported_settings_are_refused() { + let unsupported = + |codec, opts: &EncodeOptions, rate, channels| matches!(PacketEncoder::new(codec, opts, rate, channels), Err(AudioError::Unsupported(_))); + let opts = EncodeOptions::default(); + assert!(unsupported(CodecId::Vorbis, &opts, 48_000, 2)); + assert!(unsupported(CodecId::Flac, &opts, 48_000, 2)); + assert!(unsupported(CodecId::Opus, &opts, 44_100, 2)); + assert!(unsupported(CodecId::Opus, &opts, 48_000, 3)); + assert!(unsupported(CodecId::Opus, &opts.clone().with_quality(0.5), 48_000, 2)); + for (codec, format, rate, channels) in [ + (CodecId::Mp3, EncodeFormat::Mp3, 96_000, 2), + (CodecId::Mp3, EncodeFormat::Mp3, 48_000, 0), + (CodecId::Mp3, EncodeFormat::Mp3, 48_000, 6), + (CodecId::Ac3, EncodeFormat::Ac3, 48_000, 8), + (CodecId::Aac, EncodeFormat::Aac, 44_000, 2), + ] { + let opts = EncodeOptions::new(format); + let (packets, file) = (PacketEncoder::new(codec, &opts, rate, channels).map(drop), opts.check(rate, channels)); + assert_eq!(format!("{packets:?}"), format!("{file:?}"), "{codec:?} {rate} {channels}"); + assert!(packets.is_err()); + } + assert!(unsupported(CodecId::Alac, &opts.clone().with_bit_depth(BitDepth::Float32), 48_000, 2)); + assert!(unsupported(CodecId::Ac3, &opts.clone().with_layout(ChannelLayout::unordered(2)), 48_000, 2)); + // A layout for another channel count is the caller's mistake. + assert!(matches!(PacketEncoder::new(CodecId::Aac, &opts.with_layout(ChannelLayout::STEREO), 48_000, 1), Err(AudioError::Encode(_)))); +} + +/// Blocks that do not fit, and calls after `finish`, are errors that leave the stream as it was. +#[test] +fn misuse_is_an_error() { + let mut enc = PacketEncoder::new(CodecId::Aac, &EncodeOptions::new(EncodeFormat::Aac), 48_000, 2).unwrap(); + let short = [vec![0.0f32; 10], vec![0.0; 5]]; + assert!(matches!(enc.encode(&short, 10), Err(AudioError::Encode(_)))); + assert!(matches!(enc.encode(&short[..1], 5), Err(AudioError::Encode(_)))); + assert_eq!(enc.frames(), 0); + assert!(enc.encode(&short, 5).unwrap().is_empty()); + assert_eq!(enc.finish().unwrap().len(), 2, "5 frames after 1024 of priming fit in two packets"); + assert!(matches!(enc.finish(), Err(AudioError::Encode(_)))); + assert!(matches!(enc.encode(&short, 5), Err(AudioError::Encode(_)))); + // An encoder given nothing returns nothing. + for codec in [CodecId::Aac, CodecId::Alac, CodecId::Mp3, CodecId::Ac3, CodecId::Eac3, CodecId::Opus] { + let mut enc = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap(); + assert!(enc.finish().unwrap().is_empty(), "{codec:?}"); + assert_eq!(enc.padding(), 0); + } +} From d5fd018316bdb2d7f4a21530767008e71d1281c4 Mon Sep 17 00:00:00 2001 From: alehel Date: Sun, 15 Nov 2026 00:03:32 +0100 Subject: [PATCH 003/130] craft-audio: README table of ALAC sizes against the reference's fixed shift (#1368) Co-Authored-By: Claude Fable 5.2 --- crates/audio/README.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/audio/README.md b/crates/audio/README.md index 8546bc6a7b..31e69bff42 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -542,6 +542,34 @@ Each codec module's rustdoc lists the coding tools it implements. | 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 (except 24- and 32-bit packets quiet enough to shift off fewer low bytes, such as silence), same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | +### ALAC encoding + +Apple's reference encoder stores the low byte (24-bit) or low two bytes (32-bit) of every sample +uncompressed. This encoder shifts off fewer bytes, per element and per packet, when the samples +allow it: at 24 bits a packet that peaks below −54 dBFS keeps no uncompressed byte; at 32 bits one +below −54 dBFS keeps one, and a mono or LFE element below −102 dBFS none (a 32-bit pair always keeps +one). Other packets are the same as the reference's, and decoders need no change. + +Stream sizes in MB (10⁶ bytes) for 4 minutes at 48 kHz in 4096-frame packets. "Reference" is this +encoder with the reference's fixed shift; Apple's `afconvert` gives the same sizes for the 24-bit stereo rows. The +music is synthetic (decaying harmonic notes over a noise floor, peaking at −3 dBFS); a stem plays +5 or 10 seconds in every 20. + +| Material | Depth / ch | PCM | Reference | This encoder | Saved | +|---|---|---|---|---|---| +| Music throughout | 24 / 2 | 69.1 | 45.5 | 45.5 | 0% | +| Music, 2 s of digital silence at each end | 24 / 2 | 69.1 | 45.1 | 44.7 | 0.8% | +| Stem playing half the time, digital silence between | 24 / 2 | 69.1 | 34.3 | 22.8 | 33% | +| Stem playing a quarter of the time, digital silence between | 24 / 2 | 69.1 | 28.7 | 11.5 | 60% | +| The same, noise at −110 dBFS in place of silence | 24 / 2 | 69.1 | 32.6 | 25.1 | 23% | +| Quiet music, peaking at −60 dBFS | 24 / 2 | 69.1 | 27.7 | 20.1 | 27% | +| Digital silence | 24 / 2 | 69.1 | 23.1 | 0.09 | 99.6% | +| 5.1: music in front, surrounds a quarter of the time, silent LFE | 24 / 6 | 207.4 | 108.7 | 79.9 | 26% | +| Stem playing a quarter of the time, digital silence between | 32 / 1 | 46.1 | 25.9 | 8.7 | 66% | +| Stem playing a quarter of the time, digital silence between | 32 / 2 | 92.2 | 51.7 | 34.5 | 33% | +| Quiet music, peaking at −60 dBFS | 32 / 2 | 92.2 | 50.7 | 43.2 | 15% | +| Digital silence | 32 / 2 | 92.2 | 46.2 | 23.1 | 50% | + ### MP3 encoding ```rust From 38d8d118bc457542a5c4280539f3954f6e6393df Mon Sep 17 00:00:00 2001 From: alehel Date: Sun, 15 Nov 2026 00:10:02 +0100 Subject: [PATCH 004/130] craft-audio: say what PacketEncoder timing is with no input With no input, finish returns no packets, so the durations add up to 0 while priming() still reports the codec's delay. The documented sum priming + frames + padding did not say so. priming() stays the codec's delay, as OpusHead's pre-skip and the M4A sink read it before any input; the docs and README now state the empty case, and the test checks it for every codec. Refs #1230 (point 3). Co-Authored-By: Claude Fable 5.2 --- crates/audio/README.md | 4 +++- crates/audio/src/packet.rs | 7 +++++++ crates/audio/tests/codecs/packet_encoder.rs | 9 +++++++-- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/audio/README.md b/crates/audio/README.md index 5e5922ebdc..3d5bc7018b 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -353,7 +353,9 @@ get the error `EncodeOptions::check` gives for the format. Timing: a packet's `pts` is where its decoded audio starts, counted from the first decoded sample, so input frame `n` is at `n + priming()`. `finish` pads the end with silence until a decoder -returns every input frame, and the durations add up to `priming() + frames() + padding()`. A muxer +returns every input frame, and the durations add up to `priming() + frames() + padding()`. With no +input there are no packets: the durations add up to 0 and `padding()` is 0, while `priming()` still +reports the codec's delay. A muxer skips the priming (MP4: `TrackConfig::media_start` or an edit list; Matroska: `CodecDelay`; Opus: the pre-skip, which `OpusHead` already holds) and trims the padding (the end of an MP4 edit, Matroska's `DiscardPadding`). ALAC's `extradata` records the largest packet and the average bit diff --git a/crates/audio/src/packet.rs b/crates/audio/src/packet.rs index 4f2d6cb8c4..a6ba2d5749 100644 --- a/crates/audio/src/packet.rs +++ b/crates/audio/src/packet.rs @@ -437,6 +437,9 @@ impl PacketEncoder { /// Decoded samples before the first input frame: the encoder's delay, which a container /// skips (an MP4 edit list's media time, Matroska's CodecDelay, Opus's pre-skip, which /// `OpusHead` already holds). 0 for ALAC. + /// + /// This is the codec's delay and does not depend on the input. An encoder that is given no + /// input returns no packets, and this still reports the delay. pub fn priming(&self) -> u32 { match &self.inner { #[cfg(feature = "aac-encode")] @@ -461,6 +464,10 @@ impl PacketEncoder { /// edit, Matroska's DiscardPadding): the packets' durations add up to /// [`priming`](Self::priming) + [`frames`](Self::frames) + this. Complete after /// [`finish`](Self::finish). + /// + /// The sum holds once there is input. With none, [`finish`](Self::finish) returns no packets, + /// so the durations add up to 0 and this is 0, while `priming` is still the codec's delay: a + /// muxer writes an empty track and has no priming to skip. pub fn padding(&self) -> u64 { self.pts.saturating_sub(u64::from(self.priming()).saturating_add(self.frames)) } diff --git a/crates/audio/tests/codecs/packet_encoder.rs b/crates/audio/tests/codecs/packet_encoder.rs index 0933443699..584255d152 100644 --- a/crates/audio/tests/codecs/packet_encoder.rs +++ b/crates/audio/tests/codecs/packet_encoder.rs @@ -230,10 +230,15 @@ fn misuse_is_an_error() { assert_eq!(enc.finish().unwrap().len(), 2, "5 frames after 1024 of priming fit in two packets"); assert!(matches!(enc.finish(), Err(AudioError::Encode(_)))); assert!(matches!(enc.encode(&short, 5), Err(AudioError::Encode(_)))); - // An encoder given nothing returns nothing. + // An encoder given nothing returns nothing: no packets, no frames and no padding. `priming` + // is the codec's delay either way, so it equals that of an encoder that was given input. for codec in [CodecId::Aac, CodecId::Alac, CodecId::Mp3, CodecId::Ac3, CodecId::Eac3, CodecId::Opus] { let mut enc = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap(); assert!(enc.finish().unwrap().is_empty(), "{codec:?}"); - assert_eq!(enc.padding(), 0); + assert_eq!((enc.frames(), enc.padding()), (0, 0), "{codec:?}"); + let mut fed = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap(); + fed.encode(&short, 5).unwrap(); + fed.finish().unwrap(); + assert_eq!(enc.priming(), fed.priming(), "{codec:?}"); } } From 29b64c868a4ab1a4c9a7c87ebe74963c2565e6a4 Mon Sep 17 00:00:00 2001 From: el-j Date: Sun, 15 Nov 2026 21:39:56 +0100 Subject: [PATCH 005/130] craft-captions: MicroDVD, MPL2, SubViewer 2, VPlayer and SAMI subtitles Readers and writers for five legacy text formats, each a Format variant with detection. Verified against ffmpeg as a black-box oracle in both directions. Part of #1557. --- crates/captions/Cargo.toml | 2 +- crates/captions/README.md | 5 + crates/captions/src/lib.rs | 80 +++++++- crates/captions/src/microdvd.rs | 223 +++++++++++++++++++++ crates/captions/src/mpl2.rs | 95 +++++++++ crates/captions/src/sami.rs | 256 ++++++++++++++++++++++++ crates/captions/src/subviewer.rs | 116 +++++++++++ crates/captions/src/text.rs | 102 ++++++++++ crates/captions/src/vplayer.rs | 116 +++++++++++ crates/captions/tests/it/legacy_text.rs | 231 +++++++++++++++++++++ crates/captions/tests/it/main.rs | 1 + 11 files changed, 1223 insertions(+), 4 deletions(-) create mode 100644 crates/captions/src/microdvd.rs create mode 100644 crates/captions/src/mpl2.rs create mode 100644 crates/captions/src/sami.rs create mode 100644 crates/captions/src/subviewer.rs create mode 100644 crates/captions/src/vplayer.rs create mode 100644 crates/captions/tests/it/legacy_text.rs diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index cd09f7e166..d59b2b64f9 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-captions" -description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML/IMSC1/DFXP readers and writers with exact time, and CEA-608/708 coding" +description = "Caption and subtitle files behind one neutral model: SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL, ASS, TTML/IMSC1/DFXP and the legacy text formats (MicroDVD, MPL2, SubViewer, VPlayer, SAMI) readers and writers with exact time, and CEA-608/708 coding" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/captions/README.md b/crates/captions/README.md index 7380a3ce41..bcb71375ca 100644 --- a/crates/captions/README.md +++ b/crates/captions/README.md @@ -56,6 +56,11 @@ lists at most 20 characters per stream. | TTML `.ttml` (IMSC1) | yes | yes | Writes the IMSC1 Text profile (TTML2 namespaces) with the document's language as `xml:lang` (read back on import): `

` per cue, `
`, styled ``s for `` / `` / ``, `ttm:agent` speakers, exact frame times (`123f`) at the sequence rate. Reads any TTML (TTML1, TTML2, the 2006 `ttaf1` drafts): clock / frame / offset / tick times, `dur`, nested time containers (`body` / `div` begins offset and ends clip their contents; `seq` containers are read as `par` with a warning), timed spans, referenced styles. | | DFXP `.dfxp` | yes | yes | TTML1 with the DFXP presentation profile; clock times in milliseconds (frame-exact after `snap_to_frames`). | | ASS / SSA `.ass`, `.ssa` | yes | yes (ASS v4+) | The `[Events]` section: `Dialogue:` lines through the file's `Format:` line, `Name` as the speaker, `\N`, `\n`, `\h` and the `\i`, `\b`, `\u` override tags kept (as ``, ``, ``); other override tags and drawing lines are dropped. Times are centiseconds. Written files have one `Default` style. | +| MicroDVD `.sub` | yes | yes | `{first}{last}text` with frame numbers; the `{1}{1}fps` line or 23.976 fps. `\|` breaks a line; `{y:i,b,u}` and `{c:$BBGGRR}` style a line (capital `Y` / `C`: the rest of the cue too); other controls are dropped. Writing always names the rate (`WriteOptions::rate`, 23.976 by default) and styles only a line that ``, `` or `` wraps whole. | +| MPL2 `.mpl` | yes | yes | `[start][end]text` in tenths of a second; `\|` breaks a line, a leading `/` makes it italic. | +| SubViewer 2 `.sbv` (also `.sub`) | yes | yes | `start,end` in hundredths of a second after the `[INFORMATION]` header; `[br]` breaks a line. Text only; no styles. | +| VPlayer `.vpl` (also `.txt`) | yes | yes | `HH:MM:SS[.cc]=text` (`:` or a space also separate); only start times, a caption lasts to the next line (empty text clears), four seconds for the last. Text only. | +| SAMI `.smi` | yes | yes | `` blocks, ` ` clears; `
`, ``, ``, ``, `` kept; first language class only. | All cue times are exact `Tick`s. Milliseconds convert exactly (1 ms = 254 016 000 ticks); SCC frames map through `FrameRate::FPS_29_97`. `Document::snap_to_frames` snaps cues to a frame grid and diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index e8a4927229..13654686cd 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -4,7 +4,7 @@ //! - **Files:** [SubRip](srt) (`.srt`), [WebVTT](vtt) (`.vtt`), [Scenarist SCC](scc) (`.scc`, //! CEA-608 pop-on, roll-up and paint-on on read; pop-on on write), [MacCaption MCC](mcc) //! (`.mcc`, SMPTE ST 334-2 packets with CEA-608 and CEA-708), [EBU STL](stl) (`.stl`, EBU -//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a +//! Tech 3264), [ASS/SSA](ass) (`.ass`, `.ssa`), the legacy text formats [MicroDVD](microdvd) (`.sub`), [MPL2](mpl2) (`.mpl`), [SubViewer 2](subviewer) (`.sub`), [VPlayer](vplayer) (`.vpl`) and [SAMI](sami) (`.smi`) and [TTML](ttml) (`.ttml` IMSC1 Text profile, `.dfxp` DFXP) parse into a //! [`Document`] of [`Cue`]s and write back. Readers are forgiving (BOM, UTF-16, Windows-1252 //! fallback, CRLF/CR, missing SRT indexes, `,` or `.` milliseconds, missing hours, no blank //! line between cues); writers are strict. WebVTT cue identifiers, cue settings, `` @@ -35,13 +35,18 @@ struct ReadmeExamples; pub mod ass; pub mod cea608; pub mod mcc; +pub mod microdvd; +pub mod mpl2; +pub mod sami; pub mod scc; pub mod srt; pub mod stl; +pub mod subviewer; mod text; /// Exact time: `craft-timeline`'s ticks, frame rates and timecode fields. pub use craft_timeline::time; pub mod ttml; +pub mod vplayer; pub mod vtt; pub use text::{decode_entities, entity_at, plain_text}; @@ -72,10 +77,34 @@ pub enum Format { Dfxp, /// Advanced SubStation Alpha (also reads SubStation Alpha). Ass, + /// MicroDVD (frame-numbered text). + MicroDvd, + /// MPL2 (times in tenths of a second). + Mpl2, + /// SubViewer 2. + SubViewer, + /// VPlayer (start times only). + VPlayer, + /// SAMI (HTML-like). + Sami, } impl Format { - pub const ALL: [Format; 8] = [Format::Srt, Format::WebVtt, Format::Scc, Format::Mcc, Format::Stl, Format::Ttml, Format::Dfxp, Format::Ass]; + pub const ALL: [Format; 13] = [ + Format::Srt, + Format::WebVtt, + Format::Scc, + Format::Mcc, + Format::Stl, + Format::Ttml, + Format::Dfxp, + Format::Ass, + Format::MicroDvd, + Format::Mpl2, + Format::SubViewer, + Format::VPlayer, + Format::Sami, + ]; pub fn name(self) -> &'static str { match self { Format::Srt => "SubRip (SRT)", @@ -86,6 +115,11 @@ impl Format { Format::Ttml => "TTML (IMSC1)", Format::Dfxp => "DFXP (TTML1)", Format::Ass => "Advanced SubStation Alpha (ASS)", + Format::MicroDvd => "MicroDVD", + Format::Mpl2 => "MPL2", + Format::SubViewer => "SubViewer 2", + Format::VPlayer => "VPlayer", + Format::Sami => "SAMI", } } pub fn extension(self) -> &'static str { @@ -98,6 +132,12 @@ impl Format { Format::Ttml => "ttml", Format::Dfxp => "dfxp", Format::Ass => "ass", + Format::MicroDvd => "sub", + Format::Mpl2 => "mpl", + // SubViewer files are `.sub` too, as MicroDVD ones are; `.sbv` tells the two apart. + Format::SubViewer => "sbv", + Format::VPlayer => "vpl", + Format::Sami => "smi", } } pub fn from_name(s: &str) -> Option { @@ -110,6 +150,11 @@ impl Format { "ttml" | "imsc" | "imsc1" | "xml" => Some(Format::Ttml), "dfxp" => Some(Format::Dfxp), "ass" | "ssa" => Some(Format::Ass), + "sub" | "microdvd" => Some(Format::MicroDvd), + "mpl" | "mpl2" => Some(Format::Mpl2), + "subviewer" | "sbv" => Some(Format::SubViewer), + "vplayer" | "vpl" => Some(Format::VPlayer), + "smi" | "sami" => Some(Format::Sami), _ => None, } } @@ -260,6 +305,25 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if head.starts_with("[Script Info]") { return Some(Format::Ass); } + if head.get(..5).is_some_and(|h| h.eq_ignore_ascii_case(" = head.lines().map(str::trim).filter(|l| !l.is_empty()).take(3).collect(); + if first_lines.first().is_some_and(|l| microdvd::is_cue(l)) { + return Some(Format::MicroDvd); + } + if first_lines.first().is_some_and(|l| mpl2::split_cue(l).is_some()) { + return Some(Format::Mpl2); + } + if first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) { + return Some(Format::SubViewer); + } + if !first_lines.is_empty() && first_lines.iter().all(|l| vplayer::split_line(l).is_some()) { + return Some(Format::VPlayer); + } let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase()); if (head.starts_with('<') && (head.contains("") || head.contains(":tt "))) && (head.contains("ns/ttml") || head.contains("ttaf1")) @@ -271,7 +335,7 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { match ext.as_deref() { Some("srt") if has_arrow_timing || head.is_empty() => Some(Format::Srt), Some("vtt") if has_arrow_timing => Some(Format::WebVtt), - Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa") => None, + Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "sub" | "mpl" | "vpl" | "smi" | "sami") => None, _ if has_arrow_timing => Some(Format::Srt), _ => None, } @@ -306,6 +370,11 @@ fn parse_unbounded(bytes: &[u8], format: Format) -> Result { Format::Mcc => mcc::parse(&text), Format::Ttml | Format::Dfxp => ttml::parse(&text), Format::Ass => ass::parse(&text), + Format::MicroDvd => microdvd::parse(&text), + Format::Mpl2 => mpl2::parse(&text), + Format::SubViewer => subviewer::parse(&text), + Format::VPlayer => vplayer::parse(&text), + Format::Sami => sami::parse(&text), Format::Stl => stl::parse(bytes), } } @@ -344,6 +413,11 @@ pub fn write(doc: &Document, format: Format, opts: WriteOptions) -> Vec { Format::Ttml => ttml::write(doc, ttml::Flavor::Imsc1, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), Format::Dfxp => ttml::write(doc, ttml::Flavor::Dfxp, opts.rate, doc.language.as_deref().unwrap_or("")).into_bytes(), Format::Ass => ass::write(doc).into_bytes(), + Format::MicroDvd => microdvd::write(doc, opts.rate).into_bytes(), + Format::Mpl2 => mpl2::write(doc).into_bytes(), + Format::SubViewer => subviewer::write(doc).into_bytes(), + Format::VPlayer => vplayer::write(doc).into_bytes(), + Format::Sami => sami::write(doc).into_bytes(), } } diff --git a/crates/captions/src/microdvd.rs b/crates/captions/src/microdvd.rs new file mode 100644 index 0000000000..7e3d17962a --- /dev/null +++ b/crates/captions/src/microdvd.rs @@ -0,0 +1,223 @@ +//! MicroDVD (`.sub`): frame-numbered text. +//! +//! ```text +//! {1}{1}23.976 +//! {24}{72}First line|{y:i}second line in italics +//! ``` +//! +//! A line is `{first frame}{last frame}text`; `|` starts a new line. A first cue `{1}{1}` whose text +//! is a number gives the frame rate; without it the rate is 23.976 fps (the rate other readers +//! assume). Control codes `{y:i}` / `{y:b}` / `{y:u}` (italic, bold, underline; `i,b` together) +//! and `{c:$BBGGRR}` (colour) style the line they start; the capital forms `{Y:…}` and `{C:…}` +//! style every later line of the cue too. Other controls (`{f:…}` font, `{s:…}` size, `{h:…}`, …) +//! are dropped. Writing always starts with the `{1}{1}` rate line and styles a line only when +//! ``, `` or `` wraps all of it; other tags are dropped, and `{`, `}` and `|` in the +//! text become the full-width `{`, `}` and `|`. + +use crate::text::{LineStyle, escape_markup, number, plain_text, whole_line_style, wrap_style}; +use crate::time::FrameRate; +use crate::{Cue, Document, Error, Result}; + +/// The frame rate of a file that does not name one. +pub const DEFAULT_RATE: FrameRate = FrameRate::FPS_23_976; + +/// `{a}{b}text` as its parts. +fn split_cue(line: &str) -> Option<(i64, i64, &str)> { + let rest = line.strip_prefix('{')?; + let (a, rest) = rest.split_once('}')?; + let rest = rest.strip_prefix('{')?; + let (b, text) = rest.split_once('}')?; + Some((number(a.trim())?, number(b.trim())?, text)) +} + +/// Whether `line` is a `{first}{last}text` cue line. +pub(crate) fn is_cue(line: &str) -> bool { + split_cue(line).is_some() +} + +/// The frame rate a header cue's text names. +fn header_rate(text: &str) -> Option { + let fps: f64 = text.trim().parse().ok()?; + (fps.is_finite() && (1.0..=1000.0).contains(&fps)).then(|| FrameRate::from_f64(fps)) +} + +/// A `$BBGGRR` colour as `#rrggbb`. +fn colour(value: &str) -> Option { + let hex = value.trim().strip_prefix('$')?; + if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let (b, rest) = hex.split_at(2); + let (g, r) = rest.split_at(2); + Some(format!("#{}{}{}", r.to_ascii_lowercase(), g.to_ascii_lowercase(), b.to_ascii_lowercase())) +} + +/// What the styling controls of a cue's lines set. +#[derive(Default)] +struct Sticky { + style: LineStyle, + colour: Option, +} + +/// The text of one line without its `{x:…}` controls, and the controls in order. +fn split_controls(line: &str) -> (String, Vec<(char, String)>) { + let mut text = String::new(); + let mut controls = Vec::new(); + let mut rest = line; + while let Some(open) = rest.find('{') { + text.push_str(rest.get(..open).unwrap_or("")); + let after = rest.get(open + 1..).unwrap_or(""); + let control = after.split_once('}').and_then(|(body, tail)| { + let (name, value) = body.split_once(':')?; + let mut chars = name.chars(); + let c = chars.next().filter(|c| c.is_ascii_alphabetic())?; + chars.next().is_none().then(|| (c, value.to_string(), tail)) + }); + match control { + Some((c, value, tail)) => { + controls.push((c, value)); + rest = tail; + } + None => { + text.push('{'); + rest = after; + } + } + } + text.push_str(rest); + (text, controls) +} + +fn apply_style(value: &str, style: &mut LineStyle) { + for flag in value.split([',', ' ', '/']) { + match flag.trim().to_ascii_lowercase().as_str() { + "i" => style.italic = true, + "b" => style.bold = true, + "u" => style.underline = true, + _ => {} + } + } +} + +fn cue_text(raw: &str) -> String { + let mut sticky = Sticky::default(); + let mut lines = Vec::new(); + for line in raw.split('|') { + let (text, controls) = split_controls(line); + let mut style = sticky.style; + let mut line_colour = sticky.colour.clone(); + for (name, value) in controls { + match name { + 'y' => apply_style(&value, &mut style), + 'Y' => { + apply_style(&value, &mut style); + apply_style(&value, &mut sticky.style); + } + 'c' => line_colour = colour(&value).or(line_colour), + 'C' => { + line_colour = colour(&value).or(line_colour); + sticky.colour = line_colour.clone(); + } + _ => {} + } + } + let text = text.trim(); + if text.is_empty() { + continue; + } + lines.push(wrap_style(style, line_colour.as_deref(), &escape_markup(text))); + } + lines.join("\n") +} + +pub fn parse(text: &str) -> Result { + let mut rows = Vec::new(); + let mut rate = DEFAULT_RATE; + let mut has_rate_line = false; + let mut doc = Document::default(); + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + match split_cue(line) { + Some((1, 1, t)) if rows.is_empty() && !has_rate_line && header_rate(t).is_some() => { + rate = header_rate(t).unwrap_or(rate); + has_rate_line = true; + } + Some(row) => rows.push(row), + None => doc.warnings.push(format!("line {}: not a MicroDVD cue, skipped", n + 1)), + } + } + if rows.is_empty() && !has_rate_line && !text.trim().is_empty() { + return Err(Error::NotFormat("MicroDVD")); + } + for (first, last, raw) in rows { + let (start, end) = (rate.tick_of(first), rate.tick_of(last)); + let text = cue_text(raw); + if end <= start || text.is_empty() { + doc.warnings.push(format!("the cue at frame {first} is empty or ends at frame {last}; skipped")); + continue; + } + doc.cues.push(Cue { start, end, text, ..Default::default() }); + } + Ok(doc) +} + +/// Write `doc` with its frames counted at `rate` (None: [`DEFAULT_RATE`]). +pub fn write(doc: &Document, rate: Option) -> String { + let rate = rate.map_or(DEFAULT_RATE, FrameRate::sane); + let mut out = format!("{{1}}{{1}}{:.3}\n", rate.as_f64()); + let frame = |t| rate.frame_at(rate.snap_nearest(t)).max(0); + for c in &doc.cues { + let first = frame(c.start); + let last = frame(c.end).max(first.saturating_add(1)); + let mut lines = Vec::new(); + for line in c.text.lines() { + let (style, inner) = whole_line_style(line); + let text = plain_text(inner).trim().replace('{', "\u{ff5b}").replace('}', "\u{ff5d}").replace('|', "\u{ff5c}"); + if text.is_empty() { + continue; + } + let mut flags = Vec::new(); + for (on, f) in [(style.italic, "i"), (style.bold, "b"), (style.underline, "u")] { + if on { + flags.push(f); + } + } + lines.push(if flags.is_empty() { text } else { format!("{{y:{}}}{text}", flags.join(",")) }); + } + if lines.is_empty() { + continue; + } + out.push_str(&format!("{{{first}}}{{{last}}}{}\n", lines.join("|"))); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn controls_style_lines() { + assert_eq!(cue_text("{y:i,b}x|plain"), "x\nplain"); + assert_eq!(cue_text("{Y:i}a|b"), "a\nb"); + assert_eq!(cue_text("{c:$0000ff}red"), "red"); + assert_eq!(cue_text("{f:Arial}{s:20}a & b {x"), "a & b {x"); + } + + #[test] + fn rate_header() { + let d = parse("{1}{1}25.000\n{25}{50}x\n").unwrap(); + assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25)); + let d = parse("{25}{50}x\n").unwrap(); + assert_eq!(d.cues[0].start, DEFAULT_RATE.tick_of(25)); + } + + #[test] + fn rejects_other_text() { + assert!(parse("hello\nworld\n").is_err()); + assert!(parse("").unwrap().cues.is_empty()); + } +} diff --git a/crates/captions/src/mpl2.rs b/crates/captions/src/mpl2.rs new file mode 100644 index 0000000000..af1ac07722 --- /dev/null +++ b/crates/captions/src/mpl2.rs @@ -0,0 +1,95 @@ +//! MPL2 (`.txt`, `.mpl`): times in tenths of a second. +//! +//! ```text +//! [10][35]First line|/second line in italics +//! ``` +//! +//! A line is `[start][end]text` with times in deciseconds. `|` starts a new line; a `/` at the +//! start of a line makes it italic. Writing marks a line italic only when `` wraps all of it, +//! drops other tags, rounds times to a tenth of a second, and writes `|` in text as `|`. + +use crate::text::{escape_markup, ms_to_tick, number, plain_text, tick_to_ms, whole_line_style, wrap_style}; +use crate::{Cue, Document, Error, Result}; + +/// `[a][b]text` as its parts. +pub(crate) fn split_cue(line: &str) -> Option<(i64, i64, &str)> { + let rest = line.strip_prefix('[')?; + let (a, rest) = rest.split_once(']')?; + let rest = rest.strip_prefix('[')?; + let (b, text) = rest.split_once(']')?; + Some((number(a.trim())?, number(b.trim())?, text)) +} + +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut found = false; + for (n, line) in text.lines().enumerate() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let Some((a, b, raw)) = split_cue(line) else { + doc.warnings.push(format!("line {}: not an MPL2 cue, skipped", n + 1)); + continue; + }; + found = true; + let mut lines = Vec::new(); + for l in raw.split('|') { + let (italic, l) = match l.trim().strip_prefix('/') { + Some(r) => (true, r.trim()), + None => (false, l.trim()), + }; + if !l.is_empty() { + lines.push(wrap_style(crate::text::LineStyle { italic, ..Default::default() }, None, &escape_markup(l))); + } + } + let (start, end) = (ms_to_tick(a.saturating_mul(100)), ms_to_tick(b.saturating_mul(100))); + if end <= start || lines.is_empty() { + doc.warnings.push(format!("line {}: empty or ends before it starts; skipped", n + 1)); + continue; + } + doc.cues.push(Cue { start, end, text: lines.join("\n"), ..Default::default() }); + } + if !found && !text.trim().is_empty() { + return Err(Error::NotFormat("MPL2")); + } + Ok(doc) +} + +pub fn write(doc: &Document) -> String { + let mut out = String::new(); + let ds = |t| (tick_to_ms(t) + 50) / 100; + for c in &doc.cues { + let start = ds(c.start); + let end = ds(c.end).max(start + 1); + let mut lines = Vec::new(); + for line in c.text.lines() { + let (style, inner) = whole_line_style(line); + let text = plain_text(inner).trim().replace('|', "\u{ff5c}"); + if !text.is_empty() { + lines.push(if style.italic { format!("/{text}") } else { text }); + } + } + if !lines.is_empty() { + out.push_str(&format!("[{start}][{end}]{}\n", lines.join("|"))); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn italics_and_lines() { + let d = parse("[10][35]Hello|/italic\n").unwrap(); + assert_eq!(d.cues[0].text, "Hello\nitalic"); + assert_eq!(d.cues[0].end, ms_to_tick(3500)); + } + + #[test] + fn rejects_other_text() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err()); + } +} diff --git a/crates/captions/src/sami.rs b/crates/captions/src/sami.rs new file mode 100644 index 0000000000..3329cc53e0 --- /dev/null +++ b/crates/captions/src/sami.rs @@ -0,0 +1,256 @@ +//! SAMI (`.smi`, `.sami`): Microsoft's HTML-like captions. +//! +//! ```text +//! +//!

First line
second line +//!

  +//! +//! ``` +//! +//! A `` block shows its text from that millisecond until the next block; a block +//! holding only ` ` clears the screen. The last caption lasts four seconds if nothing clears +//! it. `
` starts a new line; ``, ``, `` and `` are kept, other tags +//! dropped; `&`, `<`, `>`, ` ` and numeric references are read. A file can hold +//! several language classes (`

`, `

`): the first one named is read and +//! the others skipped with a warning. Writing makes one `ENCC` class, an ` ` block where a +//! caption ends before the next starts, and rounds to milliseconds. + +use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, sequential, tick_to_ms}; +use crate::time::Tick; +use crate::{Cue, Document, Error, Result}; + +/// The value of attribute `name` in the tag text `tag` (quotes optional). +fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> { + let lower = tag.to_ascii_lowercase(); + let mut from = 0; + while let Some(i) = lower.get(from..).and_then(|r| r.find(name)) { + let at = from + i; + from = at + name.len(); + let before_ok = at == 0 || lower.as_bytes().get(at - 1).is_some_and(|b| !b.is_ascii_alphanumeric()); + let rest = tag.get(from..).unwrap_or("").trim_start(); + let Some(rest) = rest.strip_prefix('=').filter(|_| before_ok) else { continue }; + let rest = rest.trim_start(); + return Some(match rest.chars().next() { + Some(q @ ('"' | '\'')) => { + let inner = rest.get(1..).unwrap_or(""); + inner.split(q).next().unwrap_or("") + } + _ => rest.split(|c: char| c.is_whitespace() || c == '>').next().unwrap_or(""), + }); + } + None +} + +/// A numeric character reference body (`#65`, `#x41`) as its character. +fn numeric_reference(body: &str) -> Option { + let digits = body.strip_prefix('#')?; + let code = match digits.strip_prefix(['x', 'X']) { + Some(hex) => u32::from_str_radix(hex, 16).ok()?, + None => digits.parse().ok()?, + }; + char::from_u32(code).filter(|c| !c.is_control() || *c == '\n') +} + +/// HTML text as cue text: entities the cue model keeps stay, numeric ones are decoded, a stray +/// `&` is escaped, whitespace runs collapse. +fn text_run(s: &str) -> String { + let mut out = String::new(); + let mut rest = s; + let mut space = false; + while let Some(c) = rest.chars().next() { + let mut advance = c.len_utf8(); + if c.is_whitespace() && c != '\u{a0}' { + space = true; + rest = rest.get(advance..).unwrap_or(""); + continue; + } + if space { + out.push(' '); + } + space = false; + if c == '&' { + if let Some((_, len)) = crate::entity_at(rest) { + out.push_str(rest.get(..len).unwrap_or("")); + advance = len; + } else if let Some((body, _)) = rest.get(1..).and_then(|r| r.split_once(';')).filter(|(b, _)| b.len() <= 8) + && let Some(ch) = numeric_reference(body) + { + out.push_str(&escape_markup(&ch.to_string())); + advance = body.len() + 2; + } else { + out.push_str("&"); + } + } else { + out.push_str(&escape_markup(&c.to_string())); + } + rest = rest.get(advance..).unwrap_or(""); + } + if space { + out.push(' '); + } + out +} + +/// One `` block's body as (class, cue text) segments, one per `

`. +fn segments(body: &str) -> Vec<(String, String)> { + let mut segs: Vec<(String, String)> = vec![(String::new(), String::new())]; + let mut open_fonts = 0usize; + let mut rest = body; + while !rest.is_empty() { + let Some(lt) = rest.find('<') else { + if let Some(last) = segs.last_mut() { + last.1.push_str(&text_run(rest)); + } + break; + }; + if let Some(last) = segs.last_mut() { + last.1.push_str(&text_run(rest.get(..lt).unwrap_or(""))); + } + let after = rest.get(lt + 1..).unwrap_or(""); + let Some(gt) = after.find('>') else { + if let Some(last) = segs.last_mut() { + last.1.push_str("<"); + last.1.push_str(&text_run(after)); + } + break; + }; + let tag = after.get(..gt).unwrap_or(""); + rest = after.get(gt + 1..).unwrap_or(""); + let closing = tag.starts_with('/'); + let name: String = tag.trim_start_matches('/').chars().take_while(char::is_ascii_alphanumeric).collect::().to_ascii_lowercase(); + let Some(last) = segs.last_mut() else { continue }; + match (name.as_str(), closing) { + ("br", _) => last.1.push('\n'), + ("p", false) => segs.push((attribute(tag, "class").unwrap_or("").to_string(), String::new())), + ("i" | "b" | "u", false) => last.1.push_str(&format!("<{name}>")), + ("i" | "b" | "u", true) => last.1.push_str(&format!("")), + ("font", false) => { + if let Some(c) = attribute(tag, "color").filter(|c| c.len() <= 20 && c.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'#')) { + open_fonts += 1; + last.1.push_str(&format!("")); + } + } + ("font", true) if open_fonts > 0 => { + open_fonts -= 1; + last.1.push_str(""); + } + _ => {} + } + } + segs +} + +/// A caption text without the whitespace and non-breaking spaces round its lines. +fn tidy(text: &str) -> String { + let lines: Vec = text + .split('\n') + .map(|l| l.replace(" ", " ").trim().to_string()) + .filter(|l| !l.is_empty() && !crate::plain_text(l).trim().is_empty()) + .collect(); + lines.join("\n") +} + +pub fn parse(text: &str) -> Result { + let lower = text.to_ascii_lowercase(); + let mut starts: Vec = Vec::new(); + let mut from = 0; + while let Some(i) = lower.get(from..).and_then(|r| r.find(" = None; + let mut skipped_class = false; + let mut syncs: Vec<(Tick, String)> = Vec::new(); + for (k, &at) in starts.iter().enumerate() { + let stop = starts.get(k + 1).copied().unwrap_or(text.len()); + let chunk = text.get(at..stop).unwrap_or(""); + let chunk = match chunk.to_ascii_lowercase().find(" chunk.get(..i).unwrap_or(chunk), + None => chunk, + }; + let Some((tag, body)) = chunk.get(1..).and_then(|c| c.split_once('>')) else { continue }; + let Some(start) = attribute(tag, "start").and_then(|v| number(v.trim())) else { + doc.warnings.push("a without a Start time was skipped".to_string()); + continue; + }; + let mut shown = String::new(); + for (cls, seg) in segments(body) { + if class.is_none() && !cls.is_empty() { + class = Some(cls.to_ascii_lowercase()); + } + if class.as_deref().is_none_or(|c| c == cls.to_ascii_lowercase() || cls.is_empty()) { + shown.push_str(&seg); + } else { + skipped_class = true; + } + } + syncs.push((ms_to_tick(start), tidy(&shown))); + } + if skipped_class { + doc.warnings.push("the file has other language classes; only the first was read".to_string()); + } + syncs.sort_by_key(|(t, _)| *t); + for (i, (start, text)) in syncs.iter().enumerate() { + if text.is_empty() { + continue; + } + let end = syncs.get(i + 1).map_or_else(|| last_cue_end(*start), |(next, _)| *next); + if end <= *start { + doc.warnings.push("two captions start at the same time; the first was skipped".to_string()); + continue; + } + doc.cues.push(Cue { start: *start, end, text: text.clone(), ..Default::default() }); + } + Ok(doc) +} + +pub fn write(doc: &Document) -> String { + let cues = sequential(doc); + let mut out = String::from( + "\n\n\n\n\n\n", + ); + for (i, c) in cues.iter().enumerate() { + let lines: Vec<&str> = c.text.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); + if lines.is_empty() { + continue; + } + out.push_str(&format!("

{}\n", tick_to_ms(c.start), lines.join("
"))); + if cues.get(i + 1).map(|n| tick_to_ms(n.start)) != Some(tick_to_ms(c.end)) { + out.push_str(&format!("

 \n", tick_to_ms(c.end))); + } + } + out.push_str("\n\n"); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blocks_clear_and_style() { + let d = parse("\n

Hello
world & you\n

 \n

x A y\n").unwrap(); + assert_eq!(d.cues.len(), 2); + assert_eq!(d.cues[0].text, "Hello\nworld & you"); + assert_eq!(d.cues[0].end, ms_to_tick(3500)); + assert_eq!(d.cues[1].text, "x A y"); + assert_eq!(d.cues[1].end, last_cue_end(ms_to_tick(4000))); + } + + #[test] + fn only_the_first_class_is_read() { + let d = parse("

en

kr

 ").unwrap(); + assert_eq!(d.cues.len(), 1); + assert_eq!(d.cues[0].text, "en"); + assert_eq!(d.warnings.len(), 1); + } + + #[test] + fn rejects_other_text() { + assert!(parse("hello").is_err()); + } +} diff --git a/crates/captions/src/subviewer.rs b/crates/captions/src/subviewer.rs new file mode 100644 index 0000000000..337788f320 --- /dev/null +++ b/crates/captions/src/subviewer.rs @@ -0,0 +1,116 @@ +//! SubViewer 2 (`.sub`): hundredths of a second, with an information header. +//! +//! ```text +//! [INFORMATION] +//! [TITLE]… +//! [END INFORMATION] +//! [SUBTITLE] +//! 00:00:01.00,00:00:03.50 +//! First line[br]second line +//! +//! ``` +//! +//! Reading skips the bracketed header lines and takes every `start,end` time line as a cue whose +//! text runs to the next blank line; `[br]` starts a new line. Fractions of one to three digits +//! are accepted. Writing adds a minimal header, rounds times to a hundredth of a second, drops +//! tags and writes `[br]` inside text as `[br]`. + +use crate::text::{escape_markup, plain_lines, tick_to_ms}; +use crate::time::Tick; +use crate::{Cue, Document, Error, Result, parse_clock}; + +/// `h:mm:ss.cc,h:mm:ss.cc` as its two times. +pub(crate) fn parse_timing(line: &str) -> Option<(Tick, Tick)> { + let (a, b) = line.trim().split_once(',')?; + let ok = |s: &str| s.contains(':') && s.contains('.'); + if !ok(a) || !ok(b) { + return None; + } + Some((parse_clock(a)?, parse_clock(b)?)) +} + +/// Split `s` at each `[br]`, whatever its case. +fn split_br(s: &str) -> Vec<&str> { + let lower = s.to_ascii_lowercase(); + let mut parts = Vec::new(); + let mut from = 0; + while let Some(i) = lower.get(from..).and_then(|r| r.find("[br]")) { + parts.push(s.get(from..from + i).unwrap_or("")); + from += i + 4; + } + parts.push(s.get(from..).unwrap_or("")); + parts +} + +pub fn parse(text: &str) -> Result { + let lines: Vec<&str> = text.lines().collect(); + let mut doc = Document::default(); + let mut found = false; + let mut i = 0; + while i < lines.len() { + let Some((start, end)) = lines.get(i).and_then(|l| parse_timing(l)) else { + i += 1; + continue; + }; + found = true; + i += 1; + let mut out: Vec = Vec::new(); + while let Some(l) = lines.get(i).filter(|l| !l.trim().is_empty()) { + if parse_timing(l).is_some() { + break; + } + out.extend(split_br(l).into_iter().map(str::trim).filter(|p| !p.is_empty()).map(escape_markup)); + i += 1; + } + if end <= start || out.is_empty() { + doc.warnings.push(format!("the cue at line {i} is empty or ends before it starts; skipped")); + continue; + } + doc.cues.push(Cue { start, end, text: out.join("\n"), ..Default::default() }); + } + let has_header = text.contains("[INFORMATION]") || text.contains("[SUBTITLE]"); + if !found && !has_header && !text.trim().is_empty() { + return Err(Error::NotFormat("SubViewer")); + } + Ok(doc) +} + +fn clock(t: Tick) -> String { + let cs = (tick_to_ms(t) + 5) / 10; + format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100) +} + +pub fn write(doc: &Document) -> String { + let mut out = String::from( + "[INFORMATION]\n[TITLE]\n[AUTHOR]\n[SOURCE]\n[PRG]\n[FILEPATH]\n[DELAY]0\n[CD TRACK]0\n[COMMENT]\n[END INFORMATION]\n[SUBTITLE]\n[COLF]&HFFFFFF,[STYLE]no,[SIZE]18,[FONT]Arial\n", + ); + for c in &doc.cues { + let lines = plain_lines(&c.text); + if lines.is_empty() { + continue; + } + let end = if clock(c.end) == clock(c.start) { Tick(c.end.0.saturating_add(crate::TICKS_PER_MS * 10)) } else { c.end }; + out.push_str(&format!("{},{}\n", clock(c.start), clock(end))); + let lines: Vec = lines.iter().map(|l| l.replace("[br]", "\u{ff3b}br\u{ff3d}").replace("[BR]", "\u{ff3b}BR\u{ff3d}")).collect(); + out.push_str(&lines.join("[br]")); + out.push_str("\n\n"); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn header_and_breaks() { + let d = parse("[INFORMATION]\n[TITLE]x\n[END INFORMATION]\n[SUBTITLE]\n00:00:01.00,00:00:03.50\nHello[BR]world\n\n").unwrap(); + assert_eq!(d.cues[0].text, "Hello\nworld"); + assert_eq!(d.cues[0].end, crate::text::ms_to_tick(3500)); + } + + #[test] + fn rejects_other_text() { + assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err()); + } +} diff --git a/crates/captions/src/text.rs b/crates/captions/src/text.rs index 634e7108d8..35cd23c0fc 100644 --- a/crates/captions/src/text.rs +++ b/crates/captions/src/text.rs @@ -85,6 +85,108 @@ pub fn plain_text(s: &str) -> String { out } +use crate::time::{TICKS_PER_SECOND, Tick}; +use crate::{Cue, Document, TICKS_PER_MS}; + +/// How long the last cue of a format that gives only start times lasts: such a file says when a +/// caption appears, and the next one ends it. +pub(crate) const LAST_CUE: Tick = Tick(4 * TICKS_PER_SECOND); + +/// `start + LAST_CUE`, not overflowing. +pub(crate) fn last_cue_end(start: Tick) -> Tick { + Tick(start.0.saturating_add(LAST_CUE.0)) +} + +/// Milliseconds as a time. +pub(crate) fn ms_to_tick(ms: i64) -> Tick { + Tick(ms.saturating_mul(TICKS_PER_MS)) +} + +/// A time in whole milliseconds, rounded to the nearest; negative times read as zero. +pub(crate) fn tick_to_ms(t: Tick) -> i64 { + let per = i128::from(TICKS_PER_MS); + ((i128::from(t.0.max(0)) + per / 2) / per) as i64 +} + +/// A decimal number of at most nine digits (so that times built from it cannot overflow). +pub(crate) fn number(s: &str) -> Option { + if s.is_empty() || s.len() > 9 || !s.bytes().all(|b| b.is_ascii_digit()) { None } else { s.parse().ok() } +} + +/// Plain text as cue text: a literal `&` or `<` becomes an entity so that it is not read as markup. +pub(crate) fn escape_markup(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + _ => out.push(c), + } + } + out +} + +/// The cue's text as plain lines (tags gone, entities decoded, empty lines dropped). +pub(crate) fn plain_lines(text: &str) -> Vec { + text.lines().map(plain_text).map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect() +} + +/// The style a whole line of cue text carries: ``, `` and `` around all of it. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub(crate) struct LineStyle { + pub italic: bool, + pub bold: bool, + pub underline: bool, +} + +/// The style that wraps the whole of `line`, and the line without it. `a b c` is not +/// italic as a whole. +pub(crate) fn whole_line_style(line: &str) -> (LineStyle, &str) { + let mut style = LineStyle::default(); + let mut rest = line.trim(); + loop { + let mut changed = false; + for (open, close, flag) in [("", "", 0), ("", "", 1), ("", "", 2)] { + if let Some(inner) = rest.strip_prefix(open).and_then(|r| r.strip_suffix(close)) + && !inner.contains(open) + && !inner.contains(close) + { + match flag { + 0 => style.italic = true, + 1 => style.bold = true, + _ => style.underline = true, + } + rest = inner.trim(); + changed = true; + } + } + if !changed { + return (style, rest); + } + } +} + +/// Cue text from a line's style and its (already escaped) text. +pub(crate) fn wrap_style(style: LineStyle, color: Option<&str>, text: &str) -> String { + let mut out = text.to_string(); + for (on, tag) in [(style.underline, "u"), (style.bold, "b"), (style.italic, "i")] { + if on { + out = format!("<{tag}>{out}"); + } + } + match color { + Some(c) => format!("{out}"), + None => out, + } +} + +/// The cues of `doc` in time order with no overlaps, for a format that holds one caption at a time. +pub(crate) fn sequential(doc: &Document) -> Vec { + let mut copy = Document { cues: doc.cues.clone(), ..Default::default() }; + copy.normalize(); + copy.cues +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/captions/src/vplayer.rs b/crates/captions/src/vplayer.rs new file mode 100644 index 0000000000..e8900c0b60 --- /dev/null +++ b/crates/captions/src/vplayer.rs @@ -0,0 +1,116 @@ +//! VPlayer (`.txt`, `.vpl`): one start time per caption. +//! +//! ```text +//! 00:00:01.00=First line|second line +//! 00:00:04.00= +//! ``` +//! +//! A line is `HH:MM:SS`, an optional `.cc` fraction, one of `:`, `=` or a space, and the text; `|` +//! starts a new line. The file gives only when each caption appears: it stays until the next +//! line, whose empty text clears it. The last caption lasts four seconds if no line ends it. +//! Writing puts a clearing line where a caption ends before the next one starts, drops tags, +//! rounds to a hundredth of a second and writes `|` in text as `|`. + +use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, plain_lines, sequential, tick_to_ms}; +use crate::time::Tick; +use crate::{Cue, Document, Error, Result}; + +/// `HH:MM:SS[.cc]` then a separator and text: the time and the text. +pub(crate) fn split_line(line: &str) -> Option<(Tick, &str)> { + let mut parts = line.splitn(3, ':'); + let h = number(parts.next()?)?; + let m = number(parts.next()?)?; + let tail = parts.next()?; + let digits = tail.bytes().take_while(u8::is_ascii_digit).count(); + let s = number(tail.get(..digits)?)?; + let mut rest = tail.get(digits..)?; + let mut ms = 0; + if let Some(frac) = rest.strip_prefix('.') { + let n = frac.bytes().take_while(u8::is_ascii_digit).count().min(3); + let f = frac.get(..n).filter(|f| !f.is_empty())?; + ms = number(f)? * 10_i64.pow(3 - n as u32); + rest = frac.get(n..)?; + // further digits of a long fraction are below a millisecond + rest = rest.trim_start_matches(|c: char| c.is_ascii_digit()); + } + if m >= 60 || s >= 60 || h > 9999 { + return None; + } + let text = rest.strip_prefix([':', '=', ' '])?; + Some((ms_to_tick(((h * 60 + m) * 60 + s) * 1000 + ms), text)) +} + +pub fn parse(text: &str) -> Result { + let mut doc = Document::default(); + let mut starts: Vec<(Tick, String)> = Vec::new(); + for (n, line) in text.lines().enumerate() { + if line.trim().is_empty() { + continue; + } + match split_line(line.trim()) { + Some((t, raw)) => { + let lines: Vec = raw.split('|').map(str::trim).filter(|l| !l.is_empty()).map(escape_markup).collect(); + starts.push((t, lines.join("\n"))); + } + None => doc.warnings.push(format!("line {}: not a VPlayer line, skipped", n + 1)), + } + } + if starts.is_empty() && !text.trim().is_empty() { + return Err(Error::NotFormat("VPlayer")); + } + for (i, (start, text)) in starts.iter().enumerate() { + if text.is_empty() { + continue; + } + let end = starts.get(i + 1).map_or_else(|| last_cue_end(*start), |(next, _)| *next); + if end <= *start { + doc.warnings.push("a caption is followed by a line at the same time; skipped".to_string()); + continue; + } + doc.cues.push(Cue { start: *start, end, text: text.clone(), ..Default::default() }); + } + Ok(doc) +} + +fn clock(t: Tick) -> String { + let cs = (tick_to_ms(t) + 5) / 10; + format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100) +} + +pub fn write(doc: &Document) -> String { + let cues = sequential(doc); + let mut out = String::new(); + for (i, c) in cues.iter().enumerate() { + let lines = plain_lines(&c.text); + if lines.is_empty() { + continue; + } + let lines: Vec = lines.iter().map(|l| l.replace('|', "\u{ff5c}")).collect(); + out.push_str(&format!("{}={}\n", clock(c.start), lines.join("|"))); + let next = cues.get(i + 1).map(|n| clock(n.start)); + if next.as_deref() != Some(clock(c.end).as_str()) { + out.push_str(&format!("{}=\n", clock(c.end))); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn separators_and_ends() { + let d = parse("00:00:01:Hello|world\n00:00:04.50=\n00:00:05 later\n").unwrap(); + assert_eq!(d.cues.len(), 2); + assert_eq!(d.cues[0].text, "Hello\nworld"); + assert_eq!(d.cues[0].end, ms_to_tick(4500)); + assert_eq!(d.cues[1].end, ms_to_tick(9000)); + } + + #[test] + fn rejects_other_text() { + assert!(parse("hello\n").is_err()); + assert!(parse("00:00:01,000 --> 00:00:02,000\n").is_err()); + } +} diff --git a/crates/captions/tests/it/legacy_text.rs b/crates/captions/tests/it/legacy_text.rs new file mode 100644 index 0000000000..14f9197ca0 --- /dev/null +++ b/crates/captions/tests/it/legacy_text.rs @@ -0,0 +1,231 @@ +//! The legacy text formats (MicroDVD, MPL2, SubViewer 2, VPlayer, SAMI): reading, writing, and +//! ffmpeg as the reference (oracle; skipped when ffmpeg is absent, a failure with +//! `CRAFT_MEDIA_REQUIRE_ORACLES=1`). + +use craft_captions::time::FrameRate; +use craft_captions::{Cue, Document, Format, TICKS_PER_SECOND, Tick, WriteOptions, detect, parse, plain_text, write}; +use std::process::Command; + +const T: i64 = TICKS_PER_SECOND; +const MS: i64 = T / 1000; + +fn ms(v: i64) -> Tick { + Tick(v * MS) +} + +/// The five formats, with the ffmpeg format name each is read and written through. +const FORMATS: [(Format, &str, &str); 5] = [ + (Format::MicroDvd, "microdvd", "sub"), + (Format::Mpl2, "mpl2", "txt"), + (Format::SubViewer, "subviewer", "sbv"), + (Format::VPlayer, "vplayer", "txt"), + (Format::Sami, "sami", "smi"), +]; + +const MICRODVD: &str = "{1}{1}23.976\n{24}{72}Hello|{y:i}second bold\n{100}{150}{c:$0000ff}red\n{200}{250}a & b < c\n"; +const MPL2: &str = "[10][35]Hello|/italic\n[40][60]plain\n[70][90]/a|/b\n"; +const SUBVIEWER: &str = "[INFORMATION]\n[TITLE]x\n[END INFORMATION]\n[SUBTITLE]\n[COLF]&HFFFFFF,[STYLE]bd,[SIZE]18,[FONT]Arial\n00:00:01.00,00:00:03.50\nHello[br]world\n\n00:00:04.00,00:00:05.00\nplain\n"; +const VPLAYER: &str = "00:00:01.00=Hello|world\n00:00:04.00=\n00:00:05:plain\n00:00:09 later\n"; +const SAMI: &str = "\nx\n\n

Hello
world\n

 \n

plain & more\n

 \n\n\n"; + +fn samples() -> [(Format, &'static str); 5] { + [(Format::MicroDvd, MICRODVD), (Format::Mpl2, MPL2), (Format::SubViewer, SUBVIEWER), (Format::VPlayer, VPLAYER), (Format::Sami, SAMI)] +} + +fn run(ff: &std::path::Path, args: &[&str]) { + let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +/// What ffmpeg reads from `bytes` as `ffmpeg_format`, as cues. +fn ffmpeg_reads(ff: &std::path::Path, name: &str, ffmpeg_format: &str, ext: &str, bytes: &[u8]) -> Document { + let dir = craft_media_testkit::fixture_subdir("captions_legacy"); + let (input, out) = (dir.join(format!("{name}.{ext}")), dir.join(format!("{name}.srt"))); + std::fs::write(&input, bytes).expect("write"); + run(ff, &["-f", ffmpeg_format, "-i", input.to_str().expect("path"), out.to_str().expect("path")]); + parse(&std::fs::read(&out).expect("read"), Format::Srt).expect("parse ffmpeg's srt") +} + +/// The lines of a cue's text as plain text, tags and entities gone. +fn plain(c: &Cue) -> String { + c.text.lines().map(|l| plain_text(l).trim().to_string()).collect::>().join("\n") +} + +#[test] +fn we_read_what_ffmpeg_reads() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + for (format, text) in samples() { + let (_, name, ext) = FORMATS.iter().copied().find(|f| f.0 == format).expect("format"); + let ours = parse(text.as_bytes(), format).expect("parse"); + let theirs = ffmpeg_reads(&ff, &format!("read_{name}"), name, ext, text.as_bytes()); + assert_eq!(ours.cues.len(), theirs.cues.len(), "{format:?}: {:?} against {:?}", ours.cues, theirs.cues); + for (i, (o, t)) in ours.cues.iter().zip(&theirs.cues).enumerate() { + // ffmpeg gives a last caption of a start-only format no end (an enormous one). + let last = i + 1 == ours.cues.len(); + let open_ended = matches!(format, Format::VPlayer | Format::Sami) && last; + assert!((o.start.0 - t.start.0).abs() <= MS, "{format:?} start of {:?}: {:?} against {:?}", o.text, o.start, t.start); + if !open_ended { + assert!((o.end.0 - t.end.0).abs() <= MS, "{format:?} end of {:?}: {:?} against {:?}", o.text, o.end, t.end); + } + assert_eq!(plain(o), plain(t), "{format:?} text of the cue at {:?}", o.start); + } + } +} + +fn sample_document() -> Document { + let cue = |a: i64, b: i64, text: &str| Cue { start: ms(a), end: ms(b), text: text.into(), ..Default::default() }; + Document { + cues: vec![ + cue(1000, 3500, "Hello\nsecond line"), + cue(3500, 5000, "straight after, with & and <"), + cue(7000, 9000, "after a gap [br] { } |"), + cue(3_600_000, 3_601_500, "an hour in"), + ], + ..Default::default() + } +} + +#[test] +fn ffmpeg_reads_what_we_write() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + // ffmpeg's own readers mangle the look-alike characters a writer uses for what a format cannot hold, + // so the cue that has those is left out here (write_then_read covers it). + let mut doc = sample_document(); + doc.cues[2].text = "after a gap".into(); + for (format, name, ext) in FORMATS { + let bytes = write(&doc, format, WriteOptions::default()); + let theirs = ffmpeg_reads(&ff, &format!("write_{name}"), name, ext, &bytes); + assert_eq!(theirs.cues.len(), doc.cues.len(), "{format:?}: {:?}", String::from_utf8_lossy(&bytes)); + for (t, d) in theirs.cues.iter().zip(&doc.cues) { + let tolerance = if format == Format::MicroDvd { 45 * MS } else { 10 * MS }; + assert!((t.start.0 - d.start.0).abs() <= tolerance, "{format:?} start of {:?}: {:?}", d.text, t.start); + // the characters a format cannot hold are written as look-alikes: compare without them + let bare = |c: &Cue| { + plain(c) + .replace('\u{ff3b}', "[") + .replace('\u{ff3d}', "]") + .replace("[br]", "") + .replace(['{', '}', '|', '\u{ff5b}', '\u{ff5d}', '\u{ff5c}'], "") + .replace(" ", " ") + }; + assert_eq!(bare(t), bare(d), "{format:?}"); + } + } +} + +#[test] +fn write_then_read_keeps_times_and_text() { + let doc = sample_document(); + for (format, _, _) in FORMATS { + let bytes = write(&doc, format, WriteOptions::default()); + let back = parse(&bytes, format).unwrap_or_else(|e| panic!("{format:?}: {e}")); + assert_eq!(back.cues.len(), doc.cues.len(), "{format:?}"); + let tolerance = match format { + Format::MicroDvd => 25 * MS, + Format::Mpl2 => 50 * MS, + _ => 5 * MS, + }; + for (b, d) in back.cues.iter().zip(&doc.cues) { + assert!((b.start.0 - d.start.0).abs() <= tolerance, "{format:?} start {:?} against {:?}", b.start, d.start); + assert!((b.end.0 - d.end.0).abs() <= tolerance, "{format:?} end {:?} against {:?}", b.end, d.end); + } + assert_eq!(back.cues[0].text.lines().count(), 2, "{format:?} keeps the line break"); + assert_eq!(plain(&back.cues[1]), "straight after, with & and <", "{format:?}"); + } +} + +#[test] +fn styles_survive_where_the_format_has_them() { + let doc = Document { + cues: vec![Cue { start: ms(0), end: ms(2000), text: "plain\nslanted".into(), ..Default::default() }], + ..Default::default() + }; + for format in [Format::MicroDvd, Format::Mpl2] { + let back = parse(&write(&doc, format, WriteOptions::default()), format).expect("parse"); + assert_eq!(back.cues[0].text, "plain\nslanted", "{format:?}"); + } + // SAMI keeps inline tags too. + let doc = Document { + cues: vec![Cue { start: ms(0), end: ms(2000), text: "a bold and more".into(), ..Default::default() }], + ..Default::default() + }; + assert_eq!(parse(&write(&doc, Format::Sami, WriteOptions::default()), Format::Sami).expect("parse").cues[0].text, doc.cues[0].text); +} + +#[test] +fn microdvd_counts_frames_at_the_given_rate() { + let doc = Document { cues: vec![Cue { start: Tick(2 * T), end: Tick(4 * T), text: "x".into(), ..Default::default() }], ..Default::default() }; + let bytes = write(&doc, Format::MicroDvd, WriteOptions { rate: Some(FrameRate::FPS_25), ..Default::default() }); + assert_eq!(String::from_utf8(bytes.clone()).expect("utf8"), "{1}{1}25.000\n{50}{100}x\n"); + let back = parse(&bytes, Format::MicroDvd).expect("parse"); + assert_eq!((back.cues[0].start, back.cues[0].end), (Tick(2 * T), Tick(4 * T))); +} + +#[test] +fn detection_finds_each_format() { + for (format, text) in samples() { + assert_eq!(detect(text.as_bytes(), None), Some(format), "{format:?}"); + let ext = FORMATS.iter().find(|f| f.0 == format).map(|f| f.2); + assert_eq!(detect(text.as_bytes(), ext), Some(format), "{format:?} with its extension"); + } + assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nx\n", None), Some(Format::Srt)); + assert_eq!(detect(b"just some prose\n", Some("txt")), None); +} + +#[test] +fn other_text_is_not_one_of_these_formats() { + for (format, _, _) in FORMATS { + assert!(parse(b"hello there\nthis is not a subtitle file\n", format).is_err(), "{format:?}"); + assert!(parse(b"", format).expect("empty").cues.is_empty(), "{format:?}"); + } +} + +#[test] +fn hostile_input_is_an_error_or_a_warning_never_a_panic() { + let mut inputs: Vec> = vec![ + "{".repeat(10_000).into_bytes(), + "{1}{1}".repeat(2000).into_bytes(), + "{999999999}{999999999}x\n{1}{99999999999999999999}y\n{5}{3}z\n".into(), + "[999999999][999999999]x\n[1][2".into(), + "99999:99:99.99,99999:99:99.99\nx\n\n00:00:01.00,00:00:00.00\ny\n".into(), + "99999999:00:00=x\n00:60:00=y\n00:00:00.=z\n".into(), + "

xy<<<<&&&&�&#x;".into(), + format!("{}", "".repeat(10_000)).into_bytes(), + format!("{}", "<".repeat(10_000)).into_bytes(), + vec![0xff, 0xfe, 0x00, 0xd8, 0x00], + vec![0u8; 1000], + ]; + // deterministic noise + let mut x = 0x9e37_79b9u32; + for len in [10usize, 100, 1000] { + let alphabet = b"{}[]<>:=,. \n|&#;0123456789abSYNC"; + let noise: Vec = (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + alphabet[x as usize % alphabet.len()] + }) + .collect(); + inputs.push(noise); + } + for (format, _, _) in FORMATS { + for input in &inputs { + if let Ok(doc) = parse(input, format) { + // what was read writes and reads again + let again = write(&doc, format, WriteOptions::default()); + parse(&again, format).expect("a written file reads back"); + } + } + } +} + +#[test] +fn the_cue_limit_applies() { + let mut text = String::new(); + for i in 0..200 { + text.push_str(&format!("[{}][{}]x\n", i * 10, i * 10 + 5)); + } + assert_eq!(parse(text.as_bytes(), Format::Mpl2).expect("parse").cues.len(), 200); +} diff --git a/crates/captions/tests/it/main.rs b/crates/captions/tests/it/main.rs index be03d2855f..07ed5a52c3 100644 --- a/crates/captions/tests/it/main.rs +++ b/crates/captions/tests/it/main.rs @@ -1,4 +1,5 @@ mod ass; +mod legacy_text; mod limits; mod literal_roundtrips; mod mcc_708_timing; From ed8c7c2621378c0922ce9bca187b9f7f37b165b8 Mon Sep 17 00:00:00 2001 From: alehel Date: Sun, 15 Nov 2026 21:57:18 +0100 Subject: [PATCH 006/130] ODT: a style or list change keeps the file's other definitions Any style or list change threw away every definition in the file's office:styles and wrote them all from the model, which does not hold everything: gradients, fill pictures, styles the model doesn't have and the default style's settings were lost. The import now records, per office:styles child, a hash of what the writer would write for it (KeptXml::style_prints, replacing the single styles_fp fingerprint) and which of the file's style names it read into which style id (KeptXml::style_ids). A save rewrites only the definitions whose hash changed, under the file's own names, escaped, with parent and next style named as the file named them; a deleted style stays deleted; everything else is written as read. Ported from storytold/wordcraft#5702 (the ODT reader and writer now live here). Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/import.rs | 9 +- crates/odf/src/text/kept.rs | 137 ++++++++- crates/odf/src/text/package.rs | 29 +- crates/odf/src/text/tests_more/kept.rs | 333 ++++++++++++++++++++- crates/odf/src/text/tests_more/lossless.rs | 25 ++ crates/wordmodel/src/kept.rs | 24 +- 6 files changed, 527 insertions(+), 30 deletions(-) diff --git a/crates/odf/src/text/import.rs b/crates/odf/src/text/import.rs index 486e67a260..45a89bd9c4 100644 --- a/crates/odf/src/text/import.rs +++ b/crates/odf/src/text/import.rs @@ -1143,11 +1143,16 @@ pub fn import_on(bytes: &[u8], page: &SectionProps) -> Result k.keep_file(path, bytes); } k.section_masters = section_masters; + // Which of the file's styles became which of the document's (by kept key): a save names + // an edited style's definition, parent and next style by the file's names for them. + let paras = named_odt.iter().map(|n| (format!("common:{n}"), super::styles::style_id(n))); + let texts = char_styles.iter().map(|(n, id)| (format!("common:{n}|text"), id.clone())); + k.style_ids = paras.chain(texts).collect(); } doc.seal_kept(); - let (fp, pages) = (craft_wordmodel::kept::styles_fingerprint(&doc), craft_wordmodel::kept::pages_fingerprint(&doc)); + let (prints, pages) = (super::package::style_prints(&doc), craft_wordmodel::kept::pages_fingerprint(&doc)); if let Some(k) = doc.kept.get_mut() { - (k.styles_fp, k.pages_fp) = (Some(fp), Some(pages)); + (k.style_prints, k.pages_fp) = (prints, Some(pages)); } Ok(doc) } diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index e9efebdec3..953b672cc3 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -313,16 +313,143 @@ fn drawing_def(xml: &str) -> bool { /// `styles` (a `styles.xml` WordCraft wrote) with its `office:styles` as read: every kept /// child of the file's, then WordCraft's own children the file had no such of. A drawing's -/// definition both have stays WordCraft's (see [`drawing_def`]). For a document whose style -/// definitions are as read. -pub(super) fn with_common_as_read(styles: &str, defs: &BTreeMap>, order: &[String]) -> String { - with_as_read(styles, "office:styles", "common", defs, order, &|_, d, ours| match ours { - Some(o) if drawing_def(o) => Some(o.to_string()), +/// definition both have stays WordCraft's (see [`drawing_def`]), as does one in `changed`, which +/// the document has changed since it was read. One in `changed` that WordCraft no longer writes +/// (a deleted style) goes. +pub(super) fn with_common_as_read( + styles: &str, + defs: &BTreeMap>, + order: &[String], + changed: &BTreeSet, + rewritten: &BTreeMap>, +) -> String { + with_as_read(styles, "office:styles", "common", defs, order, &|k, d, ours| match ours { + _ if rewritten.contains_key(k) => rewritten.get(k).cloned().flatten(), + Some(o) if drawing_def(o) || changed.contains(k) => Some(o.to_string()), + None if changed.contains(k) => None, // (The default graphic style is the file's: WordCraft's drawings say what they need.) _ => Some(d.to_string()), }) } +/// What becomes of the file's styles (`defs`) that `changed` touches but `styles` (the part being +/// written) doesn't have under the file's key, by those keys: WordCraft's definition from `now` +/// (all it would write) under the file's names, or `None` for a style it no longer has. `ids` +/// gives the style id the import read a file's style into ([`KeptXml::style_ids`]), `ours` the +/// name WordCraft writes an id under: paragraphs written as read name the file's. A style the +/// import didn't read is WordCraft's only under its own name, so another of the file's styles +/// WordCraft would have under the same id (`Base_20_Style` beside `BaseStyle`) is left alone. +/// +/// [`KeptXml::style_ids`]: craft_wordmodel::kept::KeptXml::style_ids +pub(super) fn rewritten_defs( + styles: &str, + now: &str, + defs: &BTreeMap>, + changed: &BTreeSet, + ids: &BTreeMap, + ours: &dyn Fn(&str) -> String, +) -> BTreeMap> { + use std::collections::{HashMap, HashSet}; + // A common style's name and its family's key suffix: a text style's name isn't a paragraph + // style's. + let style_of = |key: &str| { + let rest = key.strip_prefix("common:")?; + match rest.strip_suffix("|text") { + Some(name) => Some((name.to_string(), "|text")), + None => (!rest.contains('|')).then(|| (rest.to_string(), "")), + } + }; + // Each of the file's styles, its family and the name WordCraft writes it under; and by that + // name and family, the file's name (the first the import read into it). + let mut styles_of: Vec<(&String, String, &str, String)> = Vec::new(); + let mut theirs: HashMap<(&str, String), String> = HashMap::new(); + for key in defs.keys() { + let Some((name, family)) = style_of(key) else { continue }; + let mine = match ids.get(key) { + Some(id) => { + let mine = ours(id); + if mine != name { + theirs.entry((family, mine.clone())).or_insert_with(|| name.clone()); + } + mine + } + None => name.clone(), + }; + styles_of.push((key, name, family, mine)); + } + let (kids, _) = children(now, "office:styles", "common"); + let kids: HashMap = kids.into_iter().collect(); + let (written, _) = children(styles, "office:styles", "common"); + let written: HashSet = written.into_iter().map(|(k, _)| k).collect(); + let mut out = BTreeMap::new(); + for (key, name, family, mine) in styles_of { + let mine = format!("common:{mine}{family}"); + if !changed.contains(&mine) || (mine == *key && written.contains(key)) { + continue; + } + let def = kids.get(&mine).and_then(|(a, b)| now.get(*a..*b)).map(|d| { + renamed(d, &|attr, v| match attr { + // Two of the file's names can be one of WordCraft's: a style keeps its own. + "style:name" => Some(name.clone()), + _ => theirs.get(&(family, v.to_string())).cloned(), + }) + }); + out.insert(key.clone(), def); + } + out +} + +/// `def` (markup WordCraft wrote) with the values of its `style:name`, `style:parent-style-name` +/// and `style:next-style-name` attributes that `to` gives another name for (by attribute and +/// value) renamed to that, escaped. One pass: WordCraft writes these names unescaped (they are +/// letters, digits and `_xNN_`). +fn renamed(def: &str, to: &dyn Fn(&str, &str) -> Option) -> String { + const ATTRS: [&str; 3] = ["style:name", "style:parent-style-name", "style:next-style-name"]; + let mut out = String::with_capacity(def.len()); + let mut rest = def; + while let Some(at) = rest.find("=\"") { + let (head, tail) = rest.split_at(at + 2); + let attr = head.get(..at).and_then(|h| h.rsplit(|c: char| c.is_whitespace()).next()).unwrap_or(""); + let Some(end) = tail.find('"') else { break }; + let (value, tail) = tail.split_at(end); + out.push_str(head); + match ATTRS.contains(&attr).then(|| to(attr, value)).flatten() { + Some(name) => out.push_str(&super::writer::x(&name)), + None => out.push_str(value), + } + rest = tail; + } + out.push_str(rest); + out +} + +/// Each child of `office:styles` in `styles` (a `styles.xml` WordCraft wrote), as a hash by its +/// key: what to compare to tell which definitions a document has changed since it was read. +pub(super) fn prints(styles: &str) -> BTreeMap { + use std::hash::{Hash, Hasher}; + let (kids, _) = children(styles, "office:styles", "common"); + kids.into_iter() + .filter_map(|(key, (a, b))| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + styles.get(a..b)?.hash(&mut h); + Some((key, h.finish())) + }) + .collect() +} + +/// The keys whose definition differs between `then` and `now` ([`prints`]), and those no longer +/// in `now` (a deleted style). Standard goes with +/// the default paragraph style: WordCraft writes Normal in the default style, and Standard empty +/// over it, so the file's own Standard would hide a change to Normal. +pub(super) fn changed(then: &BTreeMap, now: &BTreeMap) -> BTreeSet { + let mut out: BTreeSet = now.iter().filter(|(k, v)| then.get(*k) != Some(*v)).map(|(k, _)| k.clone()).collect(); + out.extend(then.keys().filter(|k| !now.contains_key(*k)).cloned()); + if out.contains("common~style:default-style~paragraph") { + out.insert("common:Standard".to_string()); + } + out +} + /// `styles` (a `styles.xml` WordCraft wrote) with its page layouts, master pages and their /// automatic styles as read, WordCraft's own added where the file had none by that name. For a /// document whose page setup is as read. diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 97520027c9..3b91a02b52 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -815,17 +815,40 @@ fn conn_kinds(blocks: &[FBlock]) -> super::HashMap std::collections::BTreeMap { + super::kept::prints(&model_styles(doc)) +} + +/// What WordCraft would write of `doc`'s style definitions: all of them, used or not. +fn model_styles(doc: &Document) -> String { + let ids = |custom: fn(&Document, &str) -> bool| doc.styles.styles.iter().filter(|s| custom(doc, &s.id)).map(|s| s.id.clone()).collect(); + // The first section, as a save writes the document-wide line numbering from it. + let first = doc.sections().first().map_or_else(|| doc.last_section.clone(), |(_, s)| (*s).clone()); + let page = [(String::new(), first)]; + let xml = styles_xml(doc, &page, &[], "", &ids(model::is_custom_style)); + let text = char_styles(doc, &ids(model::is_custom_char_style)); + xml.replacen("", &format!("{text}"), 1) +} + +/// `styles` with the file's own style definitions except those `doc` has since changed (see /// `super::kept`), and the font faces they name added to those kept paragraphs need (`used`). +/// Changing one style or list leaves the rest of what the file defines alone: its gradients and +/// fill pictures, the styles WordCraft doesn't model, its default style's settings. fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, styles: String, used: &mut super::kept::Needed) -> String { - let Some(k) = kept.filter(|k| k.styles_as_read(doc)) else { return styles }; + let Some(k) = kept else { return styles }; // With the font faces they name (any of the file's, by its names). for (key, d) in &k.defs { if let Some(name) = key.strip_prefix("font:") { used.2.entry(name.to_string()).or_insert_with(|| d.clone()); } } - super::kept::with_common_as_read(&styles, &k.defs, &k.order) + let now = model_styles(doc); + let changed = super::kept::changed(&k.style_prints, &super::kept::prints(&now)); + // The name WordCraft writes a style id under (`My_20_Custom` was read as `MyCustom`). + let ours = |id: &str| super::writer::odf_name(id); + let rewritten = super::kept::rewritten_defs(&styles, &now, &k.defs, &changed, &k.style_ids, &ours); + super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten) } /// The package files the file's own definitions refer to, and those the markup written as read diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index 88d271142a..d47ea57389 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -128,12 +128,18 @@ fn unedited_style_definitions_are_written_as_read() { assert!(s.contains(r#"x:odd="1""#) && s.contains(r#"xmlns:x="urn:example:x""#), "{s}"); assert_eq!(s.matches("").next().is_some_and(|q| q.contains(r#"fo:font-weight="bold""#))), + "{s}" + ); assert_eq!(s.matches(r#" Vec { + let ns = crate::text::tests::NS_T; + let draw = + r#"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0""#; + let styles = format!( + r##""## + ); + let content = format!( + r#"TextInOwn"# + ); + crate::text::tests::package(&content, Some(&styles)) +} + +#[test] +fn changing_one_style_leaves_the_files_other_definitions_alone() { + use std::sync::Arc; + let bytes = file_with_definitions(); + let as_read = |saved: &[u8]| { + let s = crate::text::tests::entry(saved, "styles.xml"); + assert!(s.contains(r#"draw:gradient draw:name="Sunset""#), "its gradient: {s}"); + assert!(s.contains(r#"fo:margin-bottom="7pt""#), "a style WordCraft doesn't model: {s}"); + assert!(s.contains(r#"style:wrap="dynamic""#), "what its frames derive from: {s}"); + assert!(s.contains(r#"style:writing-mode="page""#) && s.contains(r#"fo:language="de""#), "its default style: {s}"); + s + }; + // A style no text uses. + let mut d = crate::text::import(&bytes).unwrap(); + Arc::make_mut(&mut d.styles).get_mut("Quote").unwrap().chr.size = Some(13.0); + let saved = crate::text::export(&d).unwrap(); + let s = as_read(&saved); + assert!(s.contains(r#"fo:font-size="13pt""#), "the change: {s}"); + assert_eq!(crate::text::import(&saved).unwrap().styles.get("Quote").unwrap().chr.size, Some(13.0)); + // A style the file defined: that one is WordCraft's now, the others still the file's. + let mut d = crate::text::import(&bytes).unwrap(); + Arc::make_mut(&mut d.styles).get_mut("Eigen").unwrap().chr.size = Some(21.0); + let saved = crate::text::export(&d).unwrap(); + let s = as_read(&saved); + assert!(s.contains(r#"fo:font-size="21pt""#) && !s.contains(r#"fo:font-size="9pt""#), "{s}"); + // A new list (`para.numbering`): the styles as read, and the list there. + let mut d = crate::text::import(&bytes).unwrap(); + Arc::make_mut(&mut d.numbering).add_list(craft_wordmodel::numbering::ListKind::Bullet); + as_read(&crate::text::export(&d).unwrap()); + // Normal changed: the default style and Standard are WordCraft's. + let mut d = crate::text::import(&bytes).unwrap(); + Arc::make_mut(&mut d.styles).default_chr.size = Some(15.0); + let s = crate::text::tests::entry(&crate::text::export(&d).unwrap(), "styles.xml"); + assert!(s.contains(r#"fo:font-size="15pt""#), "{s}"); + assert!(s.contains(r#"draw:gradient draw:name="Sunset""#) && s.contains(r#"fo:margin-bottom="7pt""#), "the rest stays: {s}"); + // Nothing changed: the file's own, and none of WordCraft's over them. + let d = crate::text::import(&bytes).unwrap(); + as_read(&crate::text::export(&d).unwrap()); +} + +/// A style deleted in WordCraft stays deleted: the file's own definition doesn't come back with +/// the definitions that stay as read. +#[test] +fn a_deleted_style_stays_deleted() { + use std::sync::Arc; + let mut d = crate::text::import(&file_with_definitions()).unwrap(); + assert!(d.styles.get("Eigen").is_some()); + Arc::make_mut(&mut d.styles).remove("Eigen"); + d.restyle("Eigen", None); + let saved = crate::text::export(&d).unwrap(); + let s = crate::text::tests::entry(&saved, "styles.xml"); + assert!(!s.contains(r#"style:name="Eigen""#), "{s}"); + assert!(s.contains(r#"draw:gradient draw:name="Sunset""#) && s.contains(r#"fo:margin-bottom="7pt""#), "the rest stays: {s}"); + assert!(!crate::text::tests::entry(&saved, "content.xml").contains("Eigen")); + assert!(crate::text::import(&saved).unwrap().styles.get("Eigen").is_none()); +} + +/// A file's style whose name has a space (`My_20_Custom`, WordCraft's `MyCustom`) is one style. An +/// edit reaches its definition under the file's name, a deletion removes it, and left alone it +/// stays as read with no second definition. A style nothing uses any more keeps its edit. +#[test] +fn a_style_named_with_a_space_is_the_files_style() { + use std::sync::Arc; + let s = r#""#; + let styles = format!(r#"{s}"#); + let content = format!( + r#"OneTwoThree"# + ); + let bytes = package(&content, Some(&styles)); + let open = || import(&bytes).unwrap(); + let def = |xml: &str, name: &str| xml.split(""#; + let styles = format!(r#"{s}"#); + let content = format!( + r#"OneTwo"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let saved = styles_of(&export(&d).unwrap()); + for name in ["My_20_Custom", "My_Custom"] { + assert_eq!(saved.matches(&format!(r#"style:name="{name}""#)).count(), 1, "{name}: {saved}"); + let def = saved.split(&format!(r#"style:name="{name}""#)).nth(1).and_then(|d| d.split("").next()).unwrap(); + assert!(def.contains(r#"fo:font-size="21pt""#), "{name}: {def}"); + } +} + +/// A parent's name goes by its family: a text style's other name isn't a paragraph style's. +#[test] +fn a_rewritten_styles_parent_keeps_its_own_familys_name() { + use std::sync::Arc; + let s = r#""#; + let styles = format!(r#"{s}"#); + let content = format!( + r#"OneTwo three"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.italic = Some(true); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + let mine = saved.split("').next()).unwrap(); + assert!(mine.contains(r#"style:parent-style-name="BaseStyle""#), "{mine}"); + let back = import(&bytes).unwrap(); + let p = back.body[0].as_para().unwrap(); + assert_eq!(back.styles.resolve_char(p.props.style.as_deref(), &Default::default()).size, 30.0, "inherited"); +} + +/// Whether `xml` reads as XML: tags close in order and every attribute value unescapes. +fn reads_as_xml(xml: &str) -> bool { + // craft-xml's strict read refuses unbalanced tags, malformed attributes and unknown + // references, but takes a bare `&` as itself: each `&` must start a reference too. + let refs = xml.split('&').skip(1).all(|r| { + let name = r.split(';').next().unwrap_or(""); + r.contains(';') && !name.is_empty() && name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'#') + }); + let mut events = craft_xml::Options::default().strict().events(xml.as_bytes()); + loop { + match events.next() { + Ok(Some(_)) => {} + Ok(None) => return refs, + Err(_) => return false, + } + } +} + +/// A file's paragraph style `styles` (markup inside `office:styles`) and paragraphs naming +/// `used`, opened. +fn opened(styles: &str, used: &[&str]) -> craft_wordmodel::Document { + let styles = format!(r#"{styles}"#); + let body: String = used.iter().map(|n| format!(r#"Text"#)).collect(); + let content = + format!(r#"{body}"#); + import(&package(&content, Some(&styles))).unwrap() +} + +/// The definition of the style named `name` (as written, escaped) in `xml`, up to its end. +fn def_named(xml: &str, name: &str) -> Option { + xml.split("").next()) + .map(String::from) +} + +/// A file's style whose name has `&`, `"` or `<` in it, edited, is written under its name escaped. +#[test] +fn an_edited_styles_name_is_written_escaped() { + use std::sync::Arc; + for name in ["R&D", "Say"Hi", "A<B"] { + let s = format!( + r#""# + ); + let mut d = opened(&s, &[name]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + assert!(reads_as_xml(&saved), "{name}: {saved}"); + assert!(def_named(&saved, name).is_some_and(|d| d.contains(r#"fo:font-size="21pt""#)), "{name}: {saved}"); + let back = import(&bytes).unwrap(); + assert_eq!(back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size, 21.0, "{name}"); + } +} + +/// An edited style's parent is the file's style the import read it from, not another of the +/// file's styles WordCraft would have under the same id (`BaseStyle`, `Base_20_Style`). +#[test] +fn a_rewritten_styles_parent_is_the_one_it_was_read_from() { + use std::sync::Arc; + let s = r#""#; + let mut d = opened(s, &["My_20_Custom"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.italic = Some(true); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + let mine = def_named(&saved, "My_20_Custom").unwrap_or_else(|| panic!("{saved}")); + assert!(mine.contains(r#"style:parent-style-name="BaseStyle""#), "{mine}"); + assert!(def_named(&saved, "Base_20_Style").is_some_and(|d| d.contains(r#"fo:font-size="9pt""#)), "as read: {saved}"); + let back = import(&bytes).unwrap(); + assert_eq!(back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size, 30.0, "inherited"); +} + +/// A style nothing in the file uses keeps its own definition when a used one WordCraft has +/// under the same id (`My_20_Custom`, `My_Custom`) is edited. +#[test] +fn an_unused_style_sharing_an_edited_ones_id_keeps_its_definition() { + use std::sync::Arc; + let s = r##""##; + let mut d = opened(s, &["My_20_Custom"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let saved = styles_of(&export(&d).unwrap()); + assert!(def_named(&saved, "My_20_Custom").is_some_and(|d| d.contains(r#"fo:font-size="21pt""#)), "{saved}"); + let theirs = def_named(&saved, "My_Custom").unwrap_or_else(|| panic!("{saved}")); + assert!(theirs.contains(r#"fo:font-size="30pt""#) && theirs.contains("#ff0000"), "as read: {theirs}"); +} + +/// A character style WordCraft read under another id (`AccentChar`, as a paragraph style has +/// `Accent`), edited, is written under the file's name: the text written as read names that. +#[test] +fn an_edited_character_style_read_under_another_id_keeps_the_files_name() { + use std::sync::Arc; + let s = r#""#; + let styles = format!(r#"{s}"#); + let content = format!( + r#"One two"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + let id = + d.styles.styles.iter().find(|s| s.kind == craft_wordmodel::styles::StyleKind::Character && s.name == "Accent").map(|s| s.id.clone()).unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let saved = styles_of(&export(&d).unwrap()); + let text = saved + .split("').next().is_some_and(|h| h.contains(r#"style:family="text""#))) + .and_then(|d| d.split("").next()) + .unwrap_or_else(|| panic!("{saved}")); + assert!(text.contains(r#"fo:font-size="21pt""#), "{text}"); +} + +/// Many of the file's styles WordCraft has under one id (`My-Custom`, `My.Custom`…), one edited: +/// the save looks each name up once, not every name for every style. +#[test] +fn many_styles_sharing_an_id_save_quickly() { + use std::sync::Arc; + let names: Vec = + (0..6_000u32).map(|i| format!("My{}Custom", (0..13).map(|b| if i >> b & 1 == 1 { '-' } else { '.' }).collect::())).collect(); + let mut s = String::from(r#""#); + for n in &names { + s.push_str(&format!(r#""#)); + } + let used: Vec<&str> = names.iter().take(500).map(String::as_str).collect(); + let mut d = opened(&s, &used); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let t = std::time::Instant::now(); + let saved = styles_of(&export(&d).unwrap()); + assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + assert_eq!(saved.matches(r#"fo:font-size="21pt""#).count(), 500, "the ones read into it"); + assert_eq!(saved.matches(r#"fo:font-size="9pt""#).count(), 5_500, "the others as read"); +} + #[test] fn the_files_font_declarations_are_kept() { // A reader without a font picks its substitute by how the file declares it. WordCraft's own @@ -316,3 +620,26 @@ fn a_name_space_on_the_font_declarations_goes_with_them() { assert!(part.contains(r#"xmlns:x="urn:example:x""#), "{part}"); } } + +/// Line numbering changed in the first of two sections is saved: the file's own definition stays +/// only while the section the save writes it from is as read (#5702 review). +#[test] +fn line_numbering_changed_in_the_first_section_is_saved() { + let styles = format!( + r#""# + ); + let content = format!( + r#"One.Two."# + ); + let bytes = package(&content, Some(&styles)); + let mut d = import(&bytes).unwrap(); + assert_eq!(d.sections().len(), 2, "two sections"); + let first = d.body.iter_mut().find_map(|b| match std::sync::Arc::make_mut(b) { + craft_wordmodel::Block::Para(p) => p.section.as_deref_mut(), + _ => None, + }); + let first = first.expect("the first section"); + first.line_numbers.as_mut().expect("line numbering as read").count_by = 3; + let s = styles_of(&export(&d).unwrap()); + assert!(s.contains(r#"text:increment="3""#) && !s.contains(r#"text:increment="5""#), "the change: {s}"); +} diff --git a/crates/odf/src/text/tests_more/lossless.rs b/crates/odf/src/text/tests_more/lossless.rs index 7d05e34910..6dc6506be5 100644 --- a/crates/odf/src/text/tests_more/lossless.rs +++ b/crates/odf/src/text/tests_more/lossless.rs @@ -169,6 +169,31 @@ fn a_save_without_edits_loses_nothing() { } } +/// The same gate after an edit: a save must lose nothing the edit didn't touch. Our loss checks +/// once only saved without edits, and missed that one style change rewrote every definition. +#[test] +fn a_style_or_list_change_loses_nothing_else() { + let edits: [(&str, fn(&mut craft_wordmodel::Document)); 2] = [ + ("an unused style", |d| { + if let Some(st) = std::sync::Arc::make_mut(&mut d.styles).get_mut("Quote") { + st.chr.size = Some(13.0); + } + }), + ("a new list", |d| { + std::sync::Arc::make_mut(&mut d.numbering).add_list(craft_wordmodel::numbering::ListKind::Bullet); + }), + ]; + for s in SAMPLES { + for (what, edit) in &edits { + let orig = package(&s); + let mut d = import(&orig).unwrap(); + edit(&mut d); + let lost = losses(&orig, &export(&d).unwrap()); + assert!(lost.is_empty(), "{}: lost after changing {what}:\n {}", s.name, lost.join("\n ")); + } + } +} + #[test] fn the_gate_sees_a_loss() { let with = Sample { diff --git a/crates/wordmodel/src/kept.rs b/crates/wordmodel/src/kept.rs index fcf52b60bc..e7b537439a 100644 --- a/crates/wordmodel/src/kept.rs +++ b/crates/wordmodel/src/kept.rs @@ -74,9 +74,13 @@ pub struct KeptXml { pub order: Vec, /// Files of the package kept definitions refer to (a style's fill picture), by path. pub files: BTreeMap>>, - /// The document's style definitions' [`styles_fingerprint`] when read: while it is the - /// same, the file's own style definitions can be written as they were. - pub styles_fp: Option, + /// What the format would write for each style definition when read, by [`KeptXml::defs`]' + /// key, as a hash: while a definition's is the same, the file's own is written as it was. + pub style_prints: BTreeMap, + /// The style id the reader read each of the file's styles into, by [`KeptXml::defs`]' key: + /// only those it read (its text's styles and what they derive from), not every style the + /// file defines. + pub style_ids: BTreeMap, /// The document's page setup's [`pages_fingerprint`] when read: while it is the same, the /// file's own page layouts and master pages can be written as they were. pub pages_fp: Option, @@ -267,20 +271,6 @@ impl KeptXml { let now = in_scope(doc, |sc| *sc.pages.get_or_insert_with(|| pages_fingerprint(doc))).unwrap_or_else(|| pages_fingerprint(doc)); fp == now } - /// Whether `doc`'s style definitions are still as they were read. - pub fn styles_as_read(&self, doc: &crate::Document) -> bool { - self.styles_fp.is_some_and(|fp| fp == styles_fingerprint(doc)) - } -} - -/// What `doc`'s style definitions are: its styles, lists and default tab interval. -pub fn styles_fingerprint(doc: &crate::Document) -> u64 { - let mut h = std::collections::hash_map::DefaultHasher::new(); - match serde_json::to_vec(&(&doc.styles, &doc.numbering, doc.settings.default_tab)) { - Ok(v) => v.hash(&mut h), - Err(_) => u64::MAX.hash(&mut h), - } - h.finish() } /// What a block is, as the kept markup knows it: its paragraphs' fingerprints and From 9c27cebc14850882cc825b4155c8845de6146384 Mon Sep 17 00:00:00 2001 From: alehel Date: Sun, 15 Nov 2026 21:57:23 +0100 Subject: [PATCH 007/130] ODT: a list item's further paragraphs stay paragraphs LibreOffice writes an unnumbered list entry as an item's second paragraph. The ODT reader joined it to the first with a line break, so a save could bring the file back with the wrong paragraphs, and a list header got a number. Such paragraphs are now read as paragraphs of their own, with no number, at the item's text indent, and marked with the new `ParaProps::list_item` (the flow model's `Para::item`). - HTML and Markdown export keep the paragraph in its item, so one numbered list continues across it. - Markdown `parse_list` joins a code block, quote or heading inside an item back to the item (also after a sublist), so it gets no number. - The writers keep a paragraph in its item only while it sits at the item's text indent, so text outdented to the margin leaves the list. - ODT written from the model puts a further paragraph inside its `text:list-item`. - A level first used after an unnumbered paragraph keeps the file's label. Ported from storytold/wordcraft#5723 after the readers and writers moved here. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 2 + crates/docx/tests/it/roundtrip.rs | 2 + crates/flow/src/from_doc.rs | 42 +++++- crates/flow/src/lib.rs | 1 + crates/flow/src/to_doc.rs | 22 ++- crates/flow/src/types.rs | 12 ++ crates/html/src/doc/export.rs | 14 +- crates/markdown/Cargo.toml | 4 + crates/markdown/src/blocks.rs | 22 ++- crates/markdown/src/export.rs | 23 +++ crates/markdown/src/tests.rs | 71 ++++++++++ crates/odf/Cargo.toml | 3 + crates/odf/src/text/body.rs | 44 ++++-- crates/odf/src/text/tests_more/lists.rs | 170 +++++++++++++++++++++++ crates/odf/src/text/writer.rs | 34 ++++- crates/wordmodel/src/props/para_props.rs | 5 + 16 files changed, 442 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b3325f7908..62c841a7ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2183,6 +2183,8 @@ dependencies = [ "base64 0.23.1", "chrono", "craft-flow", + "craft-html", + "craft-markdown", "craft-math", "craft-metafile", "craft-wordmodel", diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 8f3bbdd0bd..66bda8bbeb 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -225,6 +225,8 @@ fn every_para_prop_round_trips() { fmt_change: None, snap_to_grid: Some(false), text_alignment: Some(TextAlignment::Top), + // A list item's further paragraph: WordprocessingML has no such paragraph. + list_item: None, }; let variants = [ ParaProps { line_spacing: Some(LineSpacing::AtLeast(14.0)), indent_first: Some(24.0), align: Some(Align::Center), ..Default::default() }, diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index 341ded449f..8bcf4f5527 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -508,6 +508,7 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { wrap: None, index: None, group: None, + item: p.props.list_item.filter(|_| list.is_none()).map(|l| l.min(8)), }; if opts.paras { out.extra = para_extra(doc, &p.props); @@ -551,11 +552,13 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { wrap: None, index: None, group: None, + item: None, }; let prev = std::mem::replace(&mut out, next); if prev.inlines.is_empty() { out.page_break |= prev.page_break; out.list = prev.list; + out.item = prev.item; } else { done.push(prev); } @@ -907,9 +910,44 @@ fn kept_index(doc: &Document, bl: &Blocks, i: usize) -> Option<(usize, std::sync (paras.len() == *n && craft_wordmodel::kept::run_fingerprint(paras.into_iter()) == *run).then(|| (*n, xml.clone())) } +/// Where the text of each level's last numbered paragraph starts, points. +type ItemText = [Option; 9]; + +/// The flow paragraphs of `p`, a list item's further paragraph only while it still sits at its +/// item's text: one moved out of it (Enter, then Decrease Indent to the margin, the ruler, the +/// Paragraph dialog…) is body text after the list. Asked of the paragraph itself, so whichever +/// command moved it, the paragraph is where it shows. +fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemText) -> Vec { + let rp = doc.styles.resolve_para(&p.props); + // (Its own indent, or its style's.) + let left = rp.indent_left; + let mut paras = flow_paras_in(doc, p, opts); + if let Some(n) = rp.numbering.filter(|n| n.num != 0) { + // The paragraph's own indent, else its level's, else its style's (as Word places it). + let level = doc.numbering.level(n.num, n.level).map(|l| l.indent); + let text = p.props.indent_left.or(level).unwrap_or(left); + if let Some(t) = at.get_mut(usize::from(n.level)) { + *t = Some(text); + } + } else if let Some(l) = p.props.list_item { + // Before any numbered paragraph at its level (a list header), anywhere off the margin. + let kept = match at.get(usize::from(l)).copied().flatten() { + Some(text) => left >= text - 0.5, + None => left > 0.5, + }; + if !kept { + for q in &mut paras { + q.item = None; + } + } + } + paras +} + fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> Vec { let mut out = Vec::new(); let mut skip = 0usize; + let mut at: ItemText = [None; 9]; for (i, b) in bl.iter().enumerate() { if skip > 0 { skip -= 1; @@ -924,7 +962,7 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> let from = out.len(); for b in bl.get(i..i + ix.0).unwrap_or(&[]) { if let Block::Para(p) = &**b { - out.extend(flow_paras_in(doc, p, tracked).into_iter().map(FBlock::Para)); + out.extend(flow_paras_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para)); } } let n = out.len() - from; @@ -935,7 +973,7 @@ fn flow_blocks(doc: &Document, bl: &Blocks, depth: usize, tracked: FlowOpts) -> continue; } match &**b { - Block::Para(p) => out.extend(flow_paras_in(doc, p, tracked).into_iter().map(FBlock::Para)), + Block::Para(p) => out.extend(flow_paras_at(doc, p, tracked, &mut at).into_iter().map(FBlock::Para)), Block::Table(t) if depth < MAX_DEPTH => out.push(FBlock::Table(flow_table(doc, t, depth, tracked))), Block::Table(t) => { for r in &t.rows { diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index 774b5ffd17..5bcb7a68c9 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -26,6 +26,7 @@ mod media; pub mod odf_object; mod to_doc; mod types; +pub use types::continues_list; pub use color::parse_color; pub use from_doc::{ diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index c10be85c27..f10bc405e8 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -158,6 +158,9 @@ fn para_props(p: &Para, list_num: Option) -> ParaProps { } out.numbering = Some(NumRef { num, level: li.level.min(8) }); } + if p.list.is_none() { + out.list_item = p.item.map(|l| l.min(8)); + } out.align = p.align; let sp = p.spacing; out.space_before = sp.before; @@ -756,6 +759,12 @@ impl<'a> Builder<'a> { fn blocks(&mut self, blocks: &[FBlock], depth: usize) -> Blocks { let mut out = Blocks::new(); + // Each list the source numbers, all of it in these blocks: a run of it after a paragraph + // it doesn't number may be the first to use a level. + let mut of_list: std::collections::HashMap> = std::collections::HashMap::new(); + for li in blocks.iter().filter_map(|b| if let FBlock::Para(p) = b { p.list } else { None }).filter(|li| li.list != 0) { + of_list.entry(li.list).or_default().push(li); + } let mut i = 0; while let Some(b) = blocks.get(i) { match b { @@ -769,7 +778,14 @@ impl<'a> Builder<'a> { let mut top: Option = None; let id = p.list.map_or(0, |l| l.list); while let Some(FBlock::Para(q)) = blocks.get(j) { - let Some(li) = q.list else { break }; + let Some(li) = q.list else { + // An item's further paragraph is in the list: it goes on after it. + if super::continues_list(blocks, j).is_some() { + j += 1; + continue; + } + break; + }; if li.list != id { break; } @@ -785,7 +801,9 @@ impl<'a> Builder<'a> { let num = match self.lists.get(&id) { Some(num) if id != 0 => *num, _ => { - let num = self.new_list(&group); + // First met here, so this is the only time it's asked for. + let all = if id == 0 { group } else { of_list.remove(&id).unwrap_or(group) }; + let num = self.new_list(&all); if id != 0 { self.lists.insert(id, num); } diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs index e897778f9c..8503f18d4a 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -713,6 +713,9 @@ pub struct Para { pub index: Option, usize)>>, /// The group of paragraphs its markup kept as read belongs to (see [`Group`]). pub group: Option>, + /// A list item's further paragraph, with no number of its own (`list` is `None`): the level + /// of the item it belongs to. + pub item: Option, } /// Paragraphs whose markup kept as read ties them together (a comment from one to another, a @@ -1092,3 +1095,12 @@ pub fn ruby_as_text(inlines: &[Inline]) -> std::borrow::Cow<'_, [Inline]> { pub fn clean_text(s: &str) -> String { s.chars().filter(|c| *c != OBJ && (!c.is_control() || matches!(c, '\t' | '\n' | '\u{000C}' | '\u{000E}'))).collect() } + +/// Whether the paragraph at `i` in `blocks` is a list item's further paragraph, and the level of +/// its item: HTML and Markdown keep it in its item, so the list doesn't start again after it. +pub fn continues_list(blocks: &[FBlock], i: usize) -> Option { + match blocks.get(i) { + Some(FBlock::Para(p)) if p.list.is_none() && p.kind == Kind::Normal => p.item.map(|l| l.min(8)), + _ => None, + } +} diff --git a/crates/html/src/doc/export.rs b/crates/html/src/doc/export.rs index 78f6d9ae83..c50fcec0ff 100644 --- a/crates/html/src/doc/export.rs +++ b/crates/html/src/doc/export.rs @@ -275,7 +275,19 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize) { // Nested lists from consecutive list paragraphs. let mut stack: Vec<(bool, bool)> = Vec::new(); // (ordered, li open) while let Some(FBlock::Para(q)) = blocks.get(i) { - let Some(li) = q.list else { break }; + let Some(li) = q.list else { + // A list item's further paragraph, in its item (its sublists end first). + let Some(lv) = model::continues_list(blocks, i).map(usize::from) else { break }; + while stack.len() > lv + 1 { + close_list(&mut stack, out); + } + if stack.len() != lv + 1 || !stack.last().is_some_and(|s| s.1) { + break; + } + out.push_str(&format!("

{}

", inlines_html(&q.inlines))); + i += 1; + continue; + }; let lv = li.level.min(8) as usize; while stack.len() > lv + 1 { close_list(&mut stack, out); diff --git a/crates/markdown/Cargo.toml b/crates/markdown/Cargo.toml index eac067b267..aeb3b7acc8 100644 --- a/crates/markdown/Cargo.toml +++ b/crates/markdown/Cargo.toml @@ -14,3 +14,7 @@ workspace = true craft-flow = { workspace = true } craft-html = { workspace = true } craft-wordmodel = { workspace = true } + +[dev-dependencies] +# A test writes imported Markdown to HTML, to check a list stays one there. +craft-html = { workspace = true, features = ["flow"] } diff --git a/crates/markdown/src/blocks.rs b/crates/markdown/src/blocks.rs index 72a7aedfb4..919a80886d 100644 --- a/crates/markdown/src/blocks.rs +++ b/crates/markdown/src/blocks.rs @@ -682,21 +682,31 @@ fn parse_list(lines: &[String], mut i: usize, depth: usize, level: u8, out: &mut } for b in inner { match b { - FBlock::Para(mut p) if p.list.is_none() => { + FBlock::Para(mut p) if p.list.is_none() && p.item.is_none() => { if !placed { p.list = Some(li); placed = true; - out.push(FBlock::Para(p)); + } else if p.kind == Kind::Normal { + // The item's further paragraph: one with no number, at the item's text. + p.item = Some(li.level); + p.spacing.left = Some((f32::from(li.level) + 1.0) * 36.0); + p.spacing.first = Some(0.0); } else if let Some(FBlock::Para(prev)) = out.last_mut() - && prev.list.is_some_and(|x| x.level == li.level) + && (prev.list.is_some_and(|x| x.level >= li.level) || prev.item.is_some_and(|l| l >= li.level)) { - // A continuation paragraph joins the item with a line break. + // A code block, quote or heading in the item joins the item's last + // paragraph, a sublist's included, with a line break: it is no item of + // its own, and the writers keep only plain paragraphs in an item. prev.push_text("\n", &Fmt::default()); prev.inlines.extend(p.inlines); + continue; } else { - p.list = Some(li); - out.push(FBlock::Para(p)); + // One after a table: no number either, at the item's text. + p.item = Some(li.level); + p.spacing.left = Some((f32::from(li.level) + 1.0) * 36.0); + p.spacing.first = Some(0.0); } + out.push(FBlock::Para(p)); } FBlock::Para(p) => { if !placed { diff --git a/crates/markdown/src/export.rs b/crates/markdown/src/export.rs index 82fd952e3f..e1bdde3b86 100644 --- a/crates/markdown/src/export.rs +++ b/crates/markdown/src/export.rs @@ -346,6 +346,10 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) { let mut i = 0; let mut counters = [0u32; 9]; let mut prev_list = false; + // How far each level's last item's text is indented (where its further paragraphs go), and + // the level of the last item. + let mut conts = [0usize; 9]; + let mut prev_level = 0usize; let mut prev_top_ordered = false; while let Some(b) = blocks.get(i) { match b { @@ -376,6 +380,8 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) { } FBlock::Para(p) => { let body = inlines_md(&p.inlines); + // A further paragraph of an item still open: its level. + let in_item = model::continues_list(blocks, i).map(usize::from).filter(|lv| prev_list && *lv <= prev_level); match p.list { Some(li) => { let lv = li.level.min(8) as usize; @@ -398,6 +404,10 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) { let marker = if li.ordered { format!("{}.", n.unwrap_or(1)) } else { "-".to_string() }; let pad = " ".repeat(4 * lv); let cont = " ".repeat(4 * lv + marker.len() + 1); + if let Some(c) = conts.get_mut(lv) { + *c = cont.len(); + } + prev_level = lv; let body = if p.kind == Kind::Code { code_span(&p.text()) } else { @@ -419,6 +429,19 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) { out.push(String::new()); } } + // A list item's further paragraph: in its item, and the list goes on after it. + None if in_item.is_some() => { + let lv = in_item.unwrap_or_default(); + prev_level = lv; + // A sublist after it is a new one. + for d in counters.iter_mut().skip(lv + 1) { + *d = 0; + } + let pad = " ".repeat(conts.get(lv).copied().unwrap_or(0)); + let text = escape_lines(body).replace("\\\n", &format!("\\\n{pad}")); + out.push(format!("{pad}{text}").trim_end().to_string()); + out.push(String::new()); + } None => { prev_list = false; let line = match p.kind { diff --git a/crates/markdown/src/tests.rs b/crates/markdown/src/tests.rs index 96ad1dc3aa..e59ae436af 100644 --- a/crates/markdown/src/tests.rs +++ b/crates/markdown/src/tests.rs @@ -793,3 +793,74 @@ fn heading_trailing_hash_survives_round_trip() { assert_eq!(export(&import(&md)), want, "second export of {src:?}"); } } + +/// A list item's further paragraph is read as a paragraph of its own in the item, with no number: +/// written and read again, it stays one, and the list goes on after it. +#[test] +fn an_items_further_paragraph_round_trips() { + let src = "1. One\n\n Cont\n\n2. Two\n - Sub\n\n More\n"; + let shape = |d: &Document| { + d.body.iter().filter_map(|b| b.as_para()).map(|p| (p.text.clone(), p.props.numbering.map(|n| n.num), p.props.indent_left)).collect::>() + }; + let d = import(src); + let rows = shape(&d); + assert_eq!(rows.iter().map(|r| r.0.as_str()).collect::>(), ["One", "Cont", "Two", "Sub", "More"], "{rows:?}"); + for (t, at) in [("Cont", 36.0), ("More", 36.0)] { + let r = rows.iter().find(|r| r.0 == t).unwrap(); + assert_eq!((r.1, r.2), (None, Some(at)), "{t}: no number, at the item's text: {rows:?}"); + } + assert_eq!(rows[0].1, rows[2].1, "one list: {rows:?}"); + let md = export(&d); + assert!(md.starts_with("1. One\n\n Cont\n\n2. Two\n"), "{md}"); + assert!(md.contains("\n\n More"), "{md}"); + assert_eq!(shape(&import(&md)), rows, "{md}"); + // A numbered sublist after an item's further paragraph starts again. + let md = export(&import("1. One\n 1. a\n 2. b\n\n More\n\n 1. c\n")); + assert!(md.contains("\n 1. c"), "{md}"); +} + +/// A code block, quote or heading inside a list item is no item of its own: it gets no number, +/// and the list's next item keeps its number (#5723 review). +#[test] +fn a_block_inside_an_item_gets_no_number() { + let numbered = + |d: &Document| d.body.iter().filter_map(|b| b.as_para()).filter(|p| p.props.numbering.is_some()).map(|p| p.text.clone()).collect::>(); + for (src, last) in [ + ("1. Install:\n\n ```\n cargo build\n cargo test\n ```\n\n2. Run\n", "2. Run"), + ("1. Install:\n\n > quoted\n\n2. Run\n", "2. Run"), + ("1. Install:\n\n # Heading\n\n2. Run\n", "2. Run"), + ("1. Install:\n\n Cont\n\n ```\n cargo build\n ```\n\n2. Run\n", "2. Run"), + ] { + let d = import(src); + let rows = numbered(&d); + assert_eq!(rows.len(), 2, "{src:?}: two numbered items: {rows:?}"); + assert!(rows[0].starts_with("Install:"), "{src:?}: {rows:?}"); + assert_eq!(rows[1], "Run", "{src:?}: {rows:?}"); + let md = export(&d); + assert!(md.contains(&format!("\n{last}")), "{src:?}: {md}"); + assert!(!md.contains("3."), "{src:?}: {md}"); + } + let d = import("1. Install:\n\n ```\n cargo build\n cargo test\n ```\n\n2. Run\n"); + assert!(numbered(&d)[0].contains("cargo build") && numbered(&d)[0].contains("cargo test"), "the code stays in its item: {:?}", numbered(&d)); +} + +/// A code block, quote or heading after a sublist in an item stays in the list: the list's next +/// item keeps its number in Markdown and HTML (#5723 review). +#[test] +fn a_block_after_a_sublist_keeps_the_next_items_number() { + for src in + ["1. a\n - sub\n\n ```\n code\n ```\n2. b\n", "1. a\n - sub\n\n > quoted\n\n2. b\n", "1. a\n - sub\n\n # Heading\n\n2. b\n"] + { + let d = import(src); + let text: String = d.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect::>().join("|"); + for w in ["code", "quoted", "Heading"] { + if src.contains(w) { + assert!(text.contains(w), "{src:?}: the block's text stays: {text}"); + } + } + let md = export(&d); + assert!(md.contains("\n2. b"), "{src:?}: {md}"); + let html = craft_html::doc::export(&d); + assert_eq!(html.matches(" { next_comment: u32, } +/// `p`, read as a list's paragraph, as one the list doesn't number (a list item's second paragraph, +/// a list header's): a paragraph of its own at the level's text indent. +fn unnumbered(p: &mut Para) { + let Some(li) = p.list.take() else { return }; + let indent = li.label.and_then(|l| l.indent).map_or((f32::from(li.level) + 1.0) * 36.0, |i| f32::from(i) / 20.0); + p.spacing.left = p.spacing.left.or(Some(indent)); + p.spacing.first = p.spacing.first.or(Some(0.0)); + p.item = Some(li.level.min(8)); +} + impl<'a> Body<'a> { pub(super) fn new(styles: &'a Styles, pages: &'a Pages, zip: &'a mut dyn FnMut(&str) -> Option>) -> Self { let page = pages.first.clone().unwrap_or_default(); @@ -411,6 +421,14 @@ impl<'a> Body<'a> { { p.index = Some(Box::new((std::sync::Arc::from(xml), n))); } + // The list kept whole or not, an unnumbered paragraph's markup is only for it. + for b in blocks.iter_mut().skip(k.done) { + if let FBlock::Para(p) = b + && p.list.is_none() + { + p.kept = None; + } + } } None } @@ -1050,21 +1068,15 @@ impl Body<'_> { } } self.paras_done += 1; - let cont = std::mem::take(&mut self.para_cont); - let level = p.list.map(|l| l.level); - let c = self.container(); - if cont - && let Some(FBlock::Para(prev)) = c.last_mut() - && prev.list.is_some() - && prev.list.map(|l| l.level) == level - { - prev.push_text("\n", &Fmt::default()); - prev.inlines.extend(p.inlines); - // Two elements made one paragraph: neither's markup is it. - prev.kept = None; - return; + if std::mem::take(&mut self.para_cont) { + unnumbered(&mut p); + // Its markup means nothing outside its list: only a list kept whole may keep it, and + // that is seen when the list ends. + if self.kept_list.is_none() { + p.kept = None; + } } - c.push(FBlock::Para(p)); + self.container().push(FBlock::Para(p)); } fn push_text(&mut self, t: &str) { @@ -1721,6 +1733,7 @@ impl Body<'_> { } } "list-item" | "list-header" => { + let header = local(q) == "list-header"; // An item restarting the numbering begins a list of its own from there. if let Some(v) = get(a, "text:start-value").and_then(|v| v.trim().parse::().ok()) { self.list_id = self.new_list_id(); @@ -1730,8 +1743,9 @@ impl Body<'_> { if let Some(l) = self.lists.last_mut() { l.1 = true; } + // A list header's paragraphs have no number (§5.3.3), as an item's after its first. if let Some(u) = self.item_used.last_mut() { - *u = false; + *u = header; } } _ => return false, diff --git a/crates/odf/src/text/tests_more/lists.rs b/crates/odf/src/text/tests_more/lists.rs index 079413aa82..fb3d519720 100644 --- a/crates/odf/src/text/tests_more/lists.rs +++ b/crates/odf/src/text/tests_more/lists.rs @@ -166,3 +166,173 @@ fn list_level_positions_are_read_and_written() { assert_eq!((c.indent, c.hanging, c.align), (a.indent, a.hanging, a.align)); assert!((e.indent - b.indent).abs() < 0.01 && (e.hanging - b.hanging).abs() < 0.01); } + +#[test] +fn a_list_items_further_paragraphs_are_paragraphs_with_no_number() { + // LibreOffice writes an unnumbered entry as an item's second paragraph. It was joined to the + // first by a line break, losing its paragraph, and so the first's markup too. + let styles = format!( + r#""# + ); + let body = r#"HeaderOneStill oneAnd againTwoAfter"#; + let content = format!("{body}"); + let shape = |d: &craft_wordmodel::Document| { + d.body.iter().filter_map(|b| b.as_para()).map(|p| (p.text.clone(), p.props.numbering.is_some(), p.props.indent_left)).collect::>() + }; + let d = import(&package(&content, Some(&styles))).unwrap(); + let want = |a: &[(String, bool, Option)]| { + let row = |t: &str| a.iter().find(|r| r.0 == t).unwrap_or_else(|| panic!("{t} in {a:?}")); + assert_eq!(a.len(), 6, "each its own paragraph: {a:?}"); + for t in ["Header", "Still one", "And again"] { + assert!(!row(t).1, "{t} has no number: {a:?}"); + assert_eq!(row(t).2, Some(72.0), "{t} at the item's text: {a:?}"); + } + for t in ["One", "Two"] { + assert!(row(t).1, "{t} is numbered: {a:?}"); + } + assert!(!row("After").1); + }; + want(&shape(&d)); + // The numbers go on past the unnumbered paragraph: one list. + let nums: Vec = d.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.numbering.map(|n| n.num)).collect(); + assert_eq!(nums.len(), 2); + assert_eq!(nums[0], nums[1], "{nums:?}"); + // And so do they written from the model, and written as read. + for saved in [crate::text::tests::export_model(&d).unwrap(), export(&d).unwrap()] { + let back = import(&saved).unwrap(); + want(&shape(&back)); + let nums: Vec = back.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.numbering.map(|n| n.num)).collect(); + assert_eq!(nums[0], nums[1], "{nums:?}"); + } + // Edited, an unnumbered paragraph is saved as edited, not as the list's kept markup said, and + // the list around it stays one. + for t in ["Header", "Still one"] { + let mut d = import(&package(&content, Some(&styles))).unwrap(); + let i = d.body.iter().position(|b| b.as_para().is_some_and(|p| p.text == t)).unwrap(); + d.insert_text(&craft_wordmodel::Pos::body(i, 0), "Edited ", &Default::default()).unwrap(); + let back = import(&export(&d).unwrap()).unwrap(); + let rows = shape(&back); + assert_eq!(rows.len(), 6, "each its own paragraph: {rows:?}"); + assert!(!rows.iter().any(|r| r.0 == t), "{t} was edited: {rows:?}"); + let row = rows.iter().find(|r| r.0 == format!("Edited {t}")).unwrap_or_else(|| panic!("the edit: {rows:?}")); + assert_eq!((row.1, row.2), (false, Some(72.0)), "{t}: no number, at the item's text: {rows:?}"); + let nums: Vec = back.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.numbering.map(|n| n.num)).collect(); + assert_eq!(nums.len(), 2, "{rows:?}"); + assert_eq!(nums[0], nums[1], "{nums:?}"); + } +} + +/// A level first used after an unnumbered paragraph is still the file's: a bulleted sublist stays +/// bulleted, a numbered one under bullets stays numbered, read and written from the model. +#[test] +fn a_sublist_after_an_unnumbered_paragraph_keeps_its_levels() { + let open = |first: &str, second: &str| { + let styles = format!( + r#"{first}{second}"# + ); + let content = format!( + r#"OneMoreSub"# + ); + import(&package(&content, Some(&styles))).unwrap() + }; + let sub = |d: &Document| { + let p = d.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == "Sub").unwrap(); + let n = p.props.numbering.unwrap(); + d.numbering.level(n.num, n.level).map(|l| (n.level, l.format, l.text.clone(), l.start)).unwrap() + }; + let number = |level: u8, format: &str, start: u8| { + format!(r#""#) + }; + let bullet = |level: u8| format!(r#""#); + let d = open(&number(1, "1", 1), &bullet(2)); + assert_eq!(sub(&d), (1, NumFormat::Bullet, "–".to_string(), 1)); + assert_eq!(sub(&import(&crate::text::tests::export_model(&d).unwrap()).unwrap()), sub(&d), "written from the model"); + let d = open(&bullet(1), &number(2, "i", 3)); + let (level, format, _, start) = sub(&d); + assert_eq!((level, format, start), (1, NumFormat::LowerRoman, 3)); + assert_eq!(sub(&import(&crate::text::tests::export_model(&d).unwrap()).unwrap()), sub(&d), "written from the model"); +} + +/// A list item's further paragraph stays in its item in HTML and Markdown: the list goes on after it. +#[test] +fn a_list_items_further_paragraph_stays_in_it_in_html_and_markdown() { + let styles = format!( + r#""# + ); + let content = format!( + r#"OneContTwo"# + ); + let d = import(&package(&content, Some(&styles))).unwrap(); + let html = craft_html::doc::export(&d); + assert_eq!(html.matches("Cont

"), "{html}"); + let md = craft_markdown::export(&d); + assert!(md.contains("1. One\n\n Cont\n\n2. Two"), "{md}"); +} + +/// Only a list item's own further paragraph stays in it: an indented paragraph between two lists +/// joined by `text:continue-list` ends the list, and a last item's further paragraph (a one-item +/// list's too) stays in it. +#[test] +fn only_an_items_own_further_paragraph_stays_in_it() { + let styles = format!( + r#""# + ); + let open = |body: &str| { + // (An indent of its own: LibreOffice writes one as an automatic style.) + let auto = r#""#; + let content = + format!("{auto}{body}"); + import(&package(&content, Some(&styles))).unwrap() + }; + // A paragraph of its own between two parts of one list. + let d = open( + r#"OneBetweenTwo"#, + ); + let between = d.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == "Between").unwrap(); + assert_eq!(between.props.indent_left, Some(36.0)); + let html = craft_html::doc::export(&d); + assert_eq!(html.matches("Between

") && !html.contains("
  • One

    "), "{html}"); + let md = craft_markdown::export(&d); + assert!(md.contains("\n\nBetween\n\n") && !md.contains(" Between"), "{md}"); + // A last item's further paragraph, and a one-item list's. + for body in [ + r#"OneTwoContAfter"#, + r#"TwoContAfter"#, + ] { + let d = open(body); + let html = craft_html::doc::export(&d); + assert!(html.contains("

  • Two

    Cont

  • "), "{html}"); + let md = craft_markdown::export(&d); + assert!(md.contains("1. Two\n\n Cont\n\nAfter") || md.contains("2. Two\n\n Cont\n\nAfter"), "{md}"); + } +} + +/// Written from the model, a list item's further paragraph is in its `text:list-item`, after the +/// item's sublist, and the list stays one (#5723 review). +#[test] +fn a_further_paragraph_written_from_the_model_stays_in_its_item() { + let d = craft_markdown::import("1. One\n\n Cont\n - Sub\n\n More\n\n2. Two\n"); + let xml = crate::text::tests::content_of(&crate::text::tests::export_model(&d).unwrap()); + let one = xml.find(">One<").unwrap(); + let body = xml.get(one..).unwrap(); + assert!(body.contains("Cont"), "{xml}"); + assert!(body.contains("Sub = + back.body.iter().filter_map(|b| b.as_para()).map(|p| (p.text.clone(), p.props.numbering.is_some(), p.props.list_item)).collect(); + assert_eq!( + rows, + [ + ("One".to_string(), true, None), + ("Cont".to_string(), false, Some(0)), + ("Sub".to_string(), true, None), + ("More".to_string(), false, Some(0)), + ("Two".to_string(), true, None) + ], + "{xml}" + ); +} diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index 2ad475739c..88af69b94e 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -107,9 +107,22 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9 let mut kinds = [first; 9]; let mut seen = [false; 9]; let mut i = start; + // The level of the last item: an item's further paragraph goes in an item still open. + let mut last = 0usize; while let Some(FBlock::Para(q)) = blocks.get(i) { - let Some(li) = q.list else { break }; + let Some(li) = q.list else { + match model::continues_list(blocks, i).map(usize::from) { + Some(lv) if i > start && lv <= last => { + // The items below it are closed. + last = lv; + i += 1; + continue; + } + _ => break, + } + }; let l = li.level.min(8) as usize; + last = l; if li.list != id || (id == 0 && l == 0 && seen[0] && kinds[0].ordered != li.ordered) { break; } @@ -797,7 +810,9 @@ impl Writer { } // A list without its own `xml:id` (older files' lists) is given one, for a list going on // with it to name. - if p.list.is_some() + // (Its first numbered paragraph's: a list header has no number.) + let list = run.iter().find_map(|b| if let FBlock::Para(q) = b { q.list } else { None }); + if list.is_some() && list_xml_id(&ix.0).is_none() && let Some(at) = markup.find(" = Vec::new(); for (qi, q) in blocks.get(start..i).unwrap_or(&[]).iter().enumerate() { let FBlock::Para(q) = q else { continue }; + if q.list.is_none() { + // An item's further paragraph (`list_run` took it only below an open + // item at its level): in that item, its sublists ended first. + let lv = q.item.map_or(0, |l| l.min(8) as usize); + while stack.len() > lv + 1 { + if stack.pop() == Some(true) { + out.push_str(""); + } + out.push_str(""); + } + self.para_in(q, chain(start + qi), out); + continue; + } let lv = q.list.map(|l| l.level.min(8) as usize).unwrap_or(0); while stack.len() > lv + 1 { if stack.pop() == Some(true) { diff --git a/crates/wordmodel/src/props/para_props.rs b/crates/wordmodel/src/props/para_props.rs index a48540248e..619f13e917 100644 --- a/crates/wordmodel/src/props/para_props.rs +++ b/crates/wordmodel/src/props/para_props.rs @@ -506,6 +506,11 @@ pub struct ParaProps { /// file (not laid out yet); Word sizes a line by it, so dropping it changes Word's pages. #[serde(skip_serializing_if = "Option::is_none")] pub text_alignment: Option, + /// A list item's paragraph after its first (or a list header's), with no number of its own, + /// at this list level (0..=8): formats with list items (ODT, HTML, Markdown) keep it in the + /// item. Set only directly, never by a style. + #[serde(skip_serializing_if = "Option::is_none")] + pub list_item: Option, } impl ParaProps { From 7e581794bc414eae0c2721f75cb82e07e579a055 Mon Sep 17 00:00:00 2001 From: el-j Date: Sun, 15 Nov 2026 22:44:11 +0100 Subject: [PATCH 008/130] craft-video: uncompressed packed pictures (rawvideo) Unpack and pack UYVY, YUYV, YVYU, v210, r210 and R10k. Byte-exact with ffmpeg's packing and unpacking. Closes #1523. --- crates/video/Cargo.toml | 6 + crates/video/README.md | 1 + crates/video/src/lib.rs | 4 + crates/video/src/rawvideo/mod.rs | 302 +++++++++++++++++++++++++++++++ crates/video/tests/rawvideo.rs | 226 +++++++++++++++++++++++ 5 files changed, 539 insertions(+) create mode 100644 crates/video/src/rawvideo/mod.rs create mode 100644 crates/video/tests/rawvideo.rs diff --git a/crates/video/Cargo.toml b/crates/video/Cargo.toml index dae21e5b14..ae706f8374 100644 --- a/crates/video/Cargo.toml +++ b/crates/video/Cargo.toml @@ -36,6 +36,8 @@ mpeg4 = ["mpeg4-encode"] mpeg4-encode = ["craft-media/bitstream"] # FFV1 lossless video (RFC 9043): version 3, range coder, decoder and encoder. ffv1 = [] +# Uncompressed packed pictures (UYVY, YUYV, YVYU, v210, r210, R10k): unpacking and packing. +rawvideo = [] # Apple ProRes (SMPTE RDD 36): decoder and encoder. prores = ["craft-media/bitstream"] # H.264 / AVC: decoder and encoder; `h264-decode` or `h264-encode` for one of them. @@ -72,6 +74,10 @@ craft-media-testkit = { workspace = true } # The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test. craft-media = { workspace = true, features = ["avi"] } +[[test]] +name = "rawvideo" +required-features = ["rawvideo"] + [[test]] name = "dnx" required-features = ["dnx"] diff --git a/crates/video/README.md b/crates/video/README.md index 248e922b3b..849c5d9488 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -23,6 +23,7 @@ No codec feature is on by default. | `vp8` | `vp8` | VP8 (RFC 6386): decoder | | `mpeg2` | [`mpeg2`](src/mpeg2/README.md) | MPEG-2 video (ITU-T H.262) and MPEG-1 video (ISO/IEC 11172-2): decoder (`mpeg2-decode` alone); MPEG-2 encoder with I, P and B pictures (`mpeg2-encode`, which also turns on the decoder) | | `mpeg4` | [`mpeg4`](src/mpeg4/README.md) | MPEG-4 Part 2 video (ISO/IEC 14496-2, the Xvid/DivX format): Simple profile encoder (`mpeg4-encode`) | +| `rawvideo` | `rawvideo` | Uncompressed packed pictures: UYVY, YUYV, YVYU (8-bit 4:2:2), v210 (10-bit 4:2:2), r210 and R10k (10-bit RGB); unpacking to and packing from planar samples, byte-exact with ffmpeg | | `prores` | `prores` | Apple ProRes (SMPTE RDD 36): decoder and encoder | | `h264` | [`h264`](src/h264/decode/README.md) | ITU-T H.264 / AVC: decoder (`h264-decode` alone) and encoder (`h264-encode` alone) | | `hevc` | [`hevc`](src/hevc/decode/README.md) | ITU-T H.265 / HEVC: decoder (`hevc-decode` alone) and encoder (`hevc-encode` alone) | diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index 8202a93f8d..2d16d0d400 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -11,6 +11,7 @@ //! | `mpeg2` | [`mpeg2`] | MPEG-2 video (ITU-T H.262) and MPEG-1 video: decoder (`mpeg2-decode`) and MPEG-2 I/P/B encoder (`mpeg2-encode`) | //! | `mpeg4` | [`mpeg4`] | MPEG-4 Part 2 video (ISO/IEC 14496-2, Xvid/DivX): Simple profile encoder (`mpeg4-encode`) | //! | `ffv1` | [`ffv1`] | FFV1 lossless video (RFC 9043): version 3, range coder, decoder and encoder | +//! | `rawvideo` | [`rawvideo`] | Uncompressed packed pictures: UYVY, YUYV, YVYU, v210, r210, R10k | //! | `prores` | [`prores`] | Apple ProRes (SMPTE RDD 36): decoder and encoder | //! | `h264` | [`h264`] | ITU-T H.264 / AVC: decoder (`h264-decode`) and encoder (`h264-encode`) | //! | `hevc` | [`hevc`] | ITU-T H.265 / HEVC: decoder (`hevc-decode`) and encoder (`hevc-encode`) | @@ -45,6 +46,9 @@ pub mod mpeg4; #[cfg(feature = "ffv1")] pub mod ffv1; +#[cfg(feature = "rawvideo")] +pub mod rawvideo; + #[cfg(feature = "prores")] pub mod prores; diff --git a/crates/video/src/rawvideo/mod.rs b/crates/video/src/rawvideo/mod.rs new file mode 100644 index 0000000000..ab0bc3d499 --- /dev/null +++ b/crates/video/src/rawvideo/mod.rs @@ -0,0 +1,302 @@ +//! Uncompressed packed pictures: unpacking to and packing from planar samples, for the layouts +//! capture cards, QuickTime and the editing interchange formats use (feature `rawvideo`). +//! +//! | [`Layout`] | Samples | Packing | +//! |---|---|---| +//! | `Uyvy` | 8-bit 4:2:2 | `U Y0 V Y1` per two pixels (QuickTime `2vuy`, `UYVY`) | +//! | `Yuyv` | 8-bit 4:2:2 | `Y0 U Y1 V` (`YUY2`, `yuv2`, `YUYV`) | +//! | `Yvyu` | 8-bit 4:2:2 | `Y0 V Y1 U` (`YVYU`) | +//! | `V210` | 10-bit 4:2:2 | six pixels in four little-endian 32-bit words (`Cb0 Y0 Cr0`, `Y1 Cb1 Y2`, `Cr1 Y3 Cb2`, `Y4 Cr2 Y5`, ten bits each, the low field first); rows padded to a multiple of 128 bytes | +//! | `R210` | 10-bit RGB | one big-endian 32-bit word per pixel, `R` in bits 29-20, `G` in 19-10, `B` in 9-0; rows padded to a multiple of 256 bytes | +//! | `R10k` | 10-bit RGB | one big-endian 32-bit word per pixel, `R` in bits 31-22, `G` in 21-12, `B` in 11-2; rows are not padded | +//! +//! [`decode`] returns a [`Frame`] of `u16` planes (8-bit samples are stored in the low byte); +//! [`encode`] packs a frame back, so `encode(decode(x))` reproduces a well-formed `x` byte for byte +//! (padding bytes are written as zero). The luma and chroma of 4:2:2 pictures are as stored, with no +//! range or matrix conversion. 4:2:2 layouts need an even width. +//! +//! Written from the vendors' and SMPTE's packing descriptions. ffmpeg is only run as a black-box +//! oracle in the tests. + +/// What went wrong packing or unpacking. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The picture size cannot be used with the layout (zero, odd for 4:2:2, or too large). + #[error("invalid picture size {width}x{height} for {layout:?}")] + Size { + /// The layout. + layout: Layout, + /// The width. + width: u32, + /// The height. + height: u32, + }, + /// The data is shorter than the picture needs. + #[error("packed data is {got} bytes, {need} needed")] + Short { + /// Bytes given. + got: usize, + /// Bytes needed. + need: usize, + }, + /// The frame does not match the layout (kind, planes or a sample above the bit depth). + #[error("frame does not fit the layout: {0}")] + Frame(&'static str), +} + +/// `Result` of this module. +pub type Result = std::result::Result; + +/// A packed layout. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Layout { + Uyvy, + Yuyv, + Yvyu, + V210, + R210, + R10k, +} + +/// What the planes of a [`Frame`] hold. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + /// Planes Y (`width × height`), Cb and Cr (`width / 2 × height`). + Yuv422, + /// Planes R, G and B (`width × height`). + Rgb, +} + +/// The largest width or height accepted. +pub const MAX_DIMENSION: u32 = 1 << 15; + +impl Layout { + /// The planes a picture of this layout unpacks to. + pub fn kind(self) -> Kind { + match self { + Layout::Uyvy | Layout::Yuyv | Layout::Yvyu | Layout::V210 => Kind::Yuv422, + Layout::R210 | Layout::R10k => Kind::Rgb, + } + } + + /// Bits per sample: 8 or 10. + pub fn bit_depth(self) -> u8 { + match self { + Layout::Uyvy | Layout::Yuyv | Layout::Yvyu => 8, + _ => 10, + } + } + + /// Bytes of one packed row, or `None` if `width` cannot be used with the layout. + pub fn stride(self, width: u32) -> Option { + if width == 0 || width > MAX_DIMENSION || (self.kind() == Kind::Yuv422 && !width.is_multiple_of(2)) { + return None; + } + let w = width as usize; + Some(match self { + Layout::Uyvy | Layout::Yuyv | Layout::Yvyu => w * 2, + Layout::V210 => w.div_ceil(48) * 128, + Layout::R210 => w.div_ceil(64) * 256, + Layout::R10k => w * 4, + }) + } + + /// Bytes of a whole packed picture. + pub fn frame_bytes(self, width: u32, height: u32) -> Option { + if height == 0 || height > MAX_DIMENSION { + return None; + } + self.stride(width)?.checked_mul(height as usize) + } +} + +/// An unpacked picture. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Frame { + pub width: u32, + pub height: u32, + pub kind: Kind, + /// 8 or 10. + pub bit_depth: u8, + /// Y, Cb, Cr or R, G, B, row by row. + pub planes: [Vec; 3], +} + +impl Frame { + /// A black-filled frame (all zero samples). + pub fn new(width: u32, height: u32, kind: Kind, bit_depth: u8) -> Frame { + let (w, h) = (width as usize, height as usize); + let chroma = if kind == Kind::Yuv422 { w / 2 } else { w }; + Frame { width, height, kind, bit_depth, planes: [vec![0; w * h], vec![0; chroma * h], vec![0; chroma * h]] } + } +} + +/// `p[i] = v`, if `i` is in range. +fn put(p: &mut [u16], i: usize, v: u16) { + if let Some(s) = p.get_mut(i) { + *s = v; + } +} + +fn size_error(layout: Layout, width: u32, height: u32) -> Error { + Error::Size { layout, width, height } +} + +/// Unpack a picture. `data` may be longer than one picture; only the first is read. +pub fn decode(layout: Layout, width: u32, height: u32, data: &[u8]) -> Result { + let stride = layout.stride(width).ok_or_else(|| size_error(layout, width, height))?; + let need = layout.frame_bytes(width, height).ok_or_else(|| size_error(layout, width, height))?; + if data.len() < need { + return Err(Error::Short { got: data.len(), need }); + } + let mut f = Frame::new(width, height, layout.kind(), layout.bit_depth()); + let w = width as usize; + let cw = if f.kind == Kind::Yuv422 { w / 2 } else { w }; + let [p0, p1, p2] = &mut f.planes; + for (y, row) in data.chunks(stride).take(height as usize).enumerate() { + let (r0, r1, r2) = (y * w, y * cw, y * cw); + match layout { + Layout::Uyvy | Layout::Yuyv | Layout::Yvyu => { + let (iy, iu, iv) = match layout { + Layout::Uyvy => (1, 0, 2), + Layout::Yuyv => (0, 1, 3), + _ => (0, 3, 1), + }; + for (x, q) in row.as_chunks::<4>().0.iter().take(cw).enumerate() { + let at = |i: usize| u16::from(q.get(i).copied().unwrap_or(0)); + // the two lumas sit two bytes apart: first at `iy`, second at `iy + 2` + put(p0, r0 + 2 * x, at(iy)); + put(p0, r0 + 2 * x + 1, at(iy + 2)); + put(p1, r1 + x, at(iu)); + put(p2, r2 + x, at(iv)); + } + } + Layout::V210 => { + for (g, block) in row.as_chunks::<16>().0.iter().enumerate() { + let word = |i: usize| -> [u16; 3] { + let b = block.get(4 * i..4 * i + 4).unwrap_or(&[0; 4]); + let v = u32::from_le_bytes([b[0], b[1], b[2], b[3]]); + [(v & 0x3FF) as u16, ((v >> 10) & 0x3FF) as u16, ((v >> 20) & 0x3FF) as u16] + }; + let (w0, w1, w2, w3) = (word(0), word(1), word(2), word(3)); + // Cb0 Y0 Cr0 | Y1 Cb1 Y2 | Cr1 Y3 Cb2 | Y4 Cr2 Y5 + let ys = [w0[1], w1[0], w1[2], w2[1], w3[0], w3[2]]; + let cbs = [w0[0], w1[1], w2[2]]; + let crs = [w0[2], w2[0], w3[1]]; + for (k, v) in ys.into_iter().enumerate() { + if g * 6 + k < w { + put(p0, r0 + g * 6 + k, v); + } + } + for k in 0..3 { + if g * 3 + k < cw { + put(p1, r1 + g * 3 + k, cbs.get(k).copied().unwrap_or(0)); + put(p2, r2 + g * 3 + k, crs.get(k).copied().unwrap_or(0)); + } + } + } + } + Layout::R210 | Layout::R10k => { + let shift = if layout == Layout::R210 { 20 } else { 22 }; + for (x, q) in row.as_chunks::<4>().0.iter().take(w).enumerate() { + let v = u32::from_be_bytes(*q); + let field = |s: u32| ((v >> s) & 0x3FF) as u16; + put(p0, r0 + x, field(shift)); + put(p1, r1 + x, field(shift - 10)); + put(p2, r2 + x, field(shift - 20)); + } + } + } + } + Ok(f) +} + +/// Pack a frame. The frame's kind and bit depth must be the layout's, its planes the right size +/// and every sample within the bit depth. +pub fn encode(layout: Layout, frame: &Frame) -> Result> { + let (width, height) = (frame.width, frame.height); + let stride = layout.stride(width).ok_or_else(|| size_error(layout, width, height))?; + let total = layout.frame_bytes(width, height).ok_or_else(|| size_error(layout, width, height))?; + if frame.kind != layout.kind() || frame.bit_depth != layout.bit_depth() { + return Err(Error::Frame("the frame's kind or bit depth is not the layout's")); + } + let (w, h) = (width as usize, height as usize); + let cw = if frame.kind == Kind::Yuv422 { w / 2 } else { w }; + let sizes = [w * h, cw * h, cw * h]; + if frame.planes.iter().zip(sizes).any(|(p, n)| p.len() != n) { + return Err(Error::Frame("a plane has the wrong size")); + } + let max = (1u16 << frame.bit_depth) - 1; + if frame.planes.iter().flatten().any(|&v| v > max) { + return Err(Error::Frame("a sample is above the bit depth")); + } + let mut out = vec![0u8; total]; + let [p0, p1, p2] = &frame.planes; + let get = |p: &Vec, i: usize| p.get(i).copied().unwrap_or(0); + for (y, row) in out.chunks_mut(stride).enumerate() { + let (r0, r1, r2) = (y * w, y * cw, y * cw); + match layout { + Layout::Uyvy | Layout::Yuyv | Layout::Yvyu => { + let (iy, iu, iv) = match layout { + Layout::Uyvy => (1, 0, 2), + Layout::Yuyv => (0, 1, 3), + _ => (0, 3, 1), + }; + for (x, q) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (at, v) in [(iy, get(p0, r0 + 2 * x)), (iy + 2, get(p0, r0 + 2 * x + 1)), (iu, get(p1, r1 + x)), (iv, get(p2, r2 + x))] { + if let Some(b) = q.get_mut(at) { + *b = v as u8; + } + } + } + } + Layout::V210 => { + for (g, block) in row.as_chunks_mut::<16>().0.iter_mut().enumerate() { + let y = |k: usize| if g * 6 + k < w { u32::from(get(p0, r0 + g * 6 + k)) } else { 0 }; + let cb = |k: usize| if g * 3 + k < cw { u32::from(get(p1, r1 + g * 3 + k)) } else { 0 }; + let cr = |k: usize| if g * 3 + k < cw { u32::from(get(p2, r2 + g * 3 + k)) } else { 0 }; + let words = [ + cb(0) | (y(0) << 10) | (cr(0) << 20), + y(1) | (cb(1) << 10) | (y(2) << 20), + cr(1) | (y(3) << 10) | (cb(2) << 20), + y(4) | (cr(2) << 10) | (y(5) << 20), + ]; + for (i, v) in words.into_iter().enumerate() { + if let Some(b) = block.get_mut(4 * i..4 * i + 4) { + b.copy_from_slice(&v.to_le_bytes()); + } + } + } + } + Layout::R210 | Layout::R10k => { + let shift = if layout == Layout::R210 { 20 } else { 22 }; + for (x, q) in row.as_chunks_mut::<4>().0.iter_mut().take(w).enumerate() { + let v = (u32::from(get(p0, r0 + x)) << shift) + | (u32::from(get(p1, r1 + x)) << (shift - 10)) + | (u32::from(get(p2, r2 + x)) << (shift - 20)); + *q = v.to_be_bytes(); + } + } + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strides() { + assert_eq!(Layout::Uyvy.stride(1920), Some(3840)); + assert_eq!(Layout::V210.stride(1920), Some(5120)); + assert_eq!(Layout::V210.stride(50), Some(256)); + assert_eq!(Layout::R210.stride(1920), Some(7680)); + assert_eq!(Layout::R10k.stride(5), Some(20)); + assert_eq!(Layout::Uyvy.stride(3), None); + assert_eq!(Layout::R10k.stride(0), None); + assert_eq!(Layout::R10k.stride(MAX_DIMENSION + 1), None); + assert_eq!(Layout::V210.frame_bytes(50, 0), None); + } +} diff --git a/crates/video/tests/rawvideo.rs b/crates/video/tests/rawvideo.rs new file mode 100644 index 0000000000..c4af2152bf --- /dev/null +++ b/crates/video/tests/rawvideo.rs @@ -0,0 +1,226 @@ +//! Uncompressed packed pictures: packing and unpacking against each other, against ffmpeg as the +//! reference (oracle; skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`), +//! and on bad input. + +use craft_video::rawvideo::{Error, Frame, Kind, Layout, decode, encode}; +use std::path::Path; +use std::process::Command; + +const LAYOUTS: [Layout; 6] = [Layout::Uyvy, Layout::Yuyv, Layout::Yvyu, Layout::V210, Layout::R210, Layout::R10k]; + +/// A frame of pseudo-random samples at the layout's depth. +fn random_frame(layout: Layout, w: u32, h: u32, seed: u32) -> Frame { + let mut f = Frame::new(w, h, layout.kind(), layout.bit_depth()); + let mut x = seed | 1; + let max = (1u32 << layout.bit_depth()) - 1; + for p in &mut f.planes { + for v in p.iter_mut() { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + *v = ((x >> 7) & max) as u16; + } + } + f +} + +#[test] +fn pack_then_unpack_returns_the_frame() { + // widths that are, and are not, multiples of a v210 group (6 pixels) and of its 48-pixel row unit + for layout in LAYOUTS { + for (w, h) in [(2, 1), (6, 2), (8, 3), (50, 4), (96, 2), (98, 3), (130, 1)] { + let f = random_frame(layout, w, h, 7 + w); + let bytes = encode(layout, &f).expect("encode"); + assert_eq!(bytes.len(), layout.frame_bytes(w, h).expect("size")); + assert_eq!(decode(layout, w, h, &bytes).expect("decode"), f, "{layout:?} {w}x{h}"); + // longer data: only the first picture is read + let mut longer = bytes.clone(); + longer.extend([0xAA; 17]); + assert_eq!(decode(layout, w, h, &longer).expect("decode"), f); + } + } +} + +#[test] +fn the_extremes_of_every_field_survive() { + for layout in LAYOUTS { + let mut f = Frame::new(6, 1, layout.kind(), layout.bit_depth()); + let max = (1u16 << layout.bit_depth()) - 1; + for (i, p) in f.planes.iter_mut().enumerate() { + for (k, v) in p.iter_mut().enumerate() { + *v = if (i + k) % 2 == 0 { max } else { 0 }; + } + } + assert_eq!(decode(layout, 6, 1, &encode(layout, &f).expect("encode")).expect("decode"), f, "{layout:?}"); + } +} + +#[test] +fn known_bytes() { + // UYVY: U Y0 V Y1 + let f = decode(Layout::Uyvy, 2, 1, &[10, 20, 30, 40]).expect("decode"); + assert_eq!((f.planes[0].clone(), f.planes[1].clone(), f.planes[2].clone()), (vec![20, 40], vec![10], vec![30])); + // YUYV: Y0 U Y1 V; YVYU: Y0 V Y1 U + let f = decode(Layout::Yuyv, 2, 1, &[10, 20, 30, 40]).expect("decode"); + assert_eq!((f.planes[0].clone(), f.planes[1].clone(), f.planes[2].clone()), (vec![10, 30], vec![20], vec![40])); + let f = decode(Layout::Yvyu, 2, 1, &[10, 20, 30, 40]).expect("decode"); + assert_eq!((f.planes[0].clone(), f.planes[1].clone(), f.planes[2].clone()), (vec![10, 30], vec![40], vec![20])); + // R10k: R in bits 31-22; r210: R in bits 29-20 + let word = (1023u32 << 22) | (512 << 12) | (1 << 2); + let f = decode(Layout::R10k, 1, 1, &word.to_be_bytes()).expect("decode"); + assert_eq!((f.planes[0][0], f.planes[1][0], f.planes[2][0]), (1023, 512, 1)); + let word = (1023u32 << 20) | (512 << 10) | 1; + let f = decode(Layout::R210, 1, 1, &[&word.to_be_bytes()[..], &[0; 252]].concat()).expect("decode"); + assert_eq!((f.planes[0][0], f.planes[1][0], f.planes[2][0]), (1023, 512, 1)); + // v210: the first word is Cb0 | Y0 << 10 | Cr0 << 20 + let mut block = [0u8; 128]; + block[..4].copy_from_slice(&(100u32 | (200 << 10) | (300 << 20)).to_le_bytes()); + let f = decode(Layout::V210, 2, 1, &block).expect("decode"); + assert_eq!((f.planes[0][0], f.planes[1][0], f.planes[2][0]), (200, 100, 300)); +} + +#[test] +fn bad_sizes_data_and_frames_are_errors() { + assert!(matches!(decode(Layout::Uyvy, 3, 1, &[0; 100]), Err(Error::Size { .. }))); + assert!(matches!(decode(Layout::Uyvy, 0, 1, &[0; 100]), Err(Error::Size { .. }))); + assert!(matches!(decode(Layout::R10k, 4, 0, &[0; 100]), Err(Error::Size { .. }))); + assert!(matches!(decode(Layout::R10k, 1 << 20, 1, &[]), Err(Error::Size { .. }))); + assert!(matches!(decode(Layout::V210, 6, 1, &[0; 127]), Err(Error::Short { got: 127, need: 128 }))); + for layout in LAYOUTS { + let ok = random_frame(layout, 6, 2, 3); + assert!(encode(layout, &ok).is_ok()); + let mut bad = ok.clone(); + bad.planes[0].pop(); + assert!(matches!(encode(layout, &bad), Err(Error::Frame(_))), "{layout:?}"); + let mut bad = ok.clone(); + bad.planes[1][0] = 1 << layout.bit_depth(); + assert!(matches!(encode(layout, &bad), Err(Error::Frame(_))), "{layout:?}"); + let mut bad = ok.clone(); + bad.bit_depth = if layout.bit_depth() == 8 { 10 } else { 8 }; + assert!(matches!(encode(layout, &bad), Err(Error::Frame(_))), "{layout:?}"); + let mut bad = ok.clone(); + bad.kind = if layout.kind() == Kind::Rgb { Kind::Yuv422 } else { Kind::Rgb }; + assert!(matches!(encode(layout, &bad), Err(Error::Frame(_))), "{layout:?}"); + // every truncation is an error, never a panic + let bytes = encode(layout, &ok).expect("encode"); + for n in 0..bytes.len() { + assert!(decode(layout, 6, 2, &bytes[..n]).is_err(), "{layout:?} {n}"); + } + } + // an odd width for a 4:2:2 frame + let odd = Frame { width: 3, height: 1, kind: Kind::Yuv422, bit_depth: 8, planes: [vec![0; 3], vec![0; 1], vec![0; 1]] }; + assert!(matches!(encode(Layout::Uyvy, &odd), Err(Error::Size { .. }))); + // noise decodes to something and re-encodes within the bit depth + let mut x = 5u32; + let noise: Vec = (0..4096) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + x as u8 + }) + .collect(); + for layout in LAYOUTS { + let f = decode(layout, 18, 4, &noise).expect("decode noise"); + assert!(encode(layout, &f).is_ok()); + } +} + +// ---- ffmpeg as the reference +// +// The oracle pictures have even heights: ffmpeg's v210 decoder returns zeros for an odd height. + +fn ffmpeg(ff: &Path, args: &[&str]) { + let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +fn s(p: &Path) -> String { + p.to_str().expect("path").to_string() +} + +/// The planes of a planar raw file as `u16` (8-bit samples are bytes, 10-bit ones little-endian words). +fn read_planes(path: &Path, w: usize, h: usize, kind: Kind, depth: u8) -> [Vec; 3] { + let bytes = std::fs::read(path).expect("read"); + let samples: Vec = if depth == 8 { + bytes.iter().map(|&b| u16::from(b)).collect() + } else { + bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect() + }; + let cw = if kind == Kind::Yuv422 { w / 2 } else { w }; + let (a, rest) = samples.split_at(w * h); + let (b, c) = rest.split_at(cw * h); + assert_eq!(c.len(), cw * h, "plane sizes"); + [a.to_vec(), b.to_vec(), c.to_vec()] +} + +/// (layout, ffmpeg codec, pixel format of the packed picture, planar format to compare in). +const CASES: [(Layout, &str, &str, &str); 6] = [ + (Layout::Uyvy, "rawvideo", "uyvy422", "yuv422p"), + (Layout::Yuyv, "rawvideo", "yuyv422", "yuv422p"), + (Layout::Yvyu, "rawvideo", "yvyu422", "yuv422p"), + (Layout::V210, "v210", "yuv422p10le", "yuv422p10le"), + (Layout::R210, "r210", "gbrp10le", "gbrp10le"), + (Layout::R10k, "r10k", "gbrp10le", "gbrp10le"), +]; + +#[test] +fn we_unpack_and_repack_what_ffmpeg_packs() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("rawvideo"); + for (w, h) in [(50usize, 6usize), (98, 4)] { + for (layout, codec, pix, planar) in CASES { + let name = format!("{layout:?}_{w}x{h}"); + let nut = dir.join(format!("{name}.nut")); + let src = format!("gradients=size={w}x{h}:rate=1"); + ffmpeg(&ff, &["-f", "lavfi", "-i", &src, "-frames:v", "1", "-c:v", codec, "-pix_fmt", pix, "-f", "nut", &s(&nut)]); + // the packet ffmpeg wrote, and ffmpeg's own unpacking of it + let raw = dir.join(format!("{name}.raw")); + ffmpeg(&ff, &["-i", &s(&nut), "-c", "copy", "-f", "rawvideo", &s(&raw)]); + let reference = dir.join(format!("{name}.planar")); + ffmpeg(&ff, &["-i", &s(&nut), "-pix_fmt", planar, "-f", "rawvideo", &s(&reference)]); + let packet = std::fs::read(&raw).expect("read"); + assert_eq!(packet.len(), layout.frame_bytes(w as u32, h as u32).expect("size"), "{name}: packet size"); + let ours = decode(layout, w as u32, h as u32, &packet).expect("decode"); + let mut theirs = read_planes(&reference, w, h, layout.kind(), layout.bit_depth()); + if planar == "gbrp10le" { + // ffmpeg's planar RGB is G, B, R + theirs = [theirs[2].clone(), theirs[0].clone(), theirs[1].clone()]; + } + assert!(ours.planes == theirs, "{name}: our unpacking differs from ffmpeg's"); + assert!(encode(layout, &ours).expect("encode") == packet, "{name}: our packing differs from ffmpeg's"); + } + } +} + +#[test] +fn ffmpeg_unpacks_what_we_pack() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("rawvideo"); + // the layouts ffmpeg reads from a bare file: the raw pixel formats and v210 + for (layout, fmt_args, planar) in [ + (Layout::Uyvy, vec!["-f", "rawvideo", "-pix_fmt", "uyvy422"], "yuv422p"), + (Layout::Yuyv, vec!["-f", "rawvideo", "-pix_fmt", "yuyv422"], "yuv422p"), + (Layout::Yvyu, vec!["-f", "rawvideo", "-pix_fmt", "yvyu422"], "yuv422p"), + (Layout::V210, vec!["-f", "v210"], "yuv422p10le"), + ] { + for (w, h) in [(50u32, 6u32), (98, 4)] { + let f = random_frame(layout, w, h, 11); + let name = format!("ours_{layout:?}_{w}x{h}"); + let packed = dir.join(format!("{name}.raw")); + std::fs::write(&packed, encode(layout, &f).expect("encode")).expect("write"); + let out = dir.join(format!("{name}.planar")); + let size = format!("{w}x{h}"); + let mut args: Vec<&str> = fmt_args.clone(); + args.extend(["-video_size", &size, "-i"]); + let input = s(&packed); + args.push(&input); + args.extend(["-pix_fmt", planar, "-frames:v", "1", "-f", "rawvideo"]); + let output = s(&out); + args.push(&output); + ffmpeg(&ff, &args); + let theirs = read_planes(&out, w as usize, h as usize, layout.kind(), layout.bit_depth()); + assert!(theirs == f.planes, "{name}: ffmpeg unpacks our packing differently"); + } + } +} From 884f25cb653e7945b4a6e7dc73b8a50a662c1759 Mon Sep 17 00:00:00 2001 From: el-j Date: Sun, 15 Nov 2026 22:48:03 +0100 Subject: [PATCH 009/130] craft-audio: SMPTE ST 302M packet decoder and encoder (s302m) 2 to 8 channels of 16, 20 or 24 bits. Byte-identical to ffmpeg's encoder and sample-identical to its decoder in both directions. Closes #1540. --- crates/audio/Cargo.toml | 6 + crates/audio/README.md | 1 + crates/audio/src/lib.rs | 2 + crates/audio/src/s302m.rs | 234 ++++++++++++++++++++++++++++ crates/audio/tests/s302m_oracle.rs | 238 +++++++++++++++++++++++++++++ 5 files changed, 481 insertions(+) create mode 100644 crates/audio/src/s302m.rs create mode 100644 crates/audio/tests/s302m_oracle.rs diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 6452461305..30eeba2956 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -38,6 +38,8 @@ aac-decode = ["craft-media/bitstream"] # The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`. aac-encode = ["craft-media/bitstream", "craft-media/isobmff"] opus-decode = [] +# SMPTE ST 302M (AES3 audio in MPEG-2 transport streams): packet decoder and encoder. +s302m = [] # QOA (Quite OK Audio) files: decoder and encoder in the `qoa` module, each on its own. qoa = ["qoa-decode", "qoa-encode"] qoa-decode = [] @@ -88,6 +90,10 @@ required-features = ["decode", "lossless-encode", "peaks"] name = "codecs" required-features = ["decode", "encode"] +[[test]] +name = "s302m_oracle" +required-features = ["s302m"] + [[test]] name = "qoa_oracle" required-features = ["qoa"] diff --git a/crates/audio/README.md b/crates/audio/README.md index 63251db8d8..f68d2212ea 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` | +| `s302m` | `s302m::{decode, Encoder}`: SMPTE ST 302M packets (AES3 audio in MPEG-2 transport streams), 2 to 8 channels of 16, 20 or 24 bits | none | | `peaks` | `peaks::Peaks` | none | | `rayon` | parallel AAC encoding (with `aac-encode`) | `rayon` | | `serde` | `Serialize`/`Deserialize` on the shared types | `serde` | diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index be06783030..a8ce215620 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -54,6 +54,8 @@ pub mod peaks; pub mod qoa; #[cfg(feature = "decode-native")] mod read; +#[cfg(feature = "s302m")] +pub mod s302m; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] mod track; #[cfg(any(feature = "decode-native", feature = "pcm-encode"))] diff --git a/crates/audio/src/s302m.rs b/crates/audio/src/s302m.rs new file mode 100644 index 0000000000..aa50035459 --- /dev/null +++ b/crates/audio/src/s302m.rs @@ -0,0 +1,234 @@ +//! SMPTE ST 302M: AES3 audio carried in MPEG-2 transport stream packets (feature `s302m`): a +//! packet decoder ([`decode`]) and encoder ([`Encoder`]) for the payload of one PES packet. +//! +//! A packet is a 4-byte header and the audio. The header is the size in bytes of the audio (16 bits, +//! big-endian), then 16 bits: the channel count code (2 bits; 0 to 3 for 2, 4, 6 or 8 channels), the +//! identification of the first channel (8 bits), the sample size code (2 bits; 0, 1 and 2 for 16, 20 +//! and 24 bits) and 4 alignment bits. The audio is, for every frame, one 40-, 48- or 56-bit group +//! per channel pair, the pairs in order: each pair is two AES3 subframes, the left channel then the +//! right one, each of the sample (least significant bit first) and four flag bits (V, U, C and a +//! frame-start flag set on the left subframe of each channel pair in the first frame of every block of 192 frames). The +//! bits go out in transmission order, so a byte holds them most significant bit first. +//! +//! Samples are signed `i32` in the stream's own range (16, 20 or 24 bits, not scaled). The +//! decoder reads the flags and ignores them; the encoder writes the validity, user and channel +//! status bits as zero and sets the frame-start flag. +//! +//! Written from the standard's description of the packet and the AES3 subframe. ffmpeg is only run +//! as a black-box oracle in the tests. + +/// The most audio bytes one packet can hold (the size field is 16 bits). +pub const MAX_AUDIO_BYTES: usize = 0xFFFF; + +/// What went wrong decoding or encoding. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The packet is damaged, truncated, or uses a reserved code. + #[error("malformed SMPTE 302M packet: {0}")] + Malformed(&'static str), + /// The settings or samples given to the encoder cannot be written. + #[error("SMPTE 302M cannot encode: {0}")] + InvalidInput(&'static str), +} + +/// `Result` of this module. +pub type Result = std::result::Result; + +/// The header of a packet. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Header { + /// 2, 4, 6 or 8. + pub channels: usize, + /// The identification of the first channel (as the stream gives it). + pub channel_id: u8, + /// 16, 20 or 24. + pub bits: u32, + /// The alignment bits as written. + pub alignment: u8, + /// Bytes of audio after the header. + pub audio_bytes: usize, +} + +impl Header { + /// Bytes of one frame (one sample of every channel). + pub fn frame_bytes(&self) -> usize { + self.channels / 2 * ((self.bits as usize + 4) * 2 / 8) + } +} + +/// Parse the 4-byte header at the start of `packet`. +pub fn parse_header(packet: &[u8]) -> Result
    { + let [a, b, c, d, ..] = *packet else { return Err(Error::Malformed("shorter than the header")) }; + let size = usize::from(u16::from_be_bytes([a, b])); + let word = u16::from_be_bytes([c, d]); + let channels = 2 * (usize::from(word >> 14) + 1); + let bits = match (word >> 4) & 3 { + 0 => 16, + 1 => 20, + 2 => 24, + _ => return Err(Error::Malformed("reserved sample size code")), + }; + Ok(Header { channels, channel_id: ((word >> 6) & 0xFF) as u8, bits, alignment: (word & 0xF) as u8, audio_bytes: size }) +} + +/// One decoded packet. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Decoded { + /// The packet header. + pub header: Header, + /// Interleaved samples, `header.channels` per frame. + pub samples: Vec, +} + +/// Bit `i` of a byte string in transmission order (the first bit sent is the least significant bit of the sample, held in the most significant bit of the byte). +fn bit(bytes: &[u8], i: usize) -> u32 { + bytes.get(i / 8).map_or(0, |b| u32::from((b >> (7 - i % 8)) & 1)) +} + +/// Decode the payload of one PES packet. +pub fn decode(packet: &[u8]) -> Result { + let header = parse_header(packet)?; + let audio = packet.get(4..).unwrap_or(&[]); + if audio.len() < header.audio_bytes { + return Err(Error::Malformed("the audio is shorter than the header says")); + } + let audio = audio.get(..header.audio_bytes).unwrap_or(&[]); + let frame_bytes = header.frame_bytes(); + if frame_bytes == 0 || audio.len() % frame_bytes != 0 { + return Err(Error::Malformed("the audio is not a whole number of frames")); + } + let n = header.bits as usize; + let mut samples = Vec::with_capacity(audio.len() / (n + 4) * 8 / 2); + for frame in audio.chunks_exact(frame_bytes) { + for (sub, pos) in (0..header.channels).map(|c| (c, c * (n + 4))) { + let _ = sub; + let mut v = 0u32; + for k in 0..n { + v |= bit(frame, pos + k) << k; + } + // sign-extend the n-bit sample + let shift = 32 - n as u32; + samples.push(((v << shift) as i32) >> shift); + } + } + Ok(Decoded { header, samples }) +} + +/// A packet encoder. It counts frames so that the frame-start flag falls on the first frame of +/// every block of 192. +#[derive(Debug, Clone)] +pub struct Encoder { + channels: usize, + bits: u32, + channel_id: u8, + frames: u64, +} + +impl Encoder { + /// An encoder for `channels` (2, 4, 6 or 8) channels of `bits` (16, 20 or 24) bits. + pub fn new(channels: usize, bits: u32) -> Result { + if !matches!(channels, 2 | 4 | 6 | 8) { + return Err(Error::InvalidInput("SMPTE 302M carries 2, 4, 6 or 8 channels")); + } + if !matches!(bits, 16 | 20 | 24) { + return Err(Error::InvalidInput("SMPTE 302M samples have 16, 20 or 24 bits")); + } + Ok(Encoder { channels, bits, channel_id: 0, frames: 0 }) + } + + /// Set the identification of the first channel written in the header (0 by default). + pub fn channel_id(mut self, id: u8) -> Encoder { + self.channel_id = id; + self + } + + /// The most frames one packet can hold. + pub fn max_frames(&self) -> usize { + MAX_AUDIO_BYTES / (self.channels / 2 * ((self.bits as usize + 4) * 2 / 8)) + } + + /// Encode interleaved samples (a whole number of frames, at most [`Encoder::max_frames`], each + /// within the sample size) as one packet payload. + pub fn encode(&mut self, samples: &[i32]) -> Result> { + if samples.is_empty() || !samples.len().is_multiple_of(self.channels) { + return Err(Error::InvalidInput("the samples are not a whole number of frames")); + } + let frames = samples.len() / self.channels; + if frames > self.max_frames() { + return Err(Error::InvalidInput("too many frames for one packet")); + } + let n = self.bits as usize; + let limit = 1i64 << (n - 1); + if samples.iter().any(|&s| i64::from(s) < -limit || i64::from(s) >= limit) { + return Err(Error::InvalidInput("a sample is outside the sample size")); + } + let frame_bytes = self.channels / 2 * ((n + 4) * 2 / 8); + let audio_bytes = frames * frame_bytes; + let code = match self.bits { + 16 => 0u16, + 20 => 1, + _ => 2, + }; + let word = (((self.channels / 2 - 1) as u16) << 14) | (u16::from(self.channel_id) << 6) | (code << 4); + let mut out = Vec::with_capacity(4 + audio_bytes); + out.extend((audio_bytes as u16).to_be_bytes()); + out.extend(word.to_be_bytes()); + out.resize(4 + audio_bytes, 0); + for (f, frame) in samples.chunks_exact(self.channels).enumerate() { + let start = (self.frames + f as u64).is_multiple_of(192); + let base = 4 + f * frame_bytes; + for (c, &s) in frame.iter().enumerate() { + let pos = c * (n + 4); + let v = (s as u32) & ((1u32 << n) - 1); + for k in 0..n { + set_bit(&mut out, base, pos + k, (v >> k) & 1); + } + // flags V, U, C, then the frame-start flag on the left subframe of each pair + if c % 2 == 0 && start { + set_bit(&mut out, base, pos + n + 3, 1); + } + } + } + self.frames += frames as u64; + Ok(out) + } +} + +fn set_bit(out: &mut [u8], base: usize, i: usize, v: u32) { + if v != 0 + && let Some(b) = out.get_mut(base + i / 8) + { + *b |= 0x80 >> (i % 8); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_packet() { + // stereo 16-bit, one frame: L = 0x1234, R = 0xFEFF, the first frame of a block + let packet = [0x00, 0x05, 0x00, 0x00, 0x2c, 0x48, 0x1f, 0xf7, 0xf0]; + let d = decode(&packet).unwrap(); + assert_eq!(d.samples, vec![0x1234, -257]); + assert_eq!((d.header.channels, d.header.bits), (2, 16)); + let mut e = Encoder::new(2, 16).unwrap(); + assert_eq!(e.encode(&[0x1234, -257]).unwrap(), packet); + } + + #[test] + fn settings_and_packets_are_checked() { + assert!(Encoder::new(1, 16).is_err()); + assert!(Encoder::new(2, 18).is_err()); + let mut e = Encoder::new(2, 16).unwrap(); + assert!(e.encode(&[]).is_err()); + assert!(e.encode(&[1]).is_err()); + assert!(e.encode(&[40_000, 0]).is_err()); + assert!(decode(&[0, 1]).is_err()); + assert!(decode(&[0, 5, 0, 0x30, 0, 0, 0, 0, 0]).is_err()); + assert!(decode(&[0, 5, 0, 0, 0, 0]).is_err()); + assert!(decode(&[0, 4, 0, 0, 0, 0, 0, 0]).is_err()); + } +} diff --git a/crates/audio/tests/s302m_oracle.rs b/crates/audio/tests/s302m_oracle.rs new file mode 100644 index 0000000000..52b7a00f6b --- /dev/null +++ b/crates/audio/tests/s302m_oracle.rs @@ -0,0 +1,238 @@ +//! SMPTE 302M (feature `s302m`) against ffmpeg (oracle; skipped when ffmpeg is absent, a failure +//! with `CRAFT_MEDIA_REQUIRE_ORACLES=1`): we decode the packets ffmpeg's encoder puts in a transport +//! stream to the samples ffmpeg decodes, our encoder writes the same bytes, and ffmpeg decodes +//! packets of ours (patched into a transport stream) to our samples. + +use craft_audio::s302m::{Encoder, decode, parse_header}; +use std::path::Path; +use std::process::Command; + +fn signal(channels: usize, frames: usize, seed: u32) -> Vec { + let mut x = seed | 1; + let mut out = Vec::with_capacity(frames * channels); + for i in 0..frames { + for c in 0..channels { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + let tone = ((i as f64) * (0.03 + 0.011 * c as f64)).sin() * 0.6; + let noise = f64::from(x % 2000) / 2000.0 - 0.5; + out.push(((tone + 0.3 * noise) * f64::from(i32::MAX)) as i32); + } + } + out +} + +#[test] +fn round_trips_every_size_and_channel_count() { + for channels in [2usize, 4, 6, 8] { + for bits in [16u32, 20, 24] { + let max = 1i64 << (bits - 1); + let mut e = Encoder::new(channels, bits).expect("encoder"); + let frames = 500; + let samples: Vec = signal(channels, frames, 3).iter().map(|&v| (i64::from(v) * max / (1 << 31)) as i32).collect(); + let mut all = Vec::new(); + for chunk in samples.chunks(channels * 193) { + let p = e.encode(chunk).expect("encode"); + let d = decode(&p).expect("decode"); + assert_eq!((d.header.channels, d.header.bits), (channels, bits)); + all.extend(d.samples); + } + assert_eq!(all, samples, "{channels}ch {bits} bits"); + } + } + // the extremes + for bits in [16u32, 20, 24] { + let (lo, hi) = (-(1i32 << (bits - 1)), (1i32 << (bits - 1)) - 1); + let mut e = Encoder::new(2, bits).expect("encoder"); + assert_eq!(decode(&e.encode(&[lo, hi, hi, lo, 0, -1]).expect("encode")).expect("decode").samples, vec![lo, hi, hi, lo, 0, -1]); + assert!(e.encode(&[hi + 1, 0]).is_err()); + assert!(e.encode(&[lo - 1, 0]).is_err()); + } +} + +#[test] +fn the_packet_size_limit_and_headers_are_checked() { + let mut e = Encoder::new(2, 16).expect("encoder"); + let max = e.max_frames(); + assert!(e.encode(&vec![0; max * 2]).is_ok()); + assert!(e.encode(&vec![0; (max + 1) * 2]).is_err()); + let p = Encoder::new(8, 24).expect("encoder").channel_id(0x55).encode(&[0; 8]).expect("encode"); + let h = parse_header(&p).expect("header"); + assert_eq!((h.channels, h.channel_id, h.bits, h.audio_bytes), (8, 0x55, 24, 28)); + assert_eq!(h.frame_bytes(), 28); +} + +#[test] +fn damaged_packets_are_errors_never_panics() { + let mut e = Encoder::new(4, 24).expect("encoder"); + let p = e.encode(&signal(4, 40, 5).iter().map(|&v| v >> 8).collect::>()).expect("encode"); + for n in 0..p.len() { + let _ = decode(&p[..n]); + } + let mut x = 9u32; + for i in 0..p.len() { + let mut d = p.clone(); + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + d[i] ^= (x >> 8) as u8 | 1; + let _ = decode(&d); + } + assert!(decode(&[]).is_err()); + assert!(decode(&[0xFF, 0xFF, 0, 0, 1, 2, 3]).is_err()); + assert!(decode(&[0, 5, 0, 0x30, 0, 0, 0, 0, 0]).is_err(), "the reserved size code"); +} + +// ---- ffmpeg as the reference + +fn ffmpeg(ff: &Path, args: &[&str]) { + let out = Command::new(ff).args(["-v", "error", "-nostdin", "-y"]).args(args).output().expect("run ffmpeg"); + assert!(out.status.success(), "ffmpeg {args:?}: {}", String::from_utf8_lossy(&out.stderr)); +} + +fn s(p: &Path) -> String { + p.to_str().expect("path").to_string() +} + +/// The elementary-stream bytes of every PES packet of PID 0x100 in a transport stream, each as +/// the list of (offset in the file, length) pieces it is spread over. +fn pes_pieces(ts: &[u8]) -> Vec> { + let mut out: Vec> = Vec::new(); + for (i, p) in ts.chunks_exact(188).enumerate() { + if p[0] != 0x47 || ((usize::from(p[1] & 0x1F) << 8) | usize::from(p[2])) != 0x100 { + continue; + } + let mut off = 4; + if p[3] & 0x20 != 0 { + off += 1 + usize::from(p[4]); + } + if p[3] & 0x10 == 0 || off >= 188 { + continue; + } + let mut start = off; + if p[1] & 0x40 != 0 { + // a new PES packet: skip its header (00 00 01 id, length, flags, flags, header length, header) + assert_eq!(&p[off..off + 3], &[0, 0, 1]); + start = off + 9 + usize::from(p[off + 8]); + out.push(Vec::new()); + } + if let Some(last) = out.last_mut() { + last.push((i * 188 + start, 188 - start)); + } + } + out +} + +fn gather(ts: &[u8], pieces: &[(usize, usize)]) -> Vec { + pieces.iter().flat_map(|&(o, n)| ts[o..o + n].iter().copied()).collect() +} + +fn pcm_bytes(samples: &[i32], wide: bool) -> Vec { + if wide { + samples.iter().flat_map(|v| v.to_le_bytes()).collect() + } else { + samples.iter().flat_map(|&v| ((v >> 16) as i16).to_le_bytes()).collect() + } +} + +fn decoded_by_ffmpeg(ff: &Path, ts: &Path, out: &Path, wide: bool) -> Vec { + ffmpeg(ff, &["-i", &s(ts), "-f", if wide { "s32le" } else { "s16le" }, "-acodec", if wide { "pcm_s32le" } else { "pcm_s16le" }, &s(out)]); + let bytes = std::fs::read(out).expect("read"); + if wide { + bytes.as_chunks::<4>().0.iter().map(|b| i32::from_le_bytes(*b)).collect() + } else { + bytes.as_chunks::<2>().0.iter().map(|b| i32::from(i16::from_le_bytes(*b))).collect() + } +} + +#[test] +fn we_decode_and_encode_what_ffmpeg_encodes_and_ffmpeg_decodes_ours() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("s302m"); + for (channels, bits) in [(2usize, 16u32), (2, 24), (4, 24), (6, 16), (8, 24)] { + let name = format!("{channels}ch{bits}"); + let frames = 6000; + let wide = bits == 24; + let pcm = signal(channels, frames, 17); + let raw = dir.join(format!("{name}.pcm")); + std::fs::write(&raw, pcm_bytes(&pcm, wide)).expect("write"); + let ts = dir.join(format!("{name}.ts")); + ffmpeg( + &ff, + &[ + "-f", + if wide { "s32le" } else { "s16le" }, + "-ar", + "48000", + "-ac", + &channels.to_string(), + "-i", + &s(&raw), + "-af", + "asetnsamples=n=1024:p=0", + "-c:a", + "s302m", + "-strict", + "-2", + "-f", + "mpegts", + &s(&ts), + ], + ); + let bytes = std::fs::read(&ts).expect("read"); + let pieces = pes_pieces(&bytes); + assert!(pieces.len() >= 2, "{name}: {} packets", pieces.len()); + let theirs = decoded_by_ffmpeg(&ff, &ts, &dir.join(format!("{name}.out.pcm")), wide); + + let mut enc = Encoder::new(channels, bits).expect("encoder"); + let mut ours: Vec = Vec::new(); + let mut frames_seen = 0usize; + for pes in &pieces { + // the ES bytes of the packet: its own size field says how much of them is the packet + let es = gather(&bytes, pes); + let h = parse_header(&es).expect("header"); + let packet = &es[..4 + h.audio_bytes]; + let d = decode(packet).expect("decode"); + assert_eq!((d.header.channels, d.header.bits), (channels, bits), "{name}"); + // our encoder writes the same bytes ffmpeg's does + assert!(enc.encode(&d.samples).expect("encode") == packet, "{name}: our packet differs from ffmpeg's at frame {frames_seen}"); + frames_seen += d.samples.len() / channels; + // 24-bit samples are scaled to 32 bits by ffmpeg's decoder; 16-bit ones are not + ours.extend(d.samples.iter().map(|&v| if wide { v << 8 } else { v })); + } + let n = ours.len().min(theirs.len()); + assert!(n >= (frames - 1600) * channels, "{name}: {n} samples"); + assert!(ours[..n] == theirs[..n], "{name}: our decode differs from ffmpeg's"); + + // ffmpeg decodes our packets: patch them over the same-sized ones in the stream + let mine = signal(channels, frames, 23); + let mut patched = bytes.clone(); + let mut enc = Encoder::new(channels, bits).expect("encoder"); + let mut expect: Vec = Vec::new(); + for pes in &pieces { + let es = gather(&bytes, pes); + let h = parse_header(&es).expect("header"); + let n_frames = h.audio_bytes / h.frame_bytes(); + let at = expect.len(); + let src: Vec = mine[at..at + n_frames * channels].iter().map(|&v| if wide { v >> 8 } else { v >> 16 }).collect(); + let packet = enc.encode(&src).expect("encode"); + assert_eq!(packet.len(), 4 + h.audio_bytes); + expect.extend(src.iter().map(|&v| if wide { v << 8 } else { v })); + let mut k = 0; + for &(o, len) in pes { + let take = len.min(packet.len() - k); + patched[o..o + take].copy_from_slice(&packet[k..k + take]); + k += take; + } + assert!(k >= packet.len()); + } + let ours_ts = dir.join(format!("{name}.ours.ts")); + std::fs::write(&ours_ts, patched).expect("write"); + let theirs = decoded_by_ffmpeg(&ff, &ours_ts, &dir.join(format!("{name}.ours.pcm")), wide); + let n = expect.len().min(theirs.len()); + assert!(n >= (frames - 1600) * channels, "{name}: {n} samples"); + assert!(expect[..n] == theirs[..n], "{name}: ffmpeg decodes our packets differently"); + println!("{name}: {} PES packets, {n} samples identical both ways", pieces.len()); + } +} From 0207fb1117bc26897fa0f7e2be1e0bd3f60dae37 Mon Sep 17 00:00:00 2001 From: el-j Date: Sun, 15 Nov 2026 22:48:21 +0100 Subject: [PATCH 010/130] craft-audio: s302m test lint and docs --- crates/audio/src/lib.rs | 3 ++- crates/audio/tests/s302m_oracle.rs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index a8ce215620..976ed979cb 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -28,7 +28,8 @@ //! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`, and //! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`), [`mp3`] //! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-encode`: the packet encoder), [`qoa`] -//! (`qoa-decode`, `qoa-encode`: whole QOA files). +//! (`qoa-decode`, `qoa-encode`: whole QOA files) and [`s302m`] (`s302m`: +//! SMPTE 302M packets). //! //! The shared types below build with no features. diff --git a/crates/audio/tests/s302m_oracle.rs b/crates/audio/tests/s302m_oracle.rs index 52b7a00f6b..68f6582def 100644 --- a/crates/audio/tests/s302m_oracle.rs +++ b/crates/audio/tests/s302m_oracle.rs @@ -99,7 +99,7 @@ fn s(p: &Path) -> String { /// the list of (offset in the file, length) pieces it is spread over. fn pes_pieces(ts: &[u8]) -> Vec> { let mut out: Vec> = Vec::new(); - for (i, p) in ts.chunks_exact(188).enumerate() { + for (i, p) in ts.as_chunks::<188>().0.iter().enumerate() { if p[0] != 0x47 || ((usize::from(p[1] & 0x1F) << 8) | usize::from(p[2])) != 0x100 { continue; } From d795d23b31f72a5b5983cd7ffa4f01a71b048e07 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 17:08:39 -0500 Subject: [PATCH 011/130] Bound malformed subtitle scans and escape mixed-case SubViewer breaks --- crates/captions/src/microdvd.rs | 37 +++++++++++++++++++++----------- crates/captions/src/sami.rs | 17 +++++++++++++-- crates/captions/src/subviewer.rs | 20 ++++++++++++++++- 3 files changed, 59 insertions(+), 15 deletions(-) diff --git a/crates/captions/src/microdvd.rs b/crates/captions/src/microdvd.rs index 7e3d17962a..a5b606367e 100644 --- a/crates/captions/src/microdvd.rs +++ b/crates/captions/src/microdvd.rs @@ -67,21 +67,23 @@ fn split_controls(line: &str) -> (String, Vec<(char, String)>) { while let Some(open) = rest.find('{') { text.push_str(rest.get(..open).unwrap_or("")); let after = rest.get(open + 1..).unwrap_or(""); - let control = after.split_once('}').and_then(|(body, tail)| { - let (name, value) = body.split_once(':')?; - let mut chars = name.chars(); - let c = chars.next().filter(|c| c.is_ascii_alphabetic())?; - chars.next().is_none().then(|| (c, value.to_string(), tail)) - }); - match control { - Some((c, value, tail)) => { - controls.push((c, value)); + // Check the fixed-size control prefix before scanning its body. Invalid opening + // braces must not repeatedly scan the same suffix for a closing brace. + let name = after.as_bytes().first().copied().filter(u8::is_ascii_alphabetic); + if let Some(name) = name.filter(|_| after.as_bytes().get(1) == Some(&b':')) { + if let Some((body, tail)) = after.get(2..).and_then(|s| s.split_once('}')) { + controls.push((char::from(name), body.to_string())); rest = tail; - } - None => { + } else { + // No later control can close either: preserve the entire remaining text. text.push('{'); - rest = after; + text.push_str(after); + rest = ""; + break; } + } else { + text.push('{'); + rest = after; } } text.push_str(rest); @@ -207,6 +209,17 @@ mod tests { assert_eq!(cue_text("{f:Arial}{s:20}a & b {x"), "a & b {x"); } + #[test] + fn malformed_controls_inside_valid_cues_are_preserved() { + for raw in ["{".repeat(32_768), "{y:".repeat(16_384)] { + let doc = parse(&format!("{{0}}{{25}}{raw}")).unwrap(); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].text, raw); + } + assert_eq!(cue_text("{{y:i}hello"), "{hello"); + assert_eq!(cue_text("{xx:no}{y:b}hello"), "{xx:no}hello"); + } + #[test] fn rate_header() { let d = parse("{1}{1}25.000\n{25}{50}x\n").unwrap(); diff --git a/crates/captions/src/sami.rs b/crates/captions/src/sami.rs index 3329cc53e0..056cc1c6d8 100644 --- a/crates/captions/src/sami.rs +++ b/crates/captions/src/sami.rs @@ -72,8 +72,12 @@ fn text_run(s: &str) -> String { if let Some((_, len)) = crate::entity_at(rest) { out.push_str(rest.get(..len).unwrap_or("")); advance = len; - } else if let Some((body, _)) = rest.get(1..).and_then(|r| r.split_once(';')).filter(|(b, _)| b.len() <= 8) - && let Some(ch) = numeric_reference(body) + } else if let Some(body) = rest.get(1..).and_then(|r| { + // Numeric entities have at most eight body bytes. Never scan the + // unbounded remainder again for each malformed ampersand. + let end = r.bytes().take(9).position(|b| b == b';')?; + r.get(..end) + }) && let Some(ch) = numeric_reference(body) { out.push_str(&escape_markup(&ch.to_string())); advance = body.len() + 2; @@ -241,6 +245,15 @@ mod tests { assert_eq!(d.cues[1].end, last_cue_end(ms_to_tick(4000))); } + #[test] + fn malformed_entities_inside_valid_cues_are_bounded() { + let raw = "&".repeat(32_768); + let doc = parse(&format!("

    {raw}

     ")).unwrap(); + assert_eq!(doc.cues.len(), 1); + assert_eq!(doc.cues[0].text, "&".repeat(32_768)); + assert_eq!(text_run("A A A &é;"), "A &#00000065; A &é;"); + } + #[test] fn only_the_first_class_is_read() { let d = parse("

    en

    kr

     ").unwrap(); diff --git a/crates/captions/src/subviewer.rs b/crates/captions/src/subviewer.rs index 337788f320..5b94ceedd0 100644 --- a/crates/captions/src/subviewer.rs +++ b/crates/captions/src/subviewer.rs @@ -91,7 +91,15 @@ pub fn write(doc: &Document) -> String { } let end = if clock(c.end) == clock(c.start) { Tick(c.end.0.saturating_add(crate::TICKS_PER_MS * 10)) } else { c.end }; out.push_str(&format!("{},{}\n", clock(c.start), clock(end))); - let lines: Vec = lines.iter().map(|l| l.replace("[br]", "\u{ff3b}br\u{ff3d}").replace("[BR]", "\u{ff3b}BR\u{ff3d}")).collect(); + let lines: Vec = lines + .iter() + .map(|l| { + l.replace("[br]", "\u{ff3b}br\u{ff3d}") + .replace("[BR]", "\u{ff3b}BR\u{ff3d}") + .replace("[Br]", "\u{ff3b}Br\u{ff3d}") + .replace("[bR]", "\u{ff3b}bR\u{ff3d}") + }) + .collect(); out.push_str(&lines.join("[br]")); out.push_str("\n\n"); } @@ -109,6 +117,16 @@ mod tests { assert_eq!(d.cues[0].end, crate::text::ms_to_tick(3500)); } + #[test] + fn writer_escapes_every_case_of_literal_break_tokens() { + let doc = Document { + cues: vec![Cue { start: Tick(0), end: crate::text::ms_to_tick(1000), text: "a[br]b[BR]c[Br]d[bR]é".into(), ..Default::default() }], + ..Default::default() + }; + let decoded = parse(&write(&doc)).unwrap(); + assert_eq!(decoded.cues[0].text, "a[br]b[BR]c[Br]d[bR]é"); + } + #[test] fn rejects_other_text() { assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err()); From c2791310decb30172425de9c123adb16d5dace5c Mon Sep 17 00:00:00 2001 From: el-j Date: Mon, 16 Nov 2026 01:04:23 +0100 Subject: [PATCH 012/130] craft-video: validate dimensions and bounds in Frame::new --- crates/video/src/rawvideo/mod.rs | 24 ++++++++++++++++++++---- crates/video/tests/rawvideo.rs | 13 +++++++++++-- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/video/src/rawvideo/mod.rs b/crates/video/src/rawvideo/mod.rs index ab0bc3d499..8402df8eae 100644 --- a/crates/video/src/rawvideo/mod.rs +++ b/crates/video/src/rawvideo/mod.rs @@ -125,10 +125,26 @@ pub struct Frame { impl Frame { /// A black-filled frame (all zero samples). - pub fn new(width: u32, height: u32, kind: Kind, bit_depth: u8) -> Frame { + pub fn new(width: u32, height: u32, kind: Kind, bit_depth: u8) -> Result { + if width == 0 || width > MAX_DIMENSION || height == 0 || height > MAX_DIMENSION { + return Err(Error::Frame("dimensions out of range")); + } + if kind == Kind::Yuv422 && !width.is_multiple_of(2) { + return Err(Error::Frame("odd width for 4:2:2")); + } + if bit_depth != 8 && bit_depth != 10 { + return Err(Error::Frame("unsupported bit depth")); + } let (w, h) = (width as usize, height as usize); - let chroma = if kind == Kind::Yuv422 { w / 2 } else { w }; - Frame { width, height, kind, bit_depth, planes: [vec![0; w * h], vec![0; chroma * h], vec![0; chroma * h]] } + let luma_len = w.checked_mul(h).ok_or(Error::Frame("allocation overflow"))?; + let chroma_w = if kind == Kind::Yuv422 { w / 2 } else { w }; + let chroma_len = chroma_w.checked_mul(h).ok_or(Error::Frame("allocation overflow"))?; + let total_bytes = + luma_len.checked_mul(2).and_then(|l| l.checked_add(chroma_len.checked_mul(4)?)).ok_or(Error::Frame("allocation overflow"))?; + if total_bytes as u64 > crate::budget::DECODE_MEMORY_BUDGET { + return Err(Error::Frame("frame exceeds memory budget")); + } + Ok(Frame { width, height, kind, bit_depth, planes: [vec![0; luma_len], vec![0; chroma_len], vec![0; chroma_len]] }) } } @@ -150,7 +166,7 @@ pub fn decode(layout: Layout, width: u32, height: u32, data: &[u8]) -> Result Frame { - let mut f = Frame::new(w, h, layout.kind(), layout.bit_depth()); + let mut f = Frame::new(w, h, layout.kind(), layout.bit_depth()).expect("new frame"); let mut x = seed | 1; let max = (1u32 << layout.bit_depth()) - 1; for p in &mut f.planes { @@ -44,7 +44,7 @@ fn pack_then_unpack_returns_the_frame() { #[test] fn the_extremes_of_every_field_survive() { for layout in LAYOUTS { - let mut f = Frame::new(6, 1, layout.kind(), layout.bit_depth()); + let mut f = Frame::new(6, 1, layout.kind(), layout.bit_depth()).expect("new frame"); let max = (1u16 << layout.bit_depth()) - 1; for (i, p) in f.planes.iter_mut().enumerate() { for (k, v) in p.iter_mut().enumerate() { @@ -224,3 +224,12 @@ fn ffmpeg_unpacks_what_we_pack() { } } } + +#[test] +fn frame_new_validates_dimensions_and_rejects_oversized_allocation() { + assert!(Frame::new(u32::MAX, u32::MAX, Kind::Rgb, 10).is_err()); + assert!(Frame::new(0, 100, Kind::Rgb, 8).is_err()); + assert!(Frame::new(100, 0, Kind::Rgb, 8).is_err()); + assert!(Frame::new(3, 100, Kind::Yuv422, 8).is_err()); + assert!(Frame::new(100, 100, Kind::Rgb, 12).is_err()); +} From c5435ab6d77a2c9b6737e77f58d5fd8077d4756c Mon Sep 17 00:00:00 2001 From: el-j Date: Mon, 16 Nov 2026 02:24:23 +0100 Subject: [PATCH 013/130] craft-audio: drop manifest lines that belong to no file in this PR --- crates/audio/Cargo.toml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index c9c00f3a36..cc5bca15af 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -47,8 +47,6 @@ s302m = [] qoa = ["qoa-decode", "qoa-encode"] qoa-decode = [] qoa-encode = [] -# ITU-T G.726 ADPCM speech codec (16/24/32/40 kbit/s). -g726 = [] opus-encode = [] ac3-decode = ["craft-media/bitstream"] mpa-decode = ["craft-media/bitstream"] @@ -104,10 +102,6 @@ required-features = ["flac-decode", "flac-encode"] name = "qoa_oracle" required-features = ["qoa"] -[[test]] -name = "g726_oracle" -required-features = ["g726"] - [[example]] name = "info" required-features = ["decode"] From 96320ea14610bb0eb28cf88ea2e11f02d78bdd4c Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 15:21:24 +0100 Subject: [PATCH 014/130] ODT: an edited style keeps its parent's and an unread namesake's file definitions An edited style the file names as WordCraft does (`Eigen`) was skipped by the rewrite, so its parent kept WordCraft's name (`BaseStyle`) instead of the file's (`Base_20_Style`). It is now rewritten like any other. A style the import didn't read whose name is the one WordCraft writes a read style under (`MyCustom` beside `My_20_Custom`) took that style's edit or deletion. It now keeps its own definition. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/kept.rs | 33 ++++++++++++------- crates/odf/src/text/package.rs | 2 +- crates/odf/src/text/tests_more/kept.rs | 45 ++++++++++++++++++++++++++ 3 files changed, 67 insertions(+), 13 deletions(-) diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index 953b672cc3..3e507e5b67 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -332,17 +332,17 @@ pub(super) fn with_common_as_read( }) } -/// What becomes of the file's styles (`defs`) that `changed` touches but `styles` (the part being -/// written) doesn't have under the file's key, by those keys: WordCraft's definition from `now` -/// (all it would write) under the file's names, or `None` for a style it no longer has. `ids` -/// gives the style id the import read a file's style into ([`KeptXml::style_ids`]), `ours` the -/// name WordCraft writes an id under: paragraphs written as read name the file's. A style the -/// import didn't read is WordCraft's only under its own name, so another of the file's styles -/// WordCraft would have under the same id (`Base_20_Style` beside `BaseStyle`) is left alone. +/// What becomes of the file's styles (`defs`) that `changed` touches, by their keys: WordCraft's +/// definition from `now` (all it would write) under the file's names, its parent and next style +/// included, or `None` for a style it no longer has. `ids` gives the style id the import read a +/// file's style into ([`KeptXml::style_ids`]), `ours` the name WordCraft writes an id under: +/// paragraphs written as read name the file's. A style the import didn't read is WordCraft's only +/// under its own name, so another of the file's styles WordCraft would have under the same id +/// (`Base_20_Style` beside `BaseStyle`) is left alone, as is one the import didn't read named as +/// WordCraft names one it did (`MyCustom` beside `My_20_Custom`). /// /// [`KeptXml::style_ids`]: craft_wordmodel::kept::KeptXml::style_ids pub(super) fn rewritten_defs( - styles: &str, now: &str, defs: &BTreeMap>, changed: &BTreeSet, @@ -377,16 +377,25 @@ pub(super) fn rewritten_defs( }; styles_of.push((key, name, family, mine)); } + // The names WordCraft writes the styles the import read under, by family: one of the file's + // styles the import didn't read but named so (`MyCustom` beside `My_20_Custom`) isn't theirs. + let read: HashSet<(&str, &str)> = + styles_of.iter().filter(|(key, ..)| ids.contains_key(*key)).map(|(_, _, family, mine)| (*family, mine.as_str())).collect(); let (kids, _) = children(now, "office:styles", "common"); let kids: HashMap = kids.into_iter().collect(); - let (written, _) = children(styles, "office:styles", "common"); - let written: HashSet = written.into_iter().map(|(k, _)| k).collect(); let mut out = BTreeMap::new(); - for (key, name, family, mine) in styles_of { + for (key, name, family, mine) in &styles_of { + let (key, name, family) = (*key, name, *family); + let read_so = !ids.contains_key(key) && read.contains(&(family, mine.as_str())); let mine = format!("common:{mine}{family}"); - if !changed.contains(&mine) || (mine == *key && written.contains(key)) { + if !changed.contains(&mine) { continue; } + if read_so { + out.insert(key.clone(), defs.get(key).map(|d| d.to_string())); + continue; + } + // Rewritten even under its own name: its parent or next style may have another. let def = kids.get(&mine).and_then(|(a, b)| now.get(*a..*b)).map(|d| { renamed(d, &|attr, v| match attr { // Two of the file's names can be one of WordCraft's: a style keeps its own. diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 3b91a02b52..6e1b73a3a8 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -847,7 +847,7 @@ fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, let changed = super::kept::changed(&k.style_prints, &super::kept::prints(&now)); // The name WordCraft writes a style id under (`My_20_Custom` was read as `MyCustom`). let ours = |id: &str| super::writer::odf_name(id); - let rewritten = super::kept::rewritten_defs(&styles, &now, &k.defs, &changed, &k.style_ids, &ours); + let rewritten = super::kept::rewritten_defs(&now, &k.defs, &changed, &k.style_ids, &ours); super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten) } diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index d47ea57389..a87e38655e 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -418,6 +418,51 @@ fn an_unused_style_sharing_an_edited_ones_id_keeps_its_definition() { assert!(theirs.contains(r#"fo:font-size="30pt""#) && theirs.contains("#ff0000"), "as read: {theirs}"); } +/// A style nothing in the file uses, named as WordCraft names a used one (`MyCustom` beside +/// `My_20_Custom`, which WordCraft has as `MyCustom`), keeps its definition when the used one is +/// edited or deleted. +#[test] +fn an_unused_style_named_as_wordcraft_names_an_edited_one_keeps_its_definition() { + use std::sync::Arc; + let s = r##""##; + let as_read = |saved: &str| { + let theirs = def_named(saved, "MyCustom").unwrap_or_else(|| panic!("{saved}")); + assert!(theirs.contains(r#"fo:font-size="30pt""#) && theirs.contains("#ff0000"), "as read: {theirs}"); + }; + + let mut d = opened(s, &["My_20_Custom"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let saved = styles_of(&export(&d).unwrap()); + assert!(def_named(&saved, "My_20_Custom").is_some_and(|d| d.contains(r#"fo:font-size="21pt""#)), "{saved}"); + as_read(&saved); + + let mut d = opened(s, &["My_20_Custom"]); + Arc::make_mut(&mut d.styles).remove(&id); + d.restyle(&id, None); + let saved = styles_of(&export(&d).unwrap()); + assert!(def_named(&saved, "My_20_Custom").is_none(), "{saved}"); + as_read(&saved); +} + +/// An edited style the file names as WordCraft does (`Eigen`), whose parent WordCraft names +/// otherwise (`Base_20_Style`, WordCraft's `BaseStyle`), still derives from the file's parent. +#[test] +fn an_edited_style_under_its_own_name_keeps_its_parents_file_name() { + use std::sync::Arc; + let s = r#""#; + let mut d = opened(s, &["Eigen"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.italic = Some(true); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + let mine = def_named(&saved, "Eigen").unwrap_or_else(|| panic!("{saved}")); + assert!(mine.contains(r#"style:parent-style-name="Base_20_Style""#), "{mine}"); + assert!(def_named(&saved, "Base_20_Style").is_some_and(|d| d.contains(r#"style:writing-mode="tb-rl""#)), "as read: {saved}"); + let back = import(&bytes).unwrap(); + assert_eq!(back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size, 30.0, "inherited"); +} + /// A character style WordCraft read under another id (`AccentChar`, as a paragraph style has /// `Accent`), edited, is written under the file's name: the text written as read names that. #[test] From 9b944481034b47247c6f170aaae6f8dc16a10afb Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 17:44:17 +0100 Subject: [PATCH 015/130] List item further paragraphs: fixes from review - flow: each piece of a further paragraph split at a page break keeps its item. - flow: body text resets the per-level item text positions, so a list starting with a header after an earlier, further-indented list keeps the header in its list. - flow: a further paragraph in a table-style-formatted cell keeps its list_item marker. - html: a further paragraph is written through para_html, keeping alignment and page break. - markdown: a quoted list item's further paragraph joins the item with a line break, so the quoted list stays one list and keeps its numbers. - odf: a further paragraph opening or closing a kept section ends the list run, as an item does. Co-Authored-By: Claude Opus 5.5 --- crates/flow/src/from_doc.rs | 9 ++- crates/flow/src/lib.rs | 88 +++++++++++++++++++++++++ crates/html/src/doc/export.rs | 2 +- crates/html/src/doc/tests.rs | 12 ++++ crates/markdown/src/blocks.rs | 13 ++++ crates/markdown/src/tests.rs | 16 +++++ crates/odf/src/text/tests_more/lists.rs | 30 +++++++++ crates/odf/src/text/writer.rs | 7 +- 8 files changed, 173 insertions(+), 4 deletions(-) diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index 8bcf4f5527..dcebfeea68 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -552,13 +552,13 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { wrap: None, index: None, group: None, - item: None, + // A list item's further paragraph, each piece of it. + item: out.item, }; let prev = std::mem::replace(&mut out, next); if prev.inlines.is_empty() { out.page_break |= prev.page_break; out.list = prev.list; - out.item = prev.item; } else { done.push(prev); } @@ -940,6 +940,9 @@ fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemTex q.item = None; } } + } else { + // Body text: the lists before it have ended, and where their items' text was with them. + *at = [None; 9]; } paras } @@ -1098,6 +1101,8 @@ fn with_cell_text(doc: &Document, blocks: &Blocks, chr: &CharProps, align: Optio if !table.is_empty() { let mut props = doc.styles.table_para_patch(&p.props, &table); props.overlay(&p.props); + // Direct only, so no overlay carries it: a list item's further paragraph stays one. + props.list_item = p.props.list_item; p.props = props; } Arc::new(Block::Para(p)) diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index 5bcb7a68c9..f1129acc79 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -185,4 +185,92 @@ mod tests { p.trim(); assert_eq!(p.inlines, vec![Inline::Text("a ".into(), i), Inline::Text("b".into(), b)]); } + + /// Paragraphs of `text` in order, each with its props set by `set`. + fn doc_of(paras: &[(&str, &dyn Fn(&mut craft_wordmodel::ParaProps))]) -> craft_wordmodel::Document { + let mut doc = craft_wordmodel::Document::new(); + doc.body = paras + .iter() + .map(|(t, set)| { + let mut p = craft_wordmodel::Paragraph::with_text(t, Default::default()); + set(&mut p.props); + std::sync::Arc::new(craft_wordmodel::Block::Para(p)) + }) + .collect(); + doc + } + + /// The text and `item` of each flow paragraph, a table cell's included. + fn items(blocks: &[FBlock]) -> Vec<(String, Option)> { + let mut out = Vec::new(); + for b in blocks { + match b { + FBlock::Para(p) => out.push((p.text(), p.item)), + FBlock::Table(t) => { + for c in t.rows.iter().flatten() { + out.extend(items(&c.blocks)); + } + } + } + } + out + } + + /// A list item's further paragraph cut by a page break is that paragraph on both pages: the + /// text after the break stays in the item too. + #[test] + fn a_further_paragraph_stays_in_its_item_past_a_page_break() { + let cont = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(36.0); + }; + let doc = doc_of(&[("Before\u{c}After", &cont)]); + let got = items(&from_doc(&doc).blocks); + assert_eq!(got, [("Before".to_string(), Some(0)), ("After".to_string(), Some(0))], "{got:?}"); + } + + /// Body text ends the lists before it: a list starting with a header (no number) at its text + /// is a list's paragraph however far an earlier list's text was indented. + #[test] + fn a_list_header_after_body_text_is_in_its_list() { + let mut doc = craft_wordmodel::Document::new(); + let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered); + let numbered = move |p: &mut craft_wordmodel::ParaProps| { + p.numbering = Some(NumRef { num, level: 0 }); + p.indent_left = Some(72.0); + }; + let header = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(36.0); + }; + let numbered_36 = move |p: &mut craft_wordmodel::ParaProps| { + p.numbering = Some(NumRef { num, level: 0 }); + p.indent_left = Some(36.0); + }; + let body = doc_of(&[("One", &numbered), ("Body", &|_| {}), ("Header", &header), ("Two", &numbered_36)]).body; + doc.body = body; + let got = items(&from_doc(&doc).blocks); + assert_eq!(got.iter().find(|r| r.0 == "Header").map(|r| r.1), Some(Some(0)), "{got:?}"); + } + + /// A list item's further paragraph in a table cell a table style formats stays one. + #[test] + fn a_further_paragraph_in_a_styled_cell_stays_in_its_item() { + let cont = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(36.0); + }; + let mut doc = craft_wordmodel::Document::new(); + // Table Grid: paragraph formatting of its own (no space after, single spacing). + let mut t = craft_wordmodel::table::Table::new(1, 1, 200.0); + if let Some(c) = t.rows.first_mut().and_then(|r| r.cells.first_mut()) { + c.blocks = doc_of(&[("Cont", &cont)]).body; + } + doc.body = vec![ + std::sync::Arc::new(craft_wordmodel::Block::Table(t)), + std::sync::Arc::new(craft_wordmodel::Block::Para(craft_wordmodel::Paragraph::new())), + ]; + let got = items(&from_doc_with(&doc, FlowOpts { paras: true, ..Default::default() }).blocks); + assert_eq!(got.iter().find(|r| r.0 == "Cont").map(|r| r.1), Some(Some(0)), "{got:?}"); + } } diff --git a/crates/html/src/doc/export.rs b/crates/html/src/doc/export.rs index c50fcec0ff..878313dfe6 100644 --- a/crates/html/src/doc/export.rs +++ b/crates/html/src/doc/export.rs @@ -284,7 +284,7 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize) { if stack.len() != lv + 1 || !stack.last().is_some_and(|s| s.1) { break; } - out.push_str(&format!("

    {}

    ", inlines_html(&q.inlines))); + out.push_str(¶_html(q)); i += 1; continue; }; diff --git a/crates/html/src/doc/tests.rs b/crates/html/src/doc/tests.rs index 640ab07d02..673bb496e0 100644 --- a/crates/html/src/doc/tests.rs +++ b/crates/html/src/doc/tests.rs @@ -767,3 +767,15 @@ fn hostile_style_sheets_never_panic() { let _ = parse_in(&format!("

    x

    y"), &|_| None, true); } } + +/// A list item's further paragraph keeps its alignment (and page break) in its item. +#[test] +fn an_items_further_paragraph_keeps_its_alignment() { + let mut one = Para { list: Some(model::ListInfo { ordered: true, ..Default::default() }), ..Default::default() }; + one.push_text("One", &Fmt::default()); + let mut cont = Para { item: Some(0), align: Some(Align::Center), ..Default::default() }; + cont.spacing.left = Some(36.0); + cont.push_text("Cont", &Fmt::default()); + let html = export(&model::to_doc(&Flow { blocks: vec![FBlock::Para(one), FBlock::Para(cont)], meta: Meta::default() })); + assert!(html.contains("
  • One

    Cont

  • "), "{html}"); +} diff --git a/crates/markdown/src/blocks.rs b/crates/markdown/src/blocks.rs index 919a80886d..64e7eefc9e 100644 --- a/crates/markdown/src/blocks.rs +++ b/crates/markdown/src/blocks.rs @@ -593,6 +593,19 @@ fn parse_quote(lines: &[String], i: &mut usize, depth: usize, level: u8, refs: & && p.kind == Kind::Normal { p.kind = Kind::Quote; + // A quoted list item's further paragraph: the writers keep only plain paragraphs in + // an item, so it joins the item's last paragraph with a line break, as a block in an + // item does, and the list goes on after it. + if p.item.is_some() { + p.item = None; + if let Some(FBlock::Para(prev)) = out.last_mut() + && prev.list.is_some() + { + prev.push_text("\n", &Fmt::default()); + prev.inlines.append(&mut p.inlines); + continue; + } + } } out.push(block); } diff --git a/crates/markdown/src/tests.rs b/crates/markdown/src/tests.rs index e59ae436af..309fda157f 100644 --- a/crates/markdown/src/tests.rs +++ b/crates/markdown/src/tests.rs @@ -864,3 +864,19 @@ fn a_block_after_a_sublist_keeps_the_next_items_number() { assert_eq!(html.matches(" 1. One\n>\n> Cont\n>\n> 2. Two\n"); + let nums: Vec = d.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.numbering.map(|n| n.num)).collect(); + assert_eq!(nums.len(), 2, "{nums:?}"); + assert_eq!(nums[0], nums[1], "one list: {nums:?}"); + let text: String = d.body.iter().filter_map(|b| b.as_para()).map(|p| p.text.clone()).collect::>().join("|"); + assert!(text.contains("Cont"), "{text}"); + let md = export(&d); + assert!(md.contains("> 2. Two") && !md.contains("> 1. Two"), "{md}"); + let html = craft_html::doc::export(&d); + assert_eq!(html.matches(""# + ); + let content = format!( + r#"ZeroOneContTwo"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + // Edited, so the list is written from the model; the section's paragraphs are as read. + let i = d.body.iter().position(|b| b.as_para().is_some_and(|p| p.text == "One")).unwrap(); + d.insert_text(&craft_wordmodel::Pos::body(i, 0), "Edited ", &Default::default()).unwrap(); + let c = crate::text::tests::content_of(&export(&d).unwrap()); + let (close, two) = (c.find(""), c.find(">Two<")); + assert!(close.is_some() && two.is_some() && close < two, "the section closes before Two: {c}"); + assert!(c.find(">Cont<") < close, "{c}"); + // And one opening a section starts after the list: the section opens before it. + let content = format!( + r#"OneHeaderTwo"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + let i = d.body.iter().position(|b| b.as_para().is_some_and(|p| p.text == "One")).unwrap(); + d.insert_text(&craft_wordmodel::Pos::body(i, 0), "Edited ", &Default::default()).unwrap(); + let c = crate::text::tests::content_of(&export(&d).unwrap()); + let (open, header) = (c.find("Header<")); + assert!(open.is_some() && header.is_some() && open < header, "the section opens before Header: {c}"); +} diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index 88af69b94e..cefcf4009c 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -111,11 +111,16 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9 let mut last = 0usize; while let Some(FBlock::Para(q)) = blocks.get(i) { let Some(li) = q.list else { + // A section it opens or closes ends the run, as an item's does. + let wrap = q.wrap.as_deref().filter(|_| wraps); match model::continues_list(blocks, i).map(usize::from) { - Some(lv) if i > start && lv <= last => { + Some(lv) if i > start && lv <= last && !wrap.is_some_and(|w| !w.0.is_empty()) => { // The items below it are closed. last = lv; i += 1; + if wrap.is_some_and(|w| w.1 > 0) { + break; + } continue; } _ => break, From 116914c8f2233f0ba05b39ab75d0136ba84e534e Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 18:13:20 +0100 Subject: [PATCH 016/130] ODT: text written from the model names the file's style beside an unread namesake A file style the import read (My_20_Custom) whose WordCraft name (MyCustom) is another of the file's styles the import didn't read keeps that namesake's own definition. A paragraph or text span written from the model now names the file's style it was read with, directly or as its automatic style's parent, instead of resolving to the namesake. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/kept.rs | 23 +++++++++++++++ crates/odf/src/text/package.rs | 3 ++ crates/odf/src/text/tests_more/kept.rs | 39 ++++++++++++++++++++++++++ crates/odf/src/text/writer.rs | 9 ++++-- 4 files changed, 72 insertions(+), 2 deletions(-) diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index 3e507e5b67..4f1e7654a5 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -408,6 +408,29 @@ pub(super) fn rewritten_defs( out } +/// The file's names for the styles the import read whose name as WordCraft writes them (`ours`) +/// is a style of the file's the import didn't read (`MyCustom` beside `My_20_Custom`): by that +/// name with its family's key suffix (`MyCustom`, `MyCustom|text`), escaped. That namesake keeps +/// its own definition ([`rewritten_defs`]), so markup written from the model names the file's +/// style the text was read with instead. +pub(super) fn read_names( + defs: &BTreeMap>, + ids: &BTreeMap, + ours: &dyn Fn(&str) -> String, +) -> std::collections::HashMap { + let mut out = std::collections::HashMap::new(); + for (key, id) in ids { + let Some(rest) = key.strip_prefix("common:") else { continue }; + let (name, family) = rest.strip_suffix("|text").map_or((rest, ""), |n| (n, "|text")); + let mine = format!("{}{family}", ours(id)); + let namesake = format!("common:{mine}"); + if mine != rest && defs.contains_key(&namesake) && !ids.contains_key(&namesake) { + out.entry(mine).or_insert_with(|| super::writer::x(name)); + } + } + out +} + /// `def` (markup WordCraft wrote) with the values of its `style:name`, `style:parent-style-name` /// and `style:next-style-name` attributes that `to` gives another name for (by attribute and /// value) renamed to that, escaped. One pass: WordCraft writes these names unescaped (they are diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 6e1b73a3a8..8ce5726df0 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -1067,6 +1067,8 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { })); w.kept_defs = std::sync::Arc::new(kept.map(|k| k.defs.clone()).unwrap_or_default()); w.reserved = std::sync::Arc::new(kept.map(|k| k.files.keys().cloned().collect()).unwrap_or_default()); + let ours = |id: &str| super::writer::odf_name(id); + w.read_names = std::sync::Arc::new(kept.map(|k| super::kept::read_names(&k.defs, &k.style_ids, &ours)).unwrap_or_default()); w.groups_whole = whole_groups(&flow.blocks); // The file's master pages are written as read: what was kept may start them. w.kept_pages = kept.is_some_and(|k| k.pages_as_read(doc)); @@ -1189,6 +1191,7 @@ fn export_as(doc: &Document, mime: &str) -> Result, String> { let mut hw = Writer::with_prefix(if kept.is_some() { "wcM" } else { "M" }); // Headers' and footers' new pictures and objects skip the kept files' names too. hw.reserved = std::sync::Arc::clone(&w.reserved); + hw.read_names = std::sync::Arc::clone(&w.read_names); hw.accents = accents; hw.variables.clone_from(&w.variables); let parts: Vec = pages.iter().map(|(_, sec)| page_parts(doc, sec, &mut hw)).collect(); diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index a87e38655e..8fd56b5537 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -445,6 +445,45 @@ fn an_unused_style_named_as_wordcraft_names_an_edited_one_keeps_its_definition() as_read(&saved); } +/// A paragraph written from the model names the file's style it was read with (`My_20_Custom`), +/// not a style of the file's that WordCraft's name for it would land on (`MyCustom`, unused). +#[test] +fn an_edited_paragraph_keeps_its_styles_file_name_beside_an_unused_namesake() { + use std::sync::Arc; + let s = r##""##; + for (edit_style, size) in [(false, 9.0), (true, 21.0)] { + let mut d = opened(s, &["My_20_Custom"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + if edit_style { + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + } + d.insert_text(&Pos::body(0, 0), "New ", &Default::default()).unwrap(); + let bytes = export(&d).unwrap(); + let c = content_of(&bytes); + assert!(c.contains("New Text"), "{c}"); + assert!(!c.contains(r#"style-name="MyCustom""#), "{c}"); + let back = import(&bytes).unwrap(); + let got = back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size; + assert_eq!(got, size, "edited style {edit_style}: {c}\n{}", styles_of(&bytes)); + } +} + +/// The same for a character style: edited text's automatic style derives from the file's +/// character style it was read with (`My_20_Accent`), not an unused namesake (`MyAccent`). +#[test] +fn edited_text_keeps_its_character_styles_file_name_beside_an_unused_namesake() { + let s = r##""##; + let styles = format!(r#"{s}"#); + let content = format!( + r#"One two"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + d.insert_text(&Pos::body(0, 0), "New ", &Default::default()).unwrap(); + let c = content_of(&export(&d).unwrap()); + assert!(c.contains("New One"), "{c}"); + assert!(c.contains(r#"style:parent-style-name="My_20_Accent""#) && !c.contains(r#"="MyAccent""#), "{c}"); +} + /// An edited style the file names as WordCraft does (`Eigen`), whose parent WordCraft names /// otherwise (`Base_20_Style`, WordCraft's `BaseStyle`), still derives from the file's parent. #[test] diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index 2ad475739c..0f23a63ce4 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -237,6 +237,9 @@ pub(super) struct Writer { refs_open: std::collections::BTreeSet, /// The file's own package paths, kept as read: names WordCraft's own pictures don't take. pub(super) reserved: std::sync::Arc>, + /// The file's names for styles WordCraft would otherwise name as one of the file's other + /// styles (see `kept::read_names`), by WordCraft's name and family key suffix. + pub(super) read_names: std::sync::Arc>, pub(super) kept_used: super::kept::Needed, /// The file's own master pages are written (its page setup is as read): kept markup may /// start one. @@ -302,7 +305,8 @@ impl Writer { if let Some(id) = f.extra.as_ref().and_then(|x| x.style.as_deref()) { self.named_text.insert(id.to_string()); props.push('\u{1}'); - props.push_str(&odf_name(id)); + let name = odf_name(id); + props.push_str(self.read_names.get(&format!("{name}|text")).unwrap_or(&name)); } if props.is_empty() { return None; @@ -327,7 +331,8 @@ impl Writer { // A custom style: written as a common style of the same name (see `custom_styles`). (_, _, Some(id)) => { self.named.insert(id.to_string()); - odf_name(id) + let name = odf_name(id); + self.read_names.get(&name).cloned().unwrap_or(name) } (Kind::Normal, Some(n), None) => n.to_string(), _ => parent_style(p.kind).to_string(), From 9087ce027e734e6fde662d9761ca749f756ecccf Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 18:21:28 +0100 Subject: [PATCH 017/130] ODT: a new style derives from the file's style beside an unread namesake A style WordCraft writes that the file didn't have (one made after reading) is added as written, so one based on a read style whose WordCraft name is an unread style of the file's (`MyCustom` beside `My_20_Custom`) derived from that namesake. Its parent and next style now take the file's name, as text written from the model does. `kept::read_names` gives the names unescaped; the writer escapes them. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/kept.rs | 26 ++++++++++++++++++-------- crates/odf/src/text/package.rs | 3 ++- crates/odf/src/text/tests_more/kept.rs | 25 +++++++++++++++++++++++++ crates/odf/src/text/writer.rs | 4 ++-- 4 files changed, 47 insertions(+), 11 deletions(-) diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index 4f1e7654a5..6372ce55a3 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -270,7 +270,7 @@ pub(super) fn children(xml: &str, container: &str, group: &str) -> (Vec<(String, /// `xml` (a part WordCraft wrote) with `container`'s children as read: the file's (those of /// `group` in `defs`, in `order`; `pick` may choose WordCraft's instead, or neither), then -/// WordCraft's own the file had none of by that key. +/// WordCraft's own the file had none of by that key (as `fresh` gives them, by key and markup). fn with_as_read( xml: &str, container: &str, @@ -278,6 +278,7 @@ fn with_as_read( defs: &BTreeMap>, order: &[String], pick: &dyn Fn(&str, &str, Option<&str>) -> Option, + fresh: &dyn Fn(&str, &str) -> String, ) -> String { let (kids, content) = children(xml, container, group); let Some((from, to)) = content else { return xml.to_string() }; @@ -295,7 +296,7 @@ fn with_as_read( if !defs.contains_key(k) && let Some(x) = xml.get(*a..*b) { - body.push_str(x); + body.push_str(&fresh(k, x)); } } let (Some(head), Some(tail)) = (xml.get(..from), xml.get(to..)) else { return xml.to_string() }; @@ -322,14 +323,22 @@ pub(super) fn with_common_as_read( order: &[String], changed: &BTreeSet, rewritten: &BTreeMap>, + read: &std::collections::HashMap, ) -> String { - with_as_read(styles, "office:styles", "common", defs, order, &|k, d, ours| match ours { + let pick = |k: &str, d: &str, ours: Option<&str>| match ours { _ if rewritten.contains_key(k) => rewritten.get(k).cloned().flatten(), Some(o) if drawing_def(o) || changed.contains(k) => Some(o.to_string()), None if changed.contains(k) => None, // (The default graphic style is the file's: WordCraft's drawings say what they need.) _ => Some(d.to_string()), - }) + }; + // A style of WordCraft's own derives from (or is followed by) the file's style a style was + // read from, not an unread namesake of it ([`read_names`]). + let fresh = |k: &str, d: &str| { + let family = if k.ends_with("|text") { "|text" } else { "" }; + renamed(d, &|attr, v| (attr != "style:name").then(|| read.get(&format!("{v}{family}")).cloned()).flatten()) + }; + with_as_read(styles, "office:styles", "common", defs, order, &pick, &fresh) } /// What becomes of the file's styles (`defs`) that `changed` touches, by their keys: WordCraft's @@ -410,7 +419,7 @@ pub(super) fn rewritten_defs( /// The file's names for the styles the import read whose name as WordCraft writes them (`ours`) /// is a style of the file's the import didn't read (`MyCustom` beside `My_20_Custom`): by that -/// name with its family's key suffix (`MyCustom`, `MyCustom|text`), escaped. That namesake keeps +/// name with its family's key suffix (`MyCustom`, `MyCustom|text`), unescaped. That namesake keeps /// its own definition ([`rewritten_defs`]), so markup written from the model names the file's /// style the text was read with instead. pub(super) fn read_names( @@ -425,7 +434,7 @@ pub(super) fn read_names( let mine = format!("{}{family}", ours(id)); let namesake = format!("common:{mine}"); if mine != rest && defs.contains_key(&namesake) && !ids.contains_key(&namesake) { - out.entry(mine).or_insert_with(|| super::writer::x(name)); + out.entry(mine).or_insert_with(|| name.to_string()); } } out @@ -487,8 +496,9 @@ pub(super) fn changed(then: &BTreeMap, now: &BTreeMap) /// document whose page setup is as read. pub(super) fn with_pages_as_read(styles: &str, defs: &BTreeMap>, order: &[String]) -> String { let keep_file = |_: &str, d: &str, _: Option<&str>| Some(d.to_string()); - let s = with_as_read(styles, "office:automatic-styles", "sauto", defs, order, &keep_file); - with_as_read(&s, "office:master-styles", "master", defs, order, &keep_file) + let as_is = |_: &str, d: &str| d.to_string(); + let s = with_as_read(styles, "office:automatic-styles", "sauto", defs, order, &keep_file, &as_is); + with_as_read(&s, "office:master-styles", "master", defs, order, &keep_file, &as_is) } /// Attribute names whose values name a definition kept markup may refer to. diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 8ce5726df0..87ee24c553 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -848,7 +848,8 @@ fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, // The name WordCraft writes a style id under (`My_20_Custom` was read as `MyCustom`). let ours = |id: &str| super::writer::odf_name(id); let rewritten = super::kept::rewritten_defs(&now, &k.defs, &changed, &k.style_ids, &ours); - super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten) + let read = super::kept::read_names(&k.defs, &k.style_ids, &ours); + super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten, &read) } /// The package files the file's own definitions refer to, and those the markup written as read diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index 8fd56b5537..c3b778896a 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -468,6 +468,31 @@ fn an_edited_paragraph_keeps_its_styles_file_name_beside_an_unused_namesake() { } } +/// A style made after reading (`NewChild`), based on a file's style beside an unused namesake +/// (`My_20_Custom`, WordCraft's `MyCustom`, beside `MyCustom`), derives from the file's style it +/// was based on. +#[test] +fn a_new_style_based_on_one_beside_an_unused_namesake_derives_from_it() { + use std::sync::Arc; + let s = r##""##; + let mut d = opened(s, &["My_20_Custom"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + let mut child = d.styles.get(&id).unwrap().clone(); + (child.id, child.name, child.based_on, child.next) = ("NewChild".into(), "NewChild".into(), Some(id.clone()), None); + (child.para, child.chr) = Default::default(); + Arc::make_mut(&mut d.styles).upsert(child); + d.restyle(&id, Some("NewChild".to_string())); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + let new = saved.split("').next()); + assert!(new.is_some_and(|n| n.contains(r#"style:parent-style-name="My_20_Custom""#)), "{saved}"); + let theirs = def_named(&saved, "MyCustom").unwrap_or_else(|| panic!("{saved}")); + assert!(theirs.contains(r#"fo:font-size="30pt""#), "as read: {theirs}"); + let back = import(&bytes).unwrap(); + let got = back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size; + assert_eq!(got, 9.0, "{saved}\n{}", content_of(&bytes)); +} + /// The same for a character style: edited text's automatic style derives from the file's /// character style it was read with (`My_20_Accent`), not an unused namesake (`MyAccent`). #[test] diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index 0f23a63ce4..13a2dbbce3 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -306,7 +306,7 @@ impl Writer { self.named_text.insert(id.to_string()); props.push('\u{1}'); let name = odf_name(id); - props.push_str(self.read_names.get(&format!("{name}|text")).unwrap_or(&name)); + props.push_str(&self.read_names.get(&format!("{name}|text")).map_or(name, |n| x(n))); } if props.is_empty() { return None; @@ -332,7 +332,7 @@ impl Writer { (_, _, Some(id)) => { self.named.insert(id.to_string()); let name = odf_name(id); - self.read_names.get(&name).cloned().unwrap_or(name) + self.read_names.get(&name).map_or(name, |n| x(n)) } (Kind::Normal, Some(n), None) => n.to_string(), _ => parent_style(p.kind).to_string(), From 2510523bf9ca7ec4dc1d95e7fd267afefde58671 Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 19:33:54 +0100 Subject: [PATCH 018/130] flow: a further paragraph moved out of its item ends the lists before it A list item's further paragraph moved to the margin is body text, but the item text position of the list before it stayed, so a list starting with a less indented header after it lost the header. It now clears them, as body text does. Co-Authored-By: Claude Opus 5.5 --- crates/flow/src/from_doc.rs | 2 ++ crates/flow/src/lib.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index dcebfeea68..90a12e769c 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -939,6 +939,8 @@ fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemTex for q in &mut paras { q.item = None; } + // Moved out of its item, it is body text: the lists before it have ended. + *at = [None; 9]; } } else { // Body text: the lists before it have ended, and where their items' text was with them. diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index f1129acc79..2860613437 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -253,6 +253,35 @@ mod tests { assert_eq!(got.iter().find(|r| r.0 == "Header").map(|r| r.1), Some(Some(0)), "{got:?}"); } + /// A further paragraph moved out of its item (to the margin) is body text: a list starting with + /// a header after it, less indented than the list before, keeps the header in its list. + #[test] + fn a_list_header_after_an_outdented_further_paragraph_is_in_its_list() { + let mut doc = craft_wordmodel::Document::new(); + let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered); + let numbered = move |p: &mut craft_wordmodel::ParaProps| { + p.numbering = Some(NumRef { num, level: 0 }); + p.indent_left = Some(72.0); + }; + let outdented = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(0.0); + }; + let header = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(36.0); + }; + let numbered_36 = move |p: &mut craft_wordmodel::ParaProps| { + p.numbering = Some(NumRef { num, level: 0 }); + p.indent_left = Some(36.0); + }; + let body = doc_of(&[("One", &numbered), ("Out", &outdented), ("Header", &header), ("Two", &numbered_36)]).body; + doc.body = body; + let got = items(&from_doc(&doc).blocks); + assert_eq!(got.iter().find(|r| r.0 == "Out").map(|r| r.1), Some(None), "{got:?}"); + assert_eq!(got.iter().find(|r| r.0 == "Header").map(|r| r.1), Some(Some(0)), "{got:?}"); + } + /// A list item's further paragraph in a table cell a table style formats stays one. #[test] fn a_further_paragraph_in_a_styled_cell_stays_in_its_item() { From e994f6ce33de01a5687f5f94e90ba5aec6582a52 Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 19:36:36 +0100 Subject: [PATCH 019/130] flow: a heading in a list item stays in its item A text:h inside a text:list-item is read as one of the item's further paragraphs, but continues_list accepted only plain paragraphs, so the HTML, Markdown and ODT writers ended the list at the heading and the numbering restarted after it. continues_list now also accepts headings. HTML writes the heading tag inside the li, ODT writes a text:h inside the text:list-item, and Markdown writes the ATX heading indented under the item. Quotes, code and other kinds still end the list, as the writers cannot put them in an item. Co-Authored-By: Claude Opus 5.5 --- crates/flow/src/types.rs | 4 ++- crates/markdown/src/blocks.rs | 2 +- crates/markdown/src/export.rs | 5 ++- crates/odf/src/text/tests_more/lists.rs | 41 +++++++++++++++++++++++++ 4 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs index 8503f18d4a..4cbf992f8a 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -1098,9 +1098,11 @@ pub fn clean_text(s: &str) -> String { /// Whether the paragraph at `i` in `blocks` is a list item's further paragraph, and the level of /// its item: HTML and Markdown keep it in its item, so the list doesn't start again after it. +/// A plain paragraph or a heading (ODF's `text:h` may sit in a list item); the writers have no +/// way to put the other kinds in an item. pub fn continues_list(blocks: &[FBlock], i: usize) -> Option { match blocks.get(i) { - Some(FBlock::Para(p)) if p.list.is_none() && p.kind == Kind::Normal => p.item.map(|l| l.min(8)), + Some(FBlock::Para(p)) if p.list.is_none() && matches!(p.kind, Kind::Normal | Kind::Heading(_)) => p.item.map(|l| l.min(8)), _ => None, } } diff --git a/crates/markdown/src/blocks.rs b/crates/markdown/src/blocks.rs index 64e7eefc9e..9b4ade84ac 100644 --- a/crates/markdown/src/blocks.rs +++ b/crates/markdown/src/blocks.rs @@ -709,7 +709,7 @@ fn parse_list(lines: &[String], mut i: usize, depth: usize, level: u8, out: &mut { // A code block, quote or heading in the item joins the item's last // paragraph, a sublist's included, with a line break: it is no item of - // its own, and the writers keep only plain paragraphs in an item. + // its own, and only a plain paragraph is read as a further one. prev.push_text("\n", &Fmt::default()); prev.inlines.extend(p.inlines); continue; diff --git a/crates/markdown/src/export.rs b/crates/markdown/src/export.rs index e1bdde3b86..ffb4423fdc 100644 --- a/crates/markdown/src/export.rs +++ b/crates/markdown/src/export.rs @@ -438,7 +438,10 @@ pub(super) fn write_blocks(blocks: &[FBlock], out: &mut Vec) { *d = 0; } let pad = " ".repeat(conts.get(lv).copied().unwrap_or(0)); - let text = escape_lines(body).replace("\\\n", &format!("\\\n{pad}")); + let text = match p.kind { + Kind::Heading(n) => format!("{} {}", "#".repeat(n.clamp(1, 6) as usize), heading_text(&body)), + _ => escape_lines(body).replace("\\\n", &format!("\\\n{pad}")), + }; out.push(format!("{pad}{text}").trim_end().to_string()); out.push(String::new()); } diff --git a/crates/odf/src/text/tests_more/lists.rs b/crates/odf/src/text/tests_more/lists.rs index 1819b00c37..937fc05590 100644 --- a/crates/odf/src/text/tests_more/lists.rs +++ b/crates/odf/src/text/tests_more/lists.rs @@ -366,3 +366,44 @@ fn a_further_paragraph_opening_or_closing_a_section_ends_the_list_there() { let (open, header) = (c.find("Header<")); assert!(open.is_some() && header.is_some() && open < header, "the section opens before Header: {c}"); } + +/// A heading (`text:h`) in a list item is one of its further paragraphs: it stays in its item in +/// HTML, Markdown and ODT written from the model, and the list numbers on after it. +#[test] +fn a_heading_in_a_list_item_stays_in_it() { + let styles = format!( + r#""# + ); + let content = format!( + r#"OneHeadAfterTwo"# + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + let html = craft_html::doc::export(&d); + assert_eq!(html.matches("One

    Head

    After

    "), "{html}"); + let md = craft_markdown::export(&d); + assert!(md.contains("1. One\n\n ## Head\n\n After\n\n2. Two"), "{md}"); + // Edited, so the list is written from the model. + let i = d.body.iter().position(|b| b.as_para().is_some_and(|p| p.text == "One")).unwrap(); + d.insert_text(&craft_wordmodel::Pos::body(i, 0), "Edited ", &Default::default()).unwrap(); + let out = export(&d).unwrap(); + let c = crate::text::tests::content_of(&out); + assert!(c.contains("Edited OneHead"), "{c}"); + assert!(c.contains("After"), "{c}"); + let back = import(&out).unwrap(); + let rows: Vec<_> = + back.body.iter().filter_map(|b| b.as_para()).map(|p| (p.text.clone(), p.props.numbering.is_some(), p.props.list_item)).collect(); + assert_eq!( + rows, + [ + ("Edited One".to_string(), true, None), + ("Head".to_string(), false, Some(0)), + ("After".to_string(), false, Some(0)), + ("Two".to_string(), true, None) + ], + "{c}" + ); + let head = back.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == "Head").unwrap(); + assert_eq!(head.props.style.as_deref(), Some("Heading2"), "{c}"); +} From 2ceddfd4aeaeb1b142a433a0b36aefb49b5ab1ba Mon Sep 17 00:00:00 2001 From: alehel Date: Mon, 16 Nov 2026 21:46:56 +0100 Subject: [PATCH 020/130] ODT: a new style derives from the file's style under the file's name A style WordCraft writes that the file didn't have, based on a style the import read under another name (`Base_20_Style`, WordCraft's `BaseStyle`), named WordCraft's name as its parent. That resolved to WordCraft's own copy of the style, without what WordCraft doesn't model of the file's. Its parent and next style now take the file's name for every style read under another name (`kept::file_names`), not only where an unread namesake collides. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/kept.rs | 19 ++++++++++++++++++- crates/odf/src/text/package.rs | 2 +- crates/odf/src/text/tests_more/kept.rs | 24 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/crates/odf/src/text/kept.rs b/crates/odf/src/text/kept.rs index 6372ce55a3..f3c68c47ec 100644 --- a/crates/odf/src/text/kept.rs +++ b/crates/odf/src/text/kept.rs @@ -333,7 +333,8 @@ pub(super) fn with_common_as_read( _ => Some(d.to_string()), }; // A style of WordCraft's own derives from (or is followed by) the file's style a style was - // read from, not an unread namesake of it ([`read_names`]). + // read from, under the file's name ([`file_names`]): not WordCraft's copy of it, nor an + // unread namesake. let fresh = |k: &str, d: &str| { let family = if k.ends_with("|text") { "|text" } else { "" }; renamed(d, &|attr, v| (attr != "style:name").then(|| read.get(&format!("{v}{family}")).cloned()).flatten()) @@ -417,6 +418,22 @@ pub(super) fn rewritten_defs( out } +/// The file's names for the styles the import read under another name than WordCraft writes them +/// under (`ours`): by that name with its family's key suffix (`BaseStyle`, `BaseStyle|text`), +/// unescaped, the first the import read into it where several were. +pub(super) fn file_names(ids: &BTreeMap, ours: &dyn Fn(&str) -> String) -> std::collections::HashMap { + let mut out = std::collections::HashMap::new(); + for (key, id) in ids { + let Some(rest) = key.strip_prefix("common:") else { continue }; + let (name, family) = rest.strip_suffix("|text").map_or((rest, ""), |n| (n, "|text")); + let mine = format!("{}{family}", ours(id)); + if mine != rest { + out.entry(mine).or_insert_with(|| name.to_string()); + } + } + out +} + /// The file's names for the styles the import read whose name as WordCraft writes them (`ours`) /// is a style of the file's the import didn't read (`MyCustom` beside `My_20_Custom`): by that /// name with its family's key suffix (`MyCustom`, `MyCustom|text`), unescaped. That namesake keeps diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 87ee24c553..cc4023fa4c 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -848,7 +848,7 @@ fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, // The name WordCraft writes a style id under (`My_20_Custom` was read as `MyCustom`). let ours = |id: &str| super::writer::odf_name(id); let rewritten = super::kept::rewritten_defs(&now, &k.defs, &changed, &k.style_ids, &ours); - let read = super::kept::read_names(&k.defs, &k.style_ids, &ours); + let read = super::kept::file_names(&k.style_ids, &ours); super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten, &read) } diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index c3b778896a..fd75609542 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -493,6 +493,30 @@ fn a_new_style_based_on_one_beside_an_unused_namesake_derives_from_it() { assert_eq!(got, 9.0, "{saved}\n{}", content_of(&bytes)); } +/// A style made after reading (`NewChild`), based on a file's style WordCraft names otherwise +/// (`Base_20_Style`, WordCraft's `BaseStyle`), derives from the file's style, with what WordCraft +/// doesn't model of it. +#[test] +fn a_new_style_based_on_a_renamed_one_derives_from_the_files() { + use std::sync::Arc; + let s = r#""#; + let mut d = opened(s, &["Base_20_Style"]); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + let mut child = d.styles.get(&id).unwrap().clone(); + (child.id, child.name, child.based_on, child.next) = ("NewChild".into(), "NewChild".into(), Some(id.clone()), None); + (child.para, child.chr) = Default::default(); + Arc::make_mut(&mut d.styles).upsert(child); + d.restyle(&id, Some("NewChild".to_string())); + let bytes = export(&d).unwrap(); + let saved = styles_of(&bytes); + let new = saved.split("').next()); + assert!(new.is_some_and(|n| n.contains(r#"style:parent-style-name="Base_20_Style""#)), "{saved}"); + assert!(def_named(&saved, "Base_20_Style").is_some_and(|d| d.contains(r#"style:writing-mode="tb-rl""#)), "as read: {saved}"); + let back = import(&bytes).unwrap(); + let got = back.styles.resolve_char(back.body[0].as_para().unwrap().props.style.as_deref(), &Default::default()).size; + assert_eq!(got, 30.0, "{saved}"); +} + /// The same for a character style: edited text's automatic style derives from the file's /// character style it was read with (`My_20_Accent`), not an unused namesake (`MyAccent`). #[test] From 937d0a9d681916c35ab0ae971803541d72651d3e Mon Sep 17 00:00:00 2001 From: alehel Date: Tue, 17 Nov 2026 02:38:22 +0100 Subject: [PATCH 021/130] ODT: package files of a style definition follow it per definition main's page background change (#1809) asked `KeptXml::styles_as_read`, which this branch replaces with per-definition fingerprints, to tell whether the file's style definitions are written as read. `with_kept_files` now asks per definition instead: one the document changed or that is written from the model doesn't keep its package files, as a drawing definition WordCraft writes its own of doesn't. `common_changes` gives both it and `styles_as_read` the same answer. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/package.rs | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index 63abcb20a1..e9c7fd720d 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -843,13 +843,25 @@ fn styles_as_read(doc: &Document, kept: Option<&craft_wordmodel::kept::KeptXml>, used.2.entry(name.to_string()).or_insert_with(|| d.clone()); } } + let (changed, rewritten) = common_changes(doc, k); + let ours = |id: &str| super::writer::odf_name(id); + let read = super::kept::file_names(&k.style_ids, &ours); + super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten, &read) +} + +/// The keys of the file's style definitions `doc` has changed since they were read, and what +/// becomes of those written from the model under the file's names ([`super::kept::rewritten_defs`]). +/// The others are written as read. +fn common_changes( + doc: &Document, + k: &craft_wordmodel::kept::KeptXml, +) -> (std::collections::BTreeSet, std::collections::BTreeMap>) { let now = model_styles(doc); let changed = super::kept::changed(&k.style_prints, &super::kept::prints(&now)); // The name WordCraft writes a style id under (`My_20_Custom` was read as `MyCustom`). let ours = |id: &str| super::writer::odf_name(id); let rewritten = super::kept::rewritten_defs(&now, &k.defs, &changed, &k.style_ids, &ours); - let read = super::kept::file_names(&k.style_ids, &ours); - super::kept::with_common_as_read(&styles, &k.defs, &k.order, &changed, &rewritten, &read) + (changed, rewritten) } /// The package files the file's own definitions refer to, and those the markup written as read @@ -867,20 +879,16 @@ fn with_kept_files( let Some(k) = kept else { return }; let mut wanted = w.kept_files_used.clone(); let pages_kept = k.pages_as_read(doc); - let styles_kept = k.styles_as_read(doc); + let (changed, rewritten) = common_changes(doc, k); for (key, d) in &k.defs { if !pages_kept && (key.starts_with("sauto:") || key.starts_with("master:")) { continue; } if key.starts_with("common:") { - // The file's definition is written back whole (`styles_as_read`, non-`draw:` - // definitions win), or this one is restored for markup naming it. WordCraft's own - // definition takes a drawing definition's place: its href is no longer used. - let written = if styles_kept { - !(super::kept::drawing_def(d) && super::kept::defined(styles, d)) - } else { - key.strip_prefix("common:").is_some_and(|n| w.kept_used.1.contains_key(n)) && !super::kept::defined(styles, d) - }; + // The file's definition is written back as read unless the document changed it + // (`styles_as_read`): then WordCraft's takes its place, or none does. WordCraft's own + // definition takes a drawing definition's place too. Its href is then no longer used. + let written = !changed.contains(key) && !rewritten.contains_key(key) && !(super::kept::drawing_def(d) && super::kept::defined(styles, d)); if !written { continue; } From 41c7c80e8ae8f0d5a4f05ea4055841a185486069 Mon Sep 17 00:00:00 2001 From: alehel Date: Tue, 17 Nov 2026 03:14:30 +0100 Subject: [PATCH 022/130] ODT: a rewritten style definition keeps the package files it names A file style that `rewritten_defs` writes back as read (an unread namesake, `MyCustom` beside an edited `My_20_Custom`) was left out of the package files to keep, so a picture only it named was dropped while its href stayed in styles.xml. The files kept now follow the markup the rewrite writes for each key. Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/package.rs | 16 ++++++++++++---- crates/odf/src/text/tests_more/kept.rs | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/odf/src/text/package.rs b/crates/odf/src/text/package.rs index e9c7fd720d..17b6d6cdfc 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -885,10 +885,18 @@ fn with_kept_files( continue; } if key.starts_with("common:") { - // The file's definition is written back as read unless the document changed it - // (`styles_as_read`): then WordCraft's takes its place, or none does. WordCraft's own - // definition takes a drawing definition's place too. Its href is then no longer used. - let written = !changed.contains(key) && !rewritten.contains_key(key) && !(super::kept::drawing_def(d) && super::kept::defined(styles, d)); + // What `styles_as_read` writes in its place, when it rewrites it: what that names (an + // unread namesake's own definition, as read) is what is written. + if let Some(def) = rewritten.get(key) { + if let Some(def) = def { + super::kept::hrefs(def, &mut wanted); + } + continue; + } + // The file's definition is written back as read unless the document changed it: then + // WordCraft's takes its place, or none does. WordCraft's own definition takes a + // drawing definition's place too. Its href is then no longer used. + let written = !changed.contains(key) && !(super::kept::drawing_def(d) && super::kept::defined(styles, d)); if !written { continue; } diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index fd75609542..dc423669f2 100644 --- a/crates/odf/src/text/tests_more/kept.rs +++ b/crates/odf/src/text/tests_more/kept.rs @@ -165,6 +165,31 @@ fn a_file_a_kept_definition_names_is_written_with_it() { assert!(m.contains(r#"manifest:full-path="Pictures/paper.png""#), "{m}"); } +/// An unused namesake's definition written back as read (`MyCustom` beside an edited +/// `My_20_Custom`) keeps the picture it names in the package. +#[test] +fn an_unused_namesakes_picture_stays_when_the_used_style_is_edited() { + use std::sync::Arc; + let png = [b"\x89PNG\r\n\x1a\n".as_slice(), &[5u8; 64]].concat(); + let styles = format!( + r##""## + ); + let content = format!( + r#"Text"# + ); + let pkg = crate::text::tests::zip_of(&[("content.xml", content.as_bytes()), ("styles.xml", styles.as_bytes()), ("Pictures/only.png", &png)]); + let mut d = import(&pkg).unwrap(); + let id = d.body[0].as_para().unwrap().props.style.clone().unwrap(); + Arc::make_mut(&mut d.styles).get_mut(&id).unwrap().chr.size = Some(21.0); + let saved = export(&d).unwrap(); + let s = styles_of(&saved); + assert!(def_named(&s, "MyCustom").is_some_and(|d| d.contains(r#"xlink:href="Pictures/only.png""#)), "{s}"); + let mut z = crate::Package::open(&saved, &crate::Limits::DEFAULT).unwrap(); + assert_eq!(z.read("Pictures/only.png").unwrap(), Some(png)); + let m = crate::text::tests::entry(&saved, "META-INF/manifest.xml"); + assert!(m.contains(r#"manifest:full-path="Pictures/only.png""#), "{m}"); +} + /// A file defining what WordCraft doesn't model: a gradient, a paragraph style no text of its /// own uses, a default style's writing mode, and a frame style naming them. fn file_with_definitions() -> Vec { From 56a7120493e0c5d4e62751177ca353c98c290a48 Mon Sep 17 00:00:00 2001 From: istefp Date: Mon, 16 Nov 2026 23:32:30 -0500 Subject: [PATCH 023/130] =?UTF-8?q?scraft-format:=20Route::Instrument=20?= =?UTF-8?q?=E2=80=94=20an=20instrument's=20auxiliary=20output=20bus?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Multi-out instruments (drum samplers with per-channel outs) render every output bus, but a track's input route could only name None, Main, a bus or hardware — every bus past the main pair was unreachable. Route::Instrument { track, bus } names the instrument on a track's output bus so it can be picked as another track's input. Input-side only: not a valid output or send target. Serde round-trip test included; routes saved before the variant still load. Refs storytold/soundcraft#1549 --- crates/scraft-format/src/mixer.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/scraft-format/src/mixer.rs b/crates/scraft-format/src/mixer.rs index efdaf2d17d..7e5d348fd5 100644 --- a/crates/scraft-format/src/mixer.rs +++ b/crates/scraft-format/src/mixer.rs @@ -1,6 +1,6 @@ //! Per-track mixer state: inserts, sends, routing, fader, pan, mute/solo. -use crate::{AutomationMode, BusId, SourceId}; +use crate::{AutomationMode, BusId, SourceId, TrackId}; use std::collections::BTreeMap; pub const INSERT_SLOTS: usize = 10; @@ -418,6 +418,15 @@ pub enum Route { Bus(BusId), /// Hardware input/output by path name. Hardware(String), + /// An instrument's auxiliary output bus, picked as another track's input so a + /// multi-out instrument's extra outs can land on their own tracks: `track` holds + /// the instrument and `bus` is its output bus (0 is the main output the hosting + /// track's own channel already carries). Input-side only: it is not a valid + /// output or send target. + Instrument { + track: TrackId, + bus: u8, + }, } /// A plugin instance on an insert slot. @@ -664,6 +673,15 @@ mod tests { assert_eq!(fader_db_to_pos(f32::NAN), 0.0); } + #[test] + fn plugin_output_route_round_trips() { + let r = Route::Instrument { track: TrackId(42), bus: 7 }; + let json = serde_json::to_string(&r).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), r); + // Routes saved before multi-out routing still load. + assert_eq!(serde_json::from_str::(r#"{"Hardware":"in 1-2"}"#).unwrap(), Route::Hardware("in 1-2".to_string())); + } + #[test] fn mixer_defaults_and_sanitize() { let mut m = Mixer::new(ChannelFormat::Stereo); From 62cd33c0f3d479fb420b53b34fa82a778f13b3d3 Mon Sep 17 00:00:00 2001 From: el-j Date: Tue, 17 Nov 2026 10:08:54 +0100 Subject: [PATCH 024/130] craft-video: raw video frames convert to VideoFrame (#1231) --- crates/video/src/frame/convert.rs | 6 +++++- crates/video/src/lib.rs | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/video/src/frame/convert.rs b/crates/video/src/frame/convert.rs index b8e3cba71c..028a52fe9d 100644 --- a/crates/video/src/frame/convert.rs +++ b/crates/video/src/frame/convert.rs @@ -249,7 +249,11 @@ impl TryFrom for VideoFrame { Kind::Rgb => (ColorFamily::Rgb, Subsampling::S444), }; let (cw, ch) = sub.chroma_size(w, h); - let planes = vec![Plane::packed(w, h, bits, Samples::U16(a))?, Plane::packed(cw, ch, bits, Samples::U16(b))?, Plane::packed(cw, ch, bits, Samples::U16(c))?]; + let planes = vec![ + Plane::packed(w, h, bits, Samples::U16(a))?, + Plane::packed(cw, ch, bits, Samples::U16(b))?, + Plane::packed(cw, ch, bits, Samples::U16(c))?, + ]; let mut f = VideoFrame::new(w, h, family, sub, planes, None)?; if family == ColorFamily::Rgb { f.color = ColorTags { matrix: 0, full_range: true, ..ColorTags::UNSPECIFIED }; diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index 5929688488..e67abab4e7 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -52,10 +52,10 @@ pub mod mpeg4; #[cfg(feature = "ffv1")] pub mod ffv1; -#[cfg(feature = "rawvideo")] -pub mod rawvideo; #[cfg(feature = "hap")] pub mod hap; +#[cfg(feature = "rawvideo")] +pub mod rawvideo; #[cfg(feature = "mjpeg")] pub mod mjpeg; From 96dca17762705ed95333fecb2ac7b24a3fcc5087 Mon Sep 17 00:00:00 2001 From: el-j Date: Tue, 17 Nov 2026 10:09:31 +0100 Subject: [PATCH 025/130] craft-video: Hap pictures convert to VideoFrame (#1231) --- crates/video/README.md | 3 ++- crates/video/src/frame/convert.rs | 26 ++++++++++++++++++++++ crates/video/src/frame/tests.rs | 37 +++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/crates/video/README.md b/crates/video/README.md index f9db3a6e64..c5d42aacb2 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -41,7 +41,8 @@ comes with its codec's feature): - Planes are `[Y, Cb, Cr]`, `[R, G, B]` or `[Y]` (`ColorFamily`), plus an optional alpha plane. DNx, VP9 and AV1 (identity matrix) store RGB as G, B, R; the conversion reorders them. - Samples keep the decoder's storage, `u8` or `u16`, with a bit depth per plane (HEVC chroma may - differ from luma). Converting moves the buffers and copies no samples. + differ from luma). Converting moves the buffers and copies no samples, except Hap, + whose decoder returns interleaved RGBA: it is split into planes. - Chroma subsampling is a log2 shift per axis, 0 to 3 (FFV1 codes up to 3). - Colour is given as ITU-T H.273 code points (`ColorTags`), mapped from each codec's own signalling. Codecs that do not signal a value leave it unspecified (2). diff --git a/crates/video/src/frame/convert.rs b/crates/video/src/frame/convert.rs index 4089f71482..44c5123aa6 100644 --- a/crates/video/src/frame/convert.rs +++ b/crates/video/src/frame/convert.rs @@ -70,6 +70,32 @@ impl TryFrom for VideoFrame { } } +#[cfg(feature = "hap")] +impl TryFrom for VideoFrame { + type Error = FrameError; + + /// An 8-bit RGB frame with an alpha plane, full range, identity matrix (Hap Q's YCoCg is + /// already converted to RGB by the decoder). The picture does not say whether the variant has + /// alpha: Hap and Hap Q give an opaque (255) alpha plane. The decoder returns interleaved RGBA, + /// so this conversion copies the samples into planes. + fn try_from(p: crate::hap::Image) -> Result { + let (w, h) = (p.width, p.height); + let pixels = usize::try_from(w) + .ok() + .zip(usize::try_from(h).ok()) + .and_then(|(w, h)| w.checked_mul(h)) + .ok_or(FrameError::Plane("plane size overflows"))?; + if pixels.checked_mul(4) != Some(p.rgba.len()) { + return Err(FrameError::Shape("sample count does not fit the frame")); + } + let plane = |c: usize| Plane::packed(w, h, 8, Samples::U8(p.rgba.iter().skip(c).step_by(4).copied().collect())); + let planes = vec![plane(0)?, plane(1)?, plane(2)?]; + let mut f = VideoFrame::new(w, h, ColorFamily::Rgb, Subsampling::S444, planes, Some(plane(3)?))?; + f.color = ColorTags { matrix: 0, full_range: true, ..ColorTags::UNSPECIFIED }; + Ok(f) + } +} + #[cfg(feature = "hevc-decode")] impl TryFrom for VideoFrame { type Error = FrameError; diff --git a/crates/video/src/frame/tests.rs b/crates/video/src/frame/tests.rs index cba664af46..efc2bcf7dc 100644 --- a/crates/video/src/frame/tests.rs +++ b/crates/video/src/frame/tests.rs @@ -108,6 +108,43 @@ fn h264_picture_with_a_short_buffer_is_an_error() { assert_eq!(VideoFrame::try_from(h264_picture(7)), Err(FrameError::Plane("buffer is shorter than the plane"))); } +#[cfg(feature = "hap")] +#[test] +fn hap_pictures_split_into_rgb_and_alpha() { + use crate::hap::Image; + let img = Image { width: 2, height: 2, rgba: (1..=16).collect() }; + let f = VideoFrame::try_from(img).unwrap(); + assert_eq!((f.family(), f.subsampling(), f.bit_depth()), (ColorFamily::Rgb, Subsampling::S444, 8)); + assert_eq!(f.color, ColorTags { matrix: 0, full_range: true, ..ColorTags::UNSPECIFIED }); + assert_eq!(f.plane(0).unwrap().samples(), &Samples::U8(vec![1, 5, 9, 13])); + assert_eq!(f.plane(2).unwrap().samples(), &Samples::U8(vec![3, 7, 11, 15])); + assert_eq!(f.alpha().unwrap().samples(), &Samples::U8(vec![4, 8, 12, 16])); + assert!(f.pts.is_none()); +} + +#[cfg(feature = "hap")] +#[test] +fn a_hap_picture_with_the_wrong_size_is_an_error() { + use crate::hap::Image; + assert!(VideoFrame::try_from(Image { width: 2, height: 2, rgba: vec![0; 15] }).is_err()); + assert!(VideoFrame::try_from(Image { width: 2, height: 2, rgba: vec![0; 17] }).is_err()); + assert!(VideoFrame::try_from(Image { width: u32::MAX, height: u32::MAX, rgba: Vec::new() }).is_err()); +} + +#[cfg(feature = "hap")] +#[test] +fn a_decoded_hap_frame_converts() { + use crate::hap::{Decoder, Encoder, Variant}; + let (w, h) = (20u32, 12u32); + let src: Vec = (0..w * h * 4).map(|i| (i * 5 % 253) as u8).collect(); + let frame = Encoder::new(w, h, Variant::HapAlpha).unwrap().encode_rgba(&src).unwrap(); + let img = Decoder::new(w, h).unwrap().decode_rgba(&frame).unwrap(); + let want_alpha: Vec = img.rgba.iter().skip(3).step_by(4).copied().collect(); + let f = VideoFrame::try_from(img).unwrap(); + assert_eq!((f.width(), f.height()), (20, 12)); + assert_eq!(f.alpha().unwrap().samples(), &Samples::U8(want_alpha)); +} + #[cfg(feature = "hevc-decode")] #[test] fn hevc_picture_converts() { From bf7bff6c67028b954314b63b22bbb55644927c3e Mon Sep 17 00:00:00 2001 From: alehel Date: Tue, 17 Nov 2026 15:25:49 +0100 Subject: [PATCH 026/130] audio: the README says a refused PacketEncoder block leaves the encoder usable `encode` checks a block's channel count and lengths before encoding, so a refused block changes nothing and the caller may correct it and retry. Only a failure while encoding, or a call after `finish`, makes every later call an error, as the method's own documentation already says. Co-Authored-By: Claude Opus 5.5 --- crates/audio/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/audio/README.md b/crates/audio/README.md index 467e1ead3c..07f00c3b2f 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -367,7 +367,9 @@ rate, so read it after `finish`. `bitrate()` is the constant rate used (`None` f quality); `bit_depth()` is ALAC's. `encode` refuses a block without one slice per channel, or with a slice shorter than `frames`, -and encodes nothing. After `finish`, or after an encode that failed, every call returns an error. +and encodes nothing; the encoder stays usable, so the caller can correct the block and call again. +After `finish`, or after encoding itself failed (the block's packets are lost), every call returns +an error. E-AC-3 7.1 is encoded as 7.1, and this crate's `TrackDecoder` plays its 5.1 substream (see [Limits](#limits)). From cec9ee2dfe897566970cf179e1527694e6c2623f Mon Sep 17 00:00:00 2001 From: el-j Date: Tue, 17 Nov 2026 15:31:42 +0100 Subject: [PATCH 027/130] video: clean-room Theora video decoder and encoder (#1515) --- crates/video/Cargo.toml | 13 +- crates/video/src/frame/convert.rs | 52 ++ crates/video/src/lib.rs | 4 + crates/video/src/theora/decoder.rs | 724 +++++++++++++++++++++++++ crates/video/src/theora/encoder.rs | 505 +++++++++++++++++ crates/video/src/theora/header.rs | 502 +++++++++++++++++ crates/video/src/theora/huffman.rs | 308 +++++++++++ crates/video/src/theora/idct.rs | 196 +++++++ crates/video/src/theora/loopfilter.rs | 49 ++ crates/video/src/theora/mod.rs | 179 ++++++ crates/video/src/theora/quant.rs | 96 ++++ crates/video/src/theora/reconstruct.rs | 506 +++++++++++++++++ crates/video/src/theora/tables.rs | 208 +++++++ crates/video/tests/theora.rs | 266 +++++++++ 14 files changed, 3606 insertions(+), 2 deletions(-) create mode 100644 crates/video/src/theora/decoder.rs create mode 100644 crates/video/src/theora/encoder.rs create mode 100644 crates/video/src/theora/header.rs create mode 100644 crates/video/src/theora/huffman.rs create mode 100644 crates/video/src/theora/idct.rs create mode 100644 crates/video/src/theora/loopfilter.rs create mode 100644 crates/video/src/theora/mod.rs create mode 100644 crates/video/src/theora/quant.rs create mode 100644 crates/video/src/theora/reconstruct.rs create mode 100644 crates/video/src/theora/tables.rs create mode 100644 crates/video/tests/theora.rs diff --git a/crates/video/Cargo.toml b/crates/video/Cargo.toml index 004dcc6fe2..704d438afa 100644 --- a/crates/video/Cargo.toml +++ b/crates/video/Cargo.toml @@ -60,6 +60,10 @@ vp9-encode = ["craft-media/isobmff"] av1 = ["av1-decode", "av1-encode"] av1-decode = [] av1-encode = ["craft-media/isobmff"] +# Theora video (Xiph.Org specification): decoder and encoder; `theora-decode` or `theora-encode` for one of them. +theora = ["theora-decode", "theora-encode"] +theora-decode = ["craft-media/bitstream"] +theora-encode = ["craft-media/bitstream"] # Tiled AV1 fallback for frames that exceed the clean-room encoder's single-tile limits. av1-large-encode = ["av1-encode", "dep:rav1e"] # Decode and encode across worker threads (rayon) in the codecs that support it. @@ -77,8 +81,8 @@ rav1e = { version = "0.8", default-features = false, optional = true } [dev-dependencies] craft-media-testkit = { workspace = true } -# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test. -craft-media = { workspace = true, features = ["avi"] } +# The AVI muxer and Ogg page writer for tests. +craft-media = { workspace = true, features = ["avi", "ogg"] } [[test]] name = "hap" @@ -176,3 +180,8 @@ required-features = ["hevc-encode"] [[test]] name = "av1" required-features = ["av1"] + +[[test]] +name = "theora" +required-features = ["theora"] + diff --git a/crates/video/src/frame/convert.rs b/crates/video/src/frame/convert.rs index 4089f71482..b0f6fd08ed 100644 --- a/crates/video/src/frame/convert.rs +++ b/crates/video/src/frame/convert.rs @@ -369,3 +369,55 @@ impl TryFrom for VideoFrame { Ok(f) } } + +#[cfg(feature = "theora-decode")] +impl TryFrom for VideoFrame { + type Error = FrameError; + + fn try_from(p: crate::theora::Picture) -> Result { + let (sub, cw, ch, cx, cy) = match p.pixel_format { + crate::theora::PixelFormat::Yuv420 => (Subsampling::S420, p.pic_width.div_ceil(2), p.pic_height.div_ceil(2), p.pic_x / 2, p.pic_y / 2), + crate::theora::PixelFormat::Yuv422 => (Subsampling::S422, p.pic_width.div_ceil(2), p.pic_height, p.pic_x / 2, p.pic_y), + crate::theora::PixelFormat::Yuv444 => (Subsampling::S444, p.pic_width, p.pic_height, p.pic_x, p.pic_y), + }; + + let mut y_cropped = Vec::with_capacity((p.pic_width * p.pic_height) as usize); + for row in 0..p.pic_height { + let py = p.pic_y + (p.pic_height - 1 - row); + let start = py as usize * p.y_stride + p.pic_x as usize; + y_cropped.extend_from_slice(&p.y[start..start + p.pic_width as usize]); + } + + let mut u_cropped = Vec::with_capacity((cw * ch) as usize); + let mut v_cropped = Vec::with_capacity((cw * ch) as usize); + for row in 0..ch { + let py = cy + (ch - 1 - row); + let start = py as usize * p.uv_stride + cx as usize; + u_cropped.extend_from_slice(&p.u[start..start + cw as usize]); + v_cropped.extend_from_slice(&p.v[start..start + cw as usize]); + } + + let planes = vec![ + Plane::packed(p.pic_width, p.pic_height, 8, Samples::U8(y_cropped))?, + Plane::packed(cw, ch, 8, Samples::U8(u_cropped))?, + Plane::packed(cw, ch, 8, Samples::U8(v_cropped))?, + ]; + + let mut f = VideoFrame::new(p.pic_width, p.pic_height, ColorFamily::YCbCr, sub, planes, None)?; + match p.color_space { + crate::theora::ColorSpace::Rec470M => { + f.color.matrix = 6; + f.color.primaries = 6; + f.color.transfer = 6; + } + crate::theora::ColorSpace::Rec470Bg => { + f.color.matrix = 5; + f.color.primaries = 5; + f.color.transfer = 5; + } + _ => {} + } + f.pts = p.pts; + Ok(f) + } +} diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index 1f262f2dd8..629d36de07 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -78,3 +78,7 @@ pub mod raw_video; /// Bounded Screen Video key-frame decoding (FLV codec 3). #[cfg(feature = "screen-video")] pub mod screen_video; + +/// Theora video (Xiph.Org specification): decoder and encoder. +#[cfg(any(feature = "theora-decode", feature = "theora-encode"))] +pub mod theora; diff --git a/crates/video/src/theora/decoder.rs b/crates/video/src/theora/decoder.rs new file mode 100644 index 0000000000..fdc1221ec0 --- /dev/null +++ b/crates/video/src/theora/decoder.rs @@ -0,0 +1,724 @@ +//! Theora video decoder (Section 7). + +use super::header::{CommentHeader, IdentificationHeader, SetupHeader}; +use super::huffman::{decode_long_run, decode_short_run}; +use super::reconstruct::{FrameGeometry, apply_loop_filter, compute_block_predictor, mb_mode_to_ref_frame, reconstruct_block, undo_dc_prediction}; +use super::tables::MB_SCHEMES; +use super::{Error, Info, Picture, PixelFormat, Result}; +use craft_media::bitstream::BitReader; + +/// A conformant Theora video decoder. +pub struct Decoder { + pub info: Info, + pub comment: CommentHeader, + pub setup: SetupHeader, + pub geom: FrameGeometry, + pub qmat_tables: [[[[u16; 64]; 64]; 3]; 2], + + // Reference frames + ref_golden_y: Vec, + ref_golden_cb: Vec, + ref_golden_cr: Vec, + + ref_prev_y: Vec, + ref_prev_cb: Vec, + ref_prev_cr: Vec, + + has_keyframe: bool, + frame_index: u64, +} + +impl Decoder { + /// Initialize decoder from the three mandatory header packets: Identification, Comment, Setup. + pub fn from_headers(id_packet: &[u8], comment_packet: &[u8], setup_packet: &[u8]) -> Result { + let id = IdentificationHeader::parse(id_packet)?; + let comment = CommentHeader::parse(comment_packet)?; + let setup = SetupHeader::parse(setup_packet)?; + + let fmbw = (id.info.frame_width / 16) as usize; + let fmbh = (id.info.frame_height / 16) as usize; + let geom = FrameGeometry::new(fmbw, fmbh, id.info.pixel_format); + let qmat_tables = setup.quant_params.precompute_all_qmat()?; + + let (y_pw, y_ph, _, _, _, _, _, _) = geom.planes[0]; + let (c_pw, c_ph, _, _, _, _, _, _) = geom.planes[1]; + + let ref_golden_y = vec![0u8; y_pw * y_ph]; + let ref_golden_cb = vec![0u8; c_pw * c_ph]; + let ref_golden_cr = vec![0u8; c_pw * c_ph]; + + let ref_prev_y = vec![0u8; y_pw * y_ph]; + let ref_prev_cb = vec![0u8; c_pw * c_ph]; + let ref_prev_cr = vec![0u8; c_pw * c_ph]; + + Ok(Self { + info: id.info, + comment, + setup, + geom, + qmat_tables, + ref_golden_y, + ref_golden_cb, + ref_golden_cr, + ref_prev_y, + ref_prev_cb, + ref_prev_cr, + has_keyframe: false, + frame_index: 0, + }) + } + + /// Decode a single video packet into a reconstructed [`Picture`] (Section 7.11). + pub fn decode_packet(&mut self, packet: &[u8]) -> Result { + let (y_pw, y_ph, _, _, _, _, _, _) = self.geom.planes[0]; + let (c_pw, c_ph, _, _, _, _, _, _) = self.geom.planes[1]; + + // 0-byte packet is a 0-change inter frame (Section 7.11 step 2) + if packet.is_empty() { + if !self.has_keyframe { + return Err(Error::MissingReference); + } + let pic = Picture { + width: self.info.frame_width, + height: self.info.frame_height, + pic_width: self.info.pic_width, + pic_height: self.info.pic_height, + pic_x: self.info.pic_x, + pic_y: self.info.pic_y, + pixel_format: self.info.pixel_format, + color_space: self.info.color_space, + keyframe: false, + pts: None, + y: self.ref_prev_y.clone(), + u: self.ref_prev_cb.clone(), + v: self.ref_prev_cr.clone(), + y_stride: y_pw, + uv_stride: c_pw, + }; + self.frame_index += 1; + return Ok(pic); + } + + let mut r = BitReader::new(packet); + + // 1. Frame Header Decode (Section 7.1) + let header_flag = r.read_bits(1).map_err(|_| Error::Truncated("header flag"))?; + if header_flag != 0 { + return Err(Error::Corrupt("data packet header flag must be zero")); + } + + let ftype = r.read_bits(1).map_err(|_| Error::Truncated("ftype"))? as u8; + if ftype == 1 && !self.has_keyframe { + return Err(Error::MissingReference); + } + + let is_keyframe = ftype == 0; + + let mut qis = [0usize; 3]; + qis[0] = r.read_bits(6).map_err(|_| Error::Truncated("qis[0]"))? as usize; + let mut nqis = 1; + let more_qis = r.read_bits(1).map_err(|_| Error::Truncated("more_qis"))? != 0; + if more_qis { + qis[1] = r.read_bits(6).map_err(|_| Error::Truncated("qis[1]"))? as usize; + nqis = 2; + let more_qis2 = r.read_bits(1).map_err(|_| Error::Truncated("more_qis2"))? != 0; + if more_qis2 { + qis[2] = r.read_bits(6).map_err(|_| Error::Truncated("qis[2]"))? as usize; + nqis = 3; + } + } + + if is_keyframe { + let reserved = r.read_bits(3).map_err(|_| Error::Truncated("keyframe reserved bits"))?; + if reserved != 0 { + return Err(Error::Corrupt("keyframe reserved bits must be zero")); + } + } + + // 2. Coded Block Flags (Section 7.3) + let nbs = self.geom.nbs; + let nsbs = self.geom.nsbs; + let mut bcoded = vec![false; nbs]; + + if is_keyframe { + bcoded.fill(true); + } else { + let sbp_bits = decode_long_run(&mut r, nsbs)?; + let mut uncoded_sb_count = 0; + for &b in &sbp_bits { + if !b { + uncoded_sb_count += 1; + } + } + + let sbf_bits = decode_long_run(&mut r, uncoded_sb_count)?; + let mut sbf_iter = sbf_bits.into_iter(); + let mut sbf_coded = vec![false; nsbs]; + + for sbi in 0..nsbs { + if !sbp_bits[sbi] { + sbf_coded[sbi] = sbf_iter.next().unwrap_or(false); + } + } + + let mut partial_block_count = 0; + for sbi in 0..nsbs { + if sbp_bits[sbi] { + partial_block_count += self.geom.sb_block_counts[sbi]; + } + } + + let partial_bits = decode_short_run(&mut r, partial_block_count)?; + let mut partial_iter = partial_bits.into_iter(); + + for bi in 0..nbs { + let sbi = self.geom.blocks[bi].sbi; + if !sbp_bits[sbi] { + bcoded[bi] = sbf_coded[sbi]; + } else { + bcoded[bi] = partial_iter.next().unwrap_or(false); + } + } + } + + // 3. Macro Block Coding Modes (Section 7.4) + let nmbs = self.geom.nmbs; + let mut mb_modes = vec![0u8; nmbs]; + + if is_keyframe { + mb_modes.fill(1); // INTRA + } else { + let mscheme = r.read_bits(3).map_err(|_| Error::Truncated("mscheme"))? as usize; + let mut malphabet = [0u8; 8]; + + if mscheme == 0 { + for mode in 0..8 { + let mi = r.read_bits(3).map_err(|_| Error::Truncated("scheme 0 mi"))? as usize; + if mi < 8 { + malphabet[mi] = mode as u8; + } + } + } else if mscheme < 7 { + malphabet = MB_SCHEMES[mscheme]; + } + + for mbi in 0..nmbs { + let luma_has_coded = self.geom.mb_luma_blocks[mbi].iter().any(|&bi| bcoded[bi]); + if luma_has_coded { + if mscheme != 7 { + let mi = decode_mb_mode_huffman(&mut r)?; + mb_modes[mbi] = malphabet[mi]; + } else { + mb_modes[mbi] = r.read_bits(3).map_err(|_| Error::Truncated("mb_mode"))? as u8; + } + } else { + mb_modes[mbi] = 0; // INTER NOMV + } + } + } + + // 4. Motion Vectors (Section 7.5) + let mut mvects = vec![(0i8, 0i8); nbs]; + + if !is_keyframe { + let mvmode = r.read_bits(1).map_err(|_| Error::Truncated("mvmode"))? as u8; + let mut last1 = (0i8, 0i8); + let mut last2 = (0i8, 0i8); + + for mbi in 0..nmbs { + let mode = mb_modes[mbi]; + if mode == 7 { + // INTER MV FOUR + let [a, b, c, d] = self.geom.mb_luma_blocks[mbi]; + let mut mva = (0i8, 0i8); + let mut mvb = (0i8, 0i8); + let mut mvc = (0i8, 0i8); + let mut mvd = (0i8, 0i8); + let mut last_decoded = None; + + if bcoded[a] { + mva = decode_single_mv(&mut r, mvmode)?; + mvects[a] = mva; + last_decoded = Some(mva); + } + if bcoded[b] { + mvb = decode_single_mv(&mut r, mvmode)?; + mvects[b] = mvb; + last_decoded = Some(mvb); + } + if bcoded[c] { + mvc = decode_single_mv(&mut r, mvmode)?; + mvects[c] = mvc; + last_decoded = Some(mvc); + } + if bcoded[d] { + mvd = decode_single_mv(&mut r, mvmode)?; + mvects[d] = mvd; + last_decoded = Some(mvd); + } + + // Chroma vector computation + match self.info.pixel_format { + PixelFormat::Yuv420 => { + let mvx = round_div4(mva.0 as i32 + mvb.0 as i32 + mvc.0 as i32 + mvd.0 as i32); + let mvy = round_div4(mva.1 as i32 + mvb.1 as i32 + mvc.1 as i32 + mvd.1 as i32); + let mv_chroma = (mvx as i8, mvy as i8); + for &bi in &self.geom.mb_chroma_cb_blocks[mbi] { + mvects[bi] = mv_chroma; + } + for &bi in &self.geom.mb_chroma_cr_blocks[mbi] { + mvects[bi] = mv_chroma; + } + } + PixelFormat::Yuv422 => { + let mvx_bot = round_div2(mva.0 as i32 + mvb.0 as i32) as i8; + let mvy_bot = round_div2(mva.1 as i32 + mvb.1 as i32) as i8; + let mvx_top = round_div2(mvc.0 as i32 + mvd.0 as i32) as i8; + let mvy_top = round_div2(mvc.1 as i32 + mvd.1 as i32) as i8; + + if self.geom.mb_chroma_cb_blocks[mbi].len() >= 2 { + mvects[self.geom.mb_chroma_cb_blocks[mbi][0]] = (mvx_bot, mvy_bot); + mvects[self.geom.mb_chroma_cb_blocks[mbi][1]] = (mvx_top, mvy_top); + } + if self.geom.mb_chroma_cr_blocks[mbi].len() >= 2 { + mvects[self.geom.mb_chroma_cr_blocks[mbi][0]] = (mvx_bot, mvy_bot); + mvects[self.geom.mb_chroma_cr_blocks[mbi][1]] = (mvx_top, mvy_top); + } + } + PixelFormat::Yuv444 => { + if self.geom.mb_chroma_cb_blocks[mbi].len() >= 4 { + mvects[self.geom.mb_chroma_cb_blocks[mbi][0]] = mva; + mvects[self.geom.mb_chroma_cb_blocks[mbi][1]] = mvb; + mvects[self.geom.mb_chroma_cb_blocks[mbi][2]] = mvc; + mvects[self.geom.mb_chroma_cb_blocks[mbi][3]] = mvd; + } + if self.geom.mb_chroma_cr_blocks[mbi].len() >= 4 { + mvects[self.geom.mb_chroma_cr_blocks[mbi][0]] = mva; + mvects[self.geom.mb_chroma_cr_blocks[mbi][1]] = mvb; + mvects[self.geom.mb_chroma_cr_blocks[mbi][2]] = mvc; + mvects[self.geom.mb_chroma_cr_blocks[mbi][3]] = mvd; + } + } + } + + last2 = last1; + if let Some(mv_last) = last_decoded { + last1 = mv_last; + } + } else if mode == 6 { + // INTER GOLDEN MV + let mv = decode_single_mv(&mut r, mvmode)?; + self.assign_macroblock_mv(mbi, mv, &bcoded, &mut mvects); + } else if mode == 4 { + // INTER MV LAST2 + let mv = last2; + std::mem::swap(&mut last2, &mut last1); + self.assign_macroblock_mv(mbi, mv, &bcoded, &mut mvects); + } else if mode == 3 { + // INTER MV LAST + let mv = last1; + self.assign_macroblock_mv(mbi, mv, &bcoded, &mut mvects); + } else if mode == 2 { + // INTER MV + let mv = decode_single_mv(&mut r, mvmode)?; + last2 = last1; + last1 = mv; + self.assign_macroblock_mv(mbi, mv, &bcoded, &mut mvects); + } else { + // INTRA (1), INTER NOMV (0), INTER GOLDEN NOMV (5) + self.assign_macroblock_mv(mbi, (0, 0), &bcoded, &mut mvects); + } + } + } + + // 5. Block-Level qi Decode (Section 7.6) + let mut qiis = vec![0usize; nbs]; + if nqis > 1 { + for qii in 0..(nqis - 1) { + let nbits_pass = (0..nbs).filter(|&bi| bcoded[bi] && qiis[bi] == qii).count(); + if nbits_pass > 0 { + let bits = decode_long_run(&mut r, nbits_pass)?; + let mut bit_iter = bits.into_iter(); + for bi in 0..nbs { + if bcoded[bi] && qiis[bi] == qii && bit_iter.next().unwrap_or(false) { + qiis[bi] += 1; + } + } + } + } + } + + // 6. DCT Coefficients Decode (Section 7.7) + let mut coeffs = vec![[0i16; 64]; nbs]; + let mut ncoeffs = vec![0usize; nbs]; + let mut tis = vec![0usize; nbs]; + let mut eobs = 0usize; + + let nlbs = nmbs * 4; + let mut hti_l = 0usize; + let mut hti_c = 0usize; + + for ti in 0..64 { + if ti == 0 || ti == 1 { + hti_l = r.read_bits(4).map_err(|_| Error::Truncated("hti_l"))? as usize; + hti_c = r.read_bits(4).map_err(|_| Error::Truncated("hti_c"))? as usize; + } + + for bi in 0..nbs { + if !bcoded[bi] || tis[bi] != ti { + continue; + } + + ncoeffs[bi] = ti; + + if eobs > 0 { + tis[bi] = 64; + eobs -= 1; + } else { + let hg = match ti { + 0 => 0, + 1..=5 => 1, + 6..=14 => 2, + 15..=27 => 3, + _ => 4, + }; + let hti = if bi < nlbs { 16 * hg + hti_l } else { 16 * hg + hti_c }; + if hti >= self.setup.huffman_trees.len() { + return Err(Error::Corrupt("invalid Huffman table index")); + } + + let token = self.setup.huffman_trees[hti].decode_token(&mut r)?; + + if token < 7 { + // EOB token (Section 7.7.1) + let run = match token { + 0 => 1, + 1 => 2, + 2 => 3, + 3 => (r.read_bits(2).map_err(|_| Error::Truncated("eob 3"))? + 4) as usize, + 4 => (r.read_bits(3).map_err(|_| Error::Truncated("eob 4"))? + 8) as usize, + 5 => (r.read_bits(4).map_err(|_| Error::Truncated("eob 5"))? + 16) as usize, + 6 => { + let v = r.read_bits(12).map_err(|_| Error::Truncated("eob 6"))? as usize; + if v == 0 { (0..nbs).filter(|&bj| bcoded[bj] && tis[bj] < 64).count() } else { v } + } + _ => 1, + }; + tis[bi] = 64; + eobs = run.saturating_sub(1); + } else { + // Coefficient token (Section 7.7.2) + decode_coeff_token(token, &mut r, bi, ti, &mut coeffs, &mut tis, &mut ncoeffs)?; + } + } + } + } + + // 7. Undo DC Prediction (Section 7.8) + undo_dc_prediction(&self.geom, &bcoded, &mb_modes, &mut coeffs); + + // 8. Block Reconstruction (Section 7.9) + let mut rec_y = vec![0u8; y_pw * y_ph]; + let mut rec_cb = vec![0u8; c_pw * c_ph]; + let mut rec_cr = vec![0u8; c_pw * c_ph]; + + let qi0 = qis[0]; + + for bi in 0..nbs { + let meta = &self.geom.blocks[bi]; + let pli = meta.pli; + let (pw, ph, _, _, _, _, _, _) = self.geom.planes[pli]; + let stride = pw; + + let mut pred = [[0u8; 8]; 8]; + let coded = bcoded[bi]; + + let (dest_plane, _ref_golden_plane, ref_prev_plane) = match pli { + 0 => (&mut rec_y, &self.ref_golden_y, &self.ref_prev_y), + 1 => (&mut rec_cb, &self.ref_golden_cb, &self.ref_prev_cb), + 2 => (&mut rec_cr, &self.ref_golden_cr, &self.ref_prev_cr), + _ => continue, + }; + + if coded { + let mbi = meta.mbi; + let mode = mb_modes[mbi]; + let qti = if mode == 1 { 0 } else { 1 }; + let rfi = mb_mode_to_ref_frame(mode); + + let (ref_y_src, ref_cb_src, ref_cr_src) = if rfi == 2 { + (&self.ref_golden_y[..], &self.ref_golden_cb[..], &self.ref_golden_cr[..]) + } else { + (&self.ref_prev_y[..], &self.ref_prev_cb[..], &self.ref_prev_cr[..]) + }; + + compute_block_predictor( + pli, + meta.pixel_x, + meta.pixel_y, + rfi, + mvects[bi], + self.info.pixel_format, + ref_y_src, + ref_cb_src, + ref_cr_src, + pw, + ph, + &mut pred, + ); + + let qi_ac = qis[qiis[bi]]; + let dc_qmat = &self.qmat_tables[qti][pli][qi0]; + let ac_qmat = &self.qmat_tables[qti][pli][qi_ac]; + + reconstruct_block(meta, true, ncoeffs[bi], &pred, &coeffs[bi], dc_qmat, ac_qmat, dest_plane, stride); + } else { + // Copy co-located block from previous reference frame + for by in 0..8 { + let src_offset = (meta.pixel_y + by) * stride + meta.pixel_x; + let dst_offset = src_offset; + dest_plane[dst_offset..dst_offset + 8].copy_from_slice(&ref_prev_plane[src_offset..src_offset + 8]); + } + } + } + + // 9. Loop Filtering (Section 7.10) + let lflim_l = self.setup.lflims[qi0]; + apply_loop_filter(&self.geom, &bcoded, lflim_l, &mut rec_y, &mut rec_cb, &mut rec_cr); + + // 10. Update Reference Buffers (Section 7.11) + if is_keyframe { + self.ref_golden_y.copy_from_slice(&rec_y); + self.ref_golden_cb.copy_from_slice(&rec_cb); + self.ref_golden_cr.copy_from_slice(&rec_cr); + self.has_keyframe = true; + } + self.ref_prev_y.copy_from_slice(&rec_y); + self.ref_prev_cb.copy_from_slice(&rec_cb); + self.ref_prev_cr.copy_from_slice(&rec_cr); + + self.frame_index += 1; + + Ok(Picture { + width: self.info.frame_width, + height: self.info.frame_height, + pic_width: self.info.pic_width, + pic_height: self.info.pic_height, + pic_x: self.info.pic_x, + pic_y: self.info.pic_y, + pixel_format: self.info.pixel_format, + color_space: self.info.color_space, + keyframe: is_keyframe, + pts: None, + y: rec_y, + u: rec_cb, + v: rec_cr, + y_stride: y_pw, + uv_stride: c_pw, + }) + } + + fn assign_macroblock_mv(&self, mbi: usize, mv: (i8, i8), bcoded: &[bool], mvects: &mut [(i8, i8)]) { + for &bi in &self.geom.mb_luma_blocks[mbi] { + if bcoded[bi] { + mvects[bi] = mv; + } + } + for &bi in &self.geom.mb_chroma_cb_blocks[mbi] { + if bcoded[bi] { + mvects[bi] = mv; + } + } + for &bi in &self.geom.mb_chroma_cr_blocks[mbi] { + if bcoded[bi] { + mvects[bi] = mv; + } + } + } +} + +fn decode_single_mv(r: &mut BitReader, mvmode: u8) -> Result<(i8, i8)> { + if mvmode == 0 { + let mvx = super::huffman::decode_mv_component_huffman(r)? as i8; + let mvy = super::huffman::decode_mv_component_huffman(r)? as i8; + Ok((mvx, mvy)) + } else { + let mag_x = r.read_bits(5).map_err(|_| Error::Truncated("mvx mag"))? as i8; + let sign_x = r.read_bits(1).map_err(|_| Error::Truncated("mvx sign"))? != 0; + let mvx = if sign_x { -mag_x } else { mag_x }; + + let mag_y = r.read_bits(5).map_err(|_| Error::Truncated("mvy mag"))? as i8; + let sign_y = r.read_bits(1).map_err(|_| Error::Truncated("mvy sign"))? != 0; + let mvy = if sign_y { -mag_y } else { mag_y }; + + Ok((mvx, mvy)) + } +} + +fn decode_mb_mode_huffman(r: &mut BitReader) -> Result { + let mut code = 0u32; + for len in 1..=7 { + let bit = r.read_bits(1).map_err(|_| Error::Truncated("mb mode huffman"))?; + code = (code << 1) | bit; + match (len, code) { + (1, 0b0) => return Ok(0), + (2, 0b10) => return Ok(1), + (3, 0b110) => return Ok(2), + (4, 0b1110) => return Ok(3), + (5, 0b11110) => return Ok(4), + (6, 0b111110) => return Ok(5), + (7, 0b1111110) => return Ok(6), + (7, 0b1111111) => return Ok(7), + _ => {} + } + } + Err(Error::Corrupt("unrecognized macroblock mode Huffman code")) +} + +#[inline] +fn round_div4(val: i32) -> i32 { + if val >= 0 { (val + 2) / 4 } else { (val - 2) / 4 } +} + +#[inline] +fn round_div2(val: i32) -> i32 { + if val >= 0 { (val + 1) / 2 } else { (val - 1) / 2 } +} + +fn decode_coeff_token( + token: u8, + r: &mut BitReader, + bi: usize, + ti: usize, + coeffs: &mut [[i16; 64]], + tis: &mut [usize], + ncoeffs: &mut [usize], +) -> Result<()> { + match token { + 7 => { + let rlen = (r.read_bits(3).map_err(|_| Error::Truncated("token 7 rlen"))? + 1) as usize; + tis[bi] += rlen; + } + 8 => { + let rlen = (r.read_bits(6).map_err(|_| Error::Truncated("token 8 rlen"))? + 1) as usize; + tis[bi] += rlen; + } + 9 => { + coeffs[bi][ti] = 1; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 10 => { + coeffs[bi][ti] = -1; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 11 => { + coeffs[bi][ti] = 2; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 12 => { + coeffs[bi][ti] = -2; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 13..=16 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let val = (token - 10) as i16; + coeffs[bi][ti] = if sign { -val } else { val }; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 17 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let mag = (r.read_bits(1).map_err(|_| Error::Truncated("mag"))? + 7) as i16; + coeffs[bi][ti] = if sign { -mag } else { mag }; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 18 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let mag = (r.read_bits(2).map_err(|_| Error::Truncated("mag"))? + 9) as i16; + coeffs[bi][ti] = if sign { -mag } else { mag }; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 19 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let mag = (r.read_bits(3).map_err(|_| Error::Truncated("mag"))? + 13) as i16; + coeffs[bi][ti] = if sign { -mag } else { mag }; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 20 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let mag = (r.read_bits(4).map_err(|_| Error::Truncated("mag"))? + 21) as i16; + coeffs[bi][ti] = if sign { -mag } else { mag }; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 21 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let mag = (r.read_bits(5).map_err(|_| Error::Truncated("mag"))? + 37) as i16; + coeffs[bi][ti] = if sign { -mag } else { mag }; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 22 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let mag = (r.read_bits(9).map_err(|_| Error::Truncated("mag"))? + 69) as i16; + coeffs[bi][ti] = if sign { -mag } else { mag }; + tis[bi] += 1; + ncoeffs[bi] = tis[bi]; + } + 23..=27 => { + let zeros = (token - 22) as usize; + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + if ti + zeros < 64 { + coeffs[bi][ti + zeros] = if sign { -1 } else { 1 }; + } + tis[bi] += zeros + 1; + ncoeffs[bi] = tis[bi]; + } + 28 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let rlen = (r.read_bits(2).map_err(|_| Error::Truncated("rlen"))? + 6) as usize; + if ti + rlen < 64 { + coeffs[bi][ti + rlen] = if sign { -1 } else { 1 }; + } + tis[bi] += rlen + 1; + ncoeffs[bi] = tis[bi]; + } + 29 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let rlen = (r.read_bits(3).map_err(|_| Error::Truncated("rlen"))? + 10) as usize; + if ti + rlen < 64 { + coeffs[bi][ti + rlen] = if sign { -1 } else { 1 }; + } + tis[bi] += rlen + 1; + ncoeffs[bi] = tis[bi]; + } + 30 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let mag = (r.read_bits(1).map_err(|_| Error::Truncated("mag"))? + 2) as i16; + if ti + 1 < 64 { + coeffs[bi][ti + 1] = if sign { -mag } else { mag }; + } + tis[bi] += 2; + ncoeffs[bi] = tis[bi]; + } + 31 => { + let sign = r.read_bits(1).map_err(|_| Error::Truncated("sign"))? != 0; + let mag = (r.read_bits(1).map_err(|_| Error::Truncated("mag"))? + 2) as i16; + let rlen = (r.read_bits(1).map_err(|_| Error::Truncated("rlen"))? + 2) as usize; + if ti + rlen < 64 { + coeffs[bi][ti + rlen] = if sign { -mag } else { mag }; + } + tis[bi] += rlen + 1; + ncoeffs[bi] = tis[bi]; + } + _ => return Err(Error::Corrupt("unsupported coefficient token")), + } + Ok(()) +} diff --git a/crates/video/src/theora/encoder.rs b/crates/video/src/theora/encoder.rs new file mode 100644 index 0000000000..be2472389a --- /dev/null +++ b/crates/video/src/theora/encoder.rs @@ -0,0 +1,505 @@ +//! Theora video encoder (Section 7). + +use super::header::{CommentHeader, IdentificationHeader, SetupHeader}; +use super::idct::fdct_1d; +use super::reconstruct::{FrameGeometry, apply_loop_filter, reconstruct_block, undo_dc_prediction}; +use super::tables::ZIGZAG; +use super::{ColorSpace, Info, Picture, PixelFormat, Result}; +use craft_media::bitstream::BitWriter; + +/// Configuration for creating a Theora video encoder. +#[derive(Clone, Debug)] +pub struct EncoderConfig { + pub width: u32, + pub height: u32, + pub pic_width: u32, + pub pic_height: u32, + pub pic_x: u32, + pub pic_y: u32, + pub fps_num: u32, + pub fps_den: u32, + pub pixel_format: PixelFormat, + pub color_space: ColorSpace, + pub quality: u8, + pub keyframe_distance: u32, +} + +impl Default for EncoderConfig { + fn default() -> Self { + Self { + width: 320, + height: 240, + pic_width: 320, + pic_height: 240, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 32, + keyframe_distance: 64, + } + } +} + +/// A conformant Theora video keyframe and interframe encoder. +pub struct Encoder { + pub config: EncoderConfig, + pub id_header: IdentificationHeader, + pub comment_header: CommentHeader, + pub setup_header: SetupHeader, + pub geom: FrameGeometry, + pub qmat_tables: [[[[u16; 64]; 64]; 3]; 2], + + // Reference frames + ref_golden_y: Vec, + ref_golden_cb: Vec, + ref_golden_cr: Vec, + + ref_prev_y: Vec, + ref_prev_cb: Vec, + ref_prev_cr: Vec, + + frame_count: u64, + last_keyframe: u64, +} + +impl Encoder { + /// Create a new encoder with the given configuration. + pub fn new(config: EncoderConfig) -> Result { + let frame_width = (config.width + 15) & !15; + let frame_height = (config.height + 15) & !15; + let fmbw = (frame_width / 16) as usize; + let fmbh = (frame_height / 16) as usize; + + let info = Info { + version_major: 3, + version_minor: 2, + version_revision: 0, + frame_width, + frame_height, + pic_width: config.pic_width.min(frame_width), + pic_height: config.pic_height.min(frame_height), + pic_x: config.pic_x.min(frame_width - config.pic_width.min(frame_width)), + pic_y: config.pic_y.min(frame_height - config.pic_height.min(frame_height)), + fps_num: config.fps_num.max(1), + fps_den: config.fps_den.max(1), + par_num: 1, + par_den: 1, + color_space: config.color_space, + pixel_format: config.pixel_format, + nominal_bitrate: 0, + quality: config.quality.min(63), + keyframe_granule_shift: 6, + }; + + let id_header = IdentificationHeader { info }; + let comment_header = + CommentHeader { vendor: "craft-video pure-rust Theora encoder".to_string(), comments: vec!["ENCODER=craft-video".to_string()] }; + + let setup_header = SetupHeader::default_vp3()?; + let geom = FrameGeometry::new(fmbw, fmbh, config.pixel_format); + let qmat_tables = setup_header.quant_params.precompute_all_qmat()?; + + let (y_pw, y_ph, _, _, _, _, _, _) = geom.planes[0]; + let (c_pw, c_ph, _, _, _, _, _, _) = geom.planes[1]; + + let ref_golden_y = vec![0u8; y_pw * y_ph]; + let ref_golden_cb = vec![0u8; c_pw * c_ph]; + let ref_golden_cr = vec![0u8; c_pw * c_ph]; + + let ref_prev_y = vec![0u8; y_pw * y_ph]; + let ref_prev_cb = vec![0u8; c_pw * c_ph]; + let ref_prev_cr = vec![0u8; c_pw * c_ph]; + + Ok(Self { + config, + id_header, + comment_header, + setup_header, + geom, + qmat_tables, + ref_golden_y, + ref_golden_cb, + ref_golden_cr, + ref_prev_y, + ref_prev_cb, + ref_prev_cr, + frame_count: 0, + last_keyframe: 0, + }) + } + + /// Serialize the three mandatory stream headers in order: `(id, comment, setup)`. + pub fn headers(&self) -> (Vec, Vec, Vec) { + (self.id_header.serialize(), self.comment_header.serialize(), self.setup_header.serialize()) + } + + /// Encode a single picture into a conformant Theora packet. + pub fn encode_frame(&mut self, pic: &Picture, force_keyframe: bool) -> Result> { + let is_keyframe = force_keyframe || self.frame_count == 0 || (self.frame_count - self.last_keyframe >= self.config.keyframe_distance as u64); + + let mut w = BitWriter::new(); + + // 1. Frame Header (Section 7.1) + w.write_bit(false); // data packet bit = 0 + w.write_bit(!is_keyframe); // FTYPE: 0: Intra, 1: Inter + + // qi: map quality (0..=63) to qi index (63 - quality) + let qi = (63 - self.config.quality.min(63)) as usize; + w.write_bits(qi as u32, 6); + w.write_bit(false); // MOREQIS = 0 (1 qi value) + + if is_keyframe { + w.write_bits(0, 3); // 3 reserved bits = 000 + } + + let nbs = self.geom.nbs; + let (y_pw, y_ph, _, _, _, _, _, _) = self.geom.planes[0]; + let (c_pw, c_ph, _, _, _, _, _, _) = self.geom.planes[1]; + + let mut rec_y = vec![0u8; y_pw * y_ph]; + let mut rec_cb = vec![0u8; c_pw * c_ph]; + let mut rec_cr = vec![0u8; c_pw * c_ph]; + + let bcoded = vec![true; nbs]; + let mb_modes = vec![1u8; self.geom.nmbs]; // 1: INTRA + + // For intra frames, all blocks are coded + // Forward transform & quantize + let mut quant_coeffs = vec![[0i16; 64]; nbs]; + let mut ncoeffs = vec![0usize; nbs]; + + for bi in 0..nbs { + let meta = &self.geom.blocks[bi]; + let pli = meta.pli; + let (pw, _, _, _, _, _, _, _) = self.geom.planes[pli]; + let src_plane = match pli { + 0 => &pic.y, + 1 => &pic.u, + 2 => &pic.v, + _ => &pic.y, + }; + + // Read 8x8 block from source picture (origin at lower-left!) + // Note: In Theora coordinates, row 0 is at the bottom of the plane. + let mut block_samples = [0i16; 64]; + for row in 0..8 { + let py = meta.pixel_y + row; + for col in 0..8 { + let px = meta.pixel_x + col; + let sample = if py * pw + px < src_plane.len() { src_plane[py * pw + px] as i16 } else { 128 }; + // Subtract 128 (intra predictor) + block_samples[row * 8 + col] = sample - 128; + } + } + + // Forward DCT (Section 7.9.3.3) + let mut fdct_coeffs = [0i16; 64]; + // 2D forward DCT: row-by-row then col-by-col + let mut temp = [0i16; 64]; + for r in 0..8 { + let mut row_in = [0i16; 8]; + row_in.copy_from_slice(&block_samples[r * 8..r * 8 + 8]); + let row_out = fdct_1d(&row_in); + temp[r * 8..r * 8 + 8].copy_from_slice(&row_out); + } + for c in 0..8 { + let mut col_in = [0i16; 8]; + for r in 0..8 { + col_in[r] = temp[r * 8 + c]; + } + let col_out = fdct_1d(&col_in); + for r in 0..8 { + fdct_coeffs[r * 8 + c] = col_out[r]; + } + } + + // Quantize natural order -> zig-zag order + let qmat = &self.qmat_tables[0][pli][qi]; + for ci in 0..64 { + let zzi = ZIGZAG[ci]; + let coeff = fdct_coeffs[ci] as i32; + let q = qmat[ci] as i32; + let quant = if coeff >= 0 { (coeff + q / 2) / q } else { (coeff - q / 2) / q }; + quant_coeffs[bi][zzi] = quant.clamp(-580, 580) as i16; + } + + // Compute count of coefficients + let mut last_non_zero = 0; + for i in (0..64).rev() { + if quant_coeffs[bi][i] != 0 { + last_non_zero = i + 1; + break; + } + } + ncoeffs[bi] = last_non_zero; + } + + // Apply DC prediction in raster order (Section 7.8) + let mut stored_coeffs = quant_coeffs.clone(); + for pli in 0..3 { + let mut last_dc = 0i32; + + for &bi in &self.geom.blocks_raster[pli] { + let meta = &self.geom.blocks[bi]; + let mut p = [0u8; 4]; + let mut pbi = [0usize; 4]; + + for (idx, &neigh_opt) in meta.neighbors[0..4].iter().enumerate() { + if let Some(bj) = neigh_opt { + p[idx] = 1; + pbi[idx] = bj; + } + } + + let dc_pred = if p[0] == 0 && p[1] == 0 && p[2] == 0 && p[3] == 0 { + last_dc + } else { + let p_key = (p[0] as usize) | ((p[1] as usize) << 1) | ((p[2] as usize) << 2) | ((p[3] as usize) << 3); + let (w, pdiv) = super::tables::DC_PRED_CONFIG[p_key]; + + let mut sum = 0i32; + if p[0] != 0 { + sum += w[0] * quant_coeffs[pbi[0]][0] as i32; + } + if p[1] != 0 { + sum += w[1] * quant_coeffs[pbi[1]][0] as i32; + } + if p[2] != 0 { + sum += w[2] * quant_coeffs[pbi[2]][0] as i32; + } + if p[3] != 0 { + sum += w[3] * quant_coeffs[pbi[3]][0] as i32; + } + + let mut pred = sum / pdiv; + if p[0] != 0 && p[1] != 0 && p[2] != 0 { + let d0 = (pred - quant_coeffs[pbi[2]][0] as i32).abs(); + let d1 = (pred - quant_coeffs[pbi[0]][0] as i32).abs(); + let d2 = (pred - quant_coeffs[pbi[1]][0] as i32).abs(); + if d0 > 128 { + pred = quant_coeffs[pbi[2]][0] as i32; + } else if d1 > 128 { + pred = quant_coeffs[pbi[0]][0] as i32; + } else if d2 > 128 { + pred = quant_coeffs[pbi[1]][0] as i32; + } + } + pred + }; + + let original_dc = quant_coeffs[bi][0] as i32; + stored_coeffs[bi][0] = (original_dc - dc_pred) as i16; + last_dc = original_dc; + } + } + + // Write DCT Tokens in 64 passes (Section 7.7.3) + let mut tis = vec![0usize; nbs]; + + for ti in 0..64 { + if ti == 0 || ti == 1 { + w.write_bits(0, 4); // hti_l = 0 + w.write_bits(0, 4); // hti_c = 0 + } + + let mut bi = 0; + while bi < nbs { + if tis[bi] != ti { + bi += 1; + continue; + } + + // Check remaining coefficients in block bi from ti..64 + let remaining_all_zero = (ti..64).all(|idx| stored_coeffs[bi][idx] == 0); + + if remaining_all_zero { + // Count how many consecutive blocks also have remaining all zero at ti + let mut eob_run = 0usize; + let mut lookahead = bi; + while lookahead < nbs { + if tis[lookahead] == ti { + if (ti..64).all(|idx| stored_coeffs[lookahead][idx] == 0) { + eob_run += 1; + lookahead += 1; + } else { + break; + } + } else { + lookahead += 1; + } + } + + let hg = match ti { + 0 => 0, + 1..=5 => 1, + 6..=14 => 2, + 15..=27 => 3, + _ => 4, + }; + let hti = 16 * hg; + let tree = &self.setup_header.huffman_trees[hti]; + + // Write optimal EOB token + let (token, extra_bits, extra_len) = if eob_run == 1 { + (0u8, 0u32, 0u32) + } else if eob_run == 2 { + (1u8, 0u32, 0u32) + } else if eob_run == 3 { + (2u8, 0u32, 0u32) + } else if eob_run <= 7 { + (3u8, (eob_run - 4) as u32, 2u32) + } else if eob_run <= 15 { + (4u8, (eob_run - 8) as u32, 3u32) + } else if eob_run <= 31 { + (5u8, (eob_run - 16) as u32, 4u32) + } else { + let clamped_run = eob_run.min(4095); + (6u8, clamped_run as u32, 12u32) + }; + + let (code, code_len) = tree.codes[token as usize]; + w.write_bits(code, code_len as u32); + if extra_len > 0 { + w.write_bits(extra_bits, extra_len); + } + + // Mark all blocks in this EOB run as finished (tis = 64) + let actual_run = match token { + 0 => 1, + 1 => 2, + 2 => 3, + 3 => 4 + extra_bits as usize, + 4 => 8 + extra_bits as usize, + 5 => 16 + extra_bits as usize, + 6 => extra_bits as usize, + _ => 1, + }; + + let mut marked = 0; + let mut curr = bi; + while curr < nbs && marked < actual_run { + if tis[curr] == ti { + tis[curr] = 64; + marked += 1; + } + curr += 1; + } + bi = curr; + } else { + // Non-zero coefficient token + let val = stored_coeffs[bi][ti]; + let hg = match ti { + 0 => 0, + 1..=5 => 1, + 6..=14 => 2, + 15..=27 => 3, + _ => 4, + }; + let hti = 16 * hg; + let tree = &self.setup_header.huffman_trees[hti]; + + if val == 0 { + // Single zero run (token 7 with rlen 1) + let (code, code_len) = tree.codes[7]; + w.write_bits(code, code_len as u32); + w.write_bits(0, 3); // rlen = 0 (represents 1 zero) + tis[bi] += 1; + } else { + let (token, extra_bits, extra_len) = match val { + 1 => (9u8, 0u32, 0u32), + -1 => (10u8, 0u32, 0u32), + 2 => (11u8, 0u32, 0u32), + -2 => (12u8, 0u32, 0u32), + 3 | -3 => (13u8, (val < 0) as u32, 1u32), + 4 | -4 => (14u8, (val < 0) as u32, 1u32), + 5 | -5 => (15u8, (val < 0) as u32, 1u32), + 6 | -6 => (16u8, (val < 0) as u32, 1u32), + 7..=8 | -8..=-7 => { + let sign = (val < 0) as u32; + let mag = (val.abs() - 7) as u32; + (17u8, (sign << 1) | mag, 2u32) + } + 9..=12 | -12..=-9 => { + let sign = (val < 0) as u32; + let mag = (val.abs() - 9) as u32; + (18u8, (sign << 2) | mag, 3u32) + } + 13..=20 | -20..=-13 => { + let sign = (val < 0) as u32; + let mag = (val.abs() - 13) as u32; + (19u8, (sign << 3) | mag, 4u32) + } + 21..=36 | -36..=-21 => { + let sign = (val < 0) as u32; + let mag = (val.abs() - 21) as u32; + (20u8, (sign << 4) | mag, 5u32) + } + 37..=68 | -68..=-37 => { + let sign = (val < 0) as u32; + let mag = (val.abs() - 37) as u32; + (21u8, (sign << 5) | mag, 6u32) + } + _ => { + let sign = (val < 0) as u32; + let mag = (val.abs().clamp(69, 580) - 69) as u32; + (22u8, (sign << 9) | mag, 10u32) + } + }; + + let (code, code_len) = tree.codes[token as usize]; + w.write_bits(code, code_len as u32); + if extra_len > 0 { + w.write_bits(extra_bits, extra_len); + } + tis[bi] += 1; + } + bi += 1; + } + } + } + + // Reconstruct local reference frame + let mut reconstructed_coeffs = stored_coeffs; + undo_dc_prediction(&self.geom, &bcoded, &mb_modes, &mut reconstructed_coeffs); + + let pred = [[128u8; 8]; 8]; + for bi in 0..nbs { + let meta = &self.geom.blocks[bi]; + let pli = meta.pli; + let (pw, _, _, _, _, _, _, _) = self.geom.planes[pli]; + let dest_plane = match pli { + 0 => &mut rec_y, + 1 => &mut rec_cb, + 2 => &mut rec_cr, + _ => continue, + }; + + let dc_qmat = &self.qmat_tables[0][pli][qi]; + let ac_qmat = &self.qmat_tables[0][pli][qi]; + + reconstruct_block(meta, true, ncoeffs[bi], &pred, &reconstructed_coeffs[bi], dc_qmat, ac_qmat, dest_plane, pw); + } + + // Apply in-loop filter + let lflim_l = self.setup_header.lflims[qi]; + apply_loop_filter(&self.geom, &bcoded, lflim_l, &mut rec_y, &mut rec_cb, &mut rec_cr); + + // Update local reference frames + if is_keyframe { + self.ref_golden_y.copy_from_slice(&rec_y); + self.ref_golden_cb.copy_from_slice(&rec_cb); + self.ref_golden_cr.copy_from_slice(&rec_cr); + self.last_keyframe = self.frame_count; + } + self.ref_prev_y.copy_from_slice(&rec_y); + self.ref_prev_cb.copy_from_slice(&rec_cb); + self.ref_prev_cr.copy_from_slice(&rec_cr); + + self.frame_count += 1; + + Ok(w.finish()) + } +} diff --git a/crates/video/src/theora/header.rs b/crates/video/src/theora/header.rs new file mode 100644 index 0000000000..b425c53d4a --- /dev/null +++ b/crates/video/src/theora/header.rs @@ -0,0 +1,502 @@ +//! Theora bitstream headers (Identification, Comment, Setup; Section 6). + +use super::huffman::HuffmanTree; +use super::quant::QuantParams; +use super::tables::{DEFAULT_ACSCALE, DEFAULT_BMS, DEFAULT_DCSCALE, DEFAULT_HUFFMAN_SETUP_BYTES, DEFAULT_LFLIMS}; +use super::{ColorSpace, Error, Info, PixelFormat, Result}; +use craft_media::bitstream::{BitReader, BitWriter}; + +/// Identification header packet (`0x80theora`, 42 bytes, Section 6.2). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct IdentificationHeader { + pub info: Info, +} + +impl IdentificationHeader { + /// Parse identification header packet bytes (Section 6.2). + pub fn parse(data: &[u8]) -> Result { + if data.len() < 42 { + return Err(Error::Truncated("identification header")); + } + if data[0] != 0x80 || &data[1..7] != b"theora" { + return Err(Error::InvalidHeader("invalid identification header magic")); + } + + let vmaj = data[7]; + let vmin = data[8]; + let vrev = data[9]; + if vmaj != 3 || vmin != 2 { + return Err(Error::UnsupportedVersion(vmaj, vmin, vrev)); + } + + let fmbw = u16::from_be_bytes([data[10], data[11]]) as u32; + let fmbh = u16::from_be_bytes([data[12], data[13]]) as u32; + if fmbw == 0 || fmbh == 0 { + return Err(Error::InvalidHeader("frame macroblock dimensions cannot be zero")); + } + + let frame_width = fmbw * 16; + let frame_height = fmbh * 16; + + let picw = u32::from_be_bytes([0, data[14], data[15], data[16]]); + let pich = u32::from_be_bytes([0, data[17], data[18], data[19]]); + let picx = data[20] as u32; + let picy = data[21] as u32; + + if picw > frame_width || pich > frame_height { + return Err(Error::InvalidHeader("picture dimensions exceed frame dimensions")); + } + if picx > frame_width.saturating_sub(picw) || picy > frame_height.saturating_sub(pich) { + return Err(Error::InvalidHeader("picture offset out of frame bounds")); + } + + let frn = u32::from_be_bytes([data[22], data[23], data[24], data[25]]); + let frd = u32::from_be_bytes([data[26], data[27], data[28], data[29]]); + if frn == 0 || frd == 0 { + return Err(Error::InvalidHeader("framerate cannot be zero")); + } + + let parn = u32::from_be_bytes([0, data[30], data[31], data[32]]); + let pard = u32::from_be_bytes([0, data[33], data[34], data[35]]); + + let cs_byte = data[36]; + let color_space = match cs_byte { + 0 => ColorSpace::Undefined, + 1 => ColorSpace::Rec470M, + 2 => ColorSpace::Rec470Bg, + _ => ColorSpace::Undefined, + }; + + let nombr = u32::from_be_bytes([0, data[37], data[38], data[39]]); + + let last_two = u16::from_be_bytes([data[40], data[41]]); + let quality = ((last_two >> 10) & 0x3F) as u8; + let kfgshift = ((last_two >> 5) & 0x1F) as u8; + let pf_bits = ((last_two >> 3) & 0x03) as u8; + let reserved = last_two & 0x07; + + if reserved != 0 { + return Err(Error::InvalidHeader("reserved bits in identification header are non-zero")); + } + + let pixel_format = match pf_bits { + 0 => PixelFormat::Yuv420, + 2 => PixelFormat::Yuv422, + 3 => PixelFormat::Yuv444, + _ => return Err(Error::UnsupportedPixelFormat(pf_bits)), + }; + + Ok(Self { + info: Info { + version_major: vmaj, + version_minor: vmin, + version_revision: vrev, + frame_width, + frame_height, + pic_width: picw, + pic_height: pich, + pic_x: picx, + pic_y: picy, + fps_num: frn, + fps_den: frd, + par_num: parn, + par_den: pard, + color_space, + pixel_format, + nominal_bitrate: nombr, + quality, + keyframe_granule_shift: kfgshift, + }, + }) + } + + /// Serialize identification header into exactly 42 packet bytes (Section 6.2). + pub fn serialize(&self) -> Vec { + let mut buf = Vec::with_capacity(42); + buf.push(0x80); + buf.extend_from_slice(b"theora"); + + buf.push(self.info.version_major); + buf.push(self.info.version_minor); + buf.push(self.info.version_revision); + + let fmbw = (self.info.frame_width / 16) as u16; + let fmbh = (self.info.frame_height / 16) as u16; + buf.extend_from_slice(&fmbw.to_be_bytes()); + buf.extend_from_slice(&fmbh.to_be_bytes()); + + let picw_bytes = self.info.pic_width.to_be_bytes(); + buf.extend_from_slice(&picw_bytes[1..4]); + let pich_bytes = self.info.pic_height.to_be_bytes(); + buf.extend_from_slice(&pich_bytes[1..4]); + + buf.push(self.info.pic_x as u8); + buf.push(self.info.pic_y as u8); + + buf.extend_from_slice(&self.info.fps_num.to_be_bytes()); + buf.extend_from_slice(&self.info.fps_den.to_be_bytes()); + + let parn_bytes = self.info.par_num.to_be_bytes(); + buf.extend_from_slice(&parn_bytes[1..4]); + let pard_bytes = self.info.par_den.to_be_bytes(); + buf.extend_from_slice(&pard_bytes[1..4]); + + buf.push(self.info.color_space as u8); + + let nombr_bytes = self.info.nominal_bitrate.to_be_bytes(); + buf.extend_from_slice(&nombr_bytes[1..4]); + + let pf_bits = match self.info.pixel_format { + PixelFormat::Yuv420 => 0u16, + PixelFormat::Yuv422 => 2u16, + PixelFormat::Yuv444 => 3u16, + }; + + let last_two: u16 = ((self.info.quality as u16 & 0x3F) << 10) | ((self.info.keyframe_granule_shift as u16 & 0x1F) << 5) | (pf_bits << 3); + buf.extend_from_slice(&last_two.to_be_bytes()); + + buf + } +} + +/// Comment header packet (`0x81theora`, Section 6.3). +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct CommentHeader { + /// Vendor identification string. + pub vendor: String, + /// List of user comments (typically `KEY=VALUE`). + pub comments: Vec, +} + +impl CommentHeader { + /// Parse comment header packet bytes (Section 6.3). + pub fn parse(data: &[u8]) -> Result { + if data.len() < 7 { + return Err(Error::Truncated("comment header")); + } + if data[0] != 0x81 || &data[1..7] != b"theora" { + return Err(Error::InvalidHeader("invalid comment header magic")); + } + + let mut pos = 7; + if data.len() < pos + 4 { + return Err(Error::Truncated("vendor string length")); + } + let vendor_len = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; + pos += 4; + + if data.len() < pos + vendor_len { + return Err(Error::Truncated("vendor string")); + } + let vendor = String::from_utf8_lossy(&data[pos..pos + vendor_len]).into_owned(); + pos += vendor_len; + + if data.len() < pos + 4 { + return Err(Error::Truncated("comment count")); + } + let ncomments = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; + pos += 4; + + // Bounded allocation protection + if ncomments > 10_000 { + return Err(Error::Corrupt("excessive comment count in header")); + } + + let mut comments = Vec::with_capacity(ncomments); + for _ in 0..ncomments { + if data.len() < pos + 4 { + return Err(Error::Truncated("user comment length")); + } + let len = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; + pos += 4; + if data.len() < pos + len { + return Err(Error::Truncated("user comment string")); + } + let s = String::from_utf8_lossy(&data[pos..pos + len]).into_owned(); + pos += len; + comments.push(s); + } + + Ok(Self { vendor, comments }) + } + + /// Serialize comment header packet bytes (Section 6.3). + pub fn serialize(&self) -> Vec { + let mut buf = Vec::new(); + buf.push(0x81); + buf.extend_from_slice(b"theora"); + + let vendor_bytes = self.vendor.as_bytes(); + buf.extend_from_slice(&(vendor_bytes.len() as u32).to_le_bytes()); + buf.extend_from_slice(vendor_bytes); + + buf.extend_from_slice(&(self.comments.len() as u32).to_le_bytes()); + for c in &self.comments { + let c_bytes = c.as_bytes(); + buf.extend_from_slice(&(c_bytes.len() as u32).to_le_bytes()); + buf.extend_from_slice(c_bytes); + } + + buf + } +} + +/// Setup header packet (`0x82theora`, Section 6.4). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SetupHeader { + /// 64 loop filter limit values. + pub lflims: [u8; 64], + /// Quantization parameters. + pub quant_params: QuantParams, + /// 80 Huffman trees for DCT tokens. + pub huffman_trees: Vec, +} + +impl SetupHeader { + /// Create a setup header initialized with the default VP3.1 tables (Appendix B). + pub fn default_vp3() -> Result { + let mut bit_r = BitReader::new(DEFAULT_HUFFMAN_SETUP_BYTES); + let mut trees = Vec::with_capacity(80); + for _ in 0..80 { + trees.push(HuffmanTree::parse(&mut bit_r)?); + } + + let mut nqrs = [[0usize; 3]; 2]; + let mut qr_sizes = [[[0usize; 63]; 3]; 2]; + let mut qr_bmis = [[[0usize; 64]; 3]; 2]; + + // VP3 default ranges + nqrs[0][0] = 1; + qr_sizes[0][0][0] = 63; + qr_bmis[0][0][0] = 0; + qr_bmis[0][0][1] = 0; + nqrs[0][1] = 1; + qr_sizes[0][1][0] = 63; + qr_bmis[0][1][0] = 1; + qr_bmis[0][1][1] = 1; + nqrs[0][2] = 1; + qr_sizes[0][2][0] = 63; + qr_bmis[0][2][0] = 1; + qr_bmis[0][2][1] = 1; + nqrs[1][0] = 1; + qr_sizes[1][0][0] = 63; + qr_bmis[1][0][0] = 2; + qr_bmis[1][0][1] = 2; + nqrs[1][1] = 1; + qr_sizes[1][1][0] = 63; + qr_bmis[1][1][0] = 2; + qr_bmis[1][1][1] = 2; + nqrs[1][2] = 1; + qr_sizes[1][2][0] = 63; + qr_bmis[1][2][0] = 2; + qr_bmis[1][2][1] = 2; + + Ok(Self { + lflims: DEFAULT_LFLIMS, + quant_params: QuantParams { + ac_scale: DEFAULT_ACSCALE, + dc_scale: DEFAULT_DCSCALE, + base_matrices: DEFAULT_BMS.to_vec(), + nqrs, + qr_sizes, + qr_bmis, + }, + huffman_trees: trees, + }) + } + + /// Parse setup header packet bytes (Section 6.4). + pub fn parse(data: &[u8]) -> Result { + if data.len() < 7 { + return Err(Error::Truncated("setup header")); + } + if data[0] != 0x82 || &data[1..7] != b"theora" { + return Err(Error::InvalidHeader("invalid setup header magic")); + } + + let mut r = BitReader::new(&data[7..]); + + // 1. Loop Filter Limit Table (Section 6.4.1) + let nbits = r.read_bits(3).map_err(|_| Error::Truncated("lflim nbits"))? as usize; + let mut lflims = [0u8; 64]; + if nbits > 0 { + for qi in 0..64 { + lflims[qi] = r.read_bits(nbits as u32).map_err(|_| Error::Truncated("lflim table"))? as u8; + } + } + + // 2. Quantization Parameters (Section 6.4.2) + let ac_nbits = (r.read_bits(4).map_err(|_| Error::Truncated("acscale nbits"))? + 1) as usize; + let mut ac_scale = [0u16; 64]; + for qi in 0..64 { + ac_scale[qi] = r.read_bits(ac_nbits as u32).map_err(|_| Error::Truncated("acscale table"))? as u16; + } + + let dc_nbits = (r.read_bits(4).map_err(|_| Error::Truncated("dcscale nbits"))? + 1) as usize; + let mut dc_scale = [0u16; 64]; + for qi in 0..64 { + dc_scale[qi] = r.read_bits(dc_nbits as u32).map_err(|_| Error::Truncated("dcscale table"))? as u16; + } + + let nbms = (r.read_bits(9).map_err(|_| Error::Truncated("nbms"))? + 1) as usize; + if nbms > 384 { + return Err(Error::Corrupt("nbms exceeds 384")); + } + + let mut base_matrices = Vec::with_capacity(nbms); + for _ in 0..nbms { + let mut bm = [0u8; 64]; + for ci in 0..64 { + bm[ci] = r.read_bits(8).map_err(|_| Error::Truncated("base matrix"))? as u8; + } + base_matrices.push(bm); + } + + let mut nqrs = [[0usize; 3]; 2]; + let mut qr_sizes = [[[0usize; 63]; 3]; 2]; + let mut qr_bmis = [[[0usize; 64]; 3]; 2]; + + for qti in 0..2 { + for pli in 0..3 { + let newqr = if qti > 0 || pli > 0 { r.read_bits(1).map_err(|_| Error::Truncated("newqr flag"))? != 0 } else { true }; + + if !newqr { + let rpqr = if qti > 0 { r.read_bits(1).map_err(|_| Error::Truncated("rpqr flag"))? != 0 } else { false }; + + let (qtj, plj) = if rpqr { (qti - 1, pli) } else { ((3 * qti + pli - 1) / 3, (pli + 2) % 3) }; + + nqrs[qti][pli] = nqrs[qtj][plj]; + qr_sizes[qti][pli] = qr_sizes[qtj][plj]; + qr_bmis[qti][pli] = qr_bmis[qtj][plj]; + } else { + let mut qri = 0; + let mut qi = 0; + let nbms_ilog = ilog(nbms.saturating_sub(1) as u32) as u32; + + let bmi = r.read_bits(nbms_ilog).map_err(|_| Error::Truncated("qrbmi initial"))? as usize; + if bmi >= nbms { + return Err(Error::Corrupt("initial bmi >= nbms")); + } + qr_bmis[qti][pli][0] = bmi; + + while qi < 63 { + let size_ilog = ilog((62 - qi) as u32) as u32; + let size = (r.read_bits(size_ilog).map_err(|_| Error::Truncated("qrsize"))? + 1) as usize; + qr_sizes[qti][pli][qri] = size; + qi += size; + qri += 1; + + let next_bmi = r.read_bits(nbms_ilog).map_err(|_| Error::Truncated("qrbmi loop"))? as usize; + if next_bmi >= nbms { + return Err(Error::Corrupt("next bmi >= nbms")); + } + qr_bmis[qti][pli][qri] = next_bmi; + } + + if qi > 63 { + return Err(Error::Corrupt("quant range sum exceeded 63")); + } + + nqrs[qti][pli] = qri; + } + } + } + + // 3. DCT Token Huffman Tables (Section 6.4.4) + let mut huffman_trees = Vec::with_capacity(80); + for _ in 0..80 { + huffman_trees.push(HuffmanTree::parse(&mut r)?); + } + + Ok(Self { lflims, quant_params: QuantParams { ac_scale, dc_scale, base_matrices, nqrs, qr_sizes, qr_bmis }, huffman_trees }) + } + + /// Serialize setup header into packet bytes (Section 6.4). + pub fn serialize(&self) -> Vec { + let mut w = BitWriter::new(); + + // 1. Loop Filter Limit Table (Section 6.4.1) + w.write_bits(7, 3); // 7 bits per entry + for &lim in &self.lflims { + w.write_bits(lim as u32, 7); + } + + // 2. Quantization Parameters (Section 6.4.2) + // Find max bits required for ac_scale and dc_scale + let ac_max = self.quant_params.ac_scale.iter().copied().max().unwrap_or(0); + let ac_nbits = ilog(ac_max as u32).clamp(1, 16); + w.write_bits((ac_nbits - 1) as u32, 4); + for &s in &self.quant_params.ac_scale { + w.write_bits(s as u32, ac_nbits as u32); + } + + let dc_max = self.quant_params.dc_scale.iter().copied().max().unwrap_or(0); + let dc_nbits = ilog(dc_max as u32).clamp(1, 16); + w.write_bits((dc_nbits - 1) as u32, 4); + for &s in &self.quant_params.dc_scale { + w.write_bits(s as u32, dc_nbits as u32); + } + + let nbms = self.quant_params.base_matrices.len(); + w.write_bits((nbms - 1) as u32, 9); + for bm in &self.quant_params.base_matrices { + for &b in bm { + w.write_bits(b as u32, 8); + } + } + + // Quant ranges + let nbms_ilog = ilog(nbms.saturating_sub(1) as u32); + for qti in 0..2 { + for pli in 0..3 { + if qti > 0 || pli > 0 { + w.write_bit(true); // Always write NEWQR = 1 for simplicity and robustness + } + let nqr = self.quant_params.nqrs[qti][pli]; + let mut qi = 0; + w.write_bits(self.quant_params.qr_bmis[qti][pli][0] as u32, nbms_ilog as u32); + for qri in 0..nqr { + let size = self.quant_params.qr_sizes[qti][pli][qri]; + let size_ilog = ilog((62 - qi) as u32); + w.write_bits((size - 1) as u32, size_ilog as u32); + qi += size; + w.write_bits(self.quant_params.qr_bmis[qti][pli][qri + 1] as u32, nbms_ilog as u32); + } + } + } + + // 3. DCT Token Huffman Tables (Section 6.4.4) + for tree in &self.huffman_trees { + Self::write_tree_node(&tree.root, &mut w); + } + + let payload = w.finish(); + let mut buf = Vec::with_capacity(7 + payload.len()); + buf.push(0x82); + buf.extend_from_slice(b"theora"); + buf.extend_from_slice(&payload); + buf + } + + fn write_tree_node(node: &super::huffman::HuffmanNode, w: &mut BitWriter) { + match node { + super::huffman::HuffmanNode::Leaf(token) => { + w.write_bit(true); + w.write_bits(*token as u32, 5); + } + super::huffman::HuffmanNode::Branch(left, right) => { + w.write_bit(false); + Self::write_tree_node(left, w); + Self::write_tree_node(right, w); + } + } + } +} + +/// Compute `ilog(v)` as defined in the Theora specification notation: +/// ilog(v) is the minimum number of bits required to store a positive integer v in two's complement, +/// or 0 for non-positive integers. +#[inline] +pub fn ilog(v: u32) -> usize { + if v == 0 { 0 } else { (32 - v.leading_zeros()) as usize } +} diff --git a/crates/video/src/theora/huffman.rs b/crates/video/src/theora/huffman.rs new file mode 100644 index 0000000000..f2a323b5df --- /dev/null +++ b/crates/video/src/theora/huffman.rs @@ -0,0 +1,308 @@ +//! Huffman trees and run-length bitstring decoding (Section 6.4.4, 7.2, 7.5.1). + +use super::Error; +use craft_media::bitstream::BitReader; + +/// A node in a binary Huffman tree. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum HuffmanNode { + /// Leaf node storing a token value (0..=31). + Leaf(u8), + /// Branch node with 0-child and 1-child. + Branch(Box, Box), +} + +/// A decoded Huffman tree for DCT tokens (up to 32 entries, max depth 32). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HuffmanTree { + pub root: HuffmanNode, + /// Code and length for each token 0..=31: `(bits, len)`. + pub codes: [(u32, u8); 32], +} + +impl HuffmanTree { + /// Parse a single Huffman tree from a bitstream (Section 6.4.4). + pub fn parse(r: &mut BitReader) -> Result { + let mut count = 0; + let root = Self::parse_node(r, 0, &mut count)?; + let mut codes = [(0u32, 0u8); 32]; + Self::build_codes(&root, 0, 0, &mut codes); + Ok(Self { root, codes }) + } + + fn parse_node(r: &mut BitReader, depth: usize, count: &mut usize) -> Result { + if depth > 32 { + return Err(Error::Corrupt("Huffman tree depth exceeds 32 bits")); + } + let is_leaf = r.read_bits(1).map_err(|_| Error::Truncated("Huffman tree"))? != 0; + if is_leaf { + if *count >= 32 { + return Err(Error::Corrupt("Huffman tree exceeds 32 entries")); + } + *count += 1; + let token = r.read_bits(5).map_err(|_| Error::Truncated("Huffman leaf token"))? as u8; + Ok(HuffmanNode::Leaf(token)) + } else { + let left = Self::parse_node(r, depth + 1, count)?; + let right = Self::parse_node(r, depth + 1, count)?; + Ok(HuffmanNode::Branch(Box::new(left), Box::new(right))) + } + } + + fn build_codes(node: &HuffmanNode, current_bits: u32, len: u8, codes: &mut [(u32, u8); 32]) { + match node { + HuffmanNode::Leaf(token) => { + let idx = *token as usize; + if idx < 32 { + codes[idx] = (current_bits, len); + } + } + HuffmanNode::Branch(left, right) => { + Self::build_codes(left, current_bits << 1, len + 1, codes); + Self::build_codes(right, (current_bits << 1) | 1, len + 1, codes); + } + } + } + + /// Decode a single token from the bitstream. + #[inline] + pub fn decode_token(&self, r: &mut BitReader) -> Result { + let mut curr = &self.root; + loop { + match curr { + HuffmanNode::Leaf(token) => return Ok(*token), + HuffmanNode::Branch(left, right) => { + let bit = r.read_bits(1).map_err(|_| Error::Truncated("Huffman token"))?; + curr = if bit == 0 { left } else { right }; + } + } + } + } +} + +/// Decode a long-run encoded bit string of `nbits` bits (Section 7.2.1). +pub fn decode_long_run(r: &mut BitReader, nbits: usize) -> Result, Error> { + let mut bits = Vec::with_capacity(nbits); + if nbits == 0 { + return Ok(bits); + } + + let mut current_bit = r.read_bits(1).map_err(|_| Error::Truncated("long run initial bit"))? != 0; + + while bits.len() < nbits { + // Decode Huffman run length per Table 7.7 + let (rstart, rbits_count) = decode_long_run_length_header(r)?; + let roffs = if rbits_count > 0 { r.read_bits(rbits_count).map_err(|_| Error::Truncated("long run offset"))? as usize } else { 0 }; + let rlen = rstart + roffs; + + let needed = nbits - bits.len(); + let to_add = rlen.min(needed); + bits.resize(bits.len() + to_add, current_bit); + + if bits.len() == nbits { + break; + } + + if rlen == 4129 { + // Read new bit after max run of 4129 + current_bit = r.read_bits(1).map_err(|_| Error::Truncated("long run toggle bit"))? != 0; + } else { + current_bit = !current_bit; + } + } + + Ok(bits) +} + +#[inline] +fn decode_long_run_length_header(r: &mut BitReader) -> Result<(usize, u32), Error> { + // Table 7.7 + // b0 -> rstart 1, rbits 0 + // b10 -> rstart 2, rbits 1 + // b110 -> rstart 4, rbits 1 + // b1110 -> rstart 6, rbits 2 + // b11110 -> rstart 10, rbits 3 + // b111110 -> rstart 18, rbits 4 + // b111111 -> rstart 34, rbits 12 + let b0 = r.read_bits(1).map_err(|_| Error::Truncated("long run header"))?; + if b0 == 0 { + return Ok((1, 0)); + } + let b1 = r.read_bits(1).map_err(|_| Error::Truncated("long run header"))?; + if b1 == 0 { + return Ok((2, 1)); + } + let b2 = r.read_bits(1).map_err(|_| Error::Truncated("long run header"))?; + if b2 == 0 { + return Ok((4, 1)); + } + let b3 = r.read_bits(1).map_err(|_| Error::Truncated("long run header"))?; + if b3 == 0 { + return Ok((6, 2)); + } + let b4 = r.read_bits(1).map_err(|_| Error::Truncated("long run header"))?; + if b4 == 0 { + return Ok((10, 3)); + } + let b5 = r.read_bits(1).map_err(|_| Error::Truncated("long run header"))?; + if b5 == 0 { Ok((18, 4)) } else { Ok((34, 12)) } +} + +/// Decode a short-run encoded bit string of `nbits` bits (Section 7.2.2). +pub fn decode_short_run(r: &mut BitReader, nbits: usize) -> Result, Error> { + let mut bits = Vec::with_capacity(nbits); + if nbits == 0 { + return Ok(bits); + } + + let mut current_bit = r.read_bits(1).map_err(|_| Error::Truncated("short run initial bit"))? != 0; + + while bits.len() < nbits { + // Decode short run length per Table 7.11 + let (rstart, rbits_count) = decode_short_run_length_header(r)?; + let roffs = r.read_bits(rbits_count).map_err(|_| Error::Truncated("short run offset"))? as usize; + let rlen = rstart + roffs; + + let needed = nbits - bits.len(); + let to_add = rlen.min(needed); + bits.resize(bits.len() + to_add, current_bit); + + if bits.len() == nbits { + break; + } + + current_bit = !current_bit; + } + + Ok(bits) +} + +#[inline] +fn decode_short_run_length_header(r: &mut BitReader) -> Result<(usize, u32), Error> { + // Table 7.11 + // b0 -> rstart 1, rbits 1 (1..2) + // b10 -> rstart 3, rbits 1 (3..4) + // b110 -> rstart 5, rbits 1 (5..6) + // b1110 -> rstart 7, rbits 2 (7..10) + // b11110 -> rstart 11, rbits 2 (11..14) + // b11111 -> rstart 15, rbits 4 (15..30) + let b0 = r.read_bits(1).map_err(|_| Error::Truncated("short run header"))?; + if b0 == 0 { + return Ok((1, 1)); + } + let b1 = r.read_bits(1).map_err(|_| Error::Truncated("short run header"))?; + if b1 == 0 { + return Ok((3, 1)); + } + let b2 = r.read_bits(1).map_err(|_| Error::Truncated("short run header"))?; + if b2 == 0 { + return Ok((5, 1)); + } + let b3 = r.read_bits(1).map_err(|_| Error::Truncated("short run header"))?; + if b3 == 0 { + return Ok((7, 2)); + } + let b4 = r.read_bits(1).map_err(|_| Error::Truncated("short run header"))?; + if b4 == 0 { Ok((11, 2)) } else { Ok((15, 4)) } +} + +/// Decode a single motion vector component using Table 7.23. +pub fn decode_mv_component_huffman(r: &mut BitReader) -> Result { + let b0 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + if b0 == 0 { + let b1 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + let b2 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + match (b1, b2) { + (0, 0) => Ok(0), + (0, 1) => Ok(1), + (1, 0) => Ok(-1), + _ => { + // b011x + let b3 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + if b3 == 0 { Ok(2) } else { Ok(-2) } + } + } + } else { + // starts with 1 + let b1 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + if b1 == 0 { + // 10... + let b2 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + if b2 == 0 { + // 100x -> +/-3 + let b3 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + if b3 == 0 { Ok(3) } else { Ok(-3) } + } else { + // 1010xx or 1011xx + let b3 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + let b4 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + let b5 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + match (b3, b4) { + (0, 0) => { + if b5 == 0 { + Ok(4) + } else { + Ok(-4) + } + } + (0, 1) => { + if b5 == 0 { + Ok(5) + } else { + Ok(-5) + } + } + (1, 0) => { + if b5 == 0 { + Ok(6) + } else { + Ok(-6) + } + } + _ => { + if b5 == 0 { + Ok(7) + } else { + Ok(-7) + } + } + } + } + } else { + // 11... + let b2 = r.read_bits(1).map_err(|_| Error::Truncated("mv"))?; + if b2 == 0 { + // 110xxxx (7 bits) -> +/-8 .. +/-15 + let val = r.read_bits(4).map_err(|_| Error::Truncated("mv"))? as i32; + let mag = 8 + (val >> 1); + let sign = val & 1; + if sign == 0 { Ok(mag) } else { Ok(-mag) } + } else { + // 111xxxxx (8 bits) -> +/-16 .. +/-31 + let val = r.read_bits(5).map_err(|_| Error::Truncated("mv"))? as i32; + let mag = 16 + (val >> 1); + let sign = val & 1; + if sign == 0 { Ok(mag) } else { Ok(-mag) } + } + } + } +} + +/// Decode a single motion vector `(MVX, MVY)` (Section 7.5.1). +pub fn decode_mv(r: &mut BitReader, mvmode: u8) -> Result<(i32, i32), Error> { + if mvmode == 0 { + let mvx = decode_mv_component_huffman(r)?; + let mvy = decode_mv_component_huffman(r)?; + Ok((mvx, mvy)) + } else { + let mag_x = r.read_bits(5).map_err(|_| Error::Truncated("mv mag"))? as i32; + let sign_x = r.read_bits(1).map_err(|_| Error::Truncated("mv sign"))?; + let mvx = if sign_x != 0 { -mag_x } else { mag_x }; + + let mag_y = r.read_bits(5).map_err(|_| Error::Truncated("mv mag"))? as i32; + let sign_y = r.read_bits(1).map_err(|_| Error::Truncated("mv sign"))?; + let mvy = if sign_y != 0 { -mag_y } else { mag_y }; + + Ok((mvx, mvy)) + } +} diff --git a/crates/video/src/theora/idct.rs b/crates/video/src/theora/idct.rs new file mode 100644 index 0000000000..9c10673383 --- /dev/null +++ b/crates/video/src/theora/idct.rs @@ -0,0 +1,196 @@ +//! 8x8 Inverse and Forward Discrete Cosine Transforms for Theora (Section 7.9.3). +//! +//! A compliant decoder MUST use the exact 16-bit integerized approximation of the 8-point +//! 1D inverse DCT based on the Chen factorization specified in Section 7.9.3.1. + +use super::tables::{C1, C2, C3, C4, C5, C6, C7}; + +// Sine aliases from Table 7.65 +#[allow(dead_code)] +const S1: i32 = C7; +#[allow(dead_code)] +const S2: i32 = C6; +const S3: i32 = C5; +const S6: i32 = C2; +const S7: i32 = C1; + +/// The 1D 8-point inverse DCT (Section 7.9.3.1). +#[inline] +pub fn idct_1d(y: &[i16; 8]) -> [i16; 8] { + let mut t = [0i32; 8]; + + // 1-3. T[0] = C4 * (Y[0] + Y[4]) >> 16 + let t0_in = (y[0] as i32 + y[4] as i32) as i16 as i32; + t[0] = (C4 * t0_in) >> 16; + + // 4-6. T[1] = C4 * (Y[0] - Y[4]) >> 16 + let t1_in = (y[0] as i32 - y[4] as i32) as i16 as i32; + t[1] = (C4 * t1_in) >> 16; + + // 7-12 + t[2] = ((C6 * y[2] as i32) >> 16) - ((S6 * y[6] as i32) >> 16); + t[3] = ((S6 * y[2] as i32) >> 16) + ((C6 * y[6] as i32) >> 16); + t[4] = ((C7 * y[1] as i32) >> 16) - ((S7 * y[7] as i32) >> 16); + t[5] = ((C3 * y[5] as i32) >> 16) - ((S3 * y[3] as i32) >> 16); + t[6] = ((S3 * y[5] as i32) >> 16) + ((C3 * y[3] as i32) >> 16); + t[7] = ((S7 * y[1] as i32) >> 16) + ((C7 * y[7] as i32) >> 16); + + // 13-17 + let r1 = t[4] + t[5]; + let t5_diff = (t[4] - t[5]) as i16 as i32; + t[5] = (C4 * t5_diff) >> 16; + t[4] = r1; + + // 18-22 + let r2 = t[7] + t[6]; + let t6_diff = (t[7] - t[6]) as i16 as i32; + t[6] = (C4 * t6_diff) >> 16; + t[7] = r2; + + // 23-25 + let r3 = t[0] + t[3]; + t[3] = t[0] - t[3]; + t[0] = r3; + + // 26-28 + let r4 = t[1] + t[2]; + t[2] = t[1] - t[2]; + t[1] = r4; + + // 29-31 + let r5 = t[6] + t[5]; + t[5] = t[6] - t[5]; + t[6] = r5; + + // 32-55 Output truncation to 16-bit signed + [ + (t[0] + t[7]) as i16, + (t[1] + t[6]) as i16, + (t[2] + t[5]) as i16, + (t[3] + t[4]) as i16, + (t[3] - t[4]) as i16, + (t[2] - t[5]) as i16, + (t[1] - t[6]) as i16, + (t[0] - t[7]) as i16, + ] +} + +/// The 2D 8x8 inverse DCT (Section 7.9.3.2). +/// +/// `dqc` is the 64 dequantized DCT coefficients in natural raster order (row-major). +/// Returns an 8x8 residual array with ties rounded towards +infinity. +pub fn idct_2d(dqc: &[i16; 64]) -> [[i16; 8]; 8] { + let mut intermediate = [[0i16; 8]; 8]; + + // Pass 1: 1D IDCT on each row + for ri in 0..8 { + let mut row_in = [0i16; 8]; + for ci in 0..8 { + row_in[ci] = dqc[ri * 8 + ci]; + } + intermediate[ri] = idct_1d(&row_in); + } + + // Pass 2: 1D IDCT on each column + let mut res = [[0i16; 8]; 8]; + for ci in 0..8 { + let mut col_in = [0i16; 8]; + for ri in 0..8 { + col_in[ri] = intermediate[ri][ci]; + } + let col_out = idct_1d(&col_in); + for ri in 0..8 { + // (x + 8) >> 4 with ties towards positive infinity + res[ri][ci] = ((col_out[ri] as i32 + 8) >> 4) as i16; + } + } + + res +} + +/// Fast DC-only residual calculation (Section 7.9.4 step 2(d)vii). +/// +/// Used when a block has at most one non-zero coefficient (the DC coefficient). +#[inline] +pub fn idct_dc_only(coeff0: i16, qmat0: u16) -> [[i16; 8]; 8] { + let dc = ((coeff0 as i32 * qmat0 as i32 + 15) >> 5) as i16; + [[dc; 8]; 8] +} + +/// Proper division by 2^16 (rounding towards zero) for forward DCT. +#[inline] +fn div2_16(v: i32) -> i32 { + let offset = if v < 0 { 0xFFFF } else { 0 }; + (v + offset) >> 16 +} + +/// The 1D 8-point forward DCT (Section 7.9.3.3). +#[inline] +pub fn fdct_1d(x: &[i16; 8]) -> [i16; 8] { + let mut t = [0i32; 8]; + + t[0] = x[0] as i32 + x[7] as i32; + t[1] = x[1] as i32 + x[6] as i32; + t[2] = x[2] as i32 + x[5] as i32; + t[3] = x[3] as i32 + x[4] as i32; + t[4] = x[3] as i32 - x[4] as i32; + t[5] = x[2] as i32 - x[5] as i32; + t[6] = x[1] as i32 - x[6] as i32; + t[7] = x[0] as i32 - x[7] as i32; + + let r1 = t[0] + t[3]; + t[3] = t[0] - t[3]; + t[0] = r1; + + let r2 = t[1] + t[2]; + t[2] = t[1] - t[2]; + t[1] = r2; + + let r3 = t[6] - t[5]; + t[6] = div2_16(C4 * (t[6] + t[5])); + t[5] = div2_16(C4 * r3); + + let r4 = t[4] + t[5]; + t[5] = t[4] - t[5]; + t[4] = r4; + + let r5 = t[7] + t[6]; + t[6] = t[7] - t[6]; + t[7] = r5; + + [ + div2_16(C4 * (t[0] + t[1])) as i16, + (div2_16(S7 * t[7]) + div2_16(C7 * t[4])) as i16, + (div2_16(S6 * t[3]) + div2_16(C6 * t[2])) as i16, + (div2_16(C3 * t[6]) - div2_16(S3 * t[5])) as i16, + div2_16(C4 * (t[0] - t[1])) as i16, + (div2_16(S3 * t[6]) + div2_16(C3 * t[5])) as i16, + (div2_16(C6 * t[3]) - div2_16(S6 * t[2])) as i16, + (div2_16(C7 * t[7]) - div2_16(S7 * t[4])) as i16, + ] +} + +/// The 2D 8x8 forward DCT (Section 7.9.3.3). +pub fn fdct_2d(pixel_block: &[[i16; 8]; 8]) -> [i16; 64] { + let mut intermediate = [[0i16; 8]; 8]; + + // Pass 1: 1D FDCT on each row + for ri in 0..8 { + intermediate[ri] = fdct_1d(&pixel_block[ri]); + } + + // Pass 2: 1D FDCT on each column + let mut coeffs = [0i16; 64]; + for ci in 0..8 { + let mut col_in = [0i16; 8]; + for ri in 0..8 { + col_in[ri] = intermediate[ri][ci]; + } + let col_out = fdct_1d(&col_in); + for ri in 0..8 { + coeffs[ri * 8 + ci] = col_out[ri]; + } + } + + coeffs +} diff --git a/crates/video/src/theora/loopfilter.rs b/crates/video/src/theora/loopfilter.rs new file mode 100644 index 0000000000..2c2126a5fe --- /dev/null +++ b/crates/video/src/theora/loopfilter.rs @@ -0,0 +1,49 @@ +//! In-loop deblocking filter for Theora (Section 7.10). + +/// Non-linear loop filter limiting response function `lflim(R, L)` (Figure 7.3). +#[inline] +pub fn lflim(r: i32, l: i32) -> i32 { + let two_l = 2 * l; + if r <= -two_l || r >= two_l { + 0 + } else if r <= -l { + -r - two_l + } else if r < l { + r + } else { + -r + two_l + } +} + +/// 4-tap horizontal block filter across a vertical edge (Section 7.10.1). +pub fn filter_horizontal_edge(recp: &mut [u8], stride: usize, fx: usize, fy: usize, l: i32) { + for by in 0..8 { + let row_start = (fy + by) * stride; + let p0 = recp[row_start + fx] as i32; + let p1 = recp[row_start + fx + 1] as i32; + let p2 = recp[row_start + fx + 2] as i32; + let p3 = recp[row_start + fx + 3] as i32; + + let r = (p0 - 3 * p1 + 3 * p2 - p3 + 4) >> 3; + let delta = lflim(r, l); + + recp[row_start + fx + 1] = (p1 + delta).clamp(0, 255) as u8; + recp[row_start + fx + 2] = (p2 - delta).clamp(0, 255) as u8; + } +} + +/// 4-tap vertical block filter across a horizontal edge (Section 7.10.2). +pub fn filter_vertical_edge(recp: &mut [u8], stride: usize, fx: usize, fy: usize, l: i32) { + for bx in 0..8 { + let p0 = recp[fy * stride + fx + bx] as i32; + let p1 = recp[(fy + 1) * stride + fx + bx] as i32; + let p2 = recp[(fy + 2) * stride + fx + bx] as i32; + let p3 = recp[(fy + 3) * stride + fx + bx] as i32; + + let r = (p0 - 3 * p1 + 3 * p2 - p3 + 4) >> 3; + let delta = lflim(r, l); + + recp[(fy + 1) * stride + fx + bx] = (p1 + delta).clamp(0, 255) as u8; + recp[(fy + 2) * stride + fx + bx] = (p2 - delta).clamp(0, 255) as u8; + } +} diff --git a/crates/video/src/theora/mod.rs b/crates/video/src/theora/mod.rs new file mode 100644 index 0000000000..0fdc69652b --- /dev/null +++ b/crates/video/src/theora/mod.rs @@ -0,0 +1,179 @@ +//! Clean-room pure-Rust Theora video codec (Xiph.Org specification). +//! +//! Provides a conformant Theora video decoder ([`Decoder`]) and keyframe/interframe +//! encoder ([`Encoder`]) operating over byte slices, planar buffers and Ogg streams. + +#![allow(clippy::needless_range_loop, clippy::type_complexity, clippy::too_many_arguments, clippy::cognitive_complexity)] + +pub mod decoder; +pub mod encoder; +pub mod header; +pub mod huffman; +pub mod idct; +pub mod loopfilter; +pub mod quant; +pub mod reconstruct; +pub mod tables; + +pub use decoder::Decoder; +pub use encoder::{Encoder, EncoderConfig}; +pub use header::{CommentHeader, IdentificationHeader, SetupHeader}; + +/// Theora pixel format (subsampling). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub enum PixelFormat { + /// 4:2:0 subsampling (default and VP3 format). + #[default] + Yuv420 = 0, + /// 4:2:2 subsampling. + Yuv422 = 2, + /// 4:4:4 subsampling (no chroma subsampling). + Yuv444 = 3, +} + +impl PixelFormat { + /// Number of blocks per macroblock for this pixel format (Table 6.6). + pub fn blocks_per_macroblock(self) -> usize { + match self { + PixelFormat::Yuv420 => 6, + PixelFormat::Yuv422 => 8, + PixelFormat::Yuv444 => 12, + } + } +} + +/// Theora color space specification (Table 6.3). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub enum ColorSpace { + /// Unspecified color space. + #[default] + Undefined = 0, + /// Rec. 470M (NTSC). + Rec470M = 1, + /// Rec. 470BG (PAL). + Rec470Bg = 2, +} + +/// Frame coding type. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum FrameType { + /// Intra keyframe (independent, updates golden and previous reference). + Intra = 0, + /// Inter frame (predicted from previous/golden reference). + Inter = 1, +} + +/// Theora stream information parsed from headers. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Info { + /// Major bitstream version (must be 3). + pub version_major: u8, + /// Minor bitstream version (must be 2). + pub version_minor: u8, + /// Revision version. + pub version_revision: u8, + /// Coded frame width in pixels (multiple of 16). + pub frame_width: u32, + /// Coded frame height in pixels (multiple of 16). + pub frame_height: u32, + /// Displayable picture width in pixels. + pub pic_width: u32, + /// Displayable picture height in pixels. + pub pic_height: u32, + /// Picture region X offset from frame lower-left corner. + pub pic_x: u32, + /// Picture region Y offset from frame lower-left corner. + pub pic_y: u32, + /// Frame rate numerator. + pub fps_num: u32, + /// Frame rate denominator. + pub fps_den: u32, + /// Pixel aspect ratio numerator. + pub par_num: u32, + /// Pixel aspect ratio denominator. + pub par_den: u32, + /// Color space. + pub color_space: ColorSpace, + /// Chroma subsampling pixel format. + pub pixel_format: PixelFormat, + /// Nominal bitrate in bits per second. + pub nominal_bitrate: u32, + /// Quality hint (0..=63). + pub quality: u8, + /// Keyframe shift in granule position. + pub keyframe_granule_shift: u8, +} + +/// A decoded Theora video picture. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Picture { + /// Coded frame width. + pub width: u32, + /// Coded frame height. + pub height: u32, + /// Display picture width. + pub pic_width: u32, + /// Display picture height. + pub pic_height: u32, + /// Display picture horizontal offset. + pub pic_x: u32, + /// Display picture vertical offset. + pub pic_y: u32, + /// Pixel format. + pub pixel_format: PixelFormat, + /// Color space. + pub color_space: ColorSpace, + /// Whether this was an intra keyframe. + pub keyframe: bool, + /// Presentation timestamp (packet pts if passed). + pub pts: Option, + /// Planar Y (luma) samples. + pub y: Vec, + /// Planar Cb (U chroma) samples. + pub u: Vec, + /// Planar Cr (V chroma) samples. + pub v: Vec, + /// Row stride in samples for luma plane. + pub y_stride: usize, + /// Row stride in samples for chroma planes. + pub uv_stride: usize, +} + +/// Errors returned by Theora operations. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// Bitstream or header was truncated before reading required fields. + #[error("unexpected end of bitstream: {0}")] + Truncated(&'static str), + + /// A header packet was malformed or failed validation. + #[error("invalid Theora header: {0}")] + InvalidHeader(&'static str), + + /// Bitstream version is not supported (only 3.2.x). + #[error("unsupported Theora version {0}.{1}.{2}")] + UnsupportedVersion(u8, u8, u8), + + /// Pixel format is invalid or unsupported. + #[error("unsupported pixel format: {0}")] + UnsupportedPixelFormat(u8), + + /// Packet data was corrupt or invalid according to the specification. + #[error("corrupt bitstream: {0}")] + Corrupt(&'static str), + + /// Operation requires an intra keyframe (e.g. first frame or missing reference). + #[error("missing reference frame (expected keyframe)")] + MissingReference, + + /// Dimensions did not match expectation. + #[error("frame dimension mismatch: {0}")] + DimensionMismatch(&'static str), + + /// Out of memory or allocation failed. + #[error("allocation failed")] + OutOfMemory, +} + +/// Result type for Theora operations. +pub type Result = std::result::Result; diff --git a/crates/video/src/theora/quant.rs b/crates/video/src/theora/quant.rs new file mode 100644 index 0000000000..f6a7ddcfe0 --- /dev/null +++ b/crates/video/src/theora/quant.rs @@ -0,0 +1,96 @@ +//! Quantization parameters and dequantization matrix generation (Section 6.4.3). + +use super::Error; + +/// Storage for decoded quantization parameters from the setup header. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct QuantParams { + /// 64-element AC scale values. + pub ac_scale: [u16; 64], + /// 64-element DC scale values. + pub dc_scale: [u16; 64], + /// Base matrices (up to 384, each 64 bytes). + pub base_matrices: Vec<[u8; 64]>, + /// Number of quant ranges for `[qti (0..2)][pli (0..3)]`. + pub nqrs: [[usize; 3]; 2], + /// Sizes of quant ranges `[qti][pli][qri]`. + pub qr_sizes: [[[usize; 63]; 3]; 2], + /// Base matrix indices `[qti][pli][qri]`. + pub qr_bmis: [[[usize; 64]; 3]; 2], +} + +impl QuantParams { + /// Compute a single 64-element quantization matrix for `(qti, pli, qi)` (Section 6.4.3). + pub fn compute_qmat(&self, qti: usize, pli: usize, qi: usize) -> Result<[u16; 64], Error> { + let nqr = self.nqrs[qti][pli]; + if nqr == 0 || nqr > 63 { + return Err(Error::Corrupt("invalid quant range count")); + } + + // 1. Locate the quant range qri containing qi + let mut qi_start = 0; + let mut selected_qri = None; + + for qri in 0..nqr { + let size = self.qr_sizes[qti][pli][qri]; + let qi_end = qi_start + size; + if qi >= qi_start && qi <= qi_end { + selected_qri = Some((qri, qi_start, qi_end, size)); + break; + } + qi_start = qi_end; + } + + let (qri, qi_start, qi_end, range_size) = selected_qri.ok_or(Error::Corrupt("qi not found in any quant range"))?; + + if range_size == 0 { + return Err(Error::Corrupt("zero-sized quant range")); + } + + let bmi = self.qr_bmis[qti][pli][qri]; + let bmj = self.qr_bmis[qti][pli][qri + 1]; + + if bmi >= self.base_matrices.len() || bmj >= self.base_matrices.len() { + return Err(Error::Corrupt("base matrix index out of bounds")); + } + + let bm_a = &self.base_matrices[bmi]; + let bm_b = &self.base_matrices[bmj]; + + let mut qmat = [0u16; 64]; + + for ci in 0..64 { + let num = 2 * (qi_end as i32 - qi as i32) * bm_a[ci] as i32 + 2 * (qi as i32 - qi_start as i32) * bm_b[ci] as i32 + range_size as i32; + let den = 2 * range_size as i32; + let bm_ci = num / den; + + let qscale = if ci == 0 { self.dc_scale[qi] as i32 } else { self.ac_scale[qi] as i32 }; + + let val = (qscale * bm_ci / 100) * 4; + let qmin = match (qti, ci == 0) { + (0, true) => 16, + (0, false) => 8, + (1, true) => 32, + (1, false) => 16, + _ => 16, + }; + + qmat[ci] = val.clamp(qmin, 4096) as u16; + } + + Ok(qmat) + } + + /// Precompute all quantization matrices `[qti][pli][qi]` for fast decoding. + pub fn precompute_all_qmat(&self) -> Result<[[[[u16; 64]; 64]; 3]; 2], Error> { + let mut tables = [[[[0u16; 64]; 64]; 3]; 2]; + for qti in 0..2 { + for pli in 0..3 { + for qi in 0..64 { + tables[qti][pli][qi] = self.compute_qmat(qti, pli, qi)?; + } + } + } + Ok(tables) + } +} diff --git a/crates/video/src/theora/reconstruct.rs b/crates/video/src/theora/reconstruct.rs new file mode 100644 index 0000000000..9c476cd704 --- /dev/null +++ b/crates/video/src/theora/reconstruct.rs @@ -0,0 +1,506 @@ +//! Frame geometry, DC prediction undoing, block reconstruction, and loop filtering (Sections 2, 7.8, 7.9, 7.10). + +use super::PixelFormat; +use super::idct::idct_2d; +use super::loopfilter::{filter_horizontal_edge, filter_vertical_edge}; +use super::tables::{DC_PRED_CONFIG, MB_HILBERT, SB_HILBERT, ZIGZAG}; + +/// Information about a single 8x8 block in the coded frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BlockMeta { + /// Color plane index (0: Y, 1: Cb, 2: Cr). + pub pli: usize, + /// Block column coordinate in its plane (0..w_blocks). + pub bx: usize, + /// Block row coordinate in its plane (0..h_blocks). + pub by: usize, + /// Pixel coordinate of bottom-left corner in plane. + pub pixel_x: usize, + pub pixel_y: usize, + /// Global superblock index this block belongs to (0..nsbs). + pub sbi: usize, + /// Global macroblock index this block belongs to (0..nmbs). + pub mbi: usize, + /// Neighbor block indices in coded order: `[Left, Down-Left, Down, Down-Right, Right, Up]`. + pub neighbors: [Option; 6], +} + +/// Precomputed layout and block mappings for a frame size and pixel format. +#[derive(Clone, Debug)] +pub struct FrameGeometry { + pub fmbw: usize, + pub fmbh: usize, + pub pixel_format: PixelFormat, + pub frame_width: usize, + pub frame_height: usize, + pub nmbs: usize, + pub nsbs: usize, + pub nbs: usize, + + /// Plane dimensions: `(width, height, w_blocks, h_blocks, sb_w, sb_h, num_blocks, num_sbs)`. + pub planes: [(usize, usize, usize, usize, usize, usize, usize, usize); 3], + + /// Metadata for each block in coded order `0..nbs`. + pub blocks: Vec, + + /// Coded-order block indices in raster order for each plane: `blocks_raster[pli]`. + pub blocks_raster: [Vec; 3], + + /// For each macroblock `mbi in 0..nmbs`: `(luma_A, luma_B, luma_C, luma_D)`. + pub mb_luma_blocks: Vec<[usize; 4]>, + + /// For each macroblock `mbi in 0..nmbs`: chroma block indices in coded order. + pub mb_chroma_cb_blocks: Vec>, + pub mb_chroma_cr_blocks: Vec>, + + /// Number of blocks inside each superblock `sbi in 0..nsbs`. + pub sb_block_counts: Vec, +} + +impl FrameGeometry { + pub fn new(fmbw: usize, fmbh: usize, pixel_format: PixelFormat) -> Self { + let frame_width = fmbw * 16; + let frame_height = fmbh * 16; + let nmbs = fmbw * fmbh; + + // Plane dimensions + // Y: + let y_pw = frame_width; + let y_ph = frame_height; + let y_wb = fmbw * 2; + let y_hb = fmbh * 2; + let y_sb_w = y_wb.div_ceil(4); + let y_sb_h = y_hb.div_ceil(4); + let y_blocks = y_wb * y_hb; + let y_sbs = y_sb_w * y_sb_h; + + // Cb & Cr: + let (c_pw, c_ph, c_wb, c_hb) = match pixel_format { + PixelFormat::Yuv420 => (fmbw * 8, fmbh * 8, fmbw, fmbh), + PixelFormat::Yuv422 => (fmbw * 8, fmbh * 16, fmbw, fmbh * 2), + PixelFormat::Yuv444 => (fmbw * 16, fmbh * 16, fmbw * 2, fmbh * 2), + }; + let c_sb_w = c_wb.div_ceil(4); + let c_sb_h = c_hb.div_ceil(4); + let c_blocks = c_wb * c_hb; + let c_sbs = c_sb_w * c_sb_h; + + let planes = [ + (y_pw, y_ph, y_wb, y_hb, y_sb_w, y_sb_h, y_blocks, y_sbs), + (c_pw, c_ph, c_wb, c_hb, c_sb_w, c_sb_h, c_blocks, c_sbs), + (c_pw, c_ph, c_wb, c_hb, c_sb_w, c_sb_h, c_blocks, c_sbs), + ]; + + let nbs = y_blocks + 2 * c_blocks; + let nsbs = y_sbs + 2 * c_sbs; + + // Map macroblocks in Hilbert coded order within luma superblocks + // `mb_grid[my][mx] = mbi` + let mut mb_grid = vec![vec![0usize; fmbw]; fmbh]; + let mut mb_coords = Vec::with_capacity(nmbs); + let mut cur_mbi = 0; + + let luma_sb_w = fmbw.div_ceil(2); + let luma_sb_h = fmbh.div_ceil(2); + + for sb_y in 0..luma_sb_h { + for sb_x in 0..luma_sb_w { + for &(dx, dy) in &MB_HILBERT { + let mx = sb_x * 2 + dx; + let my = sb_y * 2 + dy; + if mx < fmbw && my < fmbh { + mb_grid[my][mx] = cur_mbi; + mb_coords.push((mx, my)); + cur_mbi += 1; + } + } + } + } + + // Build coded blocks for all 3 planes + let mut blocks = Vec::with_capacity(nbs); + let mut plane_block_grid = [vec![vec![0usize; y_wb]; y_hb], vec![vec![0usize; c_wb]; c_hb], vec![vec![0usize; c_wb]; c_hb]]; + + let mut sb_block_counts = vec![0usize; nsbs]; + let mut global_sbi = 0; + let mut cur_bi = 0; + + for (pli, plane) in planes.iter().enumerate() { + let (_, _, wb, hb, sb_w, sb_h, _, _) = *plane; + let sb_start = global_sbi; + + for sb_y in 0..sb_h { + for sb_x in 0..sb_w { + let sbi = sb_start + sb_y * sb_w + sb_x; + let mut count_in_sb = 0; + + for &(dx, dy) in &SB_HILBERT { + let bx = sb_x * 4 + dx; + let by = sb_y * 4 + dy; + if bx < wb && by < hb { + // Find macroblock index mbi + let (mx, my) = match (pli, pixel_format) { + (0, _) => (bx / 2, by / 2), + (1 | 2, PixelFormat::Yuv420) => (bx, by), + (1 | 2, PixelFormat::Yuv422) => (bx, by / 2), + _ => (bx / 2, by / 2), + }; + let mbi = mb_grid[my][mx]; + + plane_block_grid[pli][by][bx] = cur_bi; + blocks.push(BlockMeta { pli, bx, by, pixel_x: bx * 8, pixel_y: by * 8, sbi, mbi, neighbors: [None; 6] }); + + count_in_sb += 1; + cur_bi += 1; + } + } + sb_block_counts[sbi] = count_in_sb; + } + } + global_sbi += sb_w * sb_h; + } + + // Connect neighbors within each plane + // 0: Left, 1: Down-Left, 2: Down, 3: Down-Right, 4: Right, 5: Up + for bi in 0..nbs { + let pli = blocks[bi].pli; + let bx = blocks[bi].bx; + let by = blocks[bi].by; + let (_, _, wb, hb, _, _, _, _) = planes[pli]; + + let left = if bx > 0 { Some(plane_block_grid[pli][by][bx - 1]) } else { None }; + let down_left = if bx > 0 && by > 0 { Some(plane_block_grid[pli][by - 1][bx - 1]) } else { None }; + let down = if by > 0 { Some(plane_block_grid[pli][by - 1][bx]) } else { None }; + let down_right = if bx + 1 < wb && by > 0 { Some(plane_block_grid[pli][by - 1][bx + 1]) } else { None }; + let right = if bx + 1 < wb { Some(plane_block_grid[pli][by][bx + 1]) } else { None }; + let up = if by + 1 < hb { Some(plane_block_grid[pli][by + 1][bx]) } else { None }; + + blocks[bi].neighbors = [left, down_left, down, down_right, right, up]; + } + + // Build raster order lists for each plane + let mut blocks_raster = [Vec::with_capacity(y_blocks), Vec::with_capacity(c_blocks), Vec::with_capacity(c_blocks)]; + + for (pli, plane) in planes.iter().enumerate() { + let (_, _, wb, hb, _, _, _, _) = *plane; + for by in 0..hb { + for bx in 0..wb { + blocks_raster[pli].push(plane_block_grid[pli][by][bx]); + } + } + } + + // Build macroblock -> block mappings + let mut mb_luma_blocks = vec![[0usize; 4]; nmbs]; + let mut mb_chroma_cb_blocks = vec![Vec::new(); nmbs]; + let mut mb_chroma_cr_blocks = vec![Vec::new(); nmbs]; + + for mbi in 0..nmbs { + let (mx, my) = mb_coords[mbi]; + // Luma raster: A(lower-left), B(lower-right), C(upper-left), D(upper-right) + let a = plane_block_grid[0][my * 2][mx * 2]; + let b = plane_block_grid[0][my * 2][mx * 2 + 1]; + let c = plane_block_grid[0][my * 2 + 1][mx * 2]; + let d = plane_block_grid[0][my * 2 + 1][mx * 2 + 1]; + mb_luma_blocks[mbi] = [a, b, c, d]; + + match pixel_format { + PixelFormat::Yuv420 => { + mb_chroma_cb_blocks[mbi].push(plane_block_grid[1][my][mx]); + mb_chroma_cr_blocks[mbi].push(plane_block_grid[2][my][mx]); + } + PixelFormat::Yuv422 => { + mb_chroma_cb_blocks[mbi].push(plane_block_grid[1][my * 2][mx]); + mb_chroma_cb_blocks[mbi].push(plane_block_grid[1][my * 2 + 1][mx]); + mb_chroma_cr_blocks[mbi].push(plane_block_grid[2][my * 2][mx]); + mb_chroma_cr_blocks[mbi].push(plane_block_grid[2][my * 2 + 1][mx]); + } + PixelFormat::Yuv444 => { + mb_chroma_cb_blocks[mbi].push(plane_block_grid[1][my * 2][mx * 2]); + mb_chroma_cb_blocks[mbi].push(plane_block_grid[1][my * 2][mx * 2 + 1]); + mb_chroma_cb_blocks[mbi].push(plane_block_grid[1][my * 2 + 1][mx * 2]); + mb_chroma_cb_blocks[mbi].push(plane_block_grid[1][my * 2 + 1][mx * 2 + 1]); + + mb_chroma_cr_blocks[mbi].push(plane_block_grid[2][my * 2][mx * 2]); + mb_chroma_cr_blocks[mbi].push(plane_block_grid[2][my * 2][mx * 2 + 1]); + mb_chroma_cr_blocks[mbi].push(plane_block_grid[2][my * 2 + 1][mx * 2]); + mb_chroma_cr_blocks[mbi].push(plane_block_grid[2][my * 2 + 1][mx * 2 + 1]); + } + } + } + + Self { + fmbw, + fmbh, + pixel_format, + frame_width, + frame_height, + nmbs, + nsbs, + nbs, + planes, + blocks, + blocks_raster, + mb_luma_blocks, + mb_chroma_cb_blocks, + mb_chroma_cr_blocks, + sb_block_counts, + } + } +} + +/// Map macroblock coding mode (0..=7) to reference frame index (Table 7.46). +/// 0: INTRA, 1: Previous, 2: Golden. +#[inline] +pub fn mb_mode_to_ref_frame(mode: u8) -> usize { + match mode { + 1 => 0, // INTRA + 5 | 6 => 2, // GOLDEN NOMV, GOLDEN MV + _ => 1, // INTER NOMV, INTER MV, INTER MV LAST, INTER MV LAST2, INTER MV FOUR + } +} + +/// Undo DC prediction across all planes in raster order (Section 7.8). +pub fn undo_dc_prediction(geom: &FrameGeometry, bcoded: &[bool], mb_modes: &[u8], coeffs: &mut [[i16; 64]]) { + for pli in 0..3 { + let mut last_dc = [0i32; 3]; + + for &bi in &geom.blocks_raster[pli] { + if !bcoded[bi] { + continue; + } + + let meta = &geom.blocks[bi]; + let rfi = mb_mode_to_ref_frame(mb_modes[meta.mbi]); + + // Neighbors: 0: L, 1: DL, 2: D, 3: DR + let mut p = [0u8; 4]; + let mut pbi = [0usize; 4]; + + for (idx, &neigh_opt) in meta.neighbors[0..4].iter().enumerate() { + if let Some(bj) = neigh_opt + && bcoded[bj] + { + let mbj = geom.blocks[bj].mbi; + if mb_mode_to_ref_frame(mb_modes[mbj]) == rfi { + p[idx] = 1; + pbi[idx] = bj; + } + } + } + + let dc_pred = if p[0] == 0 && p[1] == 0 && p[2] == 0 && p[3] == 0 { + last_dc[rfi] + } else { + let p_key = (p[0] as usize) | ((p[1] as usize) << 1) | ((p[2] as usize) << 2) | ((p[3] as usize) << 3); + let (w, pdiv) = DC_PRED_CONFIG[p_key]; + + let mut sum = 0i32; + if p[0] != 0 { + sum += w[0] * coeffs[pbi[0]][0] as i32; + } + if p[1] != 0 { + sum += w[1] * coeffs[pbi[1]][0] as i32; + } + if p[2] != 0 { + sum += w[2] * coeffs[pbi[2]][0] as i32; + } + if p[3] != 0 { + sum += w[3] * coeffs[pbi[3]][0] as i32; + } + + let mut pred = sum / pdiv; + + if p[0] != 0 && p[1] != 0 && p[2] != 0 { + let d0 = (pred - coeffs[pbi[2]][0] as i32).abs(); + let d1 = (pred - coeffs[pbi[0]][0] as i32).abs(); + let d2 = (pred - coeffs[pbi[1]][0] as i32).abs(); + + if d0 > 128 { + pred = coeffs[pbi[2]][0] as i32; + } else if d1 > 128 { + pred = coeffs[pbi[0]][0] as i32; + } else if d2 > 128 { + pred = coeffs[pbi[1]][0] as i32; + } + } + pred + }; + + let dc = (coeffs[bi][0] as i32 + dc_pred) as i16; + coeffs[bi][0] = dc; + last_dc[rfi] = dc as i32; + } + } +} + +/// Compute block predictor (Intra, whole-pixel, or half-pixel; Section 7.9.1). +pub fn compute_block_predictor( + pli: usize, + bx: usize, + by: usize, + rfi: usize, + mv: (i8, i8), + pixel_format: PixelFormat, + ref_y: &[u8], + ref_cb: &[u8], + ref_cr: &[u8], + plane_w: usize, + plane_h: usize, + pred: &mut [[u8; 8]; 8], +) { + if rfi == 0 { + // Intra predictor is constant 128 + for row in pred.iter_mut() { + row.fill(128); + } + return; + } + + let ref_plane = match pli { + 0 => ref_y, + 1 => ref_cb, + 2 => ref_cr, + _ => ref_y, + }; + + let is_chroma_subsampled_x = pli > 0; + let is_chroma_subsampled_y = pli > 0 && pixel_format == PixelFormat::Yuv420; + + let (mvx1, mvx2) = split_mv_component(mv.0 as i32, is_chroma_subsampled_x); + let (mvy1, mvy2) = split_mv_component(mv.1 as i32, is_chroma_subsampled_y); + + let is_whole_pixel = mvx1 == mvx2 && mvy1 == mvy2; + + for row_idx in 0..8 { + let py = by + row_idx; + let ry1 = (py as i32 + mvy1).clamp(0, plane_h as i32 - 1) as usize; + let ry2 = (py as i32 + mvy2).clamp(0, plane_h as i32 - 1) as usize; + + for col_idx in 0..8 { + let px = bx + col_idx; + let rx1 = (px as i32 + mvx1).clamp(0, plane_w as i32 - 1) as usize; + + if is_whole_pixel { + pred[row_idx][col_idx] = ref_plane[ry1 * plane_w + rx1]; + } else { + let rx2 = (px as i32 + mvx2).clamp(0, plane_w as i32 - 1) as usize; + let s1 = ref_plane[ry1 * plane_w + rx1] as u16; + let s2 = ref_plane[ry2 * plane_w + rx2] as u16; + pred[row_idx][col_idx] = ((s1 + s2) >> 1) as u8; + } + } + } +} + +/// Split motion vector component into whole-pixel bounds `(mv1, mv2)`. +/// mv1: truncated towards zero. +/// mv2: truncated away from zero. +#[inline] +fn split_mv_component(mv: i32, is_subsampled: bool) -> (i32, i32) { + if !is_subsampled { + // Half-pixel accuracy: 1 pixel = 2 units + if mv >= 0 { (mv / 2, (mv + 1) / 2) } else { (-((-mv) / 2), -((-mv + 1) / 2)) } + } else { + // Quarter-pixel accuracy: 1 pixel = 4 units + if mv >= 0 { (mv / 4, (mv + 3) / 4) } else { (-((-mv) / 4), -((-mv + 3) / 4)) } + } +} + +/// Reconstruct a single 8x8 block into the destination plane (Section 7.9). +pub fn reconstruct_block( + meta: &BlockMeta, + coded: bool, + ncoeffs: usize, + pred: &[[u8; 8]; 8], + coeffs_bi: &[i16; 64], + dc_qmat: &[u16; 64], + ac_qmat: &[u16; 64], + dest_plane: &mut [u8], + stride: usize, +) { + let mut res = [[0i16; 8]; 8]; + + if coded { + if ncoeffs < 2 { + // Special DC-only fast path (Section 7.9.4 step 2(d)vii) + let dc = ((coeffs_bi[0] as i32 * dc_qmat[0] as i32 + 15) >> 5) as i16; + for row in res.iter_mut() { + row.fill(dc); + } + } else { + // Full dequantization and inverse DCT (Section 7.9.2 & 7.9.3) + let mut dqc = [0i16; 64]; + dqc[0] = (coeffs_bi[0] as i32 * dc_qmat[0] as i32) as i16; + for ci in 1..64 { + let zzi = ZIGZAG[ci]; + dqc[ci] = (coeffs_bi[zzi] as i32 * ac_qmat[ci] as i32) as i16; + } + res = idct_2d(&dqc); + } + } + + // Add prediction and residual, clamp to 0..=255, and write to destination + for by in 0..8 { + let row_offset = (meta.pixel_y + by) * stride + meta.pixel_x; + for bx in 0..8 { + let p = pred[by][bx] as i32 + res[by][bx] as i32; + dest_plane[row_offset + bx] = p.clamp(0, 255) as u8; + } + } +} + +/// In-loop deblocking filter pass across all block boundaries (Section 7.10). +pub fn apply_loop_filter(geom: &FrameGeometry, bcoded: &[bool], lflim_l: u8, rec_y: &mut [u8], rec_cb: &mut [u8], rec_cr: &mut [u8]) { + if lflim_l == 0 { + return; + } + + let l = lflim_l as i32; + + for pli in 0..3 { + let (pw, ph, _, _, _, _, _, _) = geom.planes[pli]; + let rec_plane = match pli { + 0 => &mut *rec_y, + 1 => &mut *rec_cb, + 2 => &mut *rec_cr, + _ => continue, + }; + + for &bi in &geom.blocks_raster[pli] { + if !bcoded[bi] { + continue; + } + + let meta = &geom.blocks[bi]; + let bx = meta.pixel_x; + let by = meta.pixel_y; + + // Left edge + if bx > 0 { + filter_horizontal_edge(rec_plane, pw, bx - 2, by, l); + } + + // Bottom edge + if by > 0 { + filter_vertical_edge(rec_plane, pw, bx, by - 2, l); + } + + // Right edge (if neighbor is uncoded) + if bx + 8 < pw + && let Some(bi_right) = meta.neighbors[4] + && !bcoded[bi_right] + { + filter_horizontal_edge(rec_plane, pw, bx + 6, by, l); + } + + // Top edge (if neighbor is uncoded) + if by + 8 < ph + && let Some(bi_up) = meta.neighbors[5] + && !bcoded[bi_up] + { + filter_vertical_edge(rec_plane, pw, bx, by + 6, l); + } + } + } +} diff --git a/crates/video/src/theora/tables.rs b/crates/video/src/theora/tables.rs new file mode 100644 index 0000000000..523667b45e --- /dev/null +++ b/crates/video/src/theora/tables.rs @@ -0,0 +1,208 @@ +//! Specification tables and default VP3 constants for Theora video. + +/// 4x4 block traversal order within a super block (Hilbert curve, Section 2.3 Figure 2.4). +/// Each entry is `(bx, by)` from bottom-left (0,0). +pub const SB_HILBERT: [(usize, usize); 16] = + [(0, 0), (1, 0), (1, 1), (0, 1), (0, 2), (0, 3), (1, 3), (1, 2), (2, 2), (2, 3), (3, 3), (3, 2), (3, 1), (2, 1), (2, 0), (3, 0)]; + +/// 2x2 macroblock traversal order within a super block (Figure 2.6). +/// Each entry is `(mx, my)` from bottom-left (0,0). +pub const MB_HILBERT: [(usize, usize); 4] = [(0, 0), (0, 1), (1, 1), (1, 0)]; + +/// Zig-zag order mapping (natural raster index ci -> zig-zag index zzi, Figure 2.8). +pub const ZIGZAG: [usize; 64] = [ + 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, + 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63, +]; + +/// Inverse zig-zag order mapping (zig-zag index zzi -> natural raster index ci). +pub const INV_ZIGZAG: [usize; 64] = [ + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, + 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +]; + +/// 16-bit sine and cosine approximations for the 1D IDCT (Table 7.65). +pub const C1: i32 = 64277; +pub const C2: i32 = 60547; +pub const C3: i32 = 54491; +pub const C4: i32 = 46341; +pub const C5: i32 = 36410; +pub const C6: i32 = 25080; +pub const C7: i32 = 12785; + +/// Default loop filter limit values (Appendix B.2). +pub const DEFAULT_LFLIMS: [u8; 64] = [ + 30, 25, 20, 20, 15, 15, 14, 14, 13, 13, 12, 12, 11, 11, 10, 10, 9, 9, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, + 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +]; + +/// Default AC scale values for each qi value (Appendix B.3). +pub const DEFAULT_ACSCALE: [u16; 64] = [ + 500, 450, 400, 370, 340, 310, 285, 265, 245, 225, 210, 195, 185, 180, 170, 160, 150, 145, 135, 130, 125, 115, 110, 107, 100, 96, 93, 89, 85, 82, + 75, 74, 70, 68, 64, 60, 57, 56, 52, 50, 49, 45, 44, 43, 40, 38, 37, 35, 33, 32, 30, 29, 28, 25, 24, 22, 21, 19, 18, 17, 15, 13, 12, 10, +]; + +/// Default DC scale values for each qi value (Appendix B.3). +pub const DEFAULT_DCSCALE: [u16; 64] = [ + 220, 200, 190, 180, 170, 170, 160, 160, 150, 150, 140, 140, 130, 130, 120, 120, 110, 110, 100, 100, 90, 90, 90, 80, 80, 80, 70, 70, 70, 60, 60, + 60, 60, 50, 50, 50, 50, 40, 40, 40, 40, 40, 30, 30, 30, 30, 30, 30, 30, 20, 20, 20, 20, 20, 20, 20, 20, 10, 10, 10, 10, 10, 10, 10, +]; + +/// Default base matrices (Appendix B.3). +/// 0: Intra Y, 1: Intra Cb/Cr, 2: Inter all planes. +pub const DEFAULT_BMS: [[u8; 64]; 3] = [ + [ + 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, + 58, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99, + ], + [ + 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, + ], + [ + 16, 16, 16, 20, 24, 28, 32, 40, 16, 16, 20, 24, 28, 32, 40, 48, 16, 20, 24, 28, 32, 40, 48, 64, 20, 24, 28, 32, 40, 48, 64, 64, 24, 28, 32, + 40, 48, 64, 64, 64, 28, 32, 40, 48, 64, 64, 64, 96, 32, 40, 48, 64, 64, 64, 96, 128, 40, 48, 64, 64, 64, 96, 128, 128, + ], +]; + +/// Serialized canonical pre-order bit representations of the 80 default VP3.1 Huffman trees (Appendix B.4). +pub const DEFAULT_HUFFMAN_SETUP_BYTES: &[u8] = &[ + 0x1A, 0x66, 0x27, 0x7C, 0x85, 0x1B, 0xC1, 0xD5, 0x13, 0x7B, 0x72, 0xCC, 0x45, 0xBA, 0x8E, 0x37, 0xC0, 0x7E, 0xE5, 0x12, 0x44, 0xBD, 0xC1, 0xB1, + 0x92, 0xFA, 0xD5, 0x52, 0x34, 0xCC, 0xAE, 0xC5, 0xD8, 0x84, 0x09, 0xC8, 0xC1, 0xED, 0x1D, 0x4C, 0x97, 0xCE, 0x61, 0xB5, 0xAB, 0x0D, 0x8C, 0xAA, + 0x52, 0xBC, 0xFB, 0x77, 0x0F, 0xC9, 0x3B, 0x88, 0x69, 0x99, 0x5D, 0x8B, 0xB1, 0x04, 0x2F, 0x91, 0x47, 0x86, 0xAB, 0x50, 0x6C, 0x64, 0xBC, 0x7E, + 0x72, 0xEE, 0x62, 0x57, 0x47, 0xB4, 0x79, 0x27, 0x09, 0xF7, 0x55, 0x48, 0x41, 0x8A, 0xE6, 0xA9, 0xF7, 0x55, 0x48, 0xAE, 0xC6, 0x82, 0x33, 0x94, + 0xD2, 0x83, 0xDA, 0x3C, 0xEB, 0xB9, 0x21, 0xC0, 0xCA, 0xD6, 0x63, 0x6F, 0x9C, 0x3F, 0x8A, 0xF0, 0xBC, 0x12, 0xF3, 0xB7, 0xFC, 0x27, 0x1D, 0xA6, + 0x1E, 0xD1, 0xE7, 0x52, 0x44, 0xC6, 0x02, 0xEA, 0xD6, 0x66, 0x53, 0x50, 0x6B, 0xBE, 0x19, 0x2D, 0x21, 0x47, 0xF6, 0x81, 0x7A, 0x14, 0xF1, 0xB1, + 0xCC, 0xBB, 0x23, 0x40, 0xEE, 0x50, 0x7B, 0x47, 0x9D, 0x72, 0x9B, 0x6D, 0x77, 0xB0, 0x57, 0x05, 0x2A, 0x8C, 0x08, 0xBE, 0x24, 0xFF, 0x8B, 0x45, + 0xAC, 0x72, 0x0F, 0xB8, 0x44, 0x3B, 0x9B, 0x5F, 0xEE, 0x21, 0x69, 0x1B, 0x0C, 0xC5, 0x95, 0xA0, 0x37, 0x4E, 0x4A, 0xE4, 0x50, 0xF7, 0x6F, 0x3A, + 0x92, 0xF5, 0x54, 0x95, 0x08, 0xF3, 0x38, 0x4E, 0x95, 0xAC, 0xD8, 0x2E, 0x37, 0x8A, 0x11, 0x5D, 0x81, 0xA4, 0x81, 0xC9, 0xE2, 0x87, 0xBB, 0x75, + 0xDF, 0xFF, 0x64, 0xC6, 0xF2, 0xD8, 0x29, 0x07, 0xB3, 0xC0, 0xB4, 0xEB, 0x3B, 0x8E, 0x2C, 0x56, 0x63, 0x0F, 0x80, 0xCA, 0x8E, 0x46, 0x8D, 0x44, + 0xD2, 0xC9, 0xB5, 0xFF, 0xD4, 0xA5, 0xB9, 0xD9, 0x1C, 0x58, 0x7C, 0x1F, 0x27, 0x04, 0xD2, 0xC9, 0xB4, 0x78, 0x2D, 0xE0, 0x33, 0xEA, 0xE8, 0x16, + 0x56, 0x04, 0x5A, 0x63, 0xC9, 0x95, 0xFF, 0xD4, 0xA5, 0xB9, 0x09, 0xAD, 0x1E, 0xBC, 0xEC, 0x06, 0xD4, 0x45, 0xFF, 0x03, 0xD8, 0xF9, 0x7D, 0x09, + 0xB9, 0x84, 0xEC, 0xFA, 0x5B, 0x60, 0xAD, 0x70, 0x26, 0x96, 0x4D, 0x74, 0xC5, 0x01, 0xE6, 0x4E, 0xEF, 0x55, 0x48, 0x80, 0x24, 0xD7, 0xEB, 0xDC, + 0xBD, 0x4E, 0x26, 0x97, 0x6A, 0x0D, 0xCE, 0xB3, 0x61, 0x12, 0xD4, 0x37, 0x0B, 0x2B, 0x0D, 0x3F, 0xC5, 0x1E, 0x47, 0x7E, 0x70, 0xAA, 0x92, 0x94, + 0x05, 0xD1, 0x9D, 0x64, 0xC4, 0xA3, 0x5F, 0x85, 0x95, 0x8B, 0xC9, 0xC9, 0xA5, 0xDA, 0x47, 0x9D, 0xB8, 0x73, 0x10, 0x87, 0x71, 0xEE, 0x6C, 0x1F, + 0xE9, 0x6D, 0x45, 0x28, 0x08, 0xAE, 0x70, 0xC5, 0xEB, 0x59, 0x45, 0x95, 0x8F, 0x24, 0x5F, 0xDB, 0x77, 0x21, 0x36, 0xD4, 0x7D, 0x98, 0x8C, 0xC3, + 0xA1, 0x3F, 0xFA, 0x64, 0xB6, 0x1A, 0x8A, 0x50, 0x23, 0x84, 0x59, 0x59, 0xBA, 0xF3, 0xED, 0x49, 0xE6, 0x7E, 0xDA, 0x84, 0x44, 0xB9, 0xB0, 0xE8, + 0x5A, 0x64, 0xF7, 0x4E, 0x0B, 0x98, 0xF8, 0x91, 0xCF, 0x75, 0x15, 0x52, 0x2C, 0xAC, 0x5F, 0x28, 0x7D, 0xEF, 0x80, 0xDA, 0x89, 0xFF, 0xD7, 0xA6, + 0x78, 0x46, 0x22, 0x90, 0x65, 0xC3, 0x14, 0xDC, 0xDA, 0x2E, 0x3B, 0xD3, 0x78, 0x60, 0x0B, 0xEB, 0x59, 0xA8, 0x80, 0xEA, 0x1E, 0x1B, 0x7C, 0xBA, + 0xA1, 0x4E, 0x2B, 0x5B, 0x9E, 0x72, 0x76, 0x88, 0xF4, 0x95, 0x44, 0xD2, 0x47, 0xF9, 0xA6, 0x46, 0x13, 0xE6, 0x17, 0xCE, 0xAE, 0xC0, 0x87, 0xF3, + 0xA7, 0x71, 0x6D, 0x8A, 0xE7, 0xD0, 0x0A, 0x6A, 0x69, 0x68, 0x70, 0xE5, 0x18, 0x4D, 0x2B, 0xDA, 0x24, 0xF3, 0x5C, 0x8C, 0x37, 0xCC, 0x1A, 0xB9, + 0x86, 0xF6, 0x93, 0x95, 0xD8, 0xC6, 0xE0, 0x23, 0xDB, 0xF7, 0x07, 0x71, 0x02, 0x67, 0xB4, 0x4B, 0x27, 0x9D, 0x54, 0xA7, 0x33, 0x27, 0xD0, 0x2D, + 0x61, 0xB8, 0x0F, 0x3B, 0x36, 0x0A, 0x26, 0xF6, 0x59, 0x22, 0x6B, 0x0D, 0xED, 0xE7, 0x2B, 0xC5, 0x66, 0x60, 0xE5, 0xD4, 0x7A, 0x64, 0xB8, 0xFF, + 0x8F, 0x8A, 0xA9, 0x5A, 0xC2, 0x00, 0xFA, 0xF6, 0x30, 0x13, 0xE4, 0xDC, 0x6B, 0xDA, 0x2E, 0x9C, 0xC2, 0x2C, 0xAD, 0x73, 0x01, 0xE1, 0x2B, 0x62, + 0x89, 0xBD, 0x92, 0x3D, 0x0B, 0x59, 0xBF, 0xE1, 0x55, 0x22, 0x97, 0xC4, 0x6F, 0x3B, 0xFC, 0x9D, 0xC6, 0x68, 0x2C, 0x15, 0xDC, 0xDD, 0x80, 0x6A, + 0x4C, 0x6D, 0x47, 0xB2, 0xC9, 0x13, 0x4E, 0x8B, 0x59, 0x39, 0x84, 0xC6, 0xFA, 0x85, 0x54, 0x8C, 0xB9, 0x3A, 0xCE, 0x13, 0xFC, 0x6E, 0x0E, 0x11, + 0x84, 0xC5, 0x0D, 0xB5, 0xF6, 0x5D, 0x3B, 0xB1, 0x5D, 0xA4, 0x1B, 0x97, 0xCE, 0x12, 0x79, 0x16, 0x1F, 0x08, 0x2A, 0x52, 0x46, 0xEF, 0x0B, 0x43, + 0xF6, 0x29, 0x3C, 0xAD, 0x63, 0x89, 0xC7, 0x2E, 0xA2, 0x43, 0x73, 0x70, 0xCC, 0x1A, 0x50, 0xDB, 0x5F, 0x66, 0x97, 0x2B, 0xFE, 0x14, 0xB8, 0x9C, + 0x62, 0xCD, 0xA2, 0x24, 0x64, 0x84, 0xD2, 0xED, 0xAD, 0xC7, 0x37, 0x9D, 0xFB, 0xE0, 0xFA, 0xD5, 0x95, 0x82, 0x88, 0x70, 0xFF, 0x71, 0x97, 0x50, + 0x54, 0x2A, 0xA4, 0x3B, 0x68, 0x09, 0xA5, 0xDA, 0x4D, 0x68, 0xE6, 0xE1, 0x9C, 0x37, 0xC0, 0x3E, 0xB4, 0xFC, 0xF5, 0x1C, 0x5D, 0x58, 0x56, 0x79, + 0x84, 0xED, 0xCC, 0xB1, 0xE0, 0x52, 0x22, 0x50, 0x0D, 0xA6, 0x97, 0x59, 0x34, 0x85, 0x7F, 0x47, 0x07, 0xB9, 0x78, 0xB4, 0xC3, 0xBE, 0x47, 0xD6, + 0x2B, 0x31, 0x67, 0x1F, 0xE4, 0x09, 0xEE, 0x6F, 0x50, 0x59, 0x5D, 0x4A, 0x77, 0x09, 0xEE, 0x23, 0x04, 0xCD, 0xB5, 0x97, 0x49, 0x32, 0x85, 0xC1, + 0x7F, 0xBE, 0x0E, 0x85, 0x19, 0xE1, 0xDA, 0xDF, 0x8E, 0x4C, 0x62, 0xFE, 0x01, 0x55, 0x27, 0x22, 0x4C, 0x98, 0x63, 0xE4, 0x06, 0xEE, 0x0F, 0x62, + 0xB4, 0x75, 0xF2, 0x17, 0x73, 0x88, 0xCA, 0x01, 0xB6, 0xB3, 0x69, 0x2E, 0x77, 0xAE, 0xFD, 0x65, 0x62, 0xAA, 0x48, 0x56, 0xBD, 0x9F, 0x72, 0x07, + 0x0F, 0xA3, 0x1E, 0x2E, 0xFD, 0x65, 0x67, 0x45, 0xF2, 0x76, 0xE4, 0x61, 0x88, 0x34, 0x6D, 0xAC, 0xD9, 0xCA, 0xA3, 0x28, 0x85, 0x54, 0xB7, 0x01, + 0x9B, 0x46, 0xDA, 0xE5, 0x8C, 0xB7, 0x7D, 0x09, 0x03, 0x87, 0x85, 0xEC, 0x14, 0x4D, 0xF8, 0x8A, 0xC5, 0x69, 0x3B, 0x3A, 0x5A, 0xF6, 0x74, 0x7C, + 0x88, 0x2A, 0x52, 0xE0, 0x7A, 0x31, 0x1B, 0x6A, 0xC9, 0xA6, 0x74, 0x61, 0x7F, 0x76, 0x1B, 0xA1, 0x56, 0xB5, 0x3D, 0xC4, 0x68, 0xBA, 0x1E, 0x4B, + 0x20, 0x9B, 0xFF, 0xB9, 0x07, 0x0F, 0x35, 0xDD, 0x3D, 0xE6, 0x27, 0x24, 0x4D, 0xA8, 0x86, 0x06, 0x75, 0x8B, 0x29, 0x55, 0x91, 0x73, 0x43, 0xA7, + 0x61, 0x34, 0xB2, 0x7B, 0x1F, 0xE7, 0xD8, 0x5A, 0x1F, 0x10, 0xF9, 0xC3, 0x1B, 0xCC, 0xB7, 0x3F, 0x3B, 0x47, 0xAF, 0x33, 0x8B, 0x2B, 0x5C, 0x68, + 0xE9, 0x10, 0x26, 0x97, 0x69, 0x3D, 0xA3, 0x02, 0x9A, 0x8C, 0xE0, 0xB4, 0x5A, 0xBE, 0x03, 0xE7, 0x1F, 0xB7, 0x9C, 0x0D, 0x14, 0x12, 0x12, 0xB6, + 0x9B, 0x5F, 0x7C, 0xC2, 0xE0, 0x47, 0x17, 0x7C, 0xE5, 0x59, 0x65, 0x4A, 0x58, 0xB3, 0x75, 0x08, 0x7C, 0xCB, 0x0A, 0x55, 0x1F, 0xBA, 0x86, 0x01, + 0x73, 0x1E, 0x1B, 0xD6, 0x59, 0x69, 0x78, 0x12, 0xA6, 0x6D, 0xAC, 0x9A, 0x47, 0x9F, 0x27, 0x8E, 0xD1, 0x3D, 0xA2, 0x70, 0xFA, 0xEA, 0x55, 0x1C, + 0xB2, 0x0D, 0x12, 0xA6, 0x6D, 0xAC, 0x9E, 0xC6, 0xFE, 0xF0, 0x76, 0x89, 0x46, 0x7E, 0x1D, 0x61, 0xC2, 0xDB, 0x0A, 0xE0, 0x6E, 0x63, 0x0C, 0xE2, + 0x07, 0xCF, 0xF9, 0x53, 0x50, 0xB5, 0x0C, 0xE3, 0xB3, 0xDA, 0x06, 0x63, 0x49, 0x9B, 0x6B, 0x2C, 0x99, 0x3A, 0xBE, 0xB2, 0xC5, 0xDE, 0x1C, 0x18, + 0xE0, 0x8A, 0x3D, 0xC6, 0xE4, 0xFF, 0xAE, 0xE5, 0x05, 0x45, 0x20, 0x64, 0x36, 0xD5, 0x33, 0x4C, 0xE5, 0xA1, 0x8E, 0x1D, 0xBA, 0x8A, 0xB2, 0xC4, + 0x3F, 0x1E, 0x23, 0x3D, 0x92, 0xF7, 0x16, 0x8D, 0xD0, 0xAD, 0x17, 0xA8, 0x19, 0x34, 0xCC, 0xDB, 0x5C, 0x58, 0x4D, 0x3F, 0x68, 0x15, 0xD8, 0x53, + 0x50, 0x8B, 0xE3, 0xA9, 0x39, 0x1F, 0x92, 0xFB, 0x74, 0x6F, 0x38, 0x15, 0x52, 0x3A, 0xBF, 0x84, 0xE6, 0x18, 0xF2, 0x3E, 0xB4, 0x21, 0xA3, 0xBF, + 0xD0, 0x0C, 0xD1, 0x06, 0xDA, 0xA4, 0x4D, 0x2E, 0x91, 0xE5, 0xE9, 0x65, 0x65, 0xDE, 0x6E, 0x29, 0xDC, 0xF3, 0x85, 0xBF, 0x01, 0x16, 0x50, 0xDD, + 0x01, 0xCA, 0xF0, 0x90, 0x4D, 0x2B, 0x6D, 0x74, 0xCE, 0x3C, 0x1F, 0xBB, 0x63, 0x41, 0x65, 0x64, 0xEF, 0x7A, 0xA8, 0x52, 0xF8, 0x62, 0x48, 0x36, + 0xD5, 0x2B, 0x49, 0xB3, 0xCA, 0x88, 0x5B, 0xB8, 0x75, 0xE8, 0x7E, 0x61, 0x1A, 0x2B, 0xFC, 0x57, 0x60, 0x9F, 0x95, 0xAB, 0xBB, 0x41, 0x50, 0xDE, + 0xA5, 0x30, 0x07, 0x6B, 0xA2, 0xE0, 0xB7, 0xA7, 0xDE, 0x88, 0x4B, 0xC9, 0x0C, 0xCD, 0xB5, 0x4A, 0xD2, 0x6C, 0x98, 0xE1, 0xFF, 0x87, 0x29, 0xD4, + 0x46, 0xB2, 0xB1, 0xBD, 0x4A, 0x50, 0xF0, 0x11, 0xF4, 0x24, 0x5E, 0xC1, 0x8B, 0x21, 0xB6, 0xA9, 0x9A, 0x67, 0x2F, 0xFE, 0xC0, 0x39, 0x4E, 0xBA, + 0x82, 0xDF, 0xAB, 0x78, 0xB1, 0x17, 0x63, 0xCA, 0x55, 0x38, 0x24, 0x2F, 0x4A, 0xC0, 0x6D, 0xA9, 0x94, 0xCD, 0x33, 0xC6, 0xE4, 0xF6, 0x88, 0x51, + 0x73, 0x00, 0xF5, 0xF2, 0x8F, 0xD6, 0x56, 0x46, 0xEF, 0xAD, 0xC7, 0x95, 0x29, 0x16, 0xFD, 0x23, 0x9F, 0x48, 0x10, 0xAC, 0xAC, 0x8C, 0x17, 0x93, + 0x32, 0x69, 0x9B, 0x03, 0x6D, 0x71, 0xBB, 0xFE, 0xA2, 0x1D, 0xA7, 0x4B, 0x47, 0x1B, 0x88, 0xCE, 0x42, 0xE9, 0x8B, 0xCC, 0x19, 0x62, 0x69, 0x9B, + 0x6D, 0x68, 0xB7, 0xD9, 0x15, 0x40, 0x52, 0x3A, 0xEE, 0xC5, 0x69, 0x49, 0xFF, 0xF8, 0x85, 0xC4, 0x4D, 0xFC, 0x14, 0x8F, 0x61, 0x34, 0xA3, 0xA8, + 0x09, 0xD8, 0x70, 0x7F, 0x97, 0xC3, 0x7B, 0x8C, 0x59, 0xF3, 0x59, 0x60, 0x44, 0x48, 0x4A, 0xDA, 0x6D, 0x63, 0xEF, 0xCB, 0xD6, 0xD4, 0x2A, 0xA4, + 0xB8, 0xCB, 0xBF, 0x02, 0x30, 0x4D, 0x2B, 0x6D, 0x74, 0x93, 0x34, 0x54, 0x5F, 0xF0, 0x7E, 0xEB, 0xD7, 0x0C, 0x31, 0x41, 0xB9, 0x6D, 0x8A, 0xC8, + 0x79, 0x9C, 0x55, 0x48, 0x46, 0x48, 0x4A, 0x69, 0x33, 0x6D, 0x73, 0xA2, 0xF7, 0x2C, 0x70, 0x21, 0xF3, 0xE0, 0x76, 0xCA, 0x2F, 0xED, 0x1E, 0xF5, + 0xC6, 0xE2, 0x7B, 0xAC, 0x57, 0x00, 0x0A, 0x31, 0xBF, 0xF4, 0xFC, 0xC0, 0xA6, 0xA1, 0x6A, 0xEF, 0x01, 0x20, 0xCC, 0xD2, 0x66, 0xDA, 0xCB, 0x96, + 0x11, 0x23, 0xEE, 0xC2, 0xB4, 0x2F, 0x7A, 0x38, 0xFB, 0x71, 0xB9, 0xD0, 0xC4, 0xC9, 0x31, 0xA6, 0x6D, 0xB5, 0x95, 0x46, 0x09, 0x2F, 0x47, 0xCA, + 0x9A, 0x88, 0x0F, 0x3E, 0xAC, 0xB0, 0x9F, 0xB7, 0xB7, 0x16, 0xF0, 0x7F, 0x14, 0x23, 0x71, 0x3C, 0x9F, 0x39, 0x89, 0x55, 0x24, 0x08, 0x4F, 0x7F, + 0xB4, 0xB2, 0xB1, 0xDF, 0x51, 0xB8, 0x0A, 0x03, 0x6D, 0x59, 0x34, 0xCF, 0x16, 0x13, 0x2F, 0x96, 0xEF, 0x06, 0xE3, 0xF4, 0xEB, 0x81, 0xA6, 0x6D, + 0xB5, 0x30, 0xA1, 0x96, 0x37, 0xCD, 0x24, 0x68, 0x0E, 0x4F, 0x65, 0xFA, 0x12, 0xAA, 0x44, 0x4F, 0x2D, 0xAD, 0x61, 0xDF, 0x5C, 0x08, 0x12, 0x38, + 0x94, 0x85, 0xC9, 0xD7, 0xFD, 0xEE, 0x55, 0x49, 0x65, 0x64, 0x42, 0x73, 0xE1, 0xB6, 0xAA, 0x18, 0x5E, 0xB8, 0xCB, 0x16, 0x99, 0xFB, 0x33, 0xCB, + 0x63, 0x07, 0x5E, 0xF1, 0x4A, 0xA7, 0xD6, 0x82, 0x80, 0x36, 0xD5, 0x2B, 0x49, 0xA4, 0xCE, 0x3C, 0x79, 0x21, 0xBE, 0xE4, 0x0F, 0xDD, 0xB0, 0x65, + 0x10, 0x9F, 0xCB, 0x15, 0xEE, 0x29, 0xA9, 0x03, 0x87, 0x50, 0x8F, 0x13, 0xF2, 0xAE, 0xC0, 0x5F, 0x1D, 0xDF, 0x2D, 0x50, 0x60, 0x48, 0x25, 0x69, + 0x31, 0xB6, 0xB9, 0xE5, 0x8C, 0x4D, 0xDE, 0xBB, 0xFC, 0x53, 0x50, 0xEF, 0xE7, 0x56, 0xC0, 0x3D, 0x23, 0x8B, 0x95, 0x95, 0x9E, 0x6E, 0x42, 0xFC, + 0xBD, 0x23, 0x06, 0x23, 0x6D, 0x65, 0x26, 0x69, 0x9E, 0x57, 0x13, 0xD1, 0xC0, 0x59, 0x59, 0x17, 0x50, 0xA9, 0xA8, 0x23, 0x7C, 0xB8, 0xBC, 0x32, + 0x99, 0xA6, 0x72, 0x8D, 0xB5, 0xC7, 0x09, 0x1C, 0xAD, 0xA2, 0x03, 0xCD, 0xDE, 0x8F, 0xE7, 0xEF, 0x80, 0x8D, 0xCA, 0x47, 0xD3, 0xFA, 0xAA, 0x91, + 0xBF, 0x90, 0x10, 0x94, 0x77, 0x11, 0xC5, 0x8A, 0xC2, 0xE4, 0xAB, 0xC6, 0x99, 0xB6, 0xD4, 0xC2, 0x66, 0x58, 0xFF, 0x6F, 0x41, 0xBC, 0x5E, 0x82, + 0xD7, 0xFF, 0x77, 0xC7, 0x85, 0x95, 0x82, 0x55, 0xC3, 0x2C, 0x5A, 0x66, 0x6D, 0xAA, 0x66, 0x17, 0xCF, 0x47, 0x29, 0x3A, 0x20, 0x47, 0x0A, 0xAA, + 0x4A, 0x51, 0x9B, 0xBB, 0xEA, 0x22, 0x02, 0x47, 0x16, 0x15, 0xB9, 0x25, 0x0B, 0xA6, 0x61, 0x7F, 0xE3, 0x6D, 0x4C, 0xB1, 0x69, 0x9F, 0xCA, 0x16, + 0xCF, 0xE1, 0xEC, 0x35, 0x15, 0x52, 0x80, 0x8C, 0x59, 0x58, 0xE3, 0x7E, 0xC9, 0x5C, 0x89, 0x94, 0x4E, 0x6D, 0xAB, 0xFF, 0x86, 0x58, 0xB4, 0xCC, + 0xBA, 0xD6, 0x17, 0xF5, 0xE9, 0x13, 0xC9, 0x21, 0x10, 0x3C, 0xB5, 0x4D, 0x41, 0x0D, 0xCE, 0x7F, 0x27, 0x30, 0x24, 0x13, 0x34, 0xCC, 0xDB, 0x59, + 0x72, 0xC7, 0xBB, 0x0A, 0xF7, 0x0A, 0x23, 0x45, 0x7F, 0xCE, 0x1D, 0x7A, 0x0E, 0xBF, 0x4E, 0x48, 0x0D, 0xB5, 0x32, 0x99, 0xA6, 0x72, 0xB1, 0xC2, + 0xFB, 0xAA, 0x53, 0x00, 0xF1, 0xCF, 0xC2, 0x88, 0xAD, 0xDC, 0xB1, 0xC7, 0xAA, 0xCE, 0xE3, 0x84, 0x53, 0x51, 0x0F, 0xA5, 0xBC, 0xF8, 0x40, 0x46, + 0xA1, 0x21, 0x28, 0x69, 0x9B, 0x6D, 0x4C, 0x26, 0x65, 0x8D, 0xF7, 0x6E, 0x1F, 0xF7, 0xC5, 0x8A, 0xC9, 0xFE, 0x75, 0x10, 0x46, 0x01, 0x96, 0x2D, + 0x33, 0x36, 0xD5, 0x33, 0x0B, 0xEE, 0x97, 0xF4, 0xFF, 0x72, 0xB2, 0xB5, 0x35, 0x08, 0x7C, 0x80, 0xDD, 0x12, 0x45, 0x16, 0xBD, 0x70, 0xEB, 0xB1, + 0xE9, 0xC9, 0x42, 0xD3, 0xF9, 0x83, 0x2C, 0x5A, 0x66, 0x6D, 0xAA, 0xE6, 0x17, 0xCF, 0xDE, 0xE8, 0x2A, 0x29, 0x78, 0xE2, 0xC2, 0x35, 0x6E, 0x92, + 0xFC, 0x85, 0x14, 0x83, 0x78, 0xC9, 0x21, 0x88, 0x80, 0x70, 0x3A, 0x0C, 0x70, 0x67, 0x91, 0x6C, 0xEB, 0xEE, 0x4C, 0xF8, 0xD7, 0x47, 0xFB, 0x72, + 0xA3, 0xBF, 0x4B, 0x2B, 0x79, 0x2A, 0xAA, 0x46, 0xF1, 0x92, 0x43, 0x11, 0x00, 0xE0, 0x74, 0x18, 0xE0, 0xCF, 0x22, 0xD9, 0xD7, 0xDC, 0x99, 0xF1, + 0xAE, 0x8F, 0xF6, 0xE5, 0x47, 0x7E, 0x96, 0x56, 0xF2, 0x55, 0x54, 0x8D, 0xE3, 0x24, 0x86, 0x22, 0x01, 0xC0, 0xE8, 0x31, 0xC1, 0x9E, 0x45, 0xB3, + 0xAF, 0xB9, 0x33, 0xE3, 0x5D, 0x1F, 0xED, 0xCA, 0x8E, 0xFD, 0x2C, 0xAD, 0xE4, 0xAA, 0xA9, 0x15, 0x52, 0x70, 0x9F, 0xA8, 0x01, 0x12, 0xF0, 0x4C, + 0xD3, 0x33, 0x6D, 0x65, 0xCA, 0x46, 0x38, 0x43, 0xE2, 0xCA, 0xC5, 0xBC, 0xBE, 0xF4, 0x5D, 0xD9, 0x1D, 0x1F, 0xEE, 0x0B, 0x63, 0x86, 0xA5, 0x2F, + 0x5C, 0xBF, 0xA0, 0x59, 0x5C, 0x07, 0x9B, 0x85, 0xC9, 0x0C, 0x18, 0x8C, 0xA6, 0x69, 0x99, 0xB6, 0xB2, 0xDF, 0x3F, 0x07, 0x7F, 0x22, 0xE8, 0x0F, + 0xE7, 0xE7, 0xCA, 0x55, 0x2C, 0xAC, 0x1F, 0x51, 0x17, 0xAD, 0xE1, 0x40, 0x70, 0x48, 0x5E, 0x94, 0x69, 0x9B, 0x6D, 0x49, 0x99, 0x63, 0x85, 0xDD, + 0xA3, 0x5B, 0xD0, 0x59, 0x59, 0xCA, 0xD7, 0xD3, 0xF8, 0x46, 0xE1, 0x27, 0x6D, 0xFD, 0x20, 0x42, 0x74, 0x7E, 0x94, 0x30, 0x99, 0x96, 0x2B, 0xCD, + 0x33, 0x6D, 0xAD, 0xD4, 0x44, 0xA6, 0xA2, 0x93, 0xC8, 0x81, 0xF4, 0xF4, 0x76, 0xE3, 0x9F, 0x42, 0xBB, 0x23, 0x80, 0x6E, 0x2D, 0x3F, 0x19, 0x62, + 0xD3, 0x32, 0x66, 0x17, 0x9B, 0x6B, 0x74, 0xBD, 0x49, 0x0D, 0x42, 0x14, 0x4F, 0x56, 0x57, 0x4A, 0xA4, 0x03, 0x79, 0x1E, 0x01, 0xF2, 0x65, 0xF7, + 0x4E, 0xB4, 0x6B, 0xA3, 0xFD, 0x8C, 0x70, 0x67, 0x94, 0xBC, 0xBB, 0x70, 0xA3, 0xA8, 0xC8, 0x10, 0xA3, 0x24, 0x09, 0x45, 0xD6, 0xB0, 0xBC, 0x99, + 0x44, 0xE7, 0x7D, 0x3F, 0xFA, 0xC5, 0x60, 0xDB, 0x57, 0x3C, 0x19, 0x62, 0xD3, 0x3D, 0xFD, 0xF2, 0x25, 0x54, 0x95, 0x52, 0x80, 0x8C, 0x59, 0x58, + 0xE3, 0x7E, 0xC9, 0x5C, 0x89, 0x94, 0x4E, 0x6D, 0xAB, 0xFF, 0x86, 0x58, 0xB4, 0xCC, 0xBA, 0xD6, 0x17, 0xF5, 0xE9, 0x13, 0xC9, 0x21, +]; + +/// Macroblock mode scheme mapping (Table 7.19). +/// Schemes 1..=6 give the coding mode for each Huffman code index `mi` (0..=7). +pub const MB_SCHEMES: [[u8; 8]; 7] = [ + [0, 0, 0, 0, 0, 0, 0, 0], // Scheme 0 is bitstream-defined + [3, 4, 2, 0, 1, 5, 6, 7], // Scheme 1 + [3, 4, 0, 2, 1, 5, 6, 7], // Scheme 2 + [3, 2, 4, 0, 1, 5, 6, 7], // Scheme 3 + [3, 2, 0, 4, 1, 5, 6, 7], // Scheme 4 + [0, 3, 4, 2, 1, 5, 6, 7], // Scheme 5 + [0, 5, 3, 4, 2, 1, 6, 7], // Scheme 6 +]; + +/// Table 7.47: DC Predictor weights `[W_L, W_DL, W_D, W_DR]` and divisor `PDIV` +/// indexed by `P[0] | (P[1] << 1) | (P[2] << 2) | (P[3] << 3)`. +pub const DC_PRED_CONFIG: [([i32; 4], i32); 16] = [ + ([0, 0, 0, 0], 1), // 0: none + ([1, 0, 0, 0], 1), // 1: L + ([0, 1, 0, 0], 1), // 2: DL + ([1, 0, 0, 0], 1), // 3: L + DL + ([0, 0, 1, 0], 1), // 4: D + ([1, 0, 1, 0], 2), // 5: L + D + ([0, 0, 1, 0], 1), // 6: DL + D + ([29, -26, 29, 0], 32), // 7: L + DL + D + ([0, 0, 0, 1], 1), // 8: DR + ([75, 0, 0, 53], 128), // 9: L + DR + ([0, 1, 0, 1], 2), // 10: DL + DR + ([75, 0, 0, 53], 128), // 11: L + DL + DR + ([0, 0, 1, 0], 1), // 12: D + DR + ([75, 0, 0, 53], 128), // 13: L + D + DR + ([0, 3, 10, 3], 16), // 14: DL + D + DR + ([29, -26, 29, 0], 32), // 15: L + DL + D + DR +]; + +/// Table 7.42: Huffman Table Group by token index `ti`. +#[inline] +pub fn huffman_group(ti: usize) -> usize { + match ti { + 0 => 0, + 1..=5 => 1, + 6..=14 => 2, + 15..=27 => 3, + _ => 4, + } +} diff --git a/crates/video/tests/theora.rs b/crates/video/tests/theora.rs new file mode 100644 index 0000000000..4ce5b6c0e6 --- /dev/null +++ b/crates/video/tests/theora.rs @@ -0,0 +1,266 @@ +//! Clean-room pure-Rust Theora video tests (headers, codec roundtrips, hostile inputs, and FFmpeg oracle). + +use craft_video::frame::VideoFrame; +use craft_video::theora::{ColorSpace, Decoder, Encoder, EncoderConfig, Error, IdentificationHeader, Picture, PixelFormat, SetupHeader}; +use std::process::Command; + +fn test_picture(w: usize, h: usize) -> Picture { + let mut y = vec![0u8; w * h]; + let cw = w.div_ceil(2); + let ch = h.div_ceil(2); + let mut u = vec![128u8; cw * ch]; + let mut v = vec![128u8; cw * ch]; + + for r in 0..h { + for c in 0..w { + let val = ((r * 255 / h) ^ (c * 255 / w)) as u8; + y[r * w + c] = val; + } + } + for r in 0..ch { + for c in 0..cw { + u[r * cw + c] = (128 + ((r as i32 - ch as i32 / 2) * 2)) as u8; + v[r * cw + c] = (128 + ((c as i32 - cw as i32 / 2) * 2)) as u8; + } + } + + Picture { + width: w as u32, + height: h as u32, + pic_width: w as u32, + pic_height: h as u32, + pic_x: 0, + pic_y: 0, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + keyframe: true, + pts: Some(0), + y, + u, + v, + y_stride: w, + uv_stride: cw, + } +} + +fn psnr(a: &[u8], b: &[u8]) -> f64 { + assert_eq!(a.len(), b.len()); + let mse = a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(*y)).powi(2)).sum::() / a.len().max(1) as f64; + if mse == 0.0 { 99.0 } else { 10.0 * (255.0f64 * 255.0 / mse).log10() } +} + +#[test] +fn test_theora_headers_roundtrip() { + let cfg = EncoderConfig { + width: 320, + height: 240, + pic_width: 320, + pic_height: 240, + pic_x: 0, + pic_y: 0, + fps_num: 30, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Rec470M, + quality: 48, + keyframe_distance: 64, + }; + let enc = Encoder::new(cfg).expect("encoder"); + let (id_pkt, comm_pkt, setup_pkt) = enc.headers(); + + assert_eq!(id_pkt.len(), 42); + assert_eq!(&id_pkt[0..7], &[0x80, b't', b'h', b'e', b'o', b'r', b'a']); + assert_eq!(&comm_pkt[0..7], &[0x81, b't', b'h', b'e', b'o', b'r', b'a']); + assert_eq!(&setup_pkt[0..7], &[0x82, b't', b'h', b'e', b'o', b'r', b'a']); + + let dec = Decoder::from_headers(&id_pkt, &comm_pkt, &setup_pkt).expect("decoder from headers"); + assert_eq!(dec.info.frame_width, 320); + assert_eq!(dec.info.frame_height, 240); + assert_eq!(dec.info.pic_width, 320); + assert_eq!(dec.info.pic_height, 240); + assert_eq!(dec.info.fps_num, 30); + assert_eq!(dec.info.fps_den, 1); + assert_eq!(dec.info.pixel_format, PixelFormat::Yuv420); + assert_eq!(dec.info.color_space, ColorSpace::Rec470M); +} + +#[test] +fn test_theora_encode_decode_intra_frame() { + let (w, h) = (64, 64); + let cfg = EncoderConfig { + width: w as u32, + height: h as u32, + pic_width: w as u32, + pic_height: h as u32, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 48, + keyframe_distance: 64, + }; + let mut enc = Encoder::new(cfg).expect("encoder"); + let (id_pkt, comm_pkt, setup_pkt) = enc.headers(); + let mut dec = Decoder::from_headers(&id_pkt, &comm_pkt, &setup_pkt).expect("decoder"); + + let original = test_picture(w, h); + let packet = enc.encode_frame(&original, true).expect("encode"); + assert!(!packet.is_empty()); + + let decoded = dec.decode_packet(&packet).expect("decode"); + assert!(decoded.keyframe); + assert_eq!(decoded.width, w as u32); + assert_eq!(decoded.height, h as u32); + + let p_y = psnr(&original.y, &decoded.y); + let p_u = psnr(&original.u, &decoded.u); + let p_v = psnr(&original.v, &decoded.v); + + assert!(p_y >= 25.0, "Luma PSNR too low: {p_y:.2} dB"); + assert!(p_u >= 30.0, "Chroma U PSNR too low: {p_u:.2} dB"); + assert!(p_v >= 30.0, "Chroma V PSNR too low: {p_v:.2} dB"); +} + +#[test] +fn test_theora_empty_packet_inter_frame() { + let (w, h) = (32, 32); + let cfg = EncoderConfig { + width: w as u32, + height: h as u32, + pic_width: w as u32, + pic_height: h as u32, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 40, + keyframe_distance: 64, + }; + let mut enc = Encoder::new(cfg).expect("encoder"); + let (id_pkt, comm_pkt, setup_pkt) = enc.headers(); + let mut dec = Decoder::from_headers(&id_pkt, &comm_pkt, &setup_pkt).expect("decoder"); + + let pic = test_picture(w, h); + let key_pkt = enc.encode_frame(&pic, true).expect("encode keyframe"); + let first_dec = dec.decode_packet(&key_pkt).expect("decode keyframe"); + assert!(first_dec.keyframe); + + // 0-byte packet is a repeat frame + let repeat_dec = dec.decode_packet(&[]).expect("decode empty packet"); + assert!(!repeat_dec.keyframe); + assert_eq!(first_dec.y, repeat_dec.y); + assert_eq!(first_dec.u, repeat_dec.u); + assert_eq!(first_dec.v, repeat_dec.v); +} + +#[test] +fn test_theora_video_frame_conversion() { + let pic = test_picture(32, 32); + let vf = VideoFrame::try_from(pic).expect("convert to VideoFrame"); + assert_eq!(vf.width(), 32); + assert_eq!(vf.height(), 32); + assert_eq!(vf.planes().len(), 3); +} + +#[test] +fn test_hostile_theora_packets_do_not_panic() { + // 1. Truncated identification header + assert!(IdentificationHeader::parse(&[]).is_err()); + assert!(IdentificationHeader::parse(&[0x80, b't', b'h', b'e', b'o', b'r', b'a']).is_err()); + + // 2. Corrupted setup header + assert!(SetupHeader::parse(&[0x82, b't', b'h', b'e', b'o', b'r', b'a', 0xFF, 0xFF]).is_err()); + + // 3. Decoder on random / fuzzed packets + let (id, comm, setup) = Encoder::new(EncoderConfig::default()).unwrap().headers(); + let mut dec = Decoder::from_headers(&id, &comm, &setup).expect("decoder"); + + // Inter frame before keyframe must fail cleanly + assert!(matches!(dec.decode_packet(&[0x40, 0x00]), Err(Error::MissingReference))); + + // Fuzzed inputs + let fuzz_cases: &[&[u8]] = &[ + &[0x00], + &[0x00, 0x00, 0x00, 0x00], + &[0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF], + &[0x80, 0x00, 0x00], // Header bit set in data packet + ]; + + for case in fuzz_cases { + let _ = dec.decode_packet(case); + } +} + +#[test] +fn test_theora_ffmpeg_oracle_roundtrip() { + let Some(ff) = craft_media_testkit::ffmpeg() else { + return; + }; + let dir = craft_media_testkit::fixture_subdir("theora"); + let (w, h) = (64, 64); + let cfg = EncoderConfig { + width: w as u32, + height: h as u32, + pic_width: w as u32, + pic_height: h as u32, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 45, + keyframe_distance: 64, + }; + let mut enc = Encoder::new(cfg).expect("encoder"); + let (id_pkt, comm_pkt, setup_pkt) = enc.headers(); + + let pic = test_picture(w, h); + let video_pkt = enc.encode_frame(&pic, true).expect("encode"); + + // Write an Ogg Theora file using craft-media PageWriter + let ogv_path = dir.join("cleanroom_test.ogv"); + let mut pw = craft_media::ogg::PageWriter::new(0x12345678); + + let mut file_bytes = Vec::new(); + file_bytes.extend(pw.header(&id_pkt)); + file_bytes.extend(pw.header(&comm_pkt)); + file_bytes.extend(pw.header(&setup_pkt)); + file_bytes.extend(pw.packet(&video_pkt, 1 << 6)); + file_bytes.extend(pw.finish(None)); + + std::fs::write(&ogv_path, &file_bytes).expect("write ogv"); + + // Run ffmpeg to decode our Ogg Theora file to raw YUV + let raw_out = dir.join("ffmpeg_decoded.raw"); + let status = Command::new(&ff) + .args(["-v", "error", "-i", ogv_path.to_str().unwrap(), "-f", "rawvideo", "-pix_fmt", "yuv420p", "-y", raw_out.to_str().unwrap()]) + .status() + .expect("ffmpeg run"); + + assert!(status.success(), "ffmpeg failed to decode our Theora file"); + + let ff_raw = std::fs::read(&raw_out).expect("read ffmpeg output"); + assert_eq!(ff_raw.len(), w * h * 3 / 2); + + // Decode with our pure-Rust decoder + let mut dec = Decoder::from_headers(&id_pkt, &comm_pkt, &setup_pkt).expect("decoder"); + let our_pic = dec.decode_packet(&video_pkt).expect("decode"); + + // FFmpeg outputs top-to-bottom YUV, while Theora Picture is bottom-to-top internal storage + // Convert our Picture to VideoFrame to get top-to-bottom raster! + let vf = VideoFrame::try_from(our_pic).expect("to VideoFrame"); + let our_y = match vf.planes()[0].samples() { + craft_video::frame::Samples::U8(v) => v.as_slice(), + _ => panic!("u8 expected"), + }; + + let ff_y = &ff_raw[0..w * h]; + let p = psnr(ff_y, our_y); + println!("Oracle PSNR against FFmpeg decode: {p:.2} dB"); + assert!(p >= 35.0, "FFmpeg decode differs noticeably: {p:.2} dB"); +} From ada9e97a47f091a5c562f9fd8c1f8528df63897d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Paulo=20Moreira=20Sant=27ana?= Date: Wed, 18 Nov 2026 14:57:21 -0300 Subject: [PATCH 028/130] suite-account: Store::shared refuses an untrusted service before returning a token A row in accounts.json can name any address, or keep a handle after its service was edited in place. shared() now returns Unreadable without the token for those rows. https:// and loopback http:// still succeed. Fixes #2185 --- crates/suite-account/src/accounts.rs | 35 ++++++++++++++ crates/suite-account/src/lib.rs | 21 ++++++-- crates/suite-account/src/tests.rs | 71 ++++++++++++++++++++++++++++ 3 files changed, 122 insertions(+), 5 deletions(-) diff --git a/crates/suite-account/src/accounts.rs b/crates/suite-account/src/accounts.rs index 877848a21d..25f4914171 100644 --- a/crates/suite-account/src/accounts.rs +++ b/crates/suite-account/src/accounts.rs @@ -211,6 +211,41 @@ pub fn normalise(service: &str) -> String { service.trim().trim_end_matches('/').to_owned() } +/// Plain `http://` on loopback, with a numeric port. The host is exactly `127.0.0.1`, `localhost` +/// or `[::1]`; a userinfo prefix in front of another host does not count. The same spelling +/// `craft-update` uses for a local mirror. +fn loopback_http(url: &str) -> bool { + let Some(rest) = url.strip_prefix("http://") else { return false }; + let authority = rest.split(['/', '?', '#']).next().unwrap_or_default(); + let Some((host, port)) = authority.rsplit_once(':') else { return false }; + matches!(host, "127.0.0.1" | "localhost" | "[::1]") && !port.is_empty() && port.parse::().is_ok() +} + +/// Whether a stored deployment address is one a caller may present a token to. +/// +/// `https://` is allowed. Plain `http://` is only allowed on loopback, with a numeric port. Empty +/// is not: there is no deployment to send a token to. A row in `accounts.json` can name any +/// string; this is the gate that stops a caller sending the keychain token to it. +pub fn allowed_service_base(service: &str) -> bool { + service.starts_with("https://") || loopback_http(service) +} + +/// The checks [`crate::Store::shared`] applies before handing a token back. +/// +/// The address has to be one a Craft app may dial ([`allowed_service_base`]). The row's `id` has +/// to still be the handle its own `service` and `user` hash to. The second check is what catches +/// a row whose `service` was edited in place while its `id` was left alone: the address changes, +/// but nothing re-derives the handle, so an address check alone would wave it through. +pub fn validate_target(account: &Account) -> Result<(), String> { + if !allowed_service_base(&account.service) { + return Err("the stored account's service address is not one a Craft app may send a token to".to_owned()); + } + if handle(&account.service, &account.user) != account.id { + return Err("the stored account's service or user no longer matches its handle".to_owned()); + } + Ok(()) +} + /// Just the file's name, for an error a log might show. /// /// The full path sits under a user's profile folder and names them. [`Store::shared`] logs a diff --git a/crates/suite-account/src/lib.rs b/crates/suite-account/src/lib.rs index 88e80c6c61..5421bc4f4e 100644 --- a/crates/suite-account/src/lib.rs +++ b/crates/suite-account/src/lib.rs @@ -13,10 +13,12 @@ //! //! Nothing here is mandatory. An application asks [`Store::shared`] what the suite has to offer and //! gets one of three answers: somebody is signed in, nobody is signed in, or there is an account on -//! file whose token could not be read. The second and third leave the application exactly as it was +//! file this process will not use. The second and third leave the application exactly as it was //! before this crate existed, offering its own sign-in. A machine with no keychain, a locked -//! keychain, a missing folder and an empty suite all land on "nobody is signed in". None of them is -//! an error that stops an application starting. +//! keychain, a missing folder and an empty suite all land on "nobody is signed in". A row whose +//! service is not `https://` or loopback `http://`, or whose handle no longer hashes from its +//! service and user, comes back as unreadable and without the token. None of them is an error that +//! stops an application starting. //! //! [`Store::discard`] clears the keychain entry and then the row, for a session this machine //! should stop holding. [`Store::forget`] clears only the keychain entry, leaving the row for a @@ -126,8 +128,9 @@ pub enum Shared { Session { account: Account, token: Secret }, /// Nobody is signed in here. Offer a sign-in. None, - /// An account is on file and its token could not be read: a locked keychain, a keychain this - /// process may not reach, or an entry somebody deleted by hand. + /// An account is on file and this process will not hand its token back: a locked keychain, a + /// keychain this process may not reach, a service address it will not send a token to, or a + /// row whose handle no longer matches its service and user. /// /// Offer a sign-in. Say why the shared one did not come through. Quietly showing a signed-out /// window would leave somebody wondering where their account went. @@ -235,6 +238,14 @@ impl Store { } }; let Some(account) = list.current().cloned() else { return Shared::None }; + // The row comes from a plain JSON file. Nothing in `accounts::read` checks the address or + // that `id` still hashes from `service` and `user`. A caller that presents the token to + // `account.service` would otherwise send it wherever that file names, including a plain + // `http://` host, or a host left after `service` was edited in place. Refuse here, before + // the keychain is even read, so the token never leaves this function for a row like that. + if let Err(why) = accounts::validate_target(&account) { + return Shared::Unreadable { account, why }; + } match self.tokens.get(&account.id) { Ok(Some(token)) => Shared::Session { account, token }, // On file with no entry behind it. Somebody deleted the entry, or a sign-out got half diff --git a/crates/suite-account/src/tests.rs b/crates/suite-account/src/tests.rs index c1a614aab4..a94ecb3d5b 100644 --- a/crates/suite-account/src/tests.rs +++ b/crates/suite-account/src/tests.rs @@ -81,6 +81,20 @@ fn the_handle_is_stable_and_separates_accounts() { assert!(a.chars().all(|c| c.is_ascii_hexdigit())); } +#[test] +fn a_service_base_is_https_or_loopback_http() { + assert!(accounts::allowed_service_base("https://craft.example.com")); + assert!(accounts::allowed_service_base("https://craft.example.com/collab")); + assert!(accounts::allowed_service_base("http://127.0.0.1:8080")); + assert!(accounts::allowed_service_base("http://localhost:9")); + assert!(accounts::allowed_service_base("http://[::1]:80/path")); + assert!(!accounts::allowed_service_base("")); + assert!(!accounts::allowed_service_base("http://collab.lan:8080")); + assert!(!accounts::allowed_service_base("http://127.0.0.1")); + assert!(!accounts::allowed_service_base("http://127.0.0.1:99999")); + assert!(!accounts::allowed_service_base("http://evil@127.0.0.1:8080")); +} + // ---- signing in and out ---------------------------------------------------- #[test] @@ -569,6 +583,63 @@ fn a_machine_with_no_keychain_signs_nobody_in() { assert!(!store.path().unwrap().exists(), "a refused sign-in should write no file"); } +/// A store whose accounts file holds `account` and whose keychain holds `TOKEN` under that id. +fn store_holding(account: Account) -> (tempfile::TempDir, Store) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().to_path_buf(); + let keychain = Memory::new(); + keychain.put(&account.id, &Secret::new(TOKEN)).unwrap(); + let list = + accounts::Accounts { format: accounts::FORMAT, accounts: vec![account.clone()], active: Some(account.id.clone()), tombstones: Vec::new() }; + accounts::write(&path.join(paths::FILE), &list).unwrap(); + (dir, Store::at(Some(path), keychain)) +} + +#[test] +fn shared_does_not_hand_a_token_to_a_plain_http_host() { + let service = "http://collab.lan:8080"; + let account = Account { id: accounts::handle(service, USER), service: service.to_owned(), user: USER.to_owned(), ..account_at("unused", 0) }; + let (_dir, store) = store_holding(account); + match store.shared() { + Shared::Unreadable { why, .. } => { + assert!(why.contains("service address"), "{why}"); + } + other => panic!("expected unreadable, got {other:?}"), + } +} + +#[test] +fn shared_does_not_hand_a_token_when_the_handle_no_longer_matches() { + // `id` was minted for SERVICE; the file now names another host. + let account = Account { + id: accounts::handle(SERVICE, USER), + service: "https://evil.example.com".to_owned(), + user: USER.to_owned(), + ..account_at("unused", 0) + }; + let (_dir, store) = store_holding(account); + match store.shared() { + Shared::Unreadable { why, .. } => { + assert!(why.contains("handle"), "{why}"); + } + other => panic!("expected unreadable, got {other:?}"), + } +} + +#[test] +fn shared_still_hands_a_token_for_loopback_http() { + let service = "http://127.0.0.1:8080"; + let account = Account { id: accounts::handle(service, USER), service: service.to_owned(), user: USER.to_owned(), ..account_at("unused", 0) }; + let (_dir, store) = store_holding(account); + match store.shared() { + Shared::Session { account: found, token } => { + assert_eq!(found.service, service); + assert_eq!(token, Secret::new(TOKEN)); + } + other => panic!("expected a session, got {other:?}"), + } +} + #[test] fn an_unreadable_keychain_says_so_rather_than_pretending_nobody_signed_in() { let dir = tempfile::tempdir().unwrap(); From 74048ba9f06368a6c274eaadac4e05239aa5e854 Mon Sep 17 00:00:00 2001 From: el-j Date: Wed, 18 Nov 2026 21:10:02 +0100 Subject: [PATCH 029/130] video: avoid unresolved intra-doc links in theora module doc --- crates/video/src/theora/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/video/src/theora/mod.rs b/crates/video/src/theora/mod.rs index 0fdc69652b..46907d1af6 100644 --- a/crates/video/src/theora/mod.rs +++ b/crates/video/src/theora/mod.rs @@ -1,7 +1,7 @@ //! Clean-room pure-Rust Theora video codec (Xiph.Org specification). //! -//! Provides a conformant Theora video decoder ([`Decoder`]) and keyframe/interframe -//! encoder ([`Encoder`]) operating over byte slices, planar buffers and Ogg streams. +//! Provides a conformant Theora video decoder (`Decoder`) and keyframe/interframe +//! encoder (`Encoder`) operating over byte slices, planar buffers and Ogg streams. #![allow(clippy::needless_range_loop, clippy::type_complexity, clippy::too_many_arguments, clippy::cognitive_complexity)] From 4e6a89f006561f9f6a1dcc2f8a64f179fb54060a Mon Sep 17 00:00:00 2001 From: el-j Date: Wed, 18 Nov 2026 21:11:24 +0100 Subject: [PATCH 030/130] audio: bound s302m Header::frame_bytes arithmetic against overflow --- crates/audio/src/s302m.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/audio/src/s302m.rs b/crates/audio/src/s302m.rs index aa50035459..487391e696 100644 --- a/crates/audio/src/s302m.rs +++ b/crates/audio/src/s302m.rs @@ -51,9 +51,15 @@ pub struct Header { } impl Header { - /// Bytes of one frame (one sample of every channel). + /// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` overflow. pub fn frame_bytes(&self) -> usize { - self.channels / 2 * ((self.bits as usize + 4) * 2 / 8) + let pair_bytes = match self.bits { + 16 => 5, + 20 => 6, + 24 => 7, + b => ((b as usize).saturating_add(4) * 2) / 8, + }; + (self.channels / 2).checked_mul(pair_bytes).unwrap_or(0) } } @@ -231,4 +237,10 @@ mod tests { assert!(decode(&[0, 5, 0, 0, 0, 0]).is_err()); assert!(decode(&[0, 4, 0, 0, 0, 0, 0, 0]).is_err()); } + + #[test] + fn header_frame_bytes_overflow_does_not_panic() { + let h = Header { channels: usize::MAX, channel_id: 0, bits: 24, alignment: 0, audio_bytes: 0 }; + assert_eq!(h.frame_bytes(), 0); + } } From 853dd8ec25df4d5f0924dd7ffb334728e7441c99 Mon Sep 17 00:00:00 2001 From: el-j Date: Wed, 18 Nov 2026 21:21:31 +0100 Subject: [PATCH 031/130] Address review feedback on Theora decoder and encoder - Enforce decoder memory budget against DECODE_MEMORY_BUDGET before allocating geometry and planes - Prevent independent edits to encoder internal tables and provide read-only accessors - Validate and bound encoder dimensions in Encoder::new - Ensure encoder writes valid intra keyframes, uses Picture strides, clamps EOB lookahead, and maps quality directly - Use checked arithmetic in comment header parser - Fix YUV 4:4:4 horizontal chroma motion predictor to half-pixel units - Add regression tests covering comment bounds, memory limits, strides, consecutive roundtrips, and chroma predictor --- crates/video/src/theora/decoder.rs | 37 ++++- crates/video/src/theora/encoder.rs | 119 ++++++++++---- crates/video/src/theora/header.rs | 14 +- crates/video/src/theora/reconstruct.rs | 2 +- crates/video/tests/theora.rs | 216 +++++++++++++++++++++++++ 5 files changed, 344 insertions(+), 44 deletions(-) diff --git a/crates/video/src/theora/decoder.rs b/crates/video/src/theora/decoder.rs index fdc1221ec0..003e8ffbd3 100644 --- a/crates/video/src/theora/decoder.rs +++ b/crates/video/src/theora/decoder.rs @@ -35,8 +35,41 @@ impl Decoder { let comment = CommentHeader::parse(comment_packet)?; let setup = SetupHeader::parse(setup_packet)?; - let fmbw = (id.info.frame_width / 16) as usize; - let fmbh = (id.info.frame_height / 16) as usize; + let fmbw_u64 = (id.info.frame_width / 16) as u64; + let fmbh_u64 = (id.info.frame_height / 16) as u64; + if fmbw_u64 == 0 || fmbh_u64 == 0 { + return Err(Error::DimensionMismatch("frame dimensions must be non-zero multiples of 16")); + } + + // Validate memory budget (crate::budget::DECODE_MEMORY_BUDGET) before allocating geometry and planes + let (cw, ch) = match id.info.pixel_format { + PixelFormat::Yuv420 => (fmbw_u64.checked_mul(8).ok_or(Error::OutOfMemory)?, fmbh_u64.checked_mul(8).ok_or(Error::OutOfMemory)?), + PixelFormat::Yuv422 => (fmbw_u64.checked_mul(8).ok_or(Error::OutOfMemory)?, fmbh_u64.checked_mul(16).ok_or(Error::OutOfMemory)?), + PixelFormat::Yuv444 => (fmbw_u64.checked_mul(16).ok_or(Error::OutOfMemory)?, fmbh_u64.checked_mul(16).ok_or(Error::OutOfMemory)?), + }; + + let y_bytes = (fmbw_u64.checked_mul(16).ok_or(Error::OutOfMemory)?) + .checked_mul(fmbh_u64.checked_mul(16).ok_or(Error::OutOfMemory)?) + .ok_or(Error::OutOfMemory)?; + let c_bytes = cw.checked_mul(ch).ok_or(Error::OutOfMemory)?; + let one_picture_bytes = y_bytes.checked_add(c_bytes.checked_mul(2).ok_or(Error::OutOfMemory)?).ok_or(Error::OutOfMemory)?; + + // 2 reference pictures (golden + previous) and 1 reconstructed scratch picture + let pictures_mem = one_picture_bytes.checked_mul(3).ok_or(Error::OutOfMemory)?; + + // Geometry metadata & decode scratch buffers + let nmbs = fmbw_u64.checked_mul(fmbh_u64).ok_or(Error::OutOfMemory)?; + let blocks_per_mb = id.info.pixel_format.blocks_per_macroblock() as u64; + let nbs = nmbs.checked_mul(blocks_per_mb).ok_or(Error::OutOfMemory)?; + let meta_and_scratch_mem = nbs.checked_mul(300).ok_or(Error::OutOfMemory)?; + + let total_mem = pictures_mem.checked_add(meta_and_scratch_mem).ok_or(Error::OutOfMemory)?; + if total_mem > crate::budget::DECODE_MEMORY_BUDGET { + return Err(Error::OutOfMemory); + } + + let fmbw = fmbw_u64 as usize; + let fmbh = fmbh_u64 as usize; let geom = FrameGeometry::new(fmbw, fmbh, id.info.pixel_format); let qmat_tables = setup.quant_params.precompute_all_qmat()?; diff --git a/crates/video/src/theora/encoder.rs b/crates/video/src/theora/encoder.rs index be2472389a..c0d59021dc 100644 --- a/crates/video/src/theora/encoder.rs +++ b/crates/video/src/theora/encoder.rs @@ -4,7 +4,7 @@ use super::header::{CommentHeader, IdentificationHeader, SetupHeader}; use super::idct::fdct_1d; use super::reconstruct::{FrameGeometry, apply_loop_filter, reconstruct_block, undo_dc_prediction}; use super::tables::ZIGZAG; -use super::{ColorSpace, Info, Picture, PixelFormat, Result}; +use super::{ColorSpace, Error, Info, Picture, PixelFormat, Result}; use craft_media::bitstream::BitWriter; /// Configuration for creating a Theora video encoder. @@ -45,12 +45,12 @@ impl Default for EncoderConfig { /// A conformant Theora video keyframe and interframe encoder. pub struct Encoder { - pub config: EncoderConfig, - pub id_header: IdentificationHeader, - pub comment_header: CommentHeader, - pub setup_header: SetupHeader, - pub geom: FrameGeometry, - pub qmat_tables: [[[[u16; 64]; 64]; 3]; 2], + config: EncoderConfig, + id_header: IdentificationHeader, + comment_header: CommentHeader, + setup_header: SetupHeader, + geom: FrameGeometry, + qmat_tables: [[[[u16; 64]; 64]; 3]; 2], // Reference frames ref_golden_y: Vec, @@ -68,10 +68,42 @@ pub struct Encoder { impl Encoder { /// Create a new encoder with the given configuration. pub fn new(config: EncoderConfig) -> Result { - let frame_width = (config.width + 15) & !15; - let frame_height = (config.height + 15) & !15; - let fmbw = (frame_width / 16) as usize; - let fmbh = (frame_height / 16) as usize; + if config.width == 0 || config.height == 0 { + return Err(Error::DimensionMismatch("dimensions cannot be zero")); + } + let frame_width = config.width.checked_add(15).map(|w| w & !15).ok_or(Error::DimensionMismatch("width overflows"))?; + let frame_height = config.height.checked_add(15).map(|h| h & !15).ok_or(Error::DimensionMismatch("height overflows"))?; + let fmbw_u64 = (frame_width / 16) as u64; + let fmbh_u64 = (frame_height / 16) as u64; + if fmbw_u64 == 0 || fmbh_u64 == 0 || fmbw_u64 > u16::MAX as u64 || fmbh_u64 > u16::MAX as u64 { + return Err(Error::DimensionMismatch("macroblock dimensions must fit in u16")); + } + let fmbw = fmbw_u64 as usize; + let fmbh = fmbh_u64 as usize; + + // Validate memory budget before allocating geometry and planes + let (cw, ch) = match config.pixel_format { + PixelFormat::Yuv420 => (fmbw_u64.checked_mul(8).ok_or(Error::OutOfMemory)?, fmbh_u64.checked_mul(8).ok_or(Error::OutOfMemory)?), + PixelFormat::Yuv422 => (fmbw_u64.checked_mul(8).ok_or(Error::OutOfMemory)?, fmbh_u64.checked_mul(16).ok_or(Error::OutOfMemory)?), + PixelFormat::Yuv444 => (fmbw_u64.checked_mul(16).ok_or(Error::OutOfMemory)?, fmbh_u64.checked_mul(16).ok_or(Error::OutOfMemory)?), + }; + + let y_bytes = (fmbw_u64.checked_mul(16).ok_or(Error::OutOfMemory)?) + .checked_mul(fmbh_u64.checked_mul(16).ok_or(Error::OutOfMemory)?) + .ok_or(Error::OutOfMemory)?; + let c_bytes = cw.checked_mul(ch).ok_or(Error::OutOfMemory)?; + let one_picture_bytes = y_bytes.checked_add(c_bytes.checked_mul(2).ok_or(Error::OutOfMemory)?).ok_or(Error::OutOfMemory)?; + + let pictures_mem = one_picture_bytes.checked_mul(3).ok_or(Error::OutOfMemory)?; + let nmbs = fmbw_u64.checked_mul(fmbh_u64).ok_or(Error::OutOfMemory)?; + let blocks_per_mb = config.pixel_format.blocks_per_macroblock() as u64; + let nbs = nmbs.checked_mul(blocks_per_mb).ok_or(Error::OutOfMemory)?; + let meta_mem = nbs.checked_mul(300).ok_or(Error::OutOfMemory)?; + + let total_mem = pictures_mem.checked_add(meta_mem).ok_or(Error::OutOfMemory)?; + if total_mem > crate::budget::DECODE_MEMORY_BUDGET { + return Err(Error::OutOfMemory); + } let info = Info { version_major: 3, @@ -131,29 +163,49 @@ impl Encoder { }) } + /// Returns the encoder configuration. + pub fn config(&self) -> &EncoderConfig { + &self.config + } + + /// Returns the stream identification header. + pub fn id_header(&self) -> &IdentificationHeader { + &self.id_header + } + + /// Returns the comment header. + pub fn comment_header(&self) -> &CommentHeader { + &self.comment_header + } + + /// Returns the setup header. + pub fn setup_header(&self) -> &SetupHeader { + &self.setup_header + } + /// Serialize the three mandatory stream headers in order: `(id, comment, setup)`. pub fn headers(&self) -> (Vec, Vec, Vec) { (self.id_header.serialize(), self.comment_header.serialize(), self.setup_header.serialize()) } /// Encode a single picture into a conformant Theora packet. - pub fn encode_frame(&mut self, pic: &Picture, force_keyframe: bool) -> Result> { - let is_keyframe = force_keyframe || self.frame_count == 0 || (self.frame_count - self.last_keyframe >= self.config.keyframe_distance as u64); - + /// + /// Currently produces intra keyframes for every frame, ensuring all packets are independent + /// self-contained keyframes that decode reliably. + pub fn encode_frame(&mut self, pic: &Picture, _force_keyframe: bool) -> Result> { let mut w = BitWriter::new(); // 1. Frame Header (Section 7.1) w.write_bit(false); // data packet bit = 0 - w.write_bit(!is_keyframe); // FTYPE: 0: Intra, 1: Inter + w.write_bit(false); // FTYPE: 0: Intra (keyframe) - // qi: map quality (0..=63) to qi index (63 - quality) - let qi = (63 - self.config.quality.min(63)) as usize; + // qi: map quality (0..=63) directly to quantization index (0 = coarsest, 63 = finest) + let qi = self.config.quality.min(63) as usize; w.write_bits(qi as u32, 6); w.write_bit(false); // MOREQIS = 0 (1 qi value) - if is_keyframe { - w.write_bits(0, 3); // 3 reserved bits = 000 - } + // 3 reserved bits for intra keyframe = 000 + w.write_bits(0, 3); let nbs = self.geom.nbs; let (y_pw, y_ph, _, _, _, _, _, _) = self.geom.planes[0]; @@ -174,12 +226,11 @@ impl Encoder { for bi in 0..nbs { let meta = &self.geom.blocks[bi]; let pli = meta.pli; - let (pw, _, _, _, _, _, _, _) = self.geom.planes[pli]; - let src_plane = match pli { - 0 => &pic.y, - 1 => &pic.u, - 2 => &pic.v, - _ => &pic.y, + let (src_plane, stride) = match pli { + 0 => (&pic.y, pic.y_stride), + 1 => (&pic.u, pic.uv_stride), + 2 => (&pic.v, pic.uv_stride), + _ => (&pic.y, pic.y_stride), }; // Read 8x8 block from source picture (origin at lower-left!) @@ -189,7 +240,7 @@ impl Encoder { let py = meta.pixel_y + row; for col in 0..8 { let px = meta.pixel_x + col; - let sample = if py * pw + px < src_plane.len() { src_plane[py * pw + px] as i16 } else { 128 }; + let sample = if py * stride + px < src_plane.len() { src_plane[py * stride + px] as i16 } else { 128 }; // Subtract 128 (intra predictor) block_samples[row * 8 + col] = sample - 128; } @@ -319,7 +370,7 @@ impl Encoder { // Count how many consecutive blocks also have remaining all zero at ti let mut eob_run = 0usize; let mut lookahead = bi; - while lookahead < nbs { + while lookahead < nbs && eob_run < 4095 { if tis[lookahead] == ti { if (ti..64).all(|idx| stored_coeffs[lookahead][idx] == 0) { eob_run += 1; @@ -487,13 +538,11 @@ impl Encoder { let lflim_l = self.setup_header.lflims[qi]; apply_loop_filter(&self.geom, &bcoded, lflim_l, &mut rec_y, &mut rec_cb, &mut rec_cr); - // Update local reference frames - if is_keyframe { - self.ref_golden_y.copy_from_slice(&rec_y); - self.ref_golden_cb.copy_from_slice(&rec_cb); - self.ref_golden_cr.copy_from_slice(&rec_cr); - self.last_keyframe = self.frame_count; - } + // Update local reference frames (all frames are intra keyframes) + self.ref_golden_y.copy_from_slice(&rec_y); + self.ref_golden_cb.copy_from_slice(&rec_cb); + self.ref_golden_cr.copy_from_slice(&rec_cr); + self.last_keyframe = self.frame_count; self.ref_prev_y.copy_from_slice(&rec_y); self.ref_prev_cb.copy_from_slice(&rec_cb); self.ref_prev_cr.copy_from_slice(&rec_cr); diff --git a/crates/video/src/theora/header.rs b/crates/video/src/theora/header.rs index b425c53d4a..62dbf7635e 100644 --- a/crates/video/src/theora/header.rs +++ b/crates/video/src/theora/header.rs @@ -185,11 +185,12 @@ impl CommentHeader { let vendor_len = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; pos += 4; - if data.len() < pos + vendor_len { + let vendor_end = pos.checked_add(vendor_len).ok_or(Error::Truncated("vendor string"))?; + if data.len() < vendor_end { return Err(Error::Truncated("vendor string")); } - let vendor = String::from_utf8_lossy(&data[pos..pos + vendor_len]).into_owned(); - pos += vendor_len; + let vendor = String::from_utf8_lossy(&data[pos..vendor_end]).into_owned(); + pos = vendor_end; if data.len() < pos + 4 { return Err(Error::Truncated("comment count")); @@ -209,11 +210,12 @@ impl CommentHeader { } let len = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; pos += 4; - if data.len() < pos + len { + let comment_end = pos.checked_add(len).ok_or(Error::Truncated("user comment string"))?; + if data.len() < comment_end { return Err(Error::Truncated("user comment string")); } - let s = String::from_utf8_lossy(&data[pos..pos + len]).into_owned(); - pos += len; + let s = String::from_utf8_lossy(&data[pos..comment_end]).into_owned(); + pos = comment_end; comments.push(s); } diff --git a/crates/video/src/theora/reconstruct.rs b/crates/video/src/theora/reconstruct.rs index 9c476cd704..2792db2704 100644 --- a/crates/video/src/theora/reconstruct.rs +++ b/crates/video/src/theora/reconstruct.rs @@ -364,7 +364,7 @@ pub fn compute_block_predictor( _ => ref_y, }; - let is_chroma_subsampled_x = pli > 0; + let is_chroma_subsampled_x = pli > 0 && pixel_format != PixelFormat::Yuv444; let is_chroma_subsampled_y = pli > 0 && pixel_format == PixelFormat::Yuv420; let (mvx1, mvx2) = split_mv_component(mv.0 as i32, is_chroma_subsampled_x); diff --git a/crates/video/tests/theora.rs b/crates/video/tests/theora.rs index 4ce5b6c0e6..55ac515119 100644 --- a/crates/video/tests/theora.rs +++ b/crates/video/tests/theora.rs @@ -264,3 +264,219 @@ fn test_theora_ffmpeg_oracle_roundtrip() { println!("Oracle PSNR against FFmpeg decode: {p:.2} dB"); assert!(p >= 35.0, "FFmpeg decode differs noticeably: {p:.2} dB"); } + +#[test] +fn test_theora_encoder_consecutive_calls_roundtrip() { + let (w, h) = (32, 32); + let cfg = EncoderConfig { + width: w as u32, + height: h as u32, + pic_width: w as u32, + pic_height: h as u32, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 40, + keyframe_distance: 64, + }; + let mut enc = Encoder::new(cfg).expect("encoder"); + let (id_pkt, comm_pkt, setup_pkt) = enc.headers(); + let mut dec = Decoder::from_headers(&id_pkt, &comm_pkt, &setup_pkt).expect("decoder"); + + let pic1 = test_picture(w, h); + let pkt1 = enc.encode_frame(&pic1, false).expect("frame 1"); + let dec1 = dec.decode_packet(&pkt1).expect("decode frame 1"); + assert!(dec1.keyframe); + + let mut pic2 = test_picture(w, h); + pic2.y[0] = 200; + let pkt2 = enc.encode_frame(&pic2, false).expect("frame 2 with force_keyframe=false"); + let dec2 = dec.decode_packet(&pkt2).expect("decode frame 2"); + assert!(dec2.keyframe); +} + +#[test] +fn test_theora_comment_header_bounds() { + use craft_video::theora::CommentHeader; + + // Truncated vendor string length + let truncated = vec![0x81, b't', b'h', b'e', b'o', b'r', b'a', 0x01]; + assert!(matches!(CommentHeader::parse(&truncated), Err(Error::Truncated(_)))); + + // Vendor string length exceeding available bytes (or overflow on 32-bit: 0xFFFFFFFF) + let mut overflow_vendor = vec![0x81, b't', b'h', b'e', b'o', b'r', b'a']; + overflow_vendor.extend_from_slice(&0xFFFFFFFFu32.to_le_bytes()); + assert!(matches!(CommentHeader::parse(&overflow_vendor), Err(Error::Truncated(_)))); + + // Valid vendor, but comment length overflows + let mut overflow_comment = vec![0x81, b't', b'h', b'e', b'o', b'r', b'a']; + overflow_comment.extend_from_slice(&4u32.to_le_bytes()); + overflow_comment.extend_from_slice(b"test"); + overflow_comment.extend_from_slice(&1u32.to_le_bytes()); // 1 comment + overflow_comment.extend_from_slice(&0xFFFFFFFFu32.to_le_bytes()); // comment len overflows + assert!(matches!(CommentHeader::parse(&overflow_comment), Err(Error::Truncated(_)))); +} + +#[test] +fn test_theora_hostile_dimensions_rejected() { + // Zero dimensions + let cfg_zero = EncoderConfig { + width: 0, + height: 0, + pic_width: 0, + pic_height: 0, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 40, + keyframe_distance: 64, + }; + assert!(matches!(Encoder::new(cfg_zero), Err(Error::DimensionMismatch(_)))); + + // Overflowing dimensions + let cfg_overflow = EncoderConfig { + width: u32::MAX, + height: 16, + pic_width: 16, + pic_height: 16, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 40, + keyframe_distance: 64, + }; + assert!(matches!(Encoder::new(cfg_overflow), Err(Error::DimensionMismatch(_)))); + + // Massive dimensions exceeding memory budget + let enc_ok = Encoder::new(EncoderConfig { + width: 16, + height: 16, + pic_width: 16, + pic_height: 16, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv444, + color_space: ColorSpace::Undefined, + quality: 40, + keyframe_distance: 64, + }) + .expect("encoder"); + let (_, comm_pkt, setup_pkt) = enc_ok.headers(); + + // Create synthetic 16384x16384 YUV444 ID packet (fmbw = 1024, fmbh = 1024) + let mut huge_id = vec![0x80, b't', b'h', b'e', b'o', b'r', b'a', 3, 2, 0]; + huge_id.extend_from_slice(&1024u16.to_be_bytes()); // fmbw = 1024 (16384 px) + huge_id.extend_from_slice(&1024u16.to_be_bytes()); // fmbh = 1024 (16384 px) + huge_id.extend_from_slice(&[0, 0x40, 0x00]); // picw = 16384 + huge_id.extend_from_slice(&[0, 0x40, 0x00]); // pich = 16384 + huge_id.extend_from_slice(&[0, 0]); // picx, picy + huge_id.extend_from_slice(&30u32.to_be_bytes()); // frn + huge_id.extend_from_slice(&1u32.to_be_bytes()); // frd + huge_id.extend_from_slice(&[0, 0, 1]); // parn + huge_id.extend_from_slice(&[0, 0, 1]); // pard + huge_id.push(0); // color space + huge_id.extend_from_slice(&[0, 0, 0]); // nombr + // last two bytes: quality=0, kfgshift=6, pf_bits=3 (Yuv444), reserved=0 + // (0 << 10) | (6 << 5) | (3 << 3) = 0 | 192 | 24 = 216 = 0x00D8 + huge_id.extend_from_slice(&0x00D8u16.to_be_bytes()); + + assert!(matches!(Decoder::from_headers(&huge_id, &comm_pkt, &setup_pkt), Err(Error::OutOfMemory))); +} + +#[test] +fn test_theora_encoder_picture_strides() { + let (w, h) = (32, 32); + let cfg = EncoderConfig { + width: w as u32, + height: h as u32, + pic_width: w as u32, + pic_height: h as u32, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 50, + keyframe_distance: 64, + }; + let mut enc = Encoder::new(cfg).expect("encoder"); + let (id_pkt, comm_pkt, setup_pkt) = enc.headers(); + let mut dec = Decoder::from_headers(&id_pkt, &comm_pkt, &setup_pkt).expect("decoder"); + + let y_stride = 64; // stride > width + let uv_stride = 32; // stride > cw (16) + let mut y = vec![0u8; y_stride * h]; + let _cw = w / 2; + let ch = h / 2; + let u = vec![128u8; uv_stride * ch]; + let v = vec![128u8; uv_stride * ch]; + + for r in 0..h { + for c in 0..w { + y[r * y_stride + c] = ((r * 255 / h) ^ (c * 255 / w)) as u8; + } + // Fill stride padding with garbage to ensure encoder does not read it + for c in w..y_stride { + y[r * y_stride + c] = 255; + } + } + + let pic = Picture { + width: w as u32, + height: h as u32, + pic_width: w as u32, + pic_height: h as u32, + pic_x: 0, + pic_y: 0, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + keyframe: true, + pts: None, + y, + u, + v, + y_stride, + uv_stride, + }; + + let pkt = enc.encode_frame(&pic, true).expect("encode with stride"); + let decoded = dec.decode_packet(&pkt).expect("decode"); + assert_eq!(decoded.width, w as u32); + assert_eq!(decoded.height, h as u32); +} + +#[test] +fn test_theora_yuv444_chroma_motion_vector_half_pixel() { + use craft_video::theora::reconstruct::compute_block_predictor; + + let plane_w = 16; + let plane_h = 16; + let ref_y = vec![0u8; plane_w * plane_h]; + let mut ref_cb = vec![0u8; plane_w * plane_h]; + let ref_cr = vec![0u8; plane_w * plane_h]; + + // Set pixel (1, 0) to 200, pixel (2, 0) to 100 + ref_cb[1] = 200; + ref_cb[2] = 100; + + let mut pred = [[0u8; 8]; 8]; + + // For Yuv444, motion vector (2, 0) is 1 full pixel in half-pixel units (rfi=1: previous reference frame) + compute_block_predictor(1, 0, 0, 1, (2, 0), PixelFormat::Yuv444, &ref_y, &ref_cb, &ref_cr, plane_w, plane_h, &mut pred); + + // In Yuv444 without subsampling, (2, 0) moves by 1 full pixel, so pred[0][0] must be ref_cb[0 * plane_w + 1] = 200! + // (If quarter-pixel units were used erroneously, it would have averaged ref_cb[0] and ref_cb[1] giving (0 + 200)/2 = 100) + assert_eq!(pred[0][0], 200); +} From 9a7d5f6bc03de58a7316e80128ad5d8354da82cb Mon Sep 17 00:00:00 2001 From: el-j Date: Wed, 18 Nov 2026 21:42:59 +0100 Subject: [PATCH 032/130] Validate stride arithmetic in Theora encoder source plane extraction --- crates/video/src/theora/encoder.rs | 3 ++- crates/video/tests/theora.rs | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/video/src/theora/encoder.rs b/crates/video/src/theora/encoder.rs index c0d59021dc..f7176e8bee 100644 --- a/crates/video/src/theora/encoder.rs +++ b/crates/video/src/theora/encoder.rs @@ -240,7 +240,8 @@ impl Encoder { let py = meta.pixel_y + row; for col in 0..8 { let px = meta.pixel_x + col; - let sample = if py * stride + px < src_plane.len() { src_plane[py * stride + px] as i16 } else { 128 }; + let offset = py.checked_mul(stride).and_then(|r| r.checked_add(px)).ok_or(Error::DimensionMismatch("sample offset overflow"))?; + let sample = src_plane.get(offset).copied().map(|b| b as i16).unwrap_or(128); // Subtract 128 (intra predictor) block_samples[row * 8 + col] = sample - 128; } diff --git a/crates/video/tests/theora.rs b/crates/video/tests/theora.rs index 55ac515119..f1fa88040c 100644 --- a/crates/video/tests/theora.rs +++ b/crates/video/tests/theora.rs @@ -457,6 +457,28 @@ fn test_theora_encoder_picture_strides() { assert_eq!(decoded.height, h as u32); } +#[test] +fn test_theora_encoder_overflowing_stride_rejected() { + let cfg = EncoderConfig { + width: 32, + height: 32, + pic_width: 32, + pic_height: 32, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 40, + keyframe_distance: 64, + }; + let mut enc = Encoder::new(cfg).expect("encoder"); + let mut pic = test_picture(32, 32); + pic.y_stride = usize::MAX; + assert!(matches!(enc.encode_frame(&pic, true), Err(Error::DimensionMismatch(_)))); +} + #[test] fn test_theora_yuv444_chroma_motion_vector_half_pixel() { use craft_video::theora::reconstruct::compute_block_predictor; From 4efe28f2abda1b3f514a7775dc12a9a0031f20b1 Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 18 Nov 2026 22:25:40 +0100 Subject: [PATCH 033/130] Preserve list headers and resolved continuation indents --- crates/flow/src/from_doc.rs | 7 ++- crates/flow/src/lib.rs | 28 ++++++++++ crates/odf/src/text/tests_more/lists.rs | 21 +++++++ crates/odf/src/text/writer.rs | 73 +++++++++++++++---------- 4 files changed, 97 insertions(+), 32 deletions(-) diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index 05c7f47ed5..3662a65b89 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -957,15 +957,16 @@ fn flow_paras_at(doc: &Document, p: &Paragraph, opts: FlowOpts, at: &mut ItemTex if let Some(n) = rp.numbering.filter(|n| n.num != 0) { // The paragraph's own indent, else its level's, else its style's (as Word places it). let level = doc.numbering.level(n.num, n.level).map(|l| l.indent); - let text = p.props.indent_left.or(level).unwrap_or(left); + // Nonzero character indents override point indents, including an explicit zero. + let text = if rp.indent_chars[0] != 0.0 { left } else { p.props.indent_left.or(level).unwrap_or(left) }; if let Some(t) = at.get_mut(usize::from(n.level)) { *t = Some(text); } } else if let Some(l) = p.props.list_item { - // Before any numbered paragraph at its level (a list header), anywhere off the margin. + // Before any numbered paragraph, an explicit header has no prior baseline to outdent from. let kept = match at.get(usize::from(l)).copied().flatten() { Some(text) => left >= text - 0.5, - None => left > 0.5, + None => true, }; if !kept { for q in &mut paras { diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index a483e0c6c4..238a455fb8 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -242,6 +242,34 @@ mod tests { out } + #[test] + fn character_indents_set_the_list_continuation_baseline() { + let mut doc = craft_wordmodel::Document::new(); + let num = std::sync::Arc::make_mut(&mut doc.numbering).add_list(craft_wordmodel::ListKind::Numbered); + let numbered = move |p: &mut craft_wordmodel::ParaProps| { + p.numbering = Some(NumRef { num, level: 0 }); + p.indent_left = Some(0.0); + p.indent_left_chars = Some(6.0); + }; + let outdented = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(0.0); + }; + doc.body = doc_of(&[("One", &numbered), ("Out", &outdented)]).body; + let got = items(&from_doc(&doc).blocks); + assert_eq!(got.iter().find(|r| r.0 == "Out").map(|r| r.1), Some(None)); + } + + #[test] + fn a_zero_indent_header_keeps_its_explicit_list_membership() { + let header = |p: &mut craft_wordmodel::ParaProps| { + p.list_item = Some(0); + p.indent_left = Some(0.0); + }; + let doc = doc_of(&[("Header", &header)]); + assert_eq!(items(&from_doc(&doc).blocks), [("Header".into(), Some(0))]); + } + /// A list item's further paragraph cut by a page break is that paragraph on both pages: the /// text after the break stays in the item too. #[test] diff --git a/crates/odf/src/text/tests_more/lists.rs b/crates/odf/src/text/tests_more/lists.rs index 937fc05590..b9bb69148f 100644 --- a/crates/odf/src/text/tests_more/lists.rs +++ b/crates/odf/src/text/tests_more/lists.rs @@ -201,6 +201,7 @@ fn a_list_items_further_paragraphs_are_paragraphs_with_no_number() { for saved in [crate::text::tests::export_model(&d).unwrap(), export(&d).unwrap()] { let back = import(&saved).unwrap(); want(&shape(&back)); + assert_eq!(back.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == "Header").unwrap().props.list_item, Some(0)); let nums: Vec = back.body.iter().filter_map(|b| b.as_para()).filter_map(|p| p.props.numbering.map(|n| n.num)).collect(); assert_eq!(nums[0], nums[1], "{nums:?}"); } @@ -407,3 +408,23 @@ fn a_heading_in_a_list_item_stays_in_it() { let head = back.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == "Head").unwrap(); assert_eq!(head.props.style.as_deref(), Some("Heading2"), "{c}"); } + +#[test] +fn zero_indent_multi_paragraph_header_survives_model_export() { + let styles = format!( + r#""# + ); + let content = format!( + r#"HeaderMore headerOne"# + ); + let doc = import(&package(&content, Some(&styles))).unwrap(); + let bytes = crate::text::tests::export_model(&doc).unwrap(); + let xml = crate::text::tests::entry(&bytes, "content.xml"); + assert_eq!(xml.matches("").count(), 1); + let back = import(&bytes).unwrap(); + for text in ["Header", "More header"] { + let p = back.body.iter().filter_map(|b| b.as_para()).find(|p| p.text == text).unwrap(); + assert_eq!(p.props.list_item, Some(0)); + assert!(p.props.numbering.is_none()); + } +} diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index f64c79feca..84d0374477 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -97,24 +97,24 @@ pub(super) const GRAPHICS_PARENT: &str = "\u{0}graphics"; /// level's kind as its first item there says. An item of another list, or (lists not told apart) /// a top-level item of the other kind, starts a new list; with section wrappers (`wraps`), so /// does an item opening a section, and one closing a section ends it. -fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9]) { +fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9], u32) { let p = match blocks.get(start) { Some(FBlock::Para(p)) => p, - _ => return (start.saturating_add(1), [ListOut { ordered: false, label: None, start: 1 }; 9]), + _ => return (start.saturating_add(1), [ListOut { ordered: false, label: None, start: 1 }; 9], 0), }; - let id = p.list.map_or(0, |l| l.list); + let mut id = p.list.map(|l| l.list); let first = ListOut { ordered: p.list.is_some_and(|l| l.ordered), label: None, start: 1 }; let mut kinds = [first; 9]; let mut seen = [false; 9]; let mut i = start; // The level of the last item: an item's further paragraph goes in an item still open. - let mut last = 0usize; + let mut last = usize::from(p.item.unwrap_or(0).min(8)); while let Some(FBlock::Para(q)) = blocks.get(i) { let Some(li) = q.list else { // A section it opens or closes ends the run, as an item's does. let wrap = q.wrap.as_deref().filter(|_| wraps); match model::continues_list(blocks, i).map(usize::from) { - Some(lv) if i > start && lv <= last && !wrap.is_some_and(|w| !w.0.is_empty()) => { + Some(lv) if lv <= last && (i == start || !wrap.is_some_and(|w| !w.0.is_empty())) => { // The items below it are closed. last = lv; i += 1; @@ -128,7 +128,8 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9 }; let l = li.level.min(8) as usize; last = l; - if li.list != id || (id == 0 && l == 0 && seen[0] && kinds[0].ordered != li.ordered) { + let list_id = *id.get_or_insert(li.list); + if li.list != list_id || (list_id == 0 && l == 0 && seen[0] && kinds[0].ordered != li.ordered) { break; } let wrap = q.wrap.as_deref().filter(|_| wraps); @@ -146,7 +147,25 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9 break; } } - (i.max(start + 1), kinds) + (i.max(start + 1), kinds, id.unwrap_or(0)) +} + +/// Close nested items and lists down to the requested open depth. +fn close_lists(out: &mut String, stack: &mut Vec, depth: usize) { + while stack.len() > depth { + if stack.pop() == Some(true) { + out.push_str(""); + } + out.push_str(""); + } +} + +/// Open or close the single leading header without splitting its consecutive paragraphs. +fn list_header(out: &mut String, is_open: &mut bool, open: bool) { + if *is_open != open { + out.push_str(if open { "" } else { "" }); + *is_open = open; + } } /// The `xml:id` of the list markup `xml` (kept as read) begins with, if it does. @@ -943,10 +962,9 @@ impl Writer { } i += 1; } - FBlock::Para(p) if p.list.is_some() => { + FBlock::Para(p) if p.list.is_some() || model::continues_list(blocks, i).is_some() => { let start = i; - let id = p.list.map_or(0, |l| l.list); - let (end, kinds) = list_run(blocks, start, self.wraps_at(depth)); + let (end, kinds, id) = list_run(blocks, start, self.wraps_at(depth)); i = end; // The sections kept as read its first item opens and its last closes, around it. let wrap_of = |k: usize| match blocks.get(k) { @@ -960,28 +978,22 @@ impl Writer { let id_of_list = id; // Open lists: per level, whether a list-item is open. let mut stack: Vec = Vec::new(); + let mut header_open = false; for (qi, q) in blocks.get(start..i).unwrap_or(&[]).iter().enumerate() { let FBlock::Para(q) = q else { continue }; - if q.list.is_none() { + if q.list.is_none() && stack.get(usize::from(q.item.unwrap_or(0).min(8))).copied() == Some(true) { // An item's further paragraph (`list_run` took it only below an open // item at its level): in that item, its sublists ended first. let lv = q.item.map_or(0, |l| l.min(8) as usize); - while stack.len() > lv + 1 { - if stack.pop() == Some(true) { - out.push_str(""); - } - out.push_str(""); - } + close_lists(out, &mut stack, lv + 1); self.para_in(q, chain(start + qi), out); continue; } - let lv = q.list.map(|l| l.level.min(8) as usize).unwrap_or(0); - while stack.len() > lv + 1 { - if stack.pop() == Some(true) { - out.push_str(""); - } - out.push_str(""); + if q.list.is_some() { + list_header(out, &mut header_open, false); } + let lv = usize::from(q.list.map(|l| l.level).or(q.item).unwrap_or(0).min(8)); + close_lists(out, &mut stack, lv + 1); while stack.len() < lv + 1 { if let Some(top) = stack.last_mut() && !*top @@ -1016,6 +1028,13 @@ impl Writer { } stack.push(false); } + // Leading unnumbered paragraphs belong to one list header, not to + // the document body. Keep that membership when original markup is gone. + if q.list.is_none() { + list_header(out, &mut header_open, true); + self.para_in(q, chain(start + qi), out); + continue; + } if let Some(top) = stack.last_mut() { if *top { out.push_str(""); @@ -1025,12 +1044,8 @@ impl Writer { out.push_str(""); self.para_in(q, chain(start + qi), out); } - while let Some(open) = stack.pop() { - if open { - out.push_str(""); - } - out.push_str(""); - } + list_header(out, &mut header_open, false); + close_lists(out, &mut stack, 0); self.close_wrap(closes.as_ref(), 0, out); out.push('\n'); } From c87281acac890aa2c5940073bd7b123d7237182c Mon Sep 17 00:00:00 2001 From: istefp Date: Wed, 18 Nov 2026 21:40:44 -0500 Subject: [PATCH 034/130] scraft-format: sanitize an Instrument route used as output or send Route::Instrument is input-side only; a file naming it as the output or a send target now deserializes then normalizes instead of keeping a destination consumers treat as invalid. --- crates/scraft-format/src/mixer.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/scraft-format/src/mixer.rs b/crates/scraft-format/src/mixer.rs index 7e5d348fd5..0db71d9e84 100644 --- a/crates/scraft-format/src/mixer.rs +++ b/crates/scraft-format/src/mixer.rs @@ -570,7 +570,15 @@ impl Mixer { } self.inserts.resize(INSERT_SLOTS, None); self.sends.resize(SEND_SLOTS, None); + // An instrument's output bus is only ever an input: a file naming it as the + // output or a send target gets the unrouted default for that field. + if matches!(self.output, Route::Instrument { .. }) { + self.output = Route::Main; + } for s in self.sends.iter_mut().flatten() { + if matches!(s.target, Route::Instrument { .. }) { + s.target = Route::None; + } s.level_db = finite_or(s.level_db, -144.0).clamp(-144.0, 12.0); s.pan = finite_or(s.pan, 0.0).clamp(-1.0, 1.0); if let Some(sp) = &mut s.surround { @@ -682,6 +690,24 @@ mod tests { assert_eq!(serde_json::from_str::(r#"{"Hardware":"in 1-2"}"#).unwrap(), Route::Hardware("in 1-2".to_string())); } + #[test] + fn sanitize_clears_an_instrument_route_used_as_output_or_send() { + // Route::Instrument is input-side only: a file naming it as the output or a send + // target deserializes, then sanitize resets the field instead of keeping it. + let mut m = Mixer::new(ChannelFormat::Stereo); + m.output = Route::Instrument { track: TrackId(9), bus: 1 }; + m.sends[0] = Some(SendSlot::new(Route::Instrument { track: TrackId(9), bus: 2 })); + m.sends[1] = Some(SendSlot::new(Route::Bus(BusId(3)))); + m.sanitize(); + assert_eq!(m.output, Route::Main); + assert_eq!(m.sends[0].as_ref().unwrap().target, Route::None); + assert_eq!(m.sends[1].as_ref().unwrap().target, Route::Bus(BusId(3)), "other routes are untouched"); + // And an instrument route stays valid as an input. + m.input = Route::Instrument { track: TrackId(9), bus: 1 }; + m.sanitize(); + assert_eq!(m.input, Route::Instrument { track: TrackId(9), bus: 1 }); + } + #[test] fn mixer_defaults_and_sanitize() { let mut m = Mixer::new(ChannelFormat::Stereo); From 272379135791568596fa133a7bbf998852dfd584 Mon Sep 17 00:00:00 2001 From: el-j Date: Thu, 19 Nov 2026 09:29:42 +0100 Subject: [PATCH 035/130] craft-captions: preserve positive duration when centisecond rounding collapses cue in vplayer (#1747) --- crates/captions/src/vplayer.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/captions/src/vplayer.rs b/crates/captions/src/vplayer.rs index e8900c0b60..1124c2054c 100644 --- a/crates/captions/src/vplayer.rs +++ b/crates/captions/src/vplayer.rs @@ -87,9 +87,13 @@ pub fn write(doc: &Document) -> String { } let lines: Vec = lines.iter().map(|l| l.replace('|', "\u{ff5c}")).collect(); out.push_str(&format!("{}={}\n", clock(c.start), lines.join("|"))); + let end = if clock(c.end) == clock(c.start) { Tick(c.end.0.saturating_add(crate::TICKS_PER_MS * 10)) } else { c.end }; let next = cues.get(i + 1).map(|n| clock(n.start)); - if next.as_deref() != Some(clock(c.end).as_str()) { - out.push_str(&format!("{}=\n", clock(c.end))); + if next.as_deref() != Some(clock(end).as_str()) { + let next_too_early = cues.get(i + 1).is_some_and(|n| clock(n.start) <= clock(c.start)); + if !next_too_early { + out.push_str(&format!("{}=\n", clock(end))); + } } } out @@ -99,6 +103,20 @@ pub fn write(doc: &Document) -> String { mod tests { use super::*; + #[test] + fn short_duration_cue_preserves_positive_duration_on_write_and_read() { + let mut doc = Document::default(); + // A cue from 0 to 1 ms collapses to 00:00:00.00 under centisecond rounding. + doc.cues.push(Cue { start: ms_to_tick(0), end: ms_to_tick(1), text: "Short".to_string(), ..Default::default() }); + let written = write(&doc); + assert_eq!(written, "00:00:00.00=Short\n00:00:00.01=\n"); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 1); + assert_eq!(parsed.cues[0].text, "Short"); + assert_eq!(parsed.cues[0].start, ms_to_tick(0)); + assert_eq!(parsed.cues[0].end, ms_to_tick(10)); + } + #[test] fn separators_and_ends() { let d = parse("00:00:01:Hello|world\n00:00:04.50=\n00:00:05 later\n").unwrap(); From df2dcced497b953e2403114d7365a91e4be7a327 Mon Sep 17 00:00:00 2001 From: el-j Date: Thu, 19 Nov 2026 09:50:52 +0100 Subject: [PATCH 036/130] craft-audio: cover 20-bit in s302m oracle tests and clean up unused binding --- crates/audio/src/s302m.rs | 3 +- crates/audio/tests/s302m_oracle.rs | 58 +++++++++++++++--------------- 2 files changed, 31 insertions(+), 30 deletions(-) diff --git a/crates/audio/src/s302m.rs b/crates/audio/src/s302m.rs index 487391e696..f5e6cd790f 100644 --- a/crates/audio/src/s302m.rs +++ b/crates/audio/src/s302m.rs @@ -107,8 +107,7 @@ pub fn decode(packet: &[u8]) -> Result { let n = header.bits as usize; let mut samples = Vec::with_capacity(audio.len() / (n + 4) * 8 / 2); for frame in audio.chunks_exact(frame_bytes) { - for (sub, pos) in (0..header.channels).map(|c| (c, c * (n + 4))) { - let _ = sub; + for pos in (0..header.channels).map(|c| c * (n + 4)) { let mut v = 0u32; for k in 0..n { v |= bit(frame, pos + k) << k; diff --git a/crates/audio/tests/s302m_oracle.rs b/crates/audio/tests/s302m_oracle.rs index 68f6582def..1d1a0c60da 100644 --- a/crates/audio/tests/s302m_oracle.rs +++ b/crates/audio/tests/s302m_oracle.rs @@ -150,36 +150,38 @@ fn decoded_by_ffmpeg(ff: &Path, ts: &Path, out: &Path, wide: bool) -> Vec { fn we_decode_and_encode_what_ffmpeg_encodes_and_ffmpeg_decodes_ours() { let Some(ff) = craft_media_testkit::ffmpeg() else { return }; let dir = craft_media_testkit::fixture_subdir("s302m"); - for (channels, bits) in [(2usize, 16u32), (2, 24), (4, 24), (6, 16), (8, 24)] { + for (channels, bits) in [(2usize, 16u32), (2, 20), (2, 24), (4, 20), (4, 24), (6, 16), (6, 20), (8, 20), (8, 24)] { let name = format!("{channels}ch{bits}"); let frames = 6000; - let wide = bits == 24; + let wide = bits > 16; let pcm = signal(channels, frames, 17); let raw = dir.join(format!("{name}.pcm")); std::fs::write(&raw, pcm_bytes(&pcm, wide)).expect("write"); let ts = dir.join(format!("{name}.ts")); - ffmpeg( - &ff, - &[ - "-f", - if wide { "s32le" } else { "s16le" }, - "-ar", - "48000", - "-ac", - &channels.to_string(), - "-i", - &s(&raw), - "-af", - "asetnsamples=n=1024:p=0", - "-c:a", - "s302m", - "-strict", - "-2", - "-f", - "mpegts", - &s(&ts), - ], - ); + let ch_str = channels.to_string(); + let raw_str = s(&raw); + let ts_str = s(&ts); + let mut ff_args = vec![ + "-f", + if wide { "s32le" } else { "s16le" }, + "-ar", + "48000", + "-ac", + &ch_str, + "-i", + &raw_str, + "-af", + "asetnsamples=n=1024:p=0", + "-c:a", + "s302m", + "-strict", + "-2", + ]; + if bits == 20 { + ff_args.extend(["-bits_per_raw_sample", "20"]); + } + ff_args.extend(["-f", "mpegts", &ts_str]); + ffmpeg(&ff, &ff_args); let bytes = std::fs::read(&ts).expect("read"); let pieces = pes_pieces(&bytes); assert!(pieces.len() >= 2, "{name}: {} packets", pieces.len()); @@ -198,8 +200,8 @@ fn we_decode_and_encode_what_ffmpeg_encodes_and_ffmpeg_decodes_ours() { // our encoder writes the same bytes ffmpeg's does assert!(enc.encode(&d.samples).expect("encode") == packet, "{name}: our packet differs from ffmpeg's at frame {frames_seen}"); frames_seen += d.samples.len() / channels; - // 24-bit samples are scaled to 32 bits by ffmpeg's decoder; 16-bit ones are not - ours.extend(d.samples.iter().map(|&v| if wide { v << 8 } else { v })); + // 20-bit and 24-bit samples are scaled to 32 bits by ffmpeg's decoder; 16-bit ones are not + ours.extend(d.samples.iter().map(|&v| if bits == 16 { v } else { v << (32 - bits) })); } let n = ours.len().min(theirs.len()); assert!(n >= (frames - 1600) * channels, "{name}: {n} samples"); @@ -215,10 +217,10 @@ fn we_decode_and_encode_what_ffmpeg_encodes_and_ffmpeg_decodes_ours() { let h = parse_header(&es).expect("header"); let n_frames = h.audio_bytes / h.frame_bytes(); let at = expect.len(); - let src: Vec = mine[at..at + n_frames * channels].iter().map(|&v| if wide { v >> 8 } else { v >> 16 }).collect(); + let src: Vec = mine[at..at + n_frames * channels].iter().map(|&v| v >> (32 - bits)).collect(); let packet = enc.encode(&src).expect("encode"); assert_eq!(packet.len(), 4 + h.audio_bytes); - expect.extend(src.iter().map(|&v| if wide { v << 8 } else { v })); + expect.extend(src.iter().map(|&v| if bits == 16 { v } else { v << (32 - bits) })); let mut k = 0; for &(o, len) in pes { let take = len.min(packet.len() - k); From c36493506786f21fb54a16ac8ecb56696cb7d8b7 Mon Sep 17 00:00:00 2001 From: alehel Date: Thu, 19 Nov 2026 11:01:52 +0100 Subject: [PATCH 037/130] craft-video: adapt VideoFrame to encoder inputs --- crates/video/README.md | 50 ++++ crates/video/src/frame/encode.rs | 283 ++++++++++++++++++++++ crates/video/src/frame/encode/owned.rs | 224 +++++++++++++++++ crates/video/src/frame/encode/tests.rs | 322 +++++++++++++++++++++++++ crates/video/src/frame/mod.rs | 5 +- 5 files changed, 882 insertions(+), 2 deletions(-) create mode 100644 crates/video/src/frame/encode.rs create mode 100644 crates/video/src/frame/encode/owned.rs create mode 100644 crates/video/src/frame/encode/tests.rs diff --git a/crates/video/README.md b/crates/video/README.md index d05d503122..841042d048 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -56,6 +56,56 @@ comes with its codec's feature): The constructors check that every plane's buffer, stride and size fit the frame, so a picture with inconsistent fields is an error, not an out-of-bounds read. +## Preparing encoder input + +`frame::encode` adapts `VideoFrame` to the existing encoder APIs. It does not encode packets +or choose encoder settings. It preserves sample values: no colour-space conversion, chroma +resampling, range conversion or significant-bit-depth scaling is performed. + +| Encoder | Conversion / input | +|---|---| +| H.264 | `Planar8` then `.h264()` for 8-bit 4:2:0; `Planar16` and `.h264()` for 9/10-bit | +| HEVC, AV1 | `Planar16::try_from(&frame)?`, then `.hevc()` / `.av1()` for 8/10-bit 4:2:0 | +| MPEG-2 | `Planar8` then `.mpeg2()` for 4:2:0 or 4:2:2 | +| MPEG-4 Part 2 | `Planar8` then `.mpeg4()` for 4:2:0 | +| VP9 | `Planar8` then `.vp9()` gives packed `(y, u, v)` slices for `encode_frame` | +| ProRes, DNx, APV, FFV1 | `codec::Frame::try_from(&frame)` gives an owned input frame | +| Motion JPEG | `mjpeg::Frame::try_from(&frame)` interleaves 8-bit RGB or gray; alpha is rejected | +| Hap, VP8 | `Rgba8::try_from(&frame)` interleaves 8-bit RGB/gray and optional alpha for `encode_rgba` | + +`Planar8`, `Planar16` and `Rgba8` are in `craft_video::frame::encode` and are built with no +features. Each codec-specific method/conversion requires its encoder feature. Keep the planar +adapter alive while using a native view: + +```rust,ignore +use craft_video::frame::encode::Planar16; +let input = Planar16::try_from(&frame)?; +let native = input.hevc()?; +let packet = encoder.encode(&native)?; +``` + +Packed planes of the requested storage width are borrowed. Padded rows (including different +Cb/Cr strides) are packed; `u8` ↔ `u16` storage changes preserve values. Owned codec frames copy +the planes. DNx RGB input is reordered from R/G/B to its G/B/R layout. Conversion allocations +are checked against the shared picture memory budget and allocation failures return `FrameError`. + +Conversions reject zero dimensions, interlaced frames, mixed plane depths, out-of-range active +samples, and formats a destination cannot represent. Padding and trailing samples are ignored. +ProRes accepts limited-range YCbCr 4:2:2/4:4:4 (alpha only at 4:4:4); DNx accepts YCbCr 4:2:2/4:4:4 +or RGB without alpha; APV accepts gray or YCbCr 4:2:2/4:4:4, with alpha only at 4:4:4; FFV1 keeps +all supported families, alpha and chroma shifts. Interleaved adapters do not convert YCbCr to RGB. +VP8's encoder discards RGBA alpha, and opaque Hap variants do too: choose the codec/variant +accordingly. The RGBA adapter itself preserves alpha and synthesizes 255 only when absent. + +Set encoder dimensions, bit depth, chroma, colour tags, aspect ratio, frame rate and alpha options +from the source and export settings. Native input views do not configure the encoder. ProRes/DNx +frame metadata does not override their encoder configuration. Owned conversions copy fields +that exist in their input type, but profile IDs, frame-rate codes and HDR metadata absent from +`VideoFrame` remain unset. ProRes rejects an unrepresentable sample aspect ratio; DNx reduces it +and checks that it fits its 16-bit fields. Timestamps and the draft flag remain with the source; +pass timestamps separately to encoders that take them or to the container. Encoder profile and +size restrictions still apply at encoder construction/encoding. + ## Decoding a track `TrackDecoder` is the counterpart of `craft_audio::TrackDecoder` for an app with its own demuxer. diff --git a/crates/video/src/frame/encode.rs b/crates/video/src/frame/encode.rs new file mode 100644 index 0000000000..55a6bbcc5b --- /dev/null +++ b/crates/video/src/frame/encode.rs @@ -0,0 +1,283 @@ +//! Checked encoder input adapters. These change storage layout, never colour space, chroma +//! sampling, range or significant bit depth. Active samples outside their declared depth, +//! mixed plane depths, empty pictures and interlaced pictures are rejected. +//! +//! [`Planar8`] and [`Planar16`] borrow packed planes when their storage already matches. They +//! otherwise pack rows and widen/narrow storage without scaling values. Native views borrow +//! the adapter, so keep it alive through `encode`. Set the encoder's dimensions, depth, colour +//! tags, aspect ratio and timestamp separately from the source [`VideoFrame`]. Codec-specific +//! metadata absent from `VideoFrame` remains unset. Encoder configuration still validates +//! profile restrictions and size limits. +//! +//! ``` +//! use craft_video::frame::{VideoFrame, FrameError}; +//! use craft_video::frame::encode::Planar16; +//! fn prepare(frame: &VideoFrame) -> Result<(), FrameError> { +//! let input = Planar16::try_from(frame)?; +//! #[cfg(feature = "hevc-encode")] +//! let native = input.hevc()?; // encoder.encode(&native), while input is alive +//! Ok(()) +//! } +//! ``` +//! +//! [`Rgba8`] interleaves RGB or gray (replicated into R/G/B), with opaque alpha when absent. +//! Hap accepts these bytes; VP8 also accepts them but its encoder discards alpha. + +#[cfg(any( + test, + feature = "h264-encode", + feature = "hevc-encode", + feature = "av1-encode", + feature = "mpeg2-encode", + feature = "mpeg4-encode", + feature = "vp9-encode", + feature = "prores", + feature = "dnx", + feature = "apv-encode" +))] +use super::Subsampling; +use super::{ColorFamily, FieldOrder, FrameError, Plane, Samples, VideoFrame}; +use std::borrow::Cow; + +mod owned; + +/// Three borrowed colour planes in Y, Cb, Cr order. +pub type YuvPlanes<'a, T> = (&'a [T], &'a [T], &'a [T]); + +/// Packed planar input with samples in `u8` or `u16` storage. Construct through [`Planar8`] or +/// [`Planar16`]; padding is excluded, and the source's metadata remains available via `frame()`. +#[derive(Debug)] +pub struct PlanarInput<'a, T: Clone> { + frame: &'a VideoFrame, + planes: Vec>, + alpha: Option>, +} +/// Packed 8-bit samples (accepts either source storage at bit depth 8). +pub type Planar8<'a> = PlanarInput<'a, u8>; +/// Packed 8–16-bit samples in `u16` storage, without rescaling. +pub type Planar16<'a> = PlanarInput<'a, u16>; + +impl PlanarInput<'_, T> { + /// Source frame, including dimensions and metadata needed by encoder configuration. + pub fn frame(&self) -> &VideoFrame { + self.frame + } + /// Packed colour planes in the source's order. + pub fn planes(&self) -> &[Cow<'_, [T]>] { + &self.planes + } + /// Packed alpha, when present. + pub fn alpha(&self) -> Option<&[T]> { + self.alpha.as_deref() + } +} + +fn reserve(n: usize) -> Result, FrameError> { + let bytes = n.checked_mul(std::mem::size_of::()).ok_or(FrameError::Plane("encoder input size overflows"))?; + if bytes as u64 > crate::budget::DECODE_MEMORY_BUDGET { + return Err(FrameError::Plane("encoder input exceeds the picture memory budget")); + } + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| FrameError::Plane("cannot allocate encoder input"))?; + Ok(v) +} + +fn validate(f: &VideoFrame) -> Result<(), FrameError> { + if f.width == 0 || f.height == 0 { + return Err(FrameError::Shape("encoder input is empty")); + } + if f.field_order != FieldOrder::Progressive { + return Err(FrameError::Shape("encoder input must be progressive")); + } + let depth = f.bit_depth(); + if !(8..=16).contains(&depth) { + return Err(FrameError::Plane("encoder input depth must be 8 to 16")); + } + let mut total = 0u64; + for p in f.planes.iter().chain(f.alpha.iter()) { + if p.bit_depth != depth { + return Err(FrameError::Plane("encoder input plane depths differ")); + } + let bytes = u64::from(p.width) * u64::from(p.height); + total = bytes.checked_mul(2).and_then(|n| total.checked_add(n)).ok_or(FrameError::Plane("encoder input size overflows"))?; + if total > crate::budget::DECODE_MEMORY_BUDGET { + return Err(FrameError::Plane("encoder input exceeds the picture memory budget")); + } + for row in 0..p.height { + if let Some(values) = p.row_u16(row) + && values.iter().any(|&v| u32::from(v) >= 1u32 << depth) + { + return Err(FrameError::Plane("sample exceeds the declared bit depth")); + } + } + } + Ok(()) +} + +fn len(p: &Plane) -> Result { + usize::try_from(u64::from(p.width) * u64::from(p.height)).map_err(|_| FrameError::Plane("encoder input size overflows")) +} + +fn plane8(p: &Plane) -> Result, FrameError> { + let n = len(p)?; + if let Samples::U8(v) = &p.samples + && p.stride == p.width as usize + { + return v.get(..n).map(Cow::Borrowed).ok_or(FrameError::Plane("short plane")); + } + let mut out = reserve(n)?; + for row in 0..p.height { + match &p.samples { + Samples::U8(_) => out.extend_from_slice(p.row_u8(row).ok_or(FrameError::Plane("short row"))?), + Samples::U16(_) => { + for &v in p.row_u16(row).ok_or(FrameError::Plane("short row"))? { + out.push(u8::try_from(v).map_err(|_| FrameError::Plane("sample does not fit u8"))?); + } + } + } + } + Ok(Cow::Owned(out)) +} + +fn plane16(p: &Plane) -> Result, FrameError> { + let n = len(p)?; + if let Samples::U16(v) = &p.samples + && p.stride == p.width as usize + { + return v.get(..n).map(Cow::Borrowed).ok_or(FrameError::Plane("short plane")); + } + let mut out = reserve(n)?; + for row in 0..p.height { + match &p.samples { + Samples::U16(_) => out.extend_from_slice(p.row_u16(row).ok_or(FrameError::Plane("short row"))?), + Samples::U8(_) => out.extend(p.row_u8(row).ok_or(FrameError::Plane("short row"))?.iter().copied().map(u16::from)), + } + } + Ok(Cow::Owned(out)) +} + +impl<'a> TryFrom<&'a VideoFrame> for Planar8<'a> { + type Error = FrameError; + fn try_from(f: &'a VideoFrame) -> Result { + validate(f)?; + if f.bit_depth() != 8 { + return Err(FrameError::Plane("8-bit input required; rescale explicitly")); + } + Ok(Self { frame: f, planes: f.planes.iter().map(plane8).collect::>()?, alpha: f.alpha.as_ref().map(plane8).transpose()? }) + } +} +impl<'a> TryFrom<&'a VideoFrame> for Planar16<'a> { + type Error = FrameError; + fn try_from(f: &'a VideoFrame) -> Result { + validate(f)?; + Ok(Self { frame: f, planes: f.planes.iter().map(plane16).collect::>()?, alpha: f.alpha.as_ref().map(plane16).transpose()? }) + } +} + +// These input structs have a single shared chroma stride; packing also handles source planes +// with different strides, and VP9's slice-only API requires packed rows. +#[cfg(any( + feature = "h264-encode", + feature = "hevc-encode", + feature = "av1-encode", + feature = "mpeg2-encode", + feature = "mpeg4-encode", + feature = "vp9-encode" +))] +impl PlanarInput<'_, T> { + fn yuv(&self, subs: &[Subsampling], depths: &[u8]) -> Result, FrameError> { + if self.frame.family != ColorFamily::YCbCr || !subs.contains(&self.frame.subsampling) || self.alpha.is_some() { + return Err(FrameError::Shape("encoder requires YCbCr with supported subsampling and no alpha")); + } + if !depths.contains(&self.frame.bit_depth()) { + return Err(FrameError::Plane("unsupported encoder input depth")); + } + let [y, u, v] = self.planes.as_slice() else { + return Err(FrameError::Shape("three colour planes required")); + }; + Ok((y, u, v)) + } +} + +impl Planar8<'_> { + /// H.264 8-bit 4:2:0 view. Configure the encoder for this frame's dimensions. + #[cfg(feature = "h264-encode")] + pub fn h264(&self) -> Result, FrameError> { + let (y, u, v) = self.yuv(&[Subsampling::S420], &[8])?; + Ok(crate::h264::YuvFrame { y, u, v, y_stride: self.frame.width as usize, uv_stride: self.frame.width.div_ceil(2) as usize }) + } + /// MPEG-2 8-bit 4:2:0 or 4:2:2 view. Match the encoder's chroma configuration. + #[cfg(feature = "mpeg2-encode")] + pub fn mpeg2(&self) -> Result, FrameError> { + let (y, cb, cr) = self.yuv(&[Subsampling::S420, Subsampling::S422], &[8])?; + Ok(crate::mpeg2::YuvFrame { y, cb, cr, y_stride: self.frame.width as usize, c_stride: self.frame.width.div_ceil(2) as usize }) + } + /// MPEG-4 Part 2 8-bit 4:2:0 view. + #[cfg(feature = "mpeg4-encode")] + pub fn mpeg4(&self) -> Result, FrameError> { + let (y, u, v) = self.yuv(&[Subsampling::S420], &[8])?; + Ok(crate::mpeg4::YuvFrame { y, u, v, y_stride: self.frame.width as usize, uv_stride: self.frame.width.div_ceil(2) as usize }) + } + /// Packed 8-bit 4:2:0 slices for VP9's `encode_frame(y, u, v, force_key)`. + #[cfg(feature = "vp9-encode")] + pub fn vp9(&self) -> Result, FrameError> { + self.yuv(&[Subsampling::S420], &[8]) + } +} +impl Planar16<'_> { + /// H.264 high-depth view. Configure the encoder with the same 9- or 10-bit depth. + #[cfg(feature = "h264-encode")] + pub fn h264(&self) -> Result, FrameError> { + let (y, u, v) = self.yuv(&[Subsampling::S420], &[9, 10])?; + Ok(crate::h264::YuvFrame16 { y, u, v, y_stride: self.frame.width as usize, uv_stride: self.frame.width.div_ceil(2) as usize }) + } + /// HEVC 8- or 10-bit 4:2:0 view. Match the encoder profile to the source depth. + #[cfg(feature = "hevc-encode")] + pub fn hevc(&self) -> Result, FrameError> { + let (y, u, v) = self.yuv(&[Subsampling::S420], &[8, 10])?; + Ok(crate::hevc::Frame { y, u, v, y_stride: self.frame.width as usize, uv_stride: self.frame.width.div_ceil(2) as usize }) + } + /// AV1 8- or 10-bit 4:2:0 view. Match the configured depth to the source depth. + #[cfg(feature = "av1-encode")] + pub fn av1(&self) -> Result, FrameError> { + let (y, u, v) = self.yuv(&[Subsampling::S420], &[8, 10])?; + Ok(crate::av1::Frame { y, u, v, y_stride: self.frame.width as usize, uv_stride: self.frame.width.div_ceil(2) as usize }) + } +} + +/// Interleaved 8-bit RGBA pixels for Hap and VP8's `encode_rgba` APIs. No YCbCr-to-RGB +/// conversion is performed. The caller chooses a Hap variant that preserves alpha, or explicitly +/// accepts alpha loss in VP8 / opaque Hap variants. +#[derive(Debug)] +pub struct Rgba8 { + pub width: u32, + pub height: u32, + pub pixels: Vec, +} +impl TryFrom<&VideoFrame> for Rgba8 { + type Error = FrameError; + fn try_from(f: &VideoFrame) -> Result { + let p = Planar8::try_from(f)?; + if !matches!(f.family, ColorFamily::Rgb | ColorFamily::Gray) { + return Err(FrameError::Shape("RGBA input requires RGB or gray")); + } + let n = len(f.planes.first().ok_or(FrameError::Shape("missing plane"))?)?; + let mut pixels = reserve(n.checked_mul(4).ok_or(FrameError::Shape("RGBA size overflows"))?)?; + for i in 0..n { + let first = p.planes.first().and_then(|p| p.get(i)).copied().ok_or(FrameError::Plane("short plane"))?; + for channel in 0..3 { + let v = if f.family == ColorFamily::Gray { + first + } else { + p.planes.get(channel).and_then(|p| p.get(i)).copied().ok_or(FrameError::Plane("short plane"))? + }; + pixels.push(v); + } + pixels.push(p.alpha.as_ref().and_then(|a| a.get(i)).copied().unwrap_or(255)); + } + Ok(Self { width: f.width, height: f.height, pixels }) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/video/src/frame/encode/owned.rs b/crates/video/src/frame/encode/owned.rs new file mode 100644 index 0000000000..5735a21c8c --- /dev/null +++ b/crates/video/src/frame/encode/owned.rs @@ -0,0 +1,224 @@ +//! Owned codec frames. Their buffers are copied; source samples and metadata are not modified. + +#[cfg(any(feature = "prores", feature = "dnx", feature = "apv-encode"))] +use super::Subsampling; + +#[cfg(any(feature = "prores", feature = "dnx", feature = "apv-encode", feature = "ffv1", feature = "mjpeg"))] +// Each codec feature uses a different subset of the conversion helpers. +#[allow(unused_imports)] +use super::{ColorFamily, Cow, FrameError, Planar8, Planar16, VideoFrame, len, reserve}; + +#[cfg(any(feature = "prores", feature = "dnx", feature = "apv-encode", feature = "ffv1"))] +fn owned(plane: Cow<'_, [u16]>) -> Result, FrameError> { + match plane { + Cow::Owned(v) => Ok(v), + Cow::Borrowed(v) => { + let mut out = reserve(v.len())?; + out.extend_from_slice(v); + Ok(out) + } + } +} + +#[cfg(any(feature = "prores", feature = "dnx", feature = "apv-encode"))] +struct Components { + y: Vec, + cb: Vec, + cr: Vec, + alpha: Option>, +} + +#[cfg(any(feature = "prores", feature = "dnx", feature = "apv-encode"))] +fn components(f: &VideoFrame) -> Result { + let p = Planar16::try_from(f)?; + let mut planes = p.planes.into_iter(); + let y = owned(planes.next().ok_or(FrameError::Shape("missing colour plane"))?)?; + let cb = planes.next().map(owned).transpose()?.unwrap_or_default(); + let cr = planes.next().map(owned).transpose()?.unwrap_or_default(); + Ok(Components { y, cb, cr, alpha: p.alpha.map(owned).transpose()? }) +} + +#[cfg(feature = "prores")] +impl TryFrom<&VideoFrame> for crate::prores::Frame { + type Error = FrameError; + /// Copy YCbCr 4:2:2/4:4:4 into packed `u16` planes; alpha requires 4:4:4. + /// Colour and representable aspect ratio are copied. Frame rate is unset; configure the + /// encoder's colour, aspect, frame rate and alpha options separately (it uses its config). + fn try_from(f: &VideoFrame) -> Result { + use crate::prores::{ChromaFormat, ColorInfo, Interlace}; + if f.family != ColorFamily::YCbCr || f.color.full_range { + return Err(FrameError::Shape("ProRes requires limited-range YCbCr")); + } + let chroma = match f.subsampling { + Subsampling::S422 if f.alpha.is_none() => ChromaFormat::Yuv422, + Subsampling::S444 => ChromaFormat::Yuv444, + _ => return Err(FrameError::Shape("ProRes requires 4:2:2 without alpha or 4:4:4")), + }; + let aspect_ratio = match f.sar { + None => 0, + Some((n, d)) if n > 0 && n == d => 1, + Some((n, d)) if n > 0 && d > 0 && u128::from(n) * u128::from(f.width) * 3 == u128::from(d) * u128::from(f.height) * 4 => 2, + Some((n, d)) if n > 0 && d > 0 && u128::from(n) * u128::from(f.width) * 9 == u128::from(d) * u128::from(f.height) * 16 => 3, + _ => return Err(FrameError::Shape("aspect ratio cannot be represented by ProRes")), + }; + let Components { y, cb, cr, alpha } = components(f)?; + let code = |v| if v == 2 { 0 } else { v }; + Ok(Self { + width: f.width, + height: f.height, + chroma, + bit_depth: f.bit_depth(), + y, + cb, + cr, + alpha, + interlace: Interlace::Progressive, + color: ColorInfo { primaries: code(f.color.primaries), transfer: code(f.color.transfer), matrix: code(f.color.matrix) }, + aspect_ratio, + frame_rate_code: 0, + }) + } +} + +#[cfg(feature = "dnx")] +impl TryFrom<&VideoFrame> for crate::dnx::Frame { + type Error = FrameError; + /// Copy YCbCr 4:2:2/4:4:4 or RGB into DNx's Y/Cb/Cr or G/B/R planes. Alpha is unsupported + /// by this encoder. CID is unset (selected by encoder profile). Colour volume and pixel + /// aspect are copied where representable; encoder signalling is configured separately. + fn try_from(f: &VideoFrame) -> Result { + use crate::dnx::{ChromaFormat, ColorVolume, Interlace}; + if f.alpha.is_some() { + return Err(FrameError::Shape("DNx encoder does not support alpha")); + } + let chroma = match (f.family, f.subsampling) { + (ColorFamily::YCbCr, Subsampling::S422) => ChromaFormat::Yuv422, + (ColorFamily::YCbCr | ColorFamily::Rgb, Subsampling::S444) => ChromaFormat::Yuv444, + _ => return Err(FrameError::Shape("DNx encoder requires 4:2:2 or 4:4:4 YCbCr, or RGB")), + }; + let par = match f.sar { + None => (0, 0), + Some((mut n, mut d)) if n > 0 && d > 0 => { + let (mut a, mut b) = (n, d); + while b != 0 { + (a, b) = (b, a % b); + } + n /= a; + d /= a; + ( + u16::try_from(n).map_err(|_| FrameError::Shape("DNx pixel aspect ratio exceeds u16"))?, + u16::try_from(d).map_err(|_| FrameError::Shape("DNx pixel aspect ratio exceeds u16"))?, + ) + } + _ => return Err(FrameError::Shape("invalid pixel aspect ratio")), + }; + let Components { mut y, mut cb, mut cr, alpha } = components(f)?; + let rgb = f.family == ColorFamily::Rgb; + if rgb { + (y, cb, cr) = (cb, cr, y); + } + let color_volume = match f.color.matrix { + 1 => ColorVolume::Bt709, + 9 => ColorVolume::Bt2020Ncl, + 10 => ColorVolume::Bt2020Cl, + _ => ColorVolume::OutOfBand, + }; + Ok(Self { + width: f.width, + height: f.height, + chroma, + rgb, + bit_depth: f.bit_depth(), + y, + cb, + cr, + alpha, + interlace: Interlace::Progressive, + color_volume, + cid: 0, + par, + }) + } +} + +#[cfg(feature = "apv-encode")] +impl TryFrom<&VideoFrame> for crate::apv::Frame { + type Error = FrameError; + /// Copy gray, 4:2:2 or 4:4:4 YCbCr (alpha only with 4:4:4). Colour tags are copied. + /// Profile/level/band are unset: the encoder chooses them from its configuration. + fn try_from(f: &VideoFrame) -> Result { + use crate::apv::{ChromaFormat, ColorInfo}; + let chroma = match (f.family, f.subsampling, f.alpha.is_some()) { + (ColorFamily::Gray, _, false) => ChromaFormat::Monochrome, + (ColorFamily::YCbCr, Subsampling::S422, false) => ChromaFormat::Yuv422, + (ColorFamily::YCbCr, Subsampling::S444, false) => ChromaFormat::Yuv444, + (ColorFamily::YCbCr, Subsampling::S444, true) => ChromaFormat::Yuv4444, + _ => return Err(FrameError::Shape("APV requires gray, 4:2:2 or 4:4:4 YCbCr; alpha requires 4:4:4")), + }; + let Components { y, cb, cr, alpha } = components(f)?; + Ok(Self { + width: f.width, + height: f.height, + chroma, + bit_depth: f.bit_depth(), + y, + cb, + cr, + alpha, + color: ColorInfo { primaries: f.color.primaries, transfer: f.color.transfer, matrix: f.color.matrix, full_range: f.color.full_range }, + profile_idc: 0, + level_idc: 0, + band_idc: 0, + mastering_display: None, + content_light: None, + }) + } +} + +#[cfg(feature = "ffv1")] +impl TryFrom<&VideoFrame> for crate::ffv1::Frame { + type Error = FrameError; + /// Copy gray, YCbCr or RGB and optional alpha to FFV1 planes, preserving depth and chroma + /// shifts. Colour tags, SAR and timestamps have no fields here and remain out of band. + fn try_from(f: &VideoFrame) -> Result { + let p = Planar16::try_from(f)?; + let mut planes = p.planes.into_iter().map(owned).collect::, _>>()?; + if let Some(a) = p.alpha { + planes.push(owned(a)?); + } + Ok(Self { + width: f.width, + height: f.height, + colorspace: if f.family == ColorFamily::Rgb { crate::ffv1::Colorspace::Rgb } else { crate::ffv1::Colorspace::YCbCr }, + bit_depth: f.bit_depth(), + chroma_shift: (f.subsampling.x, f.subsampling.y), + planes, + }) + } +} + +#[cfg(feature = "mjpeg")] +impl TryFrom<&VideoFrame> for crate::mjpeg::Frame { + type Error = FrameError; + /// Interleave 8-bit RGB or gray for the baseline encoder. Alpha is rejected to avoid silently + /// dropping it. Colour tags, SAR and timestamps must be carried by the caller/container. + fn try_from(f: &VideoFrame) -> Result { + let p = Planar8::try_from(f)?; + let channels = match f.family { + ColorFamily::Rgb => 3, + ColorFamily::Gray => 1, + _ => return Err(FrameError::Shape("Motion JPEG input requires RGB or gray")), + }; + if p.alpha.is_some() { + return Err(FrameError::Shape("Motion JPEG encoder does not preserve alpha")); + } + let n = len(f.planes.first().ok_or(FrameError::Shape("missing plane"))?)?; + let mut pixels = reserve(n.checked_mul(channels).ok_or(FrameError::Shape("RGB size overflows"))?)?; + for i in 0..n { + for plane in &p.planes { + pixels.push(*plane.get(i).ok_or(FrameError::Plane("short plane"))?); + } + } + Ok(Self { width: f.width, height: f.height, channels: channels as u8, samples: crate::mjpeg::Samples::U8(pixels), damaged: false }) + } +} diff --git a/crates/video/src/frame/encode/tests.rs b/crates/video/src/frame/encode/tests.rs new file mode 100644 index 0000000000..c0089da2d2 --- /dev/null +++ b/crates/video/src/frame/encode/tests.rs @@ -0,0 +1,322 @@ +use super::*; + +fn picture(family: ColorFamily, sub: Subsampling, depth: u8, wide: bool, alpha: bool) -> VideoFrame { + let (w, h) = (4, 2); + let plane = |pw: u32, ph: u32, value: u16| { + let stride = pw as usize + 2; + let mut samples = vec![u16::MAX; stride * ph as usize]; + for row in 0..ph as usize { + samples[row * stride..row * stride + pw as usize].fill(value); + } + let samples = if wide { Samples::U16(samples) } else { Samples::U8(samples.into_iter().map(|v| v as u8).collect()) }; + Plane::new(pw, ph, stride, depth, samples).unwrap() + }; + let mut planes = vec![plane(w, h, 16)]; + if family != ColorFamily::Gray { + let (cw, ch) = sub.chroma_size(w, h); + planes.extend([plane(cw, ch, 32), plane(cw, ch, 48)]); + } + VideoFrame::new(w, h, family, sub, planes, alpha.then(|| plane(w, h, 64))).unwrap() +} + +#[test] +fn packs_rows_and_changes_storage_without_rescaling() { + for wide in [false, true] { + let f = picture(ColorFamily::YCbCr, Subsampling::S420, 8, wide, false); + let p8 = Planar8::try_from(&f).unwrap(); + let p16 = Planar16::try_from(&f).unwrap(); + assert_eq!(&*p8.planes[0], &[16; 8]); + assert_eq!(&*p8.planes[1], &[32; 2]); + assert_eq!(&*p16.planes[2], &[48; 2]); + assert_eq!(p16.frame().bit_depth(), 8); + } +} + +#[test] +fn packed_storage_is_borrowed_and_trailing_samples_are_excluded() { + let f = VideoFrame::new(2, 1, ColorFamily::Gray, Subsampling::S444, vec![Plane::packed(2, 1, 8, Samples::U8(vec![17, 18, 99])).unwrap()], None) + .unwrap(); + let p = Planar8::try_from(&f).unwrap(); + assert!(matches!(p.planes[0], Cow::Borrowed(_))); + assert_eq!(&*p.planes[0], &[17, 18]); +} + +#[test] +fn invalid_depth_values_and_fields_are_rejected() { + let mut f = picture(ColorFamily::YCbCr, Subsampling::S420, 10, true, false); + assert!(Planar8::try_from(&f).is_err()); + f.planes[1].bit_depth = 9; + assert!(Planar16::try_from(&f).is_err()); + f.planes[1].bit_depth = 10; + f.field_order = FieldOrder::TopFieldFirst; + assert!(Planar16::try_from(&f).is_err()); + f.field_order = FieldOrder::Progressive; + if let Samples::U16(v) = &mut f.planes[0].samples { + v[0] = 1024; + } + assert!(Planar16::try_from(&f).is_err()); +} + +#[test] +fn rgba_interleaves_rgb_and_gray_and_preserves_alpha() { + let f = picture(ColorFamily::Rgb, Subsampling::S444, 8, true, true); + let rgba = Rgba8::try_from(&f).unwrap(); + assert_eq!(rgba.pixels, [16, 32, 48, 64].repeat(8)); + let f = picture(ColorFamily::Gray, Subsampling::S444, 8, false, false); + assert_eq!(Rgba8::try_from(&f).unwrap().pixels, [16, 16, 16, 255].repeat(8)); + assert!(Rgba8::try_from(&picture(ColorFamily::YCbCr, Subsampling::S420, 8, false, false)).is_err()); +} + +#[cfg(feature = "h264-encode")] +#[test] +fn h264_views_reject_alpha_and_wrong_depth() { + let f = picture(ColorFamily::YCbCr, Subsampling::S420, 8, false, false); + let p = Planar8::try_from(&f).unwrap(); + assert_eq!(p.h264().unwrap().u, &[32; 2]); + assert!(Planar16::try_from(&f).unwrap().h264().is_err()); + let f = picture(ColorFamily::YCbCr, Subsampling::S420, 10, true, false); + assert_eq!(Planar16::try_from(&f).unwrap().h264().unwrap().y, &[16; 8]); + let f = picture(ColorFamily::YCbCr, Subsampling::S420, 8, false, true); + assert!(Planar8::try_from(&f).unwrap().h264().is_err()); +} + +#[cfg(feature = "prores")] +#[test] +fn prores_preserves_colour_aspect_and_alpha() { + let mut f = picture(ColorFamily::YCbCr, Subsampling::S444, 10, true, true); + f.sar = Some((2, 3)); // 4x2 at SAR 2:3 has display aspect 4:3. + let native = crate::prores::Frame::try_from(&f).unwrap(); + assert_eq!(native.aspect_ratio, 2); + assert_eq!(native.color.primaries, 0); + assert_eq!(native.alpha, Some(vec![64; 8])); + assert_eq!(VideoFrame::try_from(native).unwrap().sar, f.sar); + f.sar = Some((7, 11)); + assert!(crate::prores::Frame::try_from(&f).is_err()); +} + +#[cfg(feature = "dnx")] +#[test] +fn dnx_reorders_rgb_to_gbr_and_reduces_aspect() { + let mut f = picture(ColorFamily::Rgb, Subsampling::S444, 10, true, false); + f.sar = Some((100000, 100000)); + let native = crate::dnx::Frame::try_from(&f).unwrap(); + assert!(native.rgb); + assert_eq!(native.par, (1, 1)); + assert_eq!(native.y, vec![32; 8]); + assert_eq!(native.cb, vec![48; 8]); + assert_eq!(native.cr, vec![16; 8]); +} + +#[cfg(feature = "apv-encode")] +#[test] +fn apv_maps_gray_and_alpha_chroma() { + let f = picture(ColorFamily::Gray, Subsampling::S444, 10, true, false); + let native = crate::apv::Frame::try_from(&f).unwrap(); + assert_eq!(native.chroma, crate::apv::ChromaFormat::Monochrome); + assert!(native.cb.is_empty()); + let f = picture(ColorFamily::YCbCr, Subsampling::S444, 10, true, true); + assert_eq!(crate::apv::Frame::try_from(&f).unwrap().chroma, crate::apv::ChromaFormat::Yuv4444); +} + +#[cfg(feature = "ffv1")] +#[test] +fn ffv1_input_round_trips_samples_through_encoder() { + let f = picture(ColorFamily::Rgb, Subsampling::S444, 10, true, true); + let native = crate::ffv1::Frame::try_from(&f).unwrap(); + let enc = crate::ffv1::Encoder::new(&native, Default::default()).unwrap(); + let dec = crate::ffv1::Decoder::new(&enc.config_record(), f.width, f.height).unwrap(); + assert_eq!(dec.decode(&enc.encode(&native).unwrap()).unwrap(), native); +} + +#[cfg(feature = "mjpeg")] +#[test] +fn mjpeg_interleaves_and_refuses_alpha() { + let f = picture(ColorFamily::Rgb, Subsampling::S444, 8, false, false); + let native = crate::mjpeg::Frame::try_from(&f).unwrap(); + assert_eq!(native.samples, crate::mjpeg::Samples::U8([16, 32, 48].repeat(8))); + assert!(crate::mjpeg::Frame::try_from(&picture(ColorFamily::Rgb, Subsampling::S444, 8, false, true)).is_err()); +} + +#[cfg(any( + feature = "h264-encode", + feature = "hevc-encode", + feature = "av1-encode", + feature = "mpeg2-encode", + feature = "mpeg4-encode", + feature = "vp9-encode" +))] +#[test] +fn planar_views_are_accepted_by_the_encoders() { + let planes = vec![ + Plane::packed(32, 32, 8, Samples::U8(vec![64; 1024])).unwrap(), + Plane::packed(16, 16, 8, Samples::U8(vec![128; 256])).unwrap(), + Plane::packed(16, 16, 8, Samples::U8(vec![128; 256])).unwrap(), + ]; + let f = VideoFrame::new(32, 32, ColorFamily::YCbCr, Subsampling::S420, planes, None).unwrap(); + #[cfg(any(feature = "h264-encode", feature = "mpeg2-encode", feature = "mpeg4-encode", feature = "vp9-encode"))] + let p = Planar8::try_from(&f).unwrap(); + #[cfg(any(feature = "hevc-encode", feature = "av1-encode"))] + let deep = Planar16::try_from(&f).unwrap(); + #[cfg(feature = "h264-encode")] + { + let mut enc = crate::h264::Encoder::new(crate::h264::EncoderConfig::new(32, 32, 30, 1)).unwrap(); + let mut packets = enc.encode(&p.h264().unwrap(), 7).unwrap(); + packets.extend(enc.flush()); + assert!(!packets.is_empty()); + } + #[cfg(feature = "hevc-encode")] + { + let mut enc = crate::hevc::Encoder::new(crate::hevc::EncoderConfig::new(32, 32, 30, 1)).unwrap(); + assert!(!enc.encode(&deep.hevc().unwrap()).unwrap().data.is_empty()); + } + #[cfg(feature = "av1-encode")] + { + let mut enc = crate::av1::Encoder::new(crate::av1::EncoderConfig::new(32, 32, 30, 1)).unwrap(); + assert!(!enc.encode(&deep.av1().unwrap()).unwrap().data.is_empty()); + } + #[cfg(feature = "mpeg2-encode")] + { + let mut enc = crate::mpeg2::Encoder::new(crate::mpeg2::EncoderConfig::new(32, 32, 30, 1)).unwrap(); + let mut packets = enc.encode(&p.mpeg2().unwrap(), 7).unwrap(); + packets.extend(enc.flush()); + assert!(!packets.is_empty()); + } + #[cfg(feature = "mpeg4-encode")] + { + let mut enc = crate::mpeg4::Encoder::new(crate::mpeg4::EncoderConfig::new(32, 32, 30, 1)).unwrap(); + assert!(!enc.encode(&p.mpeg4().unwrap()).unwrap().data.is_empty()); + } + #[cfg(feature = "vp9-encode")] + { + let mut enc = crate::vp9::Vp9Encoder::new(crate::vp9::EncoderConfig { width: 32, height: 32, ..Default::default() }); + let (y, u, v) = p.vp9().unwrap(); + assert!(!enc.encode_frame(y, u, v, true).is_empty()); + } +} + +#[cfg(any(feature = "vp8-encode", feature = "hap", feature = "mjpeg"))] +#[test] +fn interleaved_inputs_are_accepted_by_the_encoders() { + let f = picture(ColorFamily::Rgb, Subsampling::S444, 8, false, false); + #[cfg(any(feature = "vp8-encode", feature = "hap"))] + let rgba = Rgba8::try_from(&f).unwrap(); + #[cfg(feature = "vp8-encode")] + assert!(!crate::vp8::encode_rgba(&rgba.pixels, rgba.width, rgba.height, &Default::default()).unwrap().data.is_empty()); + #[cfg(feature = "hap")] + assert!(!crate::hap::Encoder::new(rgba.width, rgba.height, crate::hap::Variant::Hap).unwrap().encode_rgba(&rgba.pixels).unwrap().is_empty()); + #[cfg(feature = "mjpeg")] + assert!(!crate::mjpeg::Encoder::default().encode_frame(&crate::mjpeg::Frame::try_from(&f).unwrap()).unwrap().is_empty()); +} + +#[cfg(any(feature = "prores", feature = "dnx", feature = "apv-encode"))] +#[test] +fn owned_frames_are_accepted_by_the_encoders() { + let f = VideoFrame::new( + 64, + 64, + ColorFamily::YCbCr, + Subsampling::S422, + vec![ + Plane::packed(64, 64, 10, Samples::U16(vec![256; 4096])).unwrap(), + Plane::packed(32, 64, 10, Samples::U16(vec![512; 2048])).unwrap(), + Plane::packed(32, 64, 10, Samples::U16(vec![512; 2048])).unwrap(), + ], + None, + ) + .unwrap(); + #[cfg(feature = "prores")] + assert!( + !crate::prores::Encoder::new(crate::prores::Profile::Proxy, 64, 64).encode(&crate::prores::Frame::try_from(&f).unwrap()).unwrap().is_empty() + ); + #[cfg(feature = "dnx")] + assert!( + !crate::dnx::Encoder::new(crate::dnx::Profile::Hqx, 64, 64).unwrap().encode(&crate::dnx::Frame::try_from(&f).unwrap()).unwrap().is_empty() + ); + #[cfg(feature = "apv-encode")] + assert!( + !crate::apv::Encoder::new(crate::apv::Profile::P422_10, 64, 64) + .unwrap() + .encode(&crate::apv::Frame::try_from(&f).unwrap()) + .unwrap() + .is_empty() + ); +} + +#[test] +fn zero_sizes_and_oversized_allocations_are_errors() { + let f = VideoFrame::new(0, 0, ColorFamily::Gray, Subsampling::S444, vec![Plane::packed(0, 0, 8, Samples::U8(vec![])).unwrap()], None).unwrap(); + assert!(Planar8::try_from(&f).is_err()); + assert!(reserve::(usize::MAX).is_err()); + assert!(reserve::(crate::budget::DECODE_MEMORY_BUDGET as usize + 1).is_err()); +} + +#[cfg(any( + feature = "h264-encode", + feature = "hevc-encode", + feature = "av1-encode", + feature = "mpeg2-encode", + feature = "mpeg4-encode", + feature = "vp9-encode" +))] +#[test] +fn views_reject_incompatible_chroma_and_depth() { + let f = picture(ColorFamily::YCbCr, Subsampling::S422, 8, false, false); + #[cfg(any(feature = "h264-encode", feature = "mpeg2-encode", feature = "mpeg4-encode", feature = "vp9-encode"))] + let p = Planar8::try_from(&f).unwrap(); + #[cfg(feature = "h264-encode")] + assert!(p.h264().is_err()); + #[cfg(feature = "mpeg4-encode")] + assert!(p.mpeg4().is_err()); + #[cfg(feature = "vp9-encode")] + assert!(p.vp9().is_err()); + #[cfg(feature = "mpeg2-encode")] + assert_eq!(p.mpeg2().unwrap().cb.len(), 4); + #[cfg(any(feature = "hevc-encode", feature = "av1-encode"))] + { + let p = Planar16::try_from(&f).unwrap(); + #[cfg(feature = "hevc-encode")] + assert!(p.hevc().is_err()); + #[cfg(feature = "av1-encode")] + assert!(p.av1().is_err()); + let f = picture(ColorFamily::YCbCr, Subsampling::S420, 12, true, false); + let p = Planar16::try_from(&f).unwrap(); + #[cfg(feature = "hevc-encode")] + assert!(p.hevc().is_err()); + #[cfg(feature = "av1-encode")] + assert!(p.av1().is_err()); + } +} + +#[test] +fn unequal_chroma_strides_and_high_depth_samples_are_preserved() { + let mut f = picture(ColorFamily::YCbCr, Subsampling::S422, 10, true, false); + f.planes[2] = Plane::new(2, 2, 7, 10, Samples::U16(vec![1023, 900, 65535, 65535, 65535, 65535, 65535, 800, 700])).unwrap(); + let p = Planar16::try_from(&f).unwrap(); + assert_eq!(&*p.planes[2], &[1023, 900, 800, 700]); + assert_eq!(&*p.planes[1], &[32; 4]); +} + +#[cfg(any(feature = "prores", feature = "dnx", feature = "apv-encode"))] +#[test] +fn owned_inputs_reject_shapes_that_would_drop_information() { + #[cfg(feature = "prores")] + { + let mut f = picture(ColorFamily::YCbCr, Subsampling::S422, 10, true, false); + f.color.full_range = true; + assert!(crate::prores::Frame::try_from(&f).is_err()); + let f = picture(ColorFamily::YCbCr, Subsampling::S422, 10, true, true); + assert!(crate::prores::Frame::try_from(&f).is_err()); + } + #[cfg(feature = "dnx")] + { + let f = picture(ColorFamily::Rgb, Subsampling::S444, 10, true, true); + assert!(crate::dnx::Frame::try_from(&f).is_err()); + } + #[cfg(feature = "apv-encode")] + { + let f = picture(ColorFamily::Rgb, Subsampling::S444, 10, true, false); + assert!(crate::apv::Frame::try_from(&f).is_err()); + let f = picture(ColorFamily::Gray, Subsampling::S444, 10, true, true); + assert!(crate::apv::Frame::try_from(&f).is_err()); + } +} diff --git a/crates/video/src/frame/mod.rs b/crates/video/src/frame/mod.rs index cf092f43f1..491f3c8b2d 100644 --- a/crates/video/src/frame/mod.rs +++ b/crates/video/src/frame/mod.rs @@ -1,4 +1,4 @@ -//! A codec-agnostic decoded video frame. +//! A codec-agnostic video frame, with decoder output and encoder input conversions. //! //! Each decoder in this crate returns its own picture type. [`VideoFrame`] holds what they have in //! common: planar samples at their stored width (`u8` or `u16`), per-plane bit depth, chroma @@ -16,6 +16,7 @@ //! never goes out of bounds. They do not check that sample values fit the bit depth. mod convert; +pub mod encode; /// Why a frame or plane was rejected. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] @@ -224,7 +225,7 @@ pub enum FieldOrder { BottomFieldFirst, } -/// A decoded frame in planar form, independent of the codec. +/// A frame in planar form, independent of the codec. See [`encode`] for encoder input adapters. #[derive(Clone, Debug, PartialEq, Eq)] pub struct VideoFrame { width: u32, From 9217e6db961382549dc2c1969f104726fe0fb10f Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Thu, 19 Nov 2026 20:28:08 +0530 Subject: [PATCH 038/130] cms: curve black stays within the ink limit; FOGRA39 reference test fails a NaN ink Follow-ups to the review of #2028: - `gcr` caps black at `tac`. A curve such as `[[0, 0.75]]` with a 50 % ink limit gave K 0.75 and left the CMY solve a limit of zero, so the separation broke the limit on black alone. No shipped profile changes: their black stays below their limit (regenerated bytes identical). - `separates_like_the_reference_application` asserts every ink is finite before the `f32::max` reduction, which would drop a NaN difference. --- crates/cms/src/synth.rs | 16 ++++++++++++++-- crates/cms/tests/fogra39.rs | 2 ++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index d192127ec4..e17025a78d 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -313,7 +313,8 @@ fn solve_cmy_by(model: &F, k: f64, limit: f64, seeds: &[[f6 const SEEDS: [[f64; 3]; 5] = [[0.3, 0.3, 0.3], [0.05, 0.05, 0.05], [0.8, 0.8, 0.8], [0.9, 0.2, 0.2], [0.2, 0.9, 0.9]]; -/// Black for a gray component `g` (the smallest of C, M, Y without black). +/// Black for a gray component `g` (the smallest of C, M, Y without black), at most the total ink +/// limit: the CMY solve gets `tac - k`, so black above `tac` would break the limit on its own. fn gcr(p: &CmykParams, g: f64) -> f64 { let Some(first) = p.gcr_curve.first() else { // The Photocraft profile's curve. @@ -329,7 +330,7 @@ fn gcr(p: &CmykParams, g: f64) -> f64 { break; } } - k.clamp(0.0, 1.0) + k.clamp(0.0, 1.0).min(p.tac) } /// Colorimetric separation of a relative Lab target: GCR black generation then a CMY solve. @@ -863,6 +864,17 @@ mod tests { } } + #[test] + fn curve_black_stays_within_the_ink_limit() { + let p = CmykParams { tac: 0.5, gcr_curve: vec![[0.0, 0.75]], ..CmykParams::default() }; + let m = CmykModel::coated(p.tvi); + assert_eq!(gcr(&p, 0.5), 0.5); + for target in [[50.0, 0.0, 0.0], [90.0, 0.0, 0.0], [30.0, 20.0, -10.0]] { + let (cmyk, _) = separate(&m, &p, target, None); + assert!(cmyk.iter().sum::() <= p.tac + 1e-6, "{target:?} -> {cmyk:?}"); + } + } + #[test] fn oklab_round_trips() { let m = CmykModel::coated(CmykParams::default().tvi); diff --git a/crates/cms/tests/fogra39.rs b/crates/cms/tests/fogra39.rs index d08e3bae60..d23ab0ee1c 100644 --- a/crates/cms/tests/fogra39.rs +++ b/crates/cms/tests/fogra39.rs @@ -607,6 +607,8 @@ fn separates_like_the_reference_application() { for (rgb, want) in REFERENCE_SEPARATIONS { for ((intent, bpc), want) in SEPARATION_INTENTS.into_iter().zip(want) { let got = separation(intent, bpc, rgb); + // `f32::max` drops a NaN, so a NaN ink would otherwise count as no difference. + assert!(got.iter().all(|v| v.is_finite()), "{rgb:?} {intent:?} bpc {bpc}: {got:?}"); let diff = (0..4).map(|i| (got[i] - want[i]).abs()).fold(0.0f32, f32::max); eprintln!("{rgb:?} {intent:?} bpc {bpc}: {got:.1?} reference {want:?} (max {diff:.1})"); worst = worst.max(diff); From c2cd58c7b9ae36df4322c25b2ce8328f1309afea Mon Sep 17 00:00:00 2001 From: el-j Date: Thu, 19 Nov 2026 16:44:09 +0100 Subject: [PATCH 039/130] craft-captions: gate SubViewer detection on genuine header structure --- crates/captions/src/lib.rs | 2 +- crates/captions/src/subviewer.rs | 10 ++++++++++ crates/captions/tests/it/legacy_text.rs | 5 +++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index 79eb82e0a6..80a5ac46ad 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -331,7 +331,7 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if head.get(..5).is_some_and(|h| h.eq_ignore_ascii_case(" bool { + let mut lines = head.lines().map(str::trim).filter(|l| !l.is_empty()); + match lines.next() { + Some("[INFORMATION]") => lines.any(|l| l == "[SUBTITLE]" || l == "[END INFORMATION]" || (l.starts_with('[') && l.ends_with(']'))), + Some("[SUBTITLE]") => true, + _ => false, + } +} + /// `h:mm:ss.cc,h:mm:ss.cc` as its two times. pub(crate) fn parse_timing(line: &str) -> Option<(Tick, Tick)> { let (a, b) = line.trim().split_once(',')?; diff --git a/crates/captions/tests/it/legacy_text.rs b/crates/captions/tests/it/legacy_text.rs index 14f9197ca0..42d82acf81 100644 --- a/crates/captions/tests/it/legacy_text.rs +++ b/crates/captions/tests/it/legacy_text.rs @@ -169,6 +169,11 @@ fn detection_finds_each_format() { assert_eq!(detect(text.as_bytes(), ext), Some(format), "{format:?} with its extension"); } assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nx\n", None), Some(Format::Srt)); + // Cue text containing literal SubViewer markers must not hijack SRT detection + assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nHere is a [SUBTITLE] tag\n", None), Some(Format::Srt)); + assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n[INFORMATION] about movie\n", None), Some(Format::Srt)); + // Genuine SubViewer with only [SUBTITLE] header + assert_eq!(detect(b"[SUBTITLE]\n00:00:01.00,00:00:02.00\nText\n", None), Some(Format::SubViewer)); assert_eq!(detect(b"just some prose\n", Some("txt")), None); } From 944302e57c3f48999d6f5f6a57751fb603bc64b0 Mon Sep 17 00:00:00 2001 From: el-j Date: Thu, 19 Nov 2026 16:48:38 +0100 Subject: [PATCH 040/130] craft-video: validate rawvideo sample values against bit depth --- crates/video/src/frame/convert.rs | 4 ++++ crates/video/src/frame/tests.rs | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/crates/video/src/frame/convert.rs b/crates/video/src/frame/convert.rs index 7266d8731c..492df82eff 100644 --- a/crates/video/src/frame/convert.rs +++ b/crates/video/src/frame/convert.rs @@ -291,6 +291,10 @@ impl TryFrom for VideoFrame { Kind::Yuv422 => (ColorFamily::YCbCr, Subsampling::S422), Kind::Rgb => (ColorFamily::Rgb, Subsampling::S444), }; + let max_val = if bits < 16 { (1u16 << bits) - 1 } else { u16::MAX }; + if a.iter().any(|&s| s > max_val) || b.iter().any(|&s| s > max_val) || c.iter().any(|&s| s > max_val) { + return Err(FrameError::Plane("sample value exceeds bit depth")); + } let (cw, ch) = sub.chroma_size(w, h); let planes = vec![ Plane::packed(w, h, bits, Samples::U16(a))?, diff --git a/crates/video/src/frame/tests.rs b/crates/video/src/frame/tests.rs index 3962bab030..1916df4d2d 100644 --- a/crates/video/src/frame/tests.rs +++ b/crates/video/src/frame/tests.rs @@ -364,6 +364,18 @@ fn a_rawvideo_frame_with_short_planes_is_an_error() { assert!(VideoFrame::try_from(f).is_err()); } +#[cfg(feature = "rawvideo")] +#[test] +fn rawvideo_rejects_samples_exceeding_bit_depth() { + use crate::rawvideo::{Frame as R, Kind}; + let mut rgb = R::new(1, 1, Kind::Rgb, 8).unwrap(); + rgb.planes[0][0] = 255; + assert!(VideoFrame::try_from(rgb.clone()).is_ok()); + + rgb.planes[0][0] = 256; + assert_eq!(VideoFrame::try_from(rgb), Err(FrameError::Plane("sample value exceeds bit depth"))); +} + #[cfg(feature = "rawvideo")] #[test] fn a_decoded_v210_picture_converts() { From 8b030dd1c8f71f6adba9c125c4ac1ffa15fd3319 Mon Sep 17 00:00:00 2001 From: el-j Date: Thu, 19 Nov 2026 16:50:14 +0100 Subject: [PATCH 041/130] craft-video: correct Theora H.273 color tags and validate picture buffers during conversion --- crates/video/src/frame/convert.rs | 37 +++++++++++++++++++++---------- crates/video/tests/theora.rs | 19 ++++++++++++++-- 2 files changed, 42 insertions(+), 14 deletions(-) diff --git a/crates/video/src/frame/convert.rs b/crates/video/src/frame/convert.rs index 2a70b12264..63e79d26ec 100644 --- a/crates/video/src/frame/convert.rs +++ b/crates/video/src/frame/convert.rs @@ -424,20 +424,33 @@ impl TryFrom for VideoFrame { crate::theora::PixelFormat::Yuv444 => (Subsampling::S444, p.pic_width, p.pic_height, p.pic_x, p.pic_y), }; - let mut y_cropped = Vec::with_capacity((p.pic_width * p.pic_height) as usize); + let y_len = (p.pic_width as usize).checked_mul(p.pic_height as usize).ok_or(FrameError::Shape("crop size overflow"))?; + let mut y_cropped = Vec::with_capacity(y_len); for row in 0..p.pic_height { - let py = p.pic_y + (p.pic_height - 1 - row); - let start = py as usize * p.y_stride + p.pic_x as usize; - y_cropped.extend_from_slice(&p.y[start..start + p.pic_width as usize]); + let py = p.pic_y.checked_add(p.pic_height - 1 - row).ok_or(FrameError::Shape("crop y overflow"))?; + let start = (py as usize) + .checked_mul(p.y_stride) + .and_then(|s| s.checked_add(p.pic_x as usize)) + .ok_or(FrameError::Shape("crop offset overflow"))?; + let end = start.checked_add(p.pic_width as usize).ok_or(FrameError::Shape("crop slice overflow"))?; + let slice = p.y.get(start..end).ok_or(FrameError::Plane("buffer shorter than cropped region"))?; + y_cropped.extend_from_slice(slice); } - let mut u_cropped = Vec::with_capacity((cw * ch) as usize); - let mut v_cropped = Vec::with_capacity((cw * ch) as usize); + let uv_len = (cw as usize).checked_mul(ch as usize).ok_or(FrameError::Shape("crop uv size overflow"))?; + let mut u_cropped = Vec::with_capacity(uv_len); + let mut v_cropped = Vec::with_capacity(uv_len); for row in 0..ch { - let py = cy + (ch - 1 - row); - let start = py as usize * p.uv_stride + cx as usize; - u_cropped.extend_from_slice(&p.u[start..start + cw as usize]); - v_cropped.extend_from_slice(&p.v[start..start + cw as usize]); + let py = cy.checked_add(ch - 1 - row).ok_or(FrameError::Shape("crop chroma y overflow"))?; + let start = (py as usize) + .checked_mul(p.uv_stride) + .and_then(|s| s.checked_add(cx as usize)) + .ok_or(FrameError::Shape("crop chroma offset overflow"))?; + let end = start.checked_add(cw as usize).ok_or(FrameError::Shape("crop chroma slice overflow"))?; + let u_slice = p.u.get(start..end).ok_or(FrameError::Plane("u buffer shorter than cropped region"))?; + let v_slice = p.v.get(start..end).ok_or(FrameError::Plane("v buffer shorter than cropped region"))?; + u_cropped.extend_from_slice(u_slice); + v_cropped.extend_from_slice(v_slice); } let planes = vec![ @@ -450,13 +463,13 @@ impl TryFrom for VideoFrame { match p.color_space { crate::theora::ColorSpace::Rec470M => { f.color.matrix = 6; - f.color.primaries = 6; + f.color.primaries = 4; f.color.transfer = 6; } crate::theora::ColorSpace::Rec470Bg => { f.color.matrix = 5; f.color.primaries = 5; - f.color.transfer = 5; + f.color.transfer = 1; } _ => {} } diff --git a/crates/video/tests/theora.rs b/crates/video/tests/theora.rs index f1fa88040c..e67ad74894 100644 --- a/crates/video/tests/theora.rs +++ b/crates/video/tests/theora.rs @@ -159,11 +159,26 @@ fn test_theora_empty_packet_inter_frame() { #[test] fn test_theora_video_frame_conversion() { - let pic = test_picture(32, 32); - let vf = VideoFrame::try_from(pic).expect("convert to VideoFrame"); + let mut pic = test_picture(32, 32); + pic.color_space = ColorSpace::Rec470M; + let vf = VideoFrame::try_from(pic.clone()).expect("convert to VideoFrame"); assert_eq!(vf.width(), 32); assert_eq!(vf.height(), 32); assert_eq!(vf.planes().len(), 3); + assert_eq!(vf.color.primaries, 4); + assert_eq!(vf.color.transfer, 6); + assert_eq!(vf.color.matrix, 6); + + pic.color_space = ColorSpace::Rec470Bg; + let vf_bg = VideoFrame::try_from(pic.clone()).expect("convert Rec470Bg"); + assert_eq!(vf_bg.color.primaries, 5); + assert_eq!(vf_bg.color.transfer, 1); + assert_eq!(vf_bg.color.matrix, 5); + + // Empty or short plane buffers fail with FrameError without panicking + let mut bad_pic = pic.clone(); + bad_pic.y.clear(); + assert!(VideoFrame::try_from(bad_pic).is_err()); } #[test] From 95a778b30ce038f57fdb378de4606a9fc99e7c3d Mon Sep 17 00:00:00 2001 From: el-j Date: Fri, 20 Nov 2026 09:34:14 +0100 Subject: [PATCH 042/130] craft-video: harden Theora buffer allocation, crop conversion, and input validation --- crates/video/src/frame/convert.rs | 109 +++++++++++++++++++++++------ crates/video/src/theora/decoder.rs | 25 ++++--- crates/video/src/theora/encoder.rs | 62 +++++++++++++--- crates/video/tests/theora.rs | 53 +++++++++++++- 4 files changed, 208 insertions(+), 41 deletions(-) diff --git a/crates/video/src/frame/convert.rs b/crates/video/src/frame/convert.rs index 63e79d26ec..bb60630687 100644 --- a/crates/video/src/frame/convert.rs +++ b/crates/video/src/frame/convert.rs @@ -418,14 +418,52 @@ impl TryFrom for VideoFrame { type Error = FrameError; fn try_from(p: crate::theora::Picture) -> Result { - let (sub, cw, ch, cx, cy) = match p.pixel_format { - crate::theora::PixelFormat::Yuv420 => (Subsampling::S420, p.pic_width.div_ceil(2), p.pic_height.div_ceil(2), p.pic_x / 2, p.pic_y / 2), - crate::theora::PixelFormat::Yuv422 => (Subsampling::S422, p.pic_width.div_ceil(2), p.pic_height, p.pic_x / 2, p.pic_y), - crate::theora::PixelFormat::Yuv444 => (Subsampling::S444, p.pic_width, p.pic_height, p.pic_x, p.pic_y), + if p.pic_width == 0 || p.pic_height == 0 { + return Err(FrameError::Shape("picture dimensions must be non-zero")); + } + if p.y_stride == 0 || p.uv_stride == 0 { + return Err(FrameError::Plane("stride cannot be zero")); + } + let crop_end_x = p.pic_x.checked_add(p.pic_width).ok_or(FrameError::Shape("crop width overflow"))?; + let crop_end_y = p.pic_y.checked_add(p.pic_height).ok_or(FrameError::Shape("crop height overflow"))?; + if crop_end_x > p.width || crop_end_y > p.height { + return Err(FrameError::Shape("crop bounds exceed frame dimensions")); + } + + // Determine if crop is aligned with chroma subsampling + let is_aligned = match p.pixel_format { + crate::theora::PixelFormat::Yuv420 => p.pic_x.is_multiple_of(2) && p.pic_y.is_multiple_of(2), + crate::theora::PixelFormat::Yuv422 => p.pic_x.is_multiple_of(2), + crate::theora::PixelFormat::Yuv444 => true, }; - let y_len = (p.pic_width as usize).checked_mul(p.pic_height as usize).ok_or(FrameError::Shape("crop size overflow"))?; - let mut y_cropped = Vec::with_capacity(y_len); + let (sub, cw, ch) = if is_aligned { + match p.pixel_format { + crate::theora::PixelFormat::Yuv420 => (Subsampling::S420, p.pic_width.div_ceil(2), p.pic_height.div_ceil(2)), + crate::theora::PixelFormat::Yuv422 => (Subsampling::S422, p.pic_width.div_ceil(2), p.pic_height), + crate::theora::PixelFormat::Yuv444 => (Subsampling::S444, p.pic_width, p.pic_height), + } + } else { + // Misaligned crop: retain all chroma samples across odd offsets by converting to S444 + (Subsampling::S444, p.pic_width, p.pic_height) + }; + + let w_u64 = p.pic_width as u64; + let h_u64 = p.pic_height as u64; + let cw_u64 = cw as u64; + let ch_u64 = ch as u64; + let y_bytes = w_u64.checked_mul(h_u64).ok_or(FrameError::Shape("crop size overflow"))?; + let c_bytes = cw_u64.checked_mul(ch_u64).ok_or(FrameError::Shape("crop uv size overflow"))?; + let total_bytes = y_bytes.checked_add(c_bytes.checked_mul(2).ok_or(FrameError::Shape("overflow"))?).ok_or(FrameError::Shape("overflow"))?; + if total_bytes > crate::budget::DECODE_MEMORY_BUDGET { + return Err(FrameError::Shape("frame size exceeds memory budget")); + } + + let y_len = usize::try_from(y_bytes).map_err(|_| FrameError::Shape("crop size exceeds usize"))?; + let uv_len = usize::try_from(c_bytes).map_err(|_| FrameError::Shape("crop uv size exceeds usize"))?; + + let mut y_cropped = Vec::new(); + y_cropped.try_reserve_exact(y_len).map_err(|_| FrameError::Shape("out of memory"))?; for row in 0..p.pic_height { let py = p.pic_y.checked_add(p.pic_height - 1 - row).ok_or(FrameError::Shape("crop y overflow"))?; let start = (py as usize) @@ -437,20 +475,51 @@ impl TryFrom for VideoFrame { y_cropped.extend_from_slice(slice); } - let uv_len = (cw as usize).checked_mul(ch as usize).ok_or(FrameError::Shape("crop uv size overflow"))?; - let mut u_cropped = Vec::with_capacity(uv_len); - let mut v_cropped = Vec::with_capacity(uv_len); - for row in 0..ch { - let py = cy.checked_add(ch - 1 - row).ok_or(FrameError::Shape("crop chroma y overflow"))?; - let start = (py as usize) - .checked_mul(p.uv_stride) - .and_then(|s| s.checked_add(cx as usize)) - .ok_or(FrameError::Shape("crop chroma offset overflow"))?; - let end = start.checked_add(cw as usize).ok_or(FrameError::Shape("crop chroma slice overflow"))?; - let u_slice = p.u.get(start..end).ok_or(FrameError::Plane("u buffer shorter than cropped region"))?; - let v_slice = p.v.get(start..end).ok_or(FrameError::Plane("v buffer shorter than cropped region"))?; - u_cropped.extend_from_slice(u_slice); - v_cropped.extend_from_slice(v_slice); + let mut u_cropped = Vec::new(); + u_cropped.try_reserve_exact(uv_len).map_err(|_| FrameError::Shape("out of memory"))?; + let mut v_cropped = Vec::new(); + v_cropped.try_reserve_exact(uv_len).map_err(|_| FrameError::Shape("out of memory"))?; + + if is_aligned { + let (cx, cy) = match p.pixel_format { + crate::theora::PixelFormat::Yuv420 => (p.pic_x / 2, p.pic_y / 2), + crate::theora::PixelFormat::Yuv422 => (p.pic_x / 2, p.pic_y), + crate::theora::PixelFormat::Yuv444 => (p.pic_x, p.pic_y), + }; + for row in 0..ch { + let py = cy.checked_add(ch - 1 - row).ok_or(FrameError::Shape("crop chroma y overflow"))?; + let start = (py as usize) + .checked_mul(p.uv_stride) + .and_then(|s| s.checked_add(cx as usize)) + .ok_or(FrameError::Shape("crop chroma offset overflow"))?; + let end = start.checked_add(cw as usize).ok_or(FrameError::Shape("crop chroma slice overflow"))?; + let u_slice = p.u.get(start..end).ok_or(FrameError::Plane("u buffer shorter than cropped region"))?; + let v_slice = p.v.get(start..end).ok_or(FrameError::Plane("v buffer shorter than cropped region"))?; + u_cropped.extend_from_slice(u_slice); + v_cropped.extend_from_slice(v_slice); + } + } else { + // Misaligned crop: extract full-resolution chroma for each pixel + for row in 0..p.pic_height { + let py = p.pic_y.checked_add(p.pic_height - 1 - row).ok_or(FrameError::Shape("crop y overflow"))?; + let cy = match p.pixel_format { + crate::theora::PixelFormat::Yuv420 => py / 2, + _ => py, + }; + let row_start = (cy as usize).checked_mul(p.uv_stride).ok_or(FrameError::Shape("chroma stride overflow"))?; + for col in 0..p.pic_width { + let px = p.pic_x.checked_add(col).ok_or(FrameError::Shape("crop x overflow"))?; + let cx = match p.pixel_format { + crate::theora::PixelFormat::Yuv444 => px, + _ => px / 2, + }; + let offset = row_start.checked_add(cx as usize).ok_or(FrameError::Shape("chroma offset overflow"))?; + let &u_val = p.u.get(offset).ok_or(FrameError::Plane("u buffer shorter than cropped region"))?; + let &v_val = p.v.get(offset).ok_or(FrameError::Plane("v buffer shorter than cropped region"))?; + u_cropped.push(u_val); + v_cropped.push(v_val); + } + } } let planes = vec![ diff --git a/crates/video/src/theora/decoder.rs b/crates/video/src/theora/decoder.rs index 003e8ffbd3..5b96f5d2d7 100644 --- a/crates/video/src/theora/decoder.rs +++ b/crates/video/src/theora/decoder.rs @@ -28,6 +28,13 @@ pub struct Decoder { frame_index: u64, } +fn alloc_plane_buffer(len: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| Error::OutOfMemory)?; + v.resize(len, 0); + Ok(v) +} + impl Decoder { /// Initialize decoder from the three mandatory header packets: Identification, Comment, Setup. pub fn from_headers(id_packet: &[u8], comment_packet: &[u8], setup_packet: &[u8]) -> Result { @@ -76,13 +83,13 @@ impl Decoder { let (y_pw, y_ph, _, _, _, _, _, _) = geom.planes[0]; let (c_pw, c_ph, _, _, _, _, _, _) = geom.planes[1]; - let ref_golden_y = vec![0u8; y_pw * y_ph]; - let ref_golden_cb = vec![0u8; c_pw * c_ph]; - let ref_golden_cr = vec![0u8; c_pw * c_ph]; + let ref_golden_y = alloc_plane_buffer(y_pw * y_ph)?; + let ref_golden_cb = alloc_plane_buffer(c_pw * c_ph)?; + let ref_golden_cr = alloc_plane_buffer(c_pw * c_ph)?; - let ref_prev_y = vec![0u8; y_pw * y_ph]; - let ref_prev_cb = vec![0u8; c_pw * c_ph]; - let ref_prev_cr = vec![0u8; c_pw * c_ph]; + let ref_prev_y = alloc_plane_buffer(y_pw * y_ph)?; + let ref_prev_cb = alloc_plane_buffer(c_pw * c_ph)?; + let ref_prev_cr = alloc_plane_buffer(c_pw * c_ph)?; Ok(Self { info: id.info, @@ -451,9 +458,9 @@ impl Decoder { undo_dc_prediction(&self.geom, &bcoded, &mb_modes, &mut coeffs); // 8. Block Reconstruction (Section 7.9) - let mut rec_y = vec![0u8; y_pw * y_ph]; - let mut rec_cb = vec![0u8; c_pw * c_ph]; - let mut rec_cr = vec![0u8; c_pw * c_ph]; + let mut rec_y = alloc_plane_buffer(y_pw * y_ph)?; + let mut rec_cb = alloc_plane_buffer(c_pw * c_ph)?; + let mut rec_cr = alloc_plane_buffer(c_pw * c_ph)?; let qi0 = qis[0]; diff --git a/crates/video/src/theora/encoder.rs b/crates/video/src/theora/encoder.rs index f7176e8bee..d80a237211 100644 --- a/crates/video/src/theora/encoder.rs +++ b/crates/video/src/theora/encoder.rs @@ -65,6 +65,13 @@ pub struct Encoder { last_keyframe: u64, } +fn alloc_plane_buffer(len: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(len).map_err(|_| Error::OutOfMemory)?; + v.resize(len, 0); + Ok(v) +} + impl Encoder { /// Create a new encoder with the given configuration. pub fn new(config: EncoderConfig) -> Result { @@ -137,13 +144,13 @@ impl Encoder { let (y_pw, y_ph, _, _, _, _, _, _) = geom.planes[0]; let (c_pw, c_ph, _, _, _, _, _, _) = geom.planes[1]; - let ref_golden_y = vec![0u8; y_pw * y_ph]; - let ref_golden_cb = vec![0u8; c_pw * c_ph]; - let ref_golden_cr = vec![0u8; c_pw * c_ph]; + let ref_golden_y = alloc_plane_buffer(y_pw * y_ph)?; + let ref_golden_cb = alloc_plane_buffer(c_pw * c_ph)?; + let ref_golden_cr = alloc_plane_buffer(c_pw * c_ph)?; - let ref_prev_y = vec![0u8; y_pw * y_ph]; - let ref_prev_cb = vec![0u8; c_pw * c_ph]; - let ref_prev_cr = vec![0u8; c_pw * c_ph]; + let ref_prev_y = alloc_plane_buffer(y_pw * y_ph)?; + let ref_prev_cb = alloc_plane_buffer(c_pw * c_ph)?; + let ref_prev_cr = alloc_plane_buffer(c_pw * c_ph)?; Ok(Self { config, @@ -193,6 +200,13 @@ impl Encoder { /// Currently produces intra keyframes for every frame, ensuring all packets are independent /// self-contained keyframes that decode reliably. pub fn encode_frame(&mut self, pic: &Picture, _force_keyframe: bool) -> Result> { + if pic.width != self.config.width || pic.height != self.config.height { + return Err(Error::DimensionMismatch("picture dimensions do not match encoder configuration")); + } + if pic.y_stride == 0 || pic.uv_stride == 0 { + return Err(Error::DimensionMismatch("stride cannot be zero")); + } + let mut w = BitWriter::new(); // 1. Frame Header (Section 7.1) @@ -211,9 +225,9 @@ impl Encoder { let (y_pw, y_ph, _, _, _, _, _, _) = self.geom.planes[0]; let (c_pw, c_ph, _, _, _, _, _, _) = self.geom.planes[1]; - let mut rec_y = vec![0u8; y_pw * y_ph]; - let mut rec_cb = vec![0u8; c_pw * c_ph]; - let mut rec_cr = vec![0u8; c_pw * c_ph]; + let mut rec_y = alloc_plane_buffer(y_pw * y_ph)?; + let mut rec_cb = alloc_plane_buffer(c_pw * c_ph)?; + let mut rec_cr = alloc_plane_buffer(c_pw * c_ph)?; let bcoded = vec![true; nbs]; let mb_modes = vec![1u8; self.geom.nmbs]; // 1: INTRA @@ -233,6 +247,22 @@ impl Encoder { _ => (&pic.y, pic.y_stride), }; + let (active_w, active_h, active_x, active_y) = match pli { + 0 => (pic.pic_width as usize, pic.pic_height as usize, pic.pic_x as usize, pic.pic_y as usize), + _ => match self.config.pixel_format { + PixelFormat::Yuv420 => ( + (pic.pic_width as usize).div_ceil(2), + (pic.pic_height as usize).div_ceil(2), + (pic.pic_x as usize) / 2, + (pic.pic_y as usize) / 2, + ), + PixelFormat::Yuv422 => { + ((pic.pic_width as usize).div_ceil(2), pic.pic_height as usize, (pic.pic_x as usize) / 2, pic.pic_y as usize) + } + PixelFormat::Yuv444 => (pic.pic_width as usize, pic.pic_height as usize, pic.pic_x as usize, pic.pic_y as usize), + }, + }; + // Read 8x8 block from source picture (origin at lower-left!) // Note: In Theora coordinates, row 0 is at the bottom of the plane. let mut block_samples = [0i16; 64]; @@ -240,8 +270,18 @@ impl Encoder { let py = meta.pixel_y + row; for col in 0..8 { let px = meta.pixel_x + col; - let offset = py.checked_mul(stride).and_then(|r| r.checked_add(px)).ok_or(Error::DimensionMismatch("sample offset overflow"))?; - let sample = src_plane.get(offset).copied().map(|b| b as i16).unwrap_or(128); + let sample = if px >= active_x && px < active_x + active_w && py >= active_y && py < active_y + active_h { + let offset = + py.checked_mul(stride).and_then(|r| r.checked_add(px)).ok_or(Error::DimensionMismatch("sample offset overflow"))?; + src_plane + .get(offset) + .copied() + .map(|b| b as i16) + .ok_or(Error::DimensionMismatch("source plane buffer shorter than active picture"))? + } else { + let offset = py.checked_mul(stride).and_then(|r| r.checked_add(px)); + offset.and_then(|off| src_plane.get(off).copied()).map(|b| b as i16).unwrap_or(128) + }; // Subtract 128 (intra predictor) block_samples[row * 8 + col] = sample - 128; } diff --git a/crates/video/tests/theora.rs b/crates/video/tests/theora.rs index e67ad74894..ac9dcac2fd 100644 --- a/crates/video/tests/theora.rs +++ b/crates/video/tests/theora.rs @@ -179,6 +179,40 @@ fn test_theora_video_frame_conversion() { let mut bad_pic = pic.clone(); bad_pic.y.clear(); assert!(VideoFrame::try_from(bad_pic).is_err()); + + // Zero stride fails with FrameError without panicking + let mut bad_stride = pic.clone(); + bad_stride.y_stride = 0; + assert!(VideoFrame::try_from(bad_stride).is_err()); + + // Oversized dimensions fail with FrameError without panicking + let mut bad_dims = pic.clone(); + bad_dims.pic_width = u32::MAX; + bad_dims.pic_height = u32::MAX; + assert!(VideoFrame::try_from(bad_dims).is_err()); + + // Crop bounds exceeding frame dimensions fail with FrameError + let mut bad_crop = pic.clone(); + bad_crop.pic_x = 30; + bad_crop.pic_width = 10; + assert!(VideoFrame::try_from(bad_crop).is_err()); + + // Misaligned crop offsets (odd coordinates) preserve all chroma samples via S444 conversion + let mut odd_pic = test_picture(32, 32); + odd_pic.pic_x = 1; + odd_pic.pic_y = 1; + odd_pic.pic_width = 2; + odd_pic.pic_height = 2; + odd_pic.u[0] = 50; + odd_pic.u[1] = 150; + let vf_odd = VideoFrame::try_from(odd_pic).expect("convert odd crop"); + assert_eq!(vf_odd.subsampling(), craft_video::frame::Subsampling::S444); + assert_eq!(vf_odd.width(), 2); + assert_eq!(vf_odd.height(), 2); + // Row 1 of VideoFrame corresponds to bottom row py=1 (cy=0) + let u_bottom = vf_odd.planes()[1].row_u8(1).expect("u row 1"); + assert_eq!(u_bottom[0], 50); + assert_eq!(u_bottom[1], 150); } #[test] @@ -473,7 +507,7 @@ fn test_theora_encoder_picture_strides() { } #[test] -fn test_theora_encoder_overflowing_stride_rejected() { +fn test_theora_encoder_invalid_input_rejected() { let cfg = EncoderConfig { width: 32, height: 32, @@ -489,9 +523,26 @@ fn test_theora_encoder_overflowing_stride_rejected() { keyframe_distance: 64, }; let mut enc = Encoder::new(cfg).expect("encoder"); + + // Overflowing stride let mut pic = test_picture(32, 32); pic.y_stride = usize::MAX; assert!(matches!(enc.encode_frame(&pic, true), Err(Error::DimensionMismatch(_)))); + + // Zero stride + let mut pic = test_picture(32, 32); + pic.y_stride = 0; + assert!(matches!(enc.encode_frame(&pic, true), Err(Error::DimensionMismatch(_)))); + + // Truncated/missing active samples + let mut pic = test_picture(32, 32); + pic.y.clear(); + assert!(matches!(enc.encode_frame(&pic, true), Err(Error::DimensionMismatch(_)))); + + // Dimension mismatch + let mut pic = test_picture(32, 32); + pic.width = 64; + assert!(matches!(enc.encode_frame(&pic, true), Err(Error::DimensionMismatch(_)))); } #[test] From 2aa787131b86250b194616d33c03a2c35de3b572 Mon Sep 17 00:00:00 2001 From: el-j Date: Fri, 20 Nov 2026 09:38:05 +0100 Subject: [PATCH 043/130] craft-captions: recognize truncated metadata fields in SubViewer header detection --- crates/captions/src/subviewer.rs | 13 ++++++++++++- crates/captions/tests/it/legacy_text.rs | 3 +++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/captions/src/subviewer.rs b/crates/captions/src/subviewer.rs index 3fbf8af437..abc37fc2b9 100644 --- a/crates/captions/src/subviewer.rs +++ b/crates/captions/src/subviewer.rs @@ -23,7 +23,18 @@ use crate::{Cue, Document, Error, Result, parse_clock}; pub(crate) fn is_header(head: &str) -> bool { let mut lines = head.lines().map(str::trim).filter(|l| !l.is_empty()); match lines.next() { - Some("[INFORMATION]") => lines.any(|l| l == "[SUBTITLE]" || l == "[END INFORMATION]" || (l.starts_with('[') && l.ends_with(']'))), + Some("[INFORMATION]") => lines.any(|l| { + l == "[SUBTITLE]" + || l == "[END INFORMATION]" + || l.starts_with("[TITLE") + || l.starts_with("[AUTHOR") + || l.starts_with("[SOURCE") + || l.starts_with("[FILEPATH") + || l.starts_with("[DELAY") + || l.starts_with("[CD TRACK") + || l.starts_with("[COMMENT") + || (l.starts_with('[') && l.contains(']')) + }), Some("[SUBTITLE]") => true, _ => false, } diff --git a/crates/captions/tests/it/legacy_text.rs b/crates/captions/tests/it/legacy_text.rs index 42d82acf81..c171b63f17 100644 --- a/crates/captions/tests/it/legacy_text.rs +++ b/crates/captions/tests/it/legacy_text.rs @@ -174,6 +174,9 @@ fn detection_finds_each_format() { assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n[INFORMATION] about movie\n", None), Some(Format::Srt)); // Genuine SubViewer with only [SUBTITLE] header assert_eq!(detect(b"[SUBTITLE]\n00:00:01.00,00:00:02.00\nText\n", None), Some(Format::SubViewer)); + // Genuine SubViewer with long/truncated [TITLE] line + let truncated_sv = format!("[INFORMATION]\n[TITLE]{}", "A".repeat(5000)); + assert_eq!(detect(truncated_sv.as_bytes(), None), Some(Format::SubViewer)); assert_eq!(detect(b"just some prose\n", Some("txt")), None); } From 31c6f1df962136574b57edbd5dd4da5bb7e7f56f Mon Sep 17 00:00:00 2001 From: el-j Date: Fri, 20 Nov 2026 09:53:17 +0100 Subject: [PATCH 044/130] craft-video: harden Theora memory allocations, stride checks, and picture bounds validation --- crates/video/src/frame/convert.rs | 7 +++ crates/video/src/theora/decoder.rs | 38 ++++++++----- crates/video/src/theora/encoder.rs | 54 ++++++++++++++----- crates/video/src/theora/reconstruct.rs | 74 +++++++++++++++++++++----- crates/video/tests/theora.rs | 42 +++++++++++++++ 5 files changed, 177 insertions(+), 38 deletions(-) diff --git a/crates/video/src/frame/convert.rs b/crates/video/src/frame/convert.rs index bb60630687..87f0281c7b 100644 --- a/crates/video/src/frame/convert.rs +++ b/crates/video/src/frame/convert.rs @@ -421,9 +421,16 @@ impl TryFrom for VideoFrame { if p.pic_width == 0 || p.pic_height == 0 { return Err(FrameError::Shape("picture dimensions must be non-zero")); } + let src_uv_w = match p.pixel_format { + crate::theora::PixelFormat::Yuv420 | crate::theora::PixelFormat::Yuv422 => (p.width as usize).div_ceil(2), + crate::theora::PixelFormat::Yuv444 => p.width as usize, + }; if p.y_stride == 0 || p.uv_stride == 0 { return Err(FrameError::Plane("stride cannot be zero")); } + if p.y_stride < p.width as usize || p.uv_stride < src_uv_w { + return Err(FrameError::Plane("stride shorter than plane width")); + } let crop_end_x = p.pic_x.checked_add(p.pic_width).ok_or(FrameError::Shape("crop width overflow"))?; let crop_end_y = p.pic_y.checked_add(p.pic_height).ok_or(FrameError::Shape("crop height overflow"))?; if crop_end_x > p.width || crop_end_y > p.height { diff --git a/crates/video/src/theora/decoder.rs b/crates/video/src/theora/decoder.rs index 5b96f5d2d7..109d779ff3 100644 --- a/crates/video/src/theora/decoder.rs +++ b/crates/video/src/theora/decoder.rs @@ -35,6 +35,20 @@ fn alloc_plane_buffer(len: usize) -> Result> { Ok(v) } +fn clone_plane_buffer(src: &[u8]) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(src.len()).map_err(|_| Error::OutOfMemory)?; + v.extend_from_slice(src); + Ok(v) +} + +fn alloc_vec_exact(val: T, n: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::OutOfMemory)?; + v.resize(n, val); + Ok(v) +} + impl Decoder { /// Initialize decoder from the three mandatory header packets: Identification, Comment, Setup. pub fn from_headers(id_packet: &[u8], comment_packet: &[u8], setup_packet: &[u8]) -> Result { @@ -77,7 +91,7 @@ impl Decoder { let fmbw = fmbw_u64 as usize; let fmbh = fmbh_u64 as usize; - let geom = FrameGeometry::new(fmbw, fmbh, id.info.pixel_format); + let geom = FrameGeometry::new(fmbw, fmbh, id.info.pixel_format)?; let qmat_tables = setup.quant_params.precompute_all_qmat()?; let (y_pw, y_ph, _, _, _, _, _, _) = geom.planes[0]; @@ -129,9 +143,9 @@ impl Decoder { color_space: self.info.color_space, keyframe: false, pts: None, - y: self.ref_prev_y.clone(), - u: self.ref_prev_cb.clone(), - v: self.ref_prev_cr.clone(), + y: clone_plane_buffer(&self.ref_prev_y)?, + u: clone_plane_buffer(&self.ref_prev_cb)?, + v: clone_plane_buffer(&self.ref_prev_cr)?, y_stride: y_pw, uv_stride: c_pw, }; @@ -178,7 +192,7 @@ impl Decoder { // 2. Coded Block Flags (Section 7.3) let nbs = self.geom.nbs; let nsbs = self.geom.nsbs; - let mut bcoded = vec![false; nbs]; + let mut bcoded = alloc_vec_exact(false, nbs)?; if is_keyframe { bcoded.fill(true); @@ -193,7 +207,7 @@ impl Decoder { let sbf_bits = decode_long_run(&mut r, uncoded_sb_count)?; let mut sbf_iter = sbf_bits.into_iter(); - let mut sbf_coded = vec![false; nsbs]; + let mut sbf_coded = alloc_vec_exact(false, nsbs)?; for sbi in 0..nsbs { if !sbp_bits[sbi] { @@ -223,7 +237,7 @@ impl Decoder { // 3. Macro Block Coding Modes (Section 7.4) let nmbs = self.geom.nmbs; - let mut mb_modes = vec![0u8; nmbs]; + let mut mb_modes = alloc_vec_exact(0u8, nmbs)?; if is_keyframe { mb_modes.fill(1); // INTRA @@ -258,7 +272,7 @@ impl Decoder { } // 4. Motion Vectors (Section 7.5) - let mut mvects = vec![(0i8, 0i8); nbs]; + let mut mvects = alloc_vec_exact((0i8, 0i8), nbs)?; if !is_keyframe { let mvmode = r.read_bits(1).map_err(|_| Error::Truncated("mvmode"))? as u8; @@ -372,7 +386,7 @@ impl Decoder { } // 5. Block-Level qi Decode (Section 7.6) - let mut qiis = vec![0usize; nbs]; + let mut qiis = alloc_vec_exact(0usize, nbs)?; if nqis > 1 { for qii in 0..(nqis - 1) { let nbits_pass = (0..nbs).filter(|&bi| bcoded[bi] && qiis[bi] == qii).count(); @@ -389,9 +403,9 @@ impl Decoder { } // 6. DCT Coefficients Decode (Section 7.7) - let mut coeffs = vec![[0i16; 64]; nbs]; - let mut ncoeffs = vec![0usize; nbs]; - let mut tis = vec![0usize; nbs]; + let mut coeffs = alloc_vec_exact([0i16; 64], nbs)?; + let mut ncoeffs = alloc_vec_exact(0usize, nbs)?; + let mut tis = alloc_vec_exact(0usize, nbs)?; let mut eobs = 0usize; let nlbs = nmbs * 4; diff --git a/crates/video/src/theora/encoder.rs b/crates/video/src/theora/encoder.rs index d80a237211..ec43310c96 100644 --- a/crates/video/src/theora/encoder.rs +++ b/crates/video/src/theora/encoder.rs @@ -72,6 +72,13 @@ fn alloc_plane_buffer(len: usize) -> Result> { Ok(v) } +fn alloc_vec_exact(val: T, n: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::OutOfMemory)?; + v.resize(n, val); + Ok(v) +} + impl Encoder { /// Create a new encoder with the given configuration. pub fn new(config: EncoderConfig) -> Result { @@ -138,7 +145,7 @@ impl Encoder { CommentHeader { vendor: "craft-video pure-rust Theora encoder".to_string(), comments: vec!["ENCODER=craft-video".to_string()] }; let setup_header = SetupHeader::default_vp3()?; - let geom = FrameGeometry::new(fmbw, fmbh, config.pixel_format); + let geom = FrameGeometry::new(fmbw, fmbh, config.pixel_format)?; let qmat_tables = setup_header.quant_params.precompute_all_qmat()?; let (y_pw, y_ph, _, _, _, _, _, _) = geom.planes[0]; @@ -200,12 +207,26 @@ impl Encoder { /// Currently produces intra keyframes for every frame, ensuring all packets are independent /// self-contained keyframes that decode reliably. pub fn encode_frame(&mut self, pic: &Picture, _force_keyframe: bool) -> Result> { - if pic.width != self.config.width || pic.height != self.config.height { + if pic.width != self.config.width + || pic.height != self.config.height + || pic.pic_width != self.config.pic_width + || pic.pic_height != self.config.pic_height + || pic.pic_x != self.config.pic_x + || pic.pic_y != self.config.pic_y + || pic.pixel_format != self.config.pixel_format + { return Err(Error::DimensionMismatch("picture dimensions do not match encoder configuration")); } + let src_uv_w = match self.config.pixel_format { + PixelFormat::Yuv420 | PixelFormat::Yuv422 => (self.config.width as usize).div_ceil(2), + PixelFormat::Yuv444 => self.config.width as usize, + }; if pic.y_stride == 0 || pic.uv_stride == 0 { return Err(Error::DimensionMismatch("stride cannot be zero")); } + if pic.y_stride < self.config.width as usize || pic.uv_stride < src_uv_w { + return Err(Error::DimensionMismatch("stride shorter than plane width")); + } let mut w = BitWriter::new(); @@ -229,13 +250,13 @@ impl Encoder { let mut rec_cb = alloc_plane_buffer(c_pw * c_ph)?; let mut rec_cr = alloc_plane_buffer(c_pw * c_ph)?; - let bcoded = vec![true; nbs]; - let mb_modes = vec![1u8; self.geom.nmbs]; // 1: INTRA + let bcoded = alloc_vec_exact(true, nbs)?; + let mb_modes = alloc_vec_exact(1u8, self.geom.nmbs)?; // 1: INTRA // For intra frames, all blocks are coded // Forward transform & quantize - let mut quant_coeffs = vec![[0i16; 64]; nbs]; - let mut ncoeffs = vec![0usize; nbs]; + let mut quant_coeffs = alloc_vec_exact([0i16; 64], nbs)?; + let mut ncoeffs = alloc_vec_exact(0usize, nbs)?; for bi in 0..nbs { let meta = &self.geom.blocks[bi]; @@ -248,18 +269,23 @@ impl Encoder { }; let (active_w, active_h, active_x, active_y) = match pli { - 0 => (pic.pic_width as usize, pic.pic_height as usize, pic.pic_x as usize, pic.pic_y as usize), + 0 => (self.config.pic_width as usize, self.config.pic_height as usize, self.config.pic_x as usize, self.config.pic_y as usize), _ => match self.config.pixel_format { PixelFormat::Yuv420 => ( - (pic.pic_width as usize).div_ceil(2), - (pic.pic_height as usize).div_ceil(2), - (pic.pic_x as usize) / 2, - (pic.pic_y as usize) / 2, + (self.config.pic_width as usize).div_ceil(2), + (self.config.pic_height as usize).div_ceil(2), + (self.config.pic_x as usize) / 2, + (self.config.pic_y as usize) / 2, ), - PixelFormat::Yuv422 => { - ((pic.pic_width as usize).div_ceil(2), pic.pic_height as usize, (pic.pic_x as usize) / 2, pic.pic_y as usize) + PixelFormat::Yuv422 => ( + (self.config.pic_width as usize).div_ceil(2), + self.config.pic_height as usize, + (self.config.pic_x as usize) / 2, + self.config.pic_y as usize, + ), + PixelFormat::Yuv444 => { + (self.config.pic_width as usize, self.config.pic_height as usize, self.config.pic_x as usize, self.config.pic_y as usize) } - PixelFormat::Yuv444 => (pic.pic_width as usize, pic.pic_height as usize, pic.pic_x as usize, pic.pic_y as usize), }, }; diff --git a/crates/video/src/theora/reconstruct.rs b/crates/video/src/theora/reconstruct.rs index 2792db2704..d5adf5ba4f 100644 --- a/crates/video/src/theora/reconstruct.rs +++ b/crates/video/src/theora/reconstruct.rs @@ -1,9 +1,22 @@ //! Frame geometry, DC prediction undoing, block reconstruction, and loop filtering (Sections 2, 7.8, 7.9, 7.10). -use super::PixelFormat; use super::idct::idct_2d; use super::loopfilter::{filter_horizontal_edge, filter_vertical_edge}; use super::tables::{DC_PRED_CONFIG, MB_HILBERT, SB_HILBERT, ZIGZAG}; +use super::{Error, PixelFormat}; + +fn alloc_vec(val: T, n: usize) -> Result, Error> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::OutOfMemory)?; + v.resize(n, val); + Ok(v) +} + +fn alloc_capacity(n: usize) -> Result, Error> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::OutOfMemory)?; + Ok(v) +} /// Information about a single 8x8 block in the coded frame. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -58,7 +71,7 @@ pub struct FrameGeometry { } impl FrameGeometry { - pub fn new(fmbw: usize, fmbh: usize, pixel_format: PixelFormat) -> Self { + pub fn new(fmbw: usize, fmbh: usize, pixel_format: PixelFormat) -> Result { let frame_width = fmbw * 16; let frame_height = fmbh * 16; let nmbs = fmbw * fmbh; @@ -96,8 +109,12 @@ impl FrameGeometry { // Map macroblocks in Hilbert coded order within luma superblocks // `mb_grid[my][mx] = mbi` - let mut mb_grid = vec![vec![0usize; fmbw]; fmbh]; - let mut mb_coords = Vec::with_capacity(nmbs); + let mut mb_grid = Vec::new(); + mb_grid.try_reserve_exact(fmbh).map_err(|_| Error::OutOfMemory)?; + for _ in 0..fmbh { + mb_grid.push(alloc_vec(0usize, fmbw)?); + } + let mut mb_coords = alloc_capacity(nmbs)?; let mut cur_mbi = 0; let luma_sb_w = fmbw.div_ceil(2); @@ -118,10 +135,35 @@ impl FrameGeometry { } // Build coded blocks for all 3 planes - let mut blocks = Vec::with_capacity(nbs); - let mut plane_block_grid = [vec![vec![0usize; y_wb]; y_hb], vec![vec![0usize; c_wb]; c_hb], vec![vec![0usize; c_wb]; c_hb]]; + let mut blocks = alloc_capacity(nbs)?; + let mut plane_block_grid = [ + { + let mut g = Vec::new(); + g.try_reserve_exact(y_hb).map_err(|_| Error::OutOfMemory)?; + for _ in 0..y_hb { + g.push(alloc_vec(0usize, y_wb)?); + } + g + }, + { + let mut g = Vec::new(); + g.try_reserve_exact(c_hb).map_err(|_| Error::OutOfMemory)?; + for _ in 0..c_hb { + g.push(alloc_vec(0usize, c_wb)?); + } + g + }, + { + let mut g = Vec::new(); + g.try_reserve_exact(c_hb).map_err(|_| Error::OutOfMemory)?; + for _ in 0..c_hb { + g.push(alloc_vec(0usize, c_wb)?); + } + g + }, + ]; - let mut sb_block_counts = vec![0usize; nsbs]; + let mut sb_block_counts = alloc_vec(0usize, nsbs)?; let mut global_sbi = 0; let mut cur_bi = 0; @@ -191,9 +233,17 @@ impl FrameGeometry { } // Build macroblock -> block mappings - let mut mb_luma_blocks = vec![[0usize; 4]; nmbs]; - let mut mb_chroma_cb_blocks = vec![Vec::new(); nmbs]; - let mut mb_chroma_cr_blocks = vec![Vec::new(); nmbs]; + let mut mb_luma_blocks = alloc_vec([0usize; 4], nmbs)?; + let mut mb_chroma_cb_blocks = Vec::new(); + mb_chroma_cb_blocks.try_reserve_exact(nmbs).map_err(|_| Error::OutOfMemory)?; + for _ in 0..nmbs { + mb_chroma_cb_blocks.push(Vec::new()); + } + let mut mb_chroma_cr_blocks = Vec::new(); + mb_chroma_cr_blocks.try_reserve_exact(nmbs).map_err(|_| Error::OutOfMemory)?; + for _ in 0..nmbs { + mb_chroma_cr_blocks.push(Vec::new()); + } for mbi in 0..nmbs { let (mx, my) = mb_coords[mbi]; @@ -229,7 +279,7 @@ impl FrameGeometry { } } - Self { + Ok(Self { fmbw, fmbh, pixel_format, @@ -245,7 +295,7 @@ impl FrameGeometry { mb_chroma_cb_blocks, mb_chroma_cr_blocks, sb_block_counts, - } + }) } } diff --git a/crates/video/tests/theora.rs b/crates/video/tests/theora.rs index ac9dcac2fd..0fee51d6b5 100644 --- a/crates/video/tests/theora.rs +++ b/crates/video/tests/theora.rs @@ -185,12 +185,31 @@ fn test_theora_video_frame_conversion() { bad_stride.y_stride = 0; assert!(VideoFrame::try_from(bad_stride).is_err()); + // Short non-zero stride shorter than source plane width fails with FrameError + let mut short_stride = pic.clone(); + short_stride.y_stride = 16; + assert!(VideoFrame::try_from(short_stride).is_err()); + + let mut short_uv_stride = pic.clone(); + short_uv_stride.uv_stride = 8; + assert!(VideoFrame::try_from(short_uv_stride).is_err()); + // Oversized dimensions fail with FrameError without panicking let mut bad_dims = pic.clone(); bad_dims.pic_width = u32::MAX; bad_dims.pic_height = u32::MAX; assert!(VideoFrame::try_from(bad_dims).is_err()); + // Matching frame and crop dimensions that exceed memory budget fail at budget check + let mut budget_pic = test_picture(32, 32); + budget_pic.width = 65536; + budget_pic.height = 65536; + budget_pic.pic_width = 65536; + budget_pic.pic_height = 65536; + budget_pic.y_stride = 65536; + budget_pic.uv_stride = 32768; + assert!(matches!(VideoFrame::try_from(budget_pic), Err(craft_video::frame::FrameError::Shape(_)))); + // Crop bounds exceeding frame dimensions fail with FrameError let mut bad_crop = pic.clone(); bad_crop.pic_x = 30; @@ -213,6 +232,18 @@ fn test_theora_video_frame_conversion() { let u_bottom = vf_odd.planes()[1].row_u8(1).expect("u row 1"); assert_eq!(u_bottom[0], 50); assert_eq!(u_bottom[1], 150); + + // Odd vertical crop with distinct chroma rows preserves vertical subsampling + let mut odd_y_pic = test_picture(32, 32); + odd_y_pic.pic_x = 0; + odd_y_pic.pic_y = 1; + odd_y_pic.pic_width = 4; + odd_y_pic.pic_height = 3; + odd_y_pic.u[0] = 77; + odd_y_pic.u[16] = 88; + let vf_odd_y = VideoFrame::try_from(odd_y_pic).expect("convert odd y crop"); + assert_eq!(vf_odd_y.subsampling(), craft_video::frame::Subsampling::S444); + assert_eq!(vf_odd_y.height(), 3); } #[test] @@ -543,6 +574,17 @@ fn test_theora_encoder_invalid_input_rejected() { let mut pic = test_picture(32, 32); pic.width = 64; assert!(matches!(enc.encode_frame(&pic, true), Err(Error::DimensionMismatch(_)))); + + // Mismatched picture bounds (e.g. pic_width = 0 with cleared plane) cannot bypass validation + let mut pic = test_picture(32, 32); + pic.pic_width = 0; + pic.y.clear(); + assert!(matches!(enc.encode_frame(&pic, true), Err(Error::DimensionMismatch(_)))); + + // Short non-zero stride shorter than plane width + let mut pic = test_picture(32, 32); + pic.y_stride = 16; + assert!(matches!(enc.encode_frame(&pic, true), Err(Error::DimensionMismatch(_)))); } #[test] From 12daca5ac5904cd548e8727077072d50f3857b87 Mon Sep 17 00:00:00 2001 From: el-j Date: Fri, 20 Nov 2026 10:03:07 +0100 Subject: [PATCH 045/130] craft-captions: harden legacy subtitle timing rounding, clear emission, and escaping --- crates/captions/src/lib.rs | 10 ++-- crates/captions/src/mpl2.rs | 29 +++++++-- crates/captions/src/sami.rs | 41 ++++++++++--- crates/captions/src/subviewer.rs | 63 ++++++++++++++++---- crates/captions/src/vplayer.rs | 79 ++++++++++++++++++++----- crates/captions/tests/it/legacy_text.rs | 4 ++ 6 files changed, 183 insertions(+), 43 deletions(-) diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index 80a5ac46ad..f291fa62ec 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -328,7 +328,9 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if head.starts_with("[Script Info]") { return Some(Format::Ass); } - if head.get(..5).is_some_and(|h| h.eq_ignore_ascii_case("' || b == b'/') + { return Some(Format::Sami); } if subviewer::is_header(head) { @@ -337,6 +339,8 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if realtext::is_realtext(head) { return Some(Format::RealText); } + let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase()); + let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some()); let first_lines: Vec<&str> = head.lines().map(str::trim).filter(|l| !l.is_empty()).take(3).collect(); if first_lines.first().is_some_and(|l| microdvd::is_cue(l)) { return Some(Format::MicroDvd); @@ -344,7 +348,7 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if first_lines.first().is_some_and(|l| mpl2::split_cue(l).is_some()) { return Some(Format::Mpl2); } - if first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) { + if ext.as_deref() != Some("srt") && !has_arrow_timing && first_lines.iter().any(|l| subviewer::parse_timing(l).is_some()) { return Some(Format::SubViewer); } if !first_lines.is_empty() && first_lines.iter().all(|l| vplayer::split_line(l).is_some()) { @@ -356,14 +360,12 @@ pub fn detect(bytes: &[u8], ext: Option<&str>) -> Option { if first_lines.iter().any(|l| jacosub::is_timed_line(l)) || (head.starts_with('#') && (head.contains("TimeRes") || head.contains("#T"))) { return Some(Format::JacoSub); } - let ext = ext.map(|e| e.trim_start_matches('.').to_ascii_lowercase()); if (head.starts_with('<') && (head.contains("") || head.contains(":tt "))) && (head.contains("ns/ttml") || head.contains("ttaf1")) { let legacy = head.contains("ttaf1") || head.contains("dfxp"); return Some(if ext.as_deref() == Some("dfxp") || (legacy && ext.as_deref() != Some("ttml")) { Format::Dfxp } else { Format::Ttml }); } - let has_arrow_timing = head.lines().take(40).any(|l| srt::parse_timing_line(l).is_some()); match ext.as_deref() { Some("srt") if has_arrow_timing || head.is_empty() => Some(Format::Srt), Some("vtt") if has_arrow_timing => Some(Format::WebVtt), diff --git a/crates/captions/src/mpl2.rs b/crates/captions/src/mpl2.rs index af1ac07722..b7613f073d 100644 --- a/crates/captions/src/mpl2.rs +++ b/crates/captions/src/mpl2.rs @@ -6,7 +6,8 @@ //! //! A line is `[start][end]text` with times in deciseconds. `|` starts a new line; a `/` at the //! start of a line makes it italic. Writing marks a line italic only when `` wraps all of it, -//! drops other tags, rounds times to a tenth of a second, and writes `|` in text as `|`. +//! drops other tags, rounds times to a tenth of a second, writes `|` in text as `|`, and writes +//! a leading `/` in non-italic text as `/`. use crate::text::{escape_markup, ms_to_tick, number, plain_text, tick_to_ms, whole_line_style, wrap_style}; use crate::{Cue, Document, Error, Result}; @@ -36,11 +37,14 @@ pub fn parse(text: &str) -> Result { let mut lines = Vec::new(); for l in raw.split('|') { let (italic, l) = match l.trim().strip_prefix('/') { - Some(r) => (true, r.trim()), - None => (false, l.trim()), + Some(r) => (true, r.trim().to_string()), + None => { + let t = l.trim(); + if let Some(rest) = t.strip_prefix('\u{ff0f}') { (false, format!("/{rest}")) } else { (false, t.to_string()) } + } }; if !l.is_empty() { - lines.push(wrap_style(crate::text::LineStyle { italic, ..Default::default() }, None, &escape_markup(l))); + lines.push(wrap_style(crate::text::LineStyle { italic, ..Default::default() }, None, &escape_markup(&l))); } } let (start, end) = (ms_to_tick(a.saturating_mul(100)), ms_to_tick(b.saturating_mul(100))); @@ -65,7 +69,10 @@ pub fn write(doc: &Document) -> String { let mut lines = Vec::new(); for line in c.text.lines() { let (style, inner) = whole_line_style(line); - let text = plain_text(inner).trim().replace('|', "\u{ff5c}"); + let mut text = plain_text(inner).trim().replace('|', "\u{ff5c}"); + if !style.italic && text.starts_with('/') { + text.replace_range(..1, "\u{ff0f}"); + } if !text.is_empty() { lines.push(if style.italic { format!("/{text}") } else { text }); } @@ -92,4 +99,16 @@ mod tests { fn rejects_other_text() { assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err()); } + + #[test] + fn non_italic_leading_slash_roundtrip() { + let doc = Document { + cues: vec![Cue { start: ms_to_tick(1000), end: ms_to_tick(2000), text: "/not italic\n/italic".into(), ..Default::default() }], + ..Default::default() + }; + let written = write(&doc); + assert_eq!(written, "[10][20]/not italic|//italic\n"); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues[0].text, "/not italic\n/italic"); + } } diff --git a/crates/captions/src/sami.rs b/crates/captions/src/sami.rs index 056cc1c6d8..eebbee829e 100644 --- a/crates/captions/src/sami.rs +++ b/crates/captions/src/sami.rs @@ -217,14 +217,20 @@ pub fn write(doc: &Document) -> String { let mut out = String::from( "\n\n\n\n\n\n", ); - for (i, c) in cues.iter().enumerate() { - let lines: Vec<&str> = c.text.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); - if lines.is_empty() { - continue; - } - out.push_str(&format!("

    {}\n", tick_to_ms(c.start), lines.join("
    "))); - if cues.get(i + 1).map(|n| tick_to_ms(n.start)) != Some(tick_to_ms(c.end)) { - out.push_str(&format!("

     \n", tick_to_ms(c.end))); + let active_cues: Vec<(&Cue, Vec<&str>)> = cues + .iter() + .filter_map(|c| { + let lines: Vec<&str> = c.text.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); + if lines.is_empty() { None } else { Some((c, lines)) } + }) + .collect(); + for (i, (c, lines)) in active_cues.iter().enumerate() { + let start_ms = tick_to_ms(c.start); + let end_ms = tick_to_ms(c.end).max(start_ms + 1); + out.push_str(&format!("

    {}\n", lines.join("
    "))); + let next_start = active_cues.get(i + 1).map(|(n, _)| tick_to_ms(n.start)); + if next_start != Some(end_ms) { + out.push_str(&format!("

     \n")); } } out.push_str("\n\n"); @@ -266,4 +272,23 @@ mod tests { fn rejects_other_text() { assert!(parse("hello").is_err()); } + + #[test] + fn short_duration_and_empty_cues() { + let doc = Document { + cues: vec![ + Cue { start: ms_to_tick(100), end: Tick(ms_to_tick(100).0 + 1), text: "Brief".into(), ..Default::default() }, + Cue { start: ms_to_tick(101), end: ms_to_tick(200), text: " ".into(), ..Default::default() }, + Cue { start: ms_to_tick(500), end: ms_to_tick(600), text: "After gap".into(), ..Default::default() }, + ], + ..Default::default() + }; + let written = write(&doc); + assert!(written.contains("

    Brief\n

     \n")); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 2); + assert_eq!(parsed.cues[0].start, ms_to_tick(100)); + assert_eq!(parsed.cues[0].end, ms_to_tick(101)); + assert_eq!(parsed.cues[1].start, ms_to_tick(500)); + } } diff --git a/crates/captions/src/subviewer.rs b/crates/captions/src/subviewer.rs index abc37fc2b9..fada039b24 100644 --- a/crates/captions/src/subviewer.rs +++ b/crates/captions/src/subviewer.rs @@ -13,12 +13,15 @@ //! Reading skips the bracketed header lines and takes every `start,end` time line as a cue whose //! text runs to the next blank line; `[br]` starts a new line. Fractions of one to three digits //! are accepted. Writing adds a minimal header, rounds times to a hundredth of a second, drops -//! tags and writes `[br]` inside text as `[br]`. +//! tags, writes `[br]` inside text as `[br]`, and writes `,` in lines that match the timing +//! syntax as `,`. -use crate::text::{escape_markup, plain_lines, tick_to_ms}; -use crate::time::Tick; +use crate::text::{escape_markup, plain_lines}; +use crate::time::{TICKS_PER_SECOND, Tick}; use crate::{Cue, Document, Error, Result, parse_clock}; +const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100; + /// Returns true if `head` begins with a genuine SubViewer header structure. pub(crate) fn is_header(head: &str) -> bool { let mut lines = head.lines().map(str::trim).filter(|l| !l.is_empty()); @@ -80,7 +83,14 @@ pub fn parse(text: &str) -> Result { if parse_timing(l).is_some() { break; } - out.extend(split_br(l).into_iter().map(str::trim).filter(|p| !p.is_empty()).map(escape_markup)); + out.extend(split_br(l).into_iter().map(str::trim).filter(|p| !p.is_empty()).map(|p| { + let p = if p.contains('\u{ff0c}') && parse_timing(&p.replacen('\u{ff0c}', ",", 1)).is_some() { + p.replacen('\u{ff0c}', ",", 1) + } else { + p.to_string() + }; + escape_markup(&p) + })); i += 1; } if end <= start || out.is_empty() { @@ -96,8 +106,11 @@ pub fn parse(text: &str) -> Result { Ok(doc) } -fn clock(t: Tick) -> String { - let cs = (tick_to_ms(t) + 5) / 10; +fn cs(t: Tick) -> u64 { + ((i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS)) as u64 +} + +fn clock(cs: u64) -> String { format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100) } @@ -110,11 +123,15 @@ pub fn write(doc: &Document) -> String { if lines.is_empty() { continue; } - let end = if clock(c.end) == clock(c.start) { Tick(c.end.0.saturating_add(crate::TICKS_PER_MS * 10)) } else { c.end }; - out.push_str(&format!("{},{}\n", clock(c.start), clock(end))); + let start_cs = cs(c.start); + let end_cs = cs(c.end).max(start_cs + 1); + out.push_str(&format!("{},{}\n", clock(start_cs), clock(end_cs))); let lines: Vec = lines - .iter() - .map(|l| { + .into_iter() + .map(|mut l| { + if parse_timing(&l).is_some() { + l = l.replacen(',', "\u{ff0c}", 1); + } l.replace("[br]", "\u{ff3b}br\u{ff3d}") .replace("[BR]", "\u{ff3b}BR\u{ff3d}") .replace("[Br]", "\u{ff3b}Br\u{ff3d}") @@ -152,4 +169,30 @@ mod tests { fn rejects_other_text() { assert!(parse("1\n00:00:01,000 --> 00:00:02,000\nx\n").is_err()); } + + #[test] + fn centisecond_rounding_without_double_rounding_error() { + // 1.0046s is 255_184_473_600 ticks (at 254_016_000_000 ticks/sec). + // Direct rounding to hundredths gives 100cs (00:00:01.00). + // Double-rounding through ms gives 1005ms -> 101cs (00:00:01.01). + let t = Tick(255_184_473_600); + assert_eq!(clock(cs(t)), "00:00:01.00"); + } + + #[test] + fn timing_shaped_text_escaped_and_roundtripped() { + let doc = Document { + cues: vec![ + Cue { start: Tick(TICKS_PER_SECOND), end: Tick(3 * TICKS_PER_SECOND), text: "00:00:01.00,00:00:02.00".into(), ..Default::default() }, + Cue { start: Tick(4 * TICKS_PER_SECOND), end: Tick(5 * TICKS_PER_SECOND), text: "Second cue".into(), ..Default::default() }, + ], + ..Default::default() + }; + let written = write(&doc); + assert!(written.contains("00:00:01.00,00:00:02.00")); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 2); + assert_eq!(parsed.cues[0].text, "00:00:01.00,00:00:02.00"); + assert_eq!(parsed.cues[1].text, "Second cue"); + } } diff --git a/crates/captions/src/vplayer.rs b/crates/captions/src/vplayer.rs index 1124c2054c..e1c42ba424 100644 --- a/crates/captions/src/vplayer.rs +++ b/crates/captions/src/vplayer.rs @@ -11,10 +11,12 @@ //! Writing puts a clearing line where a caption ends before the next one starts, drops tags, //! rounds to a hundredth of a second and writes `|` in text as `|`. -use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, plain_lines, sequential, tick_to_ms}; -use crate::time::Tick; +use crate::text::{escape_markup, last_cue_end, ms_to_tick, number, plain_lines, sequential}; +use crate::time::{TICKS_PER_SECOND, Tick}; use crate::{Cue, Document, Error, Result}; +const TICKS_PER_CS: i64 = TICKS_PER_SECOND / 100; + /// `HH:MM:SS[.cc]` then a separator and text: the time and the text. pub(crate) fn split_line(line: &str) -> Option<(Tick, &str)> { let mut parts = line.splitn(3, ':'); @@ -72,27 +74,39 @@ pub fn parse(text: &str) -> Result { Ok(doc) } -fn clock(t: Tick) -> String { - let cs = (tick_to_ms(t) + 5) / 10; +fn cs(t: Tick) -> i64 { + ((i128::from(t.0.max(0)) + i128::from(TICKS_PER_CS) / 2) / i128::from(TICKS_PER_CS)) as i64 +} + +fn clock(cs: i64) -> String { format!("{:02}:{:02}:{:02}.{:02}", cs / 360_000, (cs / 6000) % 60, (cs / 100) % 60, cs % 100) } pub fn write(doc: &Document) -> String { let cues = sequential(doc); let mut out = String::new(); - for (i, c) in cues.iter().enumerate() { - let lines = plain_lines(&c.text); - if lines.is_empty() { - continue; - } - let lines: Vec = lines.iter().map(|l| l.replace('|', "\u{ff5c}")).collect(); - out.push_str(&format!("{}={}\n", clock(c.start), lines.join("|"))); - let end = if clock(c.end) == clock(c.start) { Tick(c.end.0.saturating_add(crate::TICKS_PER_MS * 10)) } else { c.end }; - let next = cues.get(i + 1).map(|n| clock(n.start)); - if next.as_deref() != Some(clock(end).as_str()) { - let next_too_early = cues.get(i + 1).is_some_and(|n| clock(n.start) <= clock(c.start)); + let active_cues: Vec<(&Cue, Vec)> = cues + .iter() + .filter_map(|c| { + let lines = plain_lines(&c.text); + if lines.is_empty() { + None + } else { + let lines = lines.into_iter().map(|l| l.replace('|', "\u{ff5c}")).collect(); + Some((c, lines)) + } + }) + .collect(); + + for (i, (c, lines)) in active_cues.iter().enumerate() { + let start_cs = cs(c.start); + let end_cs = cs(c.end).max(start_cs + 1); + out.push_str(&format!("{}={}\n", clock(start_cs), lines.join("|"))); + let next_start_cs = active_cues.get(i + 1).map(|(n, _)| cs(n.start)); + if next_start_cs != Some(end_cs) { + let next_too_early = next_start_cs.is_some_and(|next| next <= start_cs); if !next_too_early { - out.push_str(&format!("{}=\n", clock(end))); + out.push_str(&format!("{}=\n", clock(end_cs))); } } } @@ -131,4 +145,37 @@ mod tests { assert!(parse("hello\n").is_err()); assert!(parse("00:00:01,000 --> 00:00:02,000\n").is_err()); } + + #[test] + fn empty_cue_skipped_and_numerical_timestamp_order() { + let doc = Document { + cues: vec![ + Cue { + start: Tick(99 * 3600 * TICKS_PER_SECOND), + end: Tick(99 * 3600 * TICKS_PER_SECOND + 2 * TICKS_PER_SECOND), + text: "At 99h".into(), + ..Default::default() + }, + Cue { + start: Tick(99 * 3600 * TICKS_PER_SECOND + 3 * TICKS_PER_SECOND), + end: Tick(99 * 3600 * TICKS_PER_SECOND + 4 * TICKS_PER_SECOND), + text: " ".into(), + ..Default::default() + }, + Cue { + start: Tick(100 * 3600 * TICKS_PER_SECOND), + end: Tick(100 * 3600 * TICKS_PER_SECOND + 2 * TICKS_PER_SECOND), + text: "At 100h".into(), + ..Default::default() + }, + ], + ..Default::default() + }; + let written = write(&doc); + assert_eq!(written, "99:00:00.00=At 99h\n99:00:02.00=\n100:00:00.00=At 100h\n100:00:02.00=\n"); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 2); + assert_eq!(parsed.cues[0].text, "At 99h"); + assert_eq!(parsed.cues[1].text, "At 100h"); + } } diff --git a/crates/captions/tests/it/legacy_text.rs b/crates/captions/tests/it/legacy_text.rs index c171b63f17..250a1d7307 100644 --- a/crates/captions/tests/it/legacy_text.rs +++ b/crates/captions/tests/it/legacy_text.rs @@ -172,6 +172,10 @@ fn detection_finds_each_format() { // Cue text containing literal SubViewer markers must not hijack SRT detection assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\nHere is a [SUBTITLE] tag\n", None), Some(Format::Srt)); assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n[INFORMATION] about movie\n", None), Some(Format::Srt)); + assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n00:00:01.00,00:00:02.00\n", None), Some(Format::Srt)); + assert_eq!(detect(b"1\n00:00:01,000 --> 00:00:02,000\n00:00:01.00,00:00:02.00\n", Some("srt")), Some(Format::Srt)); + // TTML with namespaced sami element is not SAMI + assert_ne!(detect(b"", None), Some(Format::Sami)); // Genuine SubViewer with only [SUBTITLE] header assert_eq!(detect(b"[SUBTITLE]\n00:00:01.00,00:00:02.00\nText\n", None), Some(Format::SubViewer)); // Genuine SubViewer with long/truncated [TITLE] line From 4c0c81018af97ea3223a771b82e0c869daa57a2e Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Fri, 20 Nov 2026 18:40:19 +0530 Subject: [PATCH 046/130] cms: a negative or non-finite total ink limit is refused; curve black is never negative Review of the black cap: with tac = -0.5 the cap made gcr return a negative black. check_grids now refuses a total ink limit that is not finite or is negative, and gcr caps at tac.max(0) for callers of the public separate, which does not validate. --- crates/cms/src/synth.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index e17025a78d..3532b1e664 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -330,7 +330,7 @@ fn gcr(p: &CmykParams, g: f64) -> f64 { break; } } - k.clamp(0.0, 1.0).min(p.tac) + k.clamp(0.0, 1.0).min(p.tac.max(0.0)) } /// Colorimetric separation of a relative Lab target: GCR black generation then a CMY solve. @@ -707,6 +707,9 @@ fn check_grids(p: &CmykParams) -> Result<(), CmsError> { if p.white_on_node && p.grid_b2a.is_multiple_of(2) { return Err(invalid_arg(format!("white on a node needs an odd BToA grid, not {}", p.grid_b2a))); } + if !(p.tac.is_finite() && p.tac >= 0.0) { + return Err(invalid_arg(format!("total ink limit {} must be finite and not negative", p.tac))); + } let valid = |v: &[f64; 2]| v.iter().all(|x| (0.0..=1.0).contains(x)); if !p.gcr_curve.iter().all(valid) || p.gcr_curve.windows(2).any(|w| w[1][0] <= w[0][0]) { return Err(invalid_arg(format!("black generation curve {:?} needs points in [0, 1] with increasing gray components", p.gcr_curve))); @@ -864,6 +867,17 @@ mod tests { } } + #[test] + fn total_ink_limit_must_be_finite_and_not_negative() { + for tac in [-0.5, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let p = CmykParams { grid_a2b: 2, grid_b2a: 2, tac, ..CmykParams::default() }; + assert!(cmyk_profile(&p).is_err(), "tac {tac}"); + } + // `separate` is public and does not validate: black is still never negative. + let p = CmykParams { tac: -0.5, gcr_curve: vec![[0.0, 0.75]], ..CmykParams::default() }; + assert_eq!(gcr(&p, 0.5), 0.0); + } + #[test] fn curve_black_stays_within_the_ink_limit() { let p = CmykParams { tac: 0.5, gcr_curve: vec![[0.0, 0.75]], ..CmykParams::default() }; From fdd3e35b6aaaa8db389181adc3337bb500c0a595 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 09:18:28 -0800 Subject: [PATCH 047/130] test(control): retry ports taken by a competing listener --- crates/control/src/client_tests.rs | 50 +++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/crates/control/src/client_tests.rs b/crates/control/src/client_tests.rs index f5af19a004..ea41cd56fc 100644 --- a/crates/control/src/client_tests.rs +++ b/crates/control/src/client_tests.rs @@ -78,11 +78,38 @@ fn addr(port: u16) -> String { format!("127.0.0.1:{port}") } -/// A port nothing listens on. +/// A candidate port: another process may bind it after this listener is dropped. fn free_port() -> u16 { TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() } +/// Check a closed port, trying another candidate only when a successful TCP connection proves +/// that a listener took this one. A wrong error for a port we never reached still fails. +fn assert_not_running_on_unused_port(mut next_port: impl FnMut() -> u16) -> (u16, Vec) { + let mut occupied = Vec::new(); + for _ in 0..10 { + let port = next_port(); + let mut c = Connection::new(APP, &addr(port), Some(TOKEN)); + let result = c.call(Request::new("document.inspect", json!({}))); + if c.serial() != 0 { + occupied.push(port); + continue; + } + let e = result.unwrap_err(); + let CallError::NotRunning(m) = &e else { panic!("{e:?}") }; + assert!(m.starts_with(&format!("no Probe app is listening at 127.0.0.1:{port}")), "{m}"); + assert!(m.contains(&format!("`probe --control {port}`")), "{m}"); + let connected = c.try_connect(); + if c.serial() != 0 { + occupied.push(port); + continue; + } + assert_eq!(connected.unwrap_err().kind(), std::io::ErrorKind::NotConnected); + return (port, occupied); + } + panic!("another listener took every candidate port"); +} + #[test] fn a_call_is_one_round_trip_with_the_token() { let app = serve(0, Duration::ZERO, Duration::from_secs(10)); @@ -115,13 +142,20 @@ fn a_wrong_token_or_none_is_refused() { #[test] fn an_app_not_running_says_how_to_start_it() { - let port = free_port(); - let mut c = Connection::new(APP, &addr(port), Some(TOKEN)); - let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err(); - let CallError::NotRunning(m) = &e else { panic!("{e:?}") }; - assert!(m.starts_with(&format!("no Probe app is listening at 127.0.0.1:{port}")), "{m}"); - assert!(m.contains(&format!("`probe --control {port}`")), "{m}"); - assert_eq!(c.try_connect().unwrap_err().kind(), std::io::ErrorKind::NotConnected); + assert_not_running_on_unused_port(free_port); +} + +#[test] +fn the_not_running_fixture_retries_a_port_taken_by_another_server() { + let rival = serve(0, Duration::ZERO, Duration::from_secs(10)); + let mut candidates = 0; + let (port, occupied) = assert_not_running_on_unused_port(|| { + candidates += 1; + if candidates == 1 { rival.port() } else { free_port() } + }); + assert!(candidates >= 2); + assert_eq!(occupied.first(), Some(&rival.port())); + assert_ne!(port, rival.port()); } /// An app that goes away during a call is lost, not "not running"; the next call says it is not From 7e04e999bf2dba5f9f133d5f73a94821239e0a11 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 09:18:41 -0800 Subject: [PATCH 048/130] fix(update): retry busy leftover-mount detaches --- crates/update/src/install.rs | 136 ++++++++++++++++++++++++++++++++++- 1 file changed, 134 insertions(+), 2 deletions(-) diff --git a/crates/update/src/install.rs b/crates/update/src/install.rs index 04924c6772..6eba2d856b 100644 --- a/crates/update/src/install.rs +++ b/crates/update/src/install.rs @@ -1590,6 +1590,22 @@ pub mod linux { } } +/// Retries only the disk-image helper's known busy replies. The injected wait keeps the policy's +/// tests independent of macOS and wall-clock delays; the real caller uses `thread::sleep`. +#[cfg(any(target_os = "macos", test))] +fn retry_busy_detach(mut detach: impl FnMut() -> Result<(), String>, mut wait: impl FnMut(std::time::Duration)) -> Result<(), String> { + let mut result = detach(); + for millis in [500, 1000, 2000, 4000] { + let Err(reason) = &result else { return result }; + if !reason.contains("Resource busy") && !reason.contains("Resource temporarily unavailable") { + return result; + } + wait(std::time::Duration::from_millis(millis)); + result = detach(); + } + result +} + #[cfg(target_os = "macos")] pub mod macos { use std::time::Duration; @@ -2074,6 +2090,17 @@ pub mod macos { /// when `ended` says its process ended, or when it is this process's and no install here uses /// it. `detach` detaches an image. Failures are logged and the install goes on. pub(crate) fn clear_mounts(app: &App, cache: &Path, ended: impl Fn(u32) -> bool, detach: impl Fn(&Path) -> Result<(), String>) { + clear_mounts_with_wait(app, cache, ended, detach, std::thread::sleep); + } + + /// [`clear_mounts`], with the busy-helper backoff supplied by the caller. + pub(crate) fn clear_mounts_with_wait( + app: &App, + cache: &Path, + ended: impl Fn(u32) -> bool, + detach: impl Fn(&Path) -> Result<(), String>, + mut wait: impl FnMut(Duration), + ) { let Ok(entries) = std::fs::read_dir(cache) else { return }; let prefix = format!("mount-{}-", app.id); // Read before `ended` runs `ps`, which then lists every process that made one of them. @@ -2087,7 +2114,7 @@ pub mod macos { if !gone { continue; } - match detach(&mount).and_then(|()| std::fs::remove_dir(&mount).map_err(|e| e.to_string())) { + match super::retry_busy_detach(|| detach(&mount), &mut wait).and_then(|()| std::fs::remove_dir(&mount).map_err(|e| e.to_string())) { Ok(()) => log::info!("removed {}, left by an install that ended partway", mount.display()), Err(e) => log::warn!("couldn't clear {}, left by an install that ended partway ({e})", mount.display()), } @@ -4250,6 +4277,60 @@ exit 0 } } + #[test] + fn a_busy_detach_retries_and_stops_as_soon_as_it_succeeds() { + for reason in ["hdiutil: detach failed - Resource busy", "hdiutil: detach failed - Resource temporarily unavailable"] { + let mut attempts = 0; + let mut waits = Vec::new(); + let result = retry_busy_detach( + || { + attempts += 1; + if attempts == 1 { Err(reason.to_string()) } else { Ok(()) } + }, + |delay| waits.push(delay), + ); + assert_eq!(result, Ok(()), "{reason}"); + assert_eq!(attempts, 2, "the successful second detach must be the last"); + assert_eq!(waits.len(), 1); + assert!(!waits[0].is_zero()); + } + } + + #[test] + fn a_detach_that_stays_busy_returns_its_last_error_after_bounded_retries() { + let mut attempts = 0; + let mut waits = Vec::new(); + let result = retry_busy_detach( + || { + attempts += 1; + assert!(attempts <= 5, "a busy helper must not be retried indefinitely"); + Err(format!("Resource busy, attempt {attempts}")) + }, + |delay| waits.push(delay), + ); + assert!((2..=5).contains(&attempts)); + assert_eq!(waits.len(), attempts - 1); + assert!(waits.iter().all(|delay| !delay.is_zero())); + assert!(waits.iter().sum::() <= std::time::Duration::from_secs(8)); + assert_eq!(result, Err(format!("Resource busy, attempt {attempts}"))); + } + + #[test] + fn a_detach_success_or_nonbusy_failure_never_waits_or_retries() { + for answer in [Ok(()), Err("Permission denied".to_string()), Err("hdiutil didn't finish within 60 seconds".to_string())] { + let mut attempts = 0; + let result = retry_busy_detach( + || { + attempts += 1; + answer.clone() + }, + |_| panic!("success and nonbusy failure must not wait"), + ); + assert_eq!(result, answer); + assert_eq!(attempts, 1); + } + } + /// Whether hdiutil's `stderr` says the disk-image helper turned the request away because it /// was busy. fn busy(stderr: &[u8]) -> bool { @@ -4899,7 +4980,8 @@ exit 0 |pid| pid == ended, |mount| { asked.borrow_mut().push(mount.to_path_buf()); - if mount == busy { Err("Resource busy".into()) } else { Ok(()) } + // This control pins a permanent refusal; busy retries have their own cases. + if mount == busy { Err("Permission denied".into()) } else { Ok(()) } }, ); let mut asked = asked.into_inner(); @@ -4913,6 +4995,56 @@ exit 0 } } + #[test] + fn an_ended_mount_is_removed_after_a_busy_detach_succeeds() { + let dir = tempfile::tempdir().unwrap(); + let mount = dir.path().join("mount-photocraft-4000001-1"); + std::fs::create_dir(&mount).unwrap(); + let attempts = std::cell::Cell::new(0); + let waits = std::cell::Cell::new(0); + macos::clear_mounts_with_wait( + photocraft(), + dir.path(), + |pid| pid == 4_000_001, + |path| { + assert_eq!(path, mount.as_path()); + attempts.set(attempts.get() + 1); + if attempts.get() == 1 { Err("Resource temporarily unavailable".into()) } else { Ok(()) } + }, + |delay| { + assert!(!delay.is_zero()); + waits.set(waits.get() + 1); + }, + ); + assert!(!mount.exists(), "a transiently busy leftover image must not block the next install"); + assert_eq!(attempts.get(), 2); + assert_eq!(waits.get(), 1); + } + + #[test] + fn a_mount_that_stays_busy_is_left_after_bounded_cleanup() { + let dir = tempfile::tempdir().unwrap(); + let mount = dir.path().join("mount-photocraft-4000001-1"); + std::fs::create_dir(&mount).unwrap(); + let attempts = std::cell::Cell::new(0); + let waits = std::cell::Cell::new(0); + macos::clear_mounts_with_wait( + photocraft(), + dir.path(), + |pid| pid == 4_000_001, + |path| { + assert_eq!(path, mount.as_path()); + attempts.set(attempts.get() + 1); + assert!(attempts.get() <= 5, "cleanup must stop retrying"); + Err("Resource busy".into()) + }, + |_| waits.set(waits.get() + 1), + ); + assert!(mount.exists(), "a mount whose detach failed must not be removed"); + assert!((2..=5).contains(&attempts.get())); + assert_eq!(waits.get(), attempts.get() - 1); + } + #[test] fn a_failed_attach_detaches_only_unmounted_attachments_of_its_image() { let image = |path: &str, entities: &[(&str, Option<&str>)]| { From b175f61fda3594875f925df49931ba3044fa9c6b Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 09:26:00 -0800 Subject: [PATCH 049/130] test(control): hold a non-listening port reservation --- Cargo.lock | 1 + crates/control/Cargo.toml | 4 ++ crates/control/src/client_tests.rs | 63 +++++++++++------------------- 3 files changed, 27 insertions(+), 41 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6223511b3a..8f913e195c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1720,6 +1720,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "socket2", "tempfile", ] diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 3e756aff75..cc5f7b10a5 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -36,6 +36,10 @@ log = { workspace = true, optional = true } proptest = { workspace = true } tempfile = "3" +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +# Reserve an unused control port without opening a listener, including between assertions. +socket2 = "0.6.5" + [[test]] name = "agents" required-features = ["agents"] diff --git a/crates/control/src/client_tests.rs b/crates/control/src/client_tests.rs index ea41cd56fc..e19aa62302 100644 --- a/crates/control/src/client_tests.rs +++ b/crates/control/src/client_tests.rs @@ -1,6 +1,7 @@ //! The client against the shared server ([`crate::server::Hub`]) on an ephemeral loopback port. use super::*; +use socket2::{Domain, Protocol, Socket, Type}; use crate::ControlRequest; use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits}; use std::ffi::OsString; @@ -78,36 +79,14 @@ fn addr(port: u16) -> String { format!("127.0.0.1:{port}") } -/// A candidate port: another process may bind it after this listener is dropped. -fn free_port() -> u16 { - TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() -} - -/// Check a closed port, trying another candidate only when a successful TCP connection proves -/// that a listener took this one. A wrong error for a port we never reached still fails. -fn assert_not_running_on_unused_port(mut next_port: impl FnMut() -> u16) -> (u16, Vec) { - let mut occupied = Vec::new(); - for _ in 0..10 { - let port = next_port(); - let mut c = Connection::new(APP, &addr(port), Some(TOKEN)); - let result = c.call(Request::new("document.inspect", json!({}))); - if c.serial() != 0 { - occupied.push(port); - continue; - } - let e = result.unwrap_err(); - let CallError::NotRunning(m) = &e else { panic!("{e:?}") }; - assert!(m.starts_with(&format!("no Probe app is listening at 127.0.0.1:{port}")), "{m}"); - assert!(m.contains(&format!("`probe --control {port}`")), "{m}"); - let connected = c.try_connect(); - if c.serial() != 0 { - occupied.push(port); - continue; - } - assert_eq!(connected.unwrap_err().kind(), std::io::ErrorKind::NotConnected); - return (port, occupied); - } - panic!("another listener took every candidate port"); +/// Keep this port bound without listening, so another normal test listener cannot take it. +fn reserve_non_listening_port() -> (Socket, u16) { + let reserved = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP)).unwrap(); + let address = std::net::SocketAddr::from(([127, 0, 0, 1], 0)); + reserved.bind(&address.into()).unwrap(); + let port = reserved.local_addr().unwrap().as_socket().unwrap().port(); + assert_ne!(port, 0); + (reserved, port) } #[test] @@ -142,20 +121,22 @@ fn a_wrong_token_or_none_is_refused() { #[test] fn an_app_not_running_says_how_to_start_it() { - assert_not_running_on_unused_port(free_port); + let (reserved, port) = reserve_non_listening_port(); + let mut c = Connection::new(APP, &addr(port), Some(TOKEN)); + let e = c.call(Request::new("document.inspect", json!({}))).unwrap_err(); + let CallError::NotRunning(m) = &e else { panic!("{e:?}") }; + assert!(m.starts_with(&format!("no Probe app is listening at 127.0.0.1:{port}")), "{m}"); + assert!(m.contains(&format!("`probe --control {port}`")), "{m}"); + assert_eq!(c.try_connect().unwrap_err().kind(), std::io::ErrorKind::NotConnected); + drop(reserved); } #[test] -fn the_not_running_fixture_retries_a_port_taken_by_another_server() { - let rival = serve(0, Duration::ZERO, Duration::from_secs(10)); - let mut candidates = 0; - let (port, occupied) = assert_not_running_on_unused_port(|| { - candidates += 1; - if candidates == 1 { rival.port() } else { free_port() } - }); - assert!(candidates >= 2); - assert_eq!(occupied.first(), Some(&rival.port())); - assert_ne!(port, rival.port()); +fn the_not_running_fixture_keeps_its_port_from_another_listener() { + let (reserved, port) = reserve_non_listening_port(); + let rival = TcpListener::bind(("127.0.0.1", port)); + assert!(rival.is_err(), "another listener acquired the reserved port"); + drop(reserved); } /// An app that goes away during a call is lost, not "not running"; the next call says it is not From 1baedb164b750a0a0873b4bc840aee2ea690c898 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 09:30:16 -0800 Subject: [PATCH 050/130] test(control): disambiguate the socket protocol type --- crates/control/src/client_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/control/src/client_tests.rs b/crates/control/src/client_tests.rs index e19aa62302..7a6ed5782e 100644 --- a/crates/control/src/client_tests.rs +++ b/crates/control/src/client_tests.rs @@ -1,7 +1,7 @@ //! The client against the shared server ([`crate::server::Hub`]) on an ephemeral loopback port. use super::*; -use socket2::{Domain, Protocol, Socket, Type}; +use socket2::{Domain, Socket, Type}; use crate::ControlRequest; use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits}; use std::ffi::OsString; @@ -81,7 +81,7 @@ fn addr(port: u16) -> String { /// Keep this port bound without listening, so another normal test listener cannot take it. fn reserve_non_listening_port() -> (Socket, u16) { - let reserved = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP)).unwrap(); + let reserved = Socket::new(Domain::IPV4, Type::STREAM, Some(socket2::Protocol::TCP)).unwrap(); let address = std::net::SocketAddr::from(([127, 0, 0, 1], 0)); reserved.bind(&address.into()).unwrap(); let port = reserved.local_addr().unwrap().as_socket().unwrap().port(); From 718e5c896d82a6598f88167dd0b2fd1aa11b846f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 09:33:49 -0800 Subject: [PATCH 051/130] fix(update): count detach time against the retry window --- crates/update/src/install.rs | 42 ++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/crates/update/src/install.rs b/crates/update/src/install.rs index 6eba2d856b..03d93d780b 100644 --- a/crates/update/src/install.rs +++ b/crates/update/src/install.rs @@ -1593,14 +1593,34 @@ pub mod linux { /// Retries only the disk-image helper's known busy replies. The injected wait keeps the policy's /// tests independent of macOS and wall-clock delays; the real caller uses `thread::sleep`. #[cfg(any(target_os = "macos", test))] -fn retry_busy_detach(mut detach: impl FnMut() -> Result<(), String>, mut wait: impl FnMut(std::time::Duration)) -> Result<(), String> { +fn retry_busy_detach(detach: impl FnMut() -> Result<(), String>, wait: impl FnMut(std::time::Duration)) -> Result<(), String> { + let started = std::time::Instant::now(); + retry_busy_detach_with_elapsed(detach, wait, || started.elapsed()) +} + +/// Counts time spent in the helper as well as backoff, so a slow failure cannot multiply the +/// ordinary/force helper timeouts. An already started detach keeps its original limits. +#[cfg(any(target_os = "macos", test))] +fn retry_busy_detach_with_elapsed( + mut detach: impl FnMut() -> Result<(), String>, + mut wait: impl FnMut(std::time::Duration), + mut elapsed: impl FnMut() -> std::time::Duration, +) -> Result<(), String> { + let window = std::time::Duration::from_secs(8); let mut result = detach(); for millis in [500, 1000, 2000, 4000] { let Err(reason) = &result else { return result }; if !reason.contains("Resource busy") && !reason.contains("Resource temporarily unavailable") { return result; } - wait(std::time::Duration::from_millis(millis)); + let delay = std::time::Duration::from_millis(millis); + if elapsed().saturating_add(delay) > window { + break; + } + wait(delay); + if elapsed() >= window { + break; + } result = detach(); } result @@ -4315,6 +4335,24 @@ exit 0 assert_eq!(result, Err(format!("Resource busy, attempt {attempts}"))); } + #[test] + fn a_slow_busy_detach_spends_the_retry_window_without_another_attempt() { + let attempts = std::cell::Cell::new(0); + let elapsed = std::cell::Cell::new(std::time::Duration::ZERO); + let reason = "hdiutil: detach failed - Resource busy"; + let result = retry_busy_detach_with_elapsed( + || { + attempts.set(attempts.get() + 1); + elapsed.set(std::time::Duration::from_secs(9)); + Err(reason.to_string()) + }, + |_| panic!("a slow detach has already spent the retry window"), + || elapsed.get(), + ); + assert_eq!(result, Err(reason.to_string())); + assert_eq!(attempts.get(), 1, "operation time counts against retries, not just sleep time"); + } + #[test] fn a_detach_success_or_nonbusy_failure_never_waits_or_retries() { for answer in [Ok(()), Err("Permission denied".to_string()), Err("hdiutil didn't finish within 60 seconds".to_string())] { From fd4aff80adeded2fce606e53c7558034c8b8b698 Mon Sep 17 00:00:00 2001 From: vangel76 <271991477+vangel76@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:46:59 +0100 Subject: [PATCH 052/130] feat(exr): stream multipart scanlines and tiles Refs #2560 --- Cargo.lock | 1 + crates/exr/Cargo.toml | 1 + crates/exr/src/decode.rs | 5 +- crates/exr/src/layer_stack.rs | 308 +++++++++++++++++ crates/exr/src/lib.rs | 7 + crates/exr/src/seek.rs | 64 +++- crates/exr/src/seek_tests.rs | 19 + crates/exr/src/write.rs | 633 ++++++++++++++++++++++++++++++++++ crates/exr/src/write_tests.rs | 344 ++++++++++++++++++ 9 files changed, 1367 insertions(+), 15 deletions(-) create mode 100644 crates/exr/src/layer_stack.rs create mode 100644 crates/exr/src/write.rs create mode 100644 crates/exr/src/write_tests.rs diff --git a/Cargo.lock b/Cargo.lock index 6223511b3a..0b8251b16c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2025,6 +2025,7 @@ dependencies = [ "exr", "flate2", "half", + "serde", "serde_json", "thiserror 2.0.21", ] diff --git a/crates/exr/Cargo.toml b/crates/exr/Cargo.toml index c277635284..db24946cf9 100644 --- a/crates/exr/Cargo.toml +++ b/crates/exr/Cargo.toml @@ -16,6 +16,7 @@ workspace = true decode = ["dep:exr", "dep:half", "dep:thiserror", "dep:flate2"] [dependencies] +serde = { workspace = true } serde_json = { workspace = true } exr = { version = "1.73", default-features = false, optional = true } half = { version = "2", optional = true } diff --git a/crates/exr/src/decode.rs b/crates/exr/src/decode.rs index 4d09aa1992..bd7aca975e 100644 --- a/crates/exr/src/decode.rs +++ b/crates/exr/src/decode.rs @@ -8,7 +8,8 @@ //! sample type, over the part's data window. Every compression the `exr` crate reads is read, //! scan lines and tiles alike (the largest resolution level). Other parts' chunks are skipped //! unread, and channels the filter drops are never allocated. Other parts may be deep. -//! - [`write`] writes one scan-line part. +//! - [`write`] writes one scan-line part. [`crate::write`] accepts rows incrementally for one +//! or more parts. //! //! The `exr` crate sizes buffers from headers before it reads pixels, so everything that reaches //! it is checked first: preview attributes against their own size, each part's samples against @@ -1004,7 +1005,7 @@ pub enum SampleDepth { Half, } -fn to_exr_compression(compression: Compression) -> ExrCompression { +pub(crate) fn to_exr_compression(compression: Compression) -> ExrCompression { match compression { Compression::None => ExrCompression::Uncompressed, Compression::Rle => ExrCompression::RLE, diff --git a/crates/exr/src/layer_stack.rs b/crates/exr/src/layer_stack.rs new file mode 100644 index 0000000000..e0664e8561 --- /dev/null +++ b/crates/exr/src/layer_stack.rs @@ -0,0 +1,308 @@ +//! The optional `craftLayerStack` string attribute describes an editable raster layer stack. +//! The EXR remains readable as an ordinary image without this attribute. Version 1 is an +//! ASCII-safe JSON object. Layer array order is bottom-to-top within each parent. The beauty +//! image and other passes can be stored in EXR parts or channels outside the manifest. + +use std::collections::HashMap; +use std::fmt::{self, Write}; + +use serde::{Deserialize, Serialize}; + +pub const ATTRIBUTE_NAME: &str = "craftLayerStack"; +pub const MAX_ATTRIBUTE_BYTES: usize = 1 << 20; +const VERSION: u64 = 1; +const MAX_LAYERS: usize = 4096; +const MAX_ANCESTORS: usize = 64; + +#[derive(Debug)] +pub enum Error { + Limit(&'static str), + Malformed(&'static str), + Json(serde_json::Error), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{ATTRIBUTE_NAME}: ")?; + match self { + Self::Limit(message) | Self::Malformed(message) => f.write_str(message), + Self::Json(error) => error.fmt(f), + } + } +} + +impl std::error::Error for Error {} + +#[derive(Debug, Clone, PartialEq)] +pub struct LayerStack { + pub layers: Vec, + /// The producer's original RGB compositing encoding. A portable profile ID or + /// `icc:` describing an ICC profile. EXR chromaticities describe the stored pixels. + pub original_blend_profile: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Layer { + pub id: u64, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub parent: Option, + pub visible: bool, + /// Portable blend mode identifier. Consumers may warn and use Normal for unsupported modes. + pub blend: String, + pub opacity: f32, + pub fill_opacity: f32, + pub clipped: bool, + pub content: LayerContent, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] +pub enum LayerContent { + Group, + Raster { pixels: PixelRef, sampling: PixelSampling }, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] +pub enum PixelRef { + /// A named, flat EXR part. Use part names that are unique within the file. + Part { name: String }, + /// The exact prefix of the RGB(A) channels in the zero-based flat EXR part. + ChannelGroup { part: u32, prefix: String }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PixelSampling { + /// Raster pixels from the source layer. + Raw, + /// Raster pixels derived by rendering the source layer. Transforms, effects or masks may + /// be baked into the pixels. The manifest's stack compositing properties still apply. + Baked, +} + +#[derive(Deserialize)] +struct Version { + version: u64, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Input { + version: u64, + layers: Vec, + original_blend_profile: Option, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Output<'a> { + version: u64, + layers: &'a [Layer], + #[serde(skip_serializing_if = "Option::is_none")] + original_blend_profile: Option<&'a str>, +} + +impl LayerStack { + /// Parse the attribute, returning `None` for an unsupported version. A caller can still + /// open the EXR as a flat image in that case. + pub fn parse(text: &str) -> Result, Error> { + if text.len() > MAX_ATTRIBUTE_BYTES { + return Err(Error::Limit("attribute is too large")); + } + if !text.trim_start().starts_with('{') { + return Err(Error::Malformed("expected a JSON object")); + } + let version = serde_json::from_str::(text).map_err(Error::Json)?.version; + if version != VERSION { + return Ok(None); + } + let Input { version, layers, original_blend_profile } = serde_json::from_str(text).map_err(Error::Json)?; + if version != VERSION { + return Ok(None); + } + let stack = Self { layers, original_blend_profile }; + stack.validate()?; + Ok(Some(stack)) + } + + /// Validate and serialize version 1. Unicode layer names are escaped to keep the EXR + /// header ASCII-safe. + pub fn to_attribute(&self) -> Result { + self.validate()?; + let json = + serde_json::to_string(&Output { version: VERSION, layers: &self.layers, original_blend_profile: self.original_blend_profile.as_deref() }) + .map_err(Error::Json)?; + if json.len() > MAX_ATTRIBUTE_BYTES { + return Err(Error::Limit("attribute is too large")); + } + let mut text = String::with_capacity(json.len()); + for c in json.chars() { + if c.is_ascii() { + text.push(c); + } else { + for unit in c.encode_utf16(&mut [0; 2]) { + write!(text, "\\u{unit:04x}").map_err(|_| Error::Limit("could not encode attribute text"))?; + } + } + if text.len() > MAX_ATTRIBUTE_BYTES { + return Err(Error::Limit("attribute is too large")); + } + } + Ok(text) + } + + /// Check the manifest's intrinsic constraints. Consumers check its pixel references + /// against the file headers before decoding. + pub fn validate(&self) -> Result<(), Error> { + if self.layers.len() > MAX_LAYERS { + return Err(Error::Limit("too many layers")); + } + if self.original_blend_profile.as_deref().is_some_and(|profile| !valid_profile(profile)) { + return Err(Error::Malformed("invalid original RGB blend profile")); + } + let mut text_bytes = self.original_blend_profile.as_ref().map_or(0, String::len); + let mut by_id = HashMap::with_capacity(self.layers.len()); + for layer in &self.layers { + if by_id.insert(layer.id, layer).is_some() { + return Err(Error::Malformed("duplicate layer ID")); + } + if layer.name.len() > 4096 { + return Err(Error::Limit("layer name is too large")); + } + if !valid_label(&layer.blend) { + return Err(Error::Malformed("invalid blend mode identifier")); + } + if !(0.0..=1.0).contains(&layer.opacity) || !(0.0..=1.0).contains(&layer.fill_opacity) { + return Err(Error::Malformed("opacity and fill opacity must be between zero and one")); + } + text_bytes = text_bytes.saturating_add(layer.name.len()).saturating_add(layer.blend.len()); + if let LayerContent::Raster { pixels, .. } = &layer.content { + let (name, max) = match pixels { + PixelRef::Part { name } => (name, 255), + PixelRef::ChannelGroup { prefix, .. } => (prefix, 253), + }; + if name.is_empty() || name.chars().count() > max || name.chars().any(|c| c.is_control() || u32::from(c) > 255) { + return Err(Error::Malformed("invalid EXR part or channel group name")); + } + text_bytes = text_bytes.saturating_add(name.len()); + } + if text_bytes > MAX_ATTRIBUTE_BYTES { + return Err(Error::Limit("attribute is too large")); + } + } + for layer in &self.layers { + let mut at = layer; + let mut depth = 0; + while let Some(parent) = at.parent { + let ancestor = by_id.get(&parent).ok_or(Error::Malformed("unknown parent layer"))?; + if ancestor.content != LayerContent::Group { + return Err(Error::Malformed("a parent layer must be a group")); + } + if ancestor.id == layer.id { + return Err(Error::Malformed("cyclic layer hierarchy")); + } + depth += 1; + if depth > MAX_ANCESTORS { + return Err(Error::Limit("layer hierarchy is too deep")); + } + at = ancestor; + } + } + Ok(()) + } +} + +fn valid_label(label: &str) -> bool { + !label.trim().is_empty() && label.len() <= 128 && label.bytes().all(|b| b == b' ' || b.is_ascii_graphic()) +} + +fn valid_profile(profile: &str) -> bool { + if let Some(encoded) = profile.strip_prefix("icc:") { + if encoded.is_empty() || encoded.len() > MAX_ATTRIBUTE_BYTES || !encoded.len().is_multiple_of(4) { + return false; + } + let data = encoded.trim_end_matches('='); + !data.is_empty() && encoded.len() - data.len() <= 2 && data.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/')) + } else { + valid_label(profile) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn stack() -> LayerStack { + LayerStack { + layers: vec![ + Layer { + id: u64::MAX, + name: "東京 🎞".into(), + parent: Some(8), + visible: false, + blend: "multiply".into(), + opacity: 0.4, + fill_opacity: 0.5, + clipped: true, + content: LayerContent::Raster { pixels: PixelRef::Part { name: "Layer".into() }, sampling: PixelSampling::Baked }, + }, + Layer { + id: 8, + name: "Group".into(), + parent: None, + visible: true, + blend: "passThrough".into(), + opacity: 1.0, + fill_opacity: 1.0, + clipped: false, + content: LayerContent::Group, + }, + ], + original_blend_profile: Some("icc:AAE=".into()), + } + } + + #[test] + fn unicode_and_compositing_fields_round_trip_through_an_ascii_attribute() { + let stack = stack(); + let encoded = stack.to_attribute().unwrap(); + assert!(encoded.is_ascii()); + assert_eq!(LayerStack::parse(&encoded).unwrap(), Some(stack)); + } + + #[test] + fn supports_flat_image_fallback_for_unknown_versions_and_rejects_bad_v1() { + assert!(LayerStack::parse(r#"{"version":2,"layout":{"different":true}}"#).unwrap().is_none()); + for text in [ + r#"{"version":1,"layers":[],"unexpected":null}"#, + r#"{"version":1,"version":2,"layers":[]}"#, + r#"{"version":1,"layers":[],"originalBlendProfile":"icc:abc?"}"#, + r#"{"version":"1","layers":[]}"#, + ] { + assert!(LayerStack::parse(text).is_err(), "{text}"); + } + assert!(matches!(LayerStack::parse(&" ".repeat(MAX_ATTRIBUTE_BYTES + 1)), Err(Error::Limit(_)))); + } + + #[test] + fn rejects_ambiguous_identity_invalid_opacity_and_bad_hierarchy() { + let mut s = stack(); + s.layers[0].id = 8; + assert!(s.to_attribute().is_err()); + let mut s = stack(); + s.layers[0].fill_opacity = f32::NAN; + assert!(s.to_attribute().is_err()); + let mut s = stack(); + s.layers[1].parent = Some(8); + assert!(s.to_attribute().is_err()); + let mut s = stack(); + s.layers[1].parent = Some(u64::MAX); + assert!(s.to_attribute().is_err()); + let mut s = stack(); + s.layers[0].parent = Some(9); + assert!(s.to_attribute().is_err()); + } +} diff --git a/crates/exr/src/lib.rs b/crates/exr/src/lib.rs index 9ff66f95d3..22fd0dea0d 100644 --- a/crates/exr/src/lib.rs +++ b/crates/exr/src/lib.rs @@ -9,6 +9,7 @@ //! and alpha. //! - [`cryptomatte`]: Cryptomatte (specification 1.2) IDs, metadata keys, manifests and rank //! channel names. +//! - [`layer_stack`]: optional layer hierarchy and compositing metadata for editable EXR exchange. //! //! Those take names and attribute text and depend on no decoder. With the `decode` feature: //! @@ -18,6 +19,7 @@ //! - [`seek`]: any channels, display rows and reduced resolution of a file's flat parts, read from //! a seekable source and delivered band by band (or collected into planes). //! - [`stream`]: one flat scan-line part read block by block, for pictures larger than memory. +//! - [`write`]: write flat scan-line parts from a row callback to a seekable destination. //! - [`cryptomatte_samples`]: a file's Cryptomatte layers and their per-pixel (ID, coverage) ranks. /// Scanline OpenEXR writer using a caller-supplied linearization table. @@ -39,9 +41,14 @@ pub mod deep; mod deep_tests; #[cfg(feature = "decode")] mod dwa_guard; +pub mod layer_stack; #[cfg(feature = "decode")] pub mod seek; #[cfg(all(test, feature = "decode"))] mod seek_tests; #[cfg(feature = "decode")] pub mod stream; +#[cfg(feature = "decode")] +pub mod write; +#[cfg(all(test, feature = "decode"))] +mod write_tests; diff --git a/crates/exr/src/seek.rs b/crates/exr/src/seek.rs index 03f0fa506b..4b18bf8809 100644 --- a/crates/exr/src/seek.rs +++ b/crates/exr/src/seek.rs @@ -293,6 +293,12 @@ impl Index { self.display } + /// Stored RGB primaries and white point (red, green, blue, white in CIE xy). + pub fn chromaticities(&self) -> Option<[[f32; 2]; 4]> { + let c = self.meta.headers.first()?.shared_attributes.chromaticities.as_ref()?; + Some([c.red, c.green, c.blue, c.white].map(|v| [v.0, v.1])) + } + /// The chunks of part `part`'s full-resolution level, in offset-table order (none for a deep /// part or a part that doesn't exist): where each lies in the file and which pixels of the /// part's data window it holds. For diagnostics and tests; [`read_bands`] picks the chunks a @@ -606,11 +612,14 @@ pub struct Request<'a> { /// them. A channel may be named more than once (each slot gets its own bands). A channel of a /// deep part is refused. pub channels: &'a [(usize, usize)], + /// Use this part's data window as the output grid, keeping samples beyond the display + /// window. Every requested channel must belong to this part. Default: the display window. + pub data_window: Option, /// The value of each requested channel (same order) where the file has no samples; missing /// entries count as 0. Only [`read_planes`] uses it ([`read_bands`] delivers samples only). pub fill: &'a [f32], - /// The rows to read, counted from the display window's top row (0, whatever the display - /// window's absolute position), at full resolution; `None`: all. + /// The rows to read, counted from the output window's top row, at full resolution. + /// `None`: all rows. pub rows: Option>, /// Every `2^level`-th row and column of the display window (0: full resolution, at most 16). pub level: u32, @@ -644,7 +653,7 @@ impl<'a> Request<'a> { /// Every row of `channels` at full resolution, fill 0, up to `max_bytes` of samples, with as /// many decoding threads as the machine runs at once. pub fn new(channels: &'a [(usize, usize)], max_bytes: usize) -> Request<'a> { - Request { channels, fill: &[], rows: None, level: 0, max_bytes, workers: None, max_block_bytes: None, groups: &[] } + Request { channels, data_window: None, fill: &[], rows: None, level: 0, max_bytes, workers: None, max_block_bytes: None, groups: &[] } } } @@ -657,7 +666,7 @@ pub fn level_size((width, height): (usize, usize), level: u32) -> (usize, usize) /// A rectangle of rows of one requested channel, or of a group of them ([`Request::groups`]), /// decoded: `samples` holds `height` rows of `width` pixels, row by row, each pixel /// `values_per_pixel` values in slot order. `x` and `y` are in the output grid, counted from the -/// display window's top-left corner (0, 0, not its absolute position): display-window pixels at +/// selected window's top-left corner (0, 0, whatever its absolute position): window pixels at /// level 0, every `2^level`-th pixel above. #[derive(Debug, Clone, PartialEq)] pub struct Band { @@ -761,6 +770,7 @@ struct Geometry<'a> { size: (usize, usize), out: (usize, usize), stride: i64, + in_data_window: bool, /// The display rows read. rows: Range, /// Each part's channel → the request slots that name it. @@ -771,6 +781,10 @@ struct Geometry<'a> { } impl Geometry<'_> { + fn offset(&self, part: &PartLayout) -> (i64, i64) { + if self.in_data_window { (0, 0) } else { part.offset } + } + /// A display row is read: in the rows, on the level's grid. fn wanted(&self, row: i64) -> bool { row >= self.rows.start && row < self.rows.end && row.rem_euclid(self.stride) == 0 @@ -810,6 +824,7 @@ struct Plan { size: (usize, usize), out: (usize, usize), stride: i64, + in_data_window: bool, rows: Range, /// The chunks to read, in file order. jobs: Vec, @@ -821,7 +836,26 @@ struct Plan { impl Plan { fn geometry(&self) -> Geometry<'_> { - Geometry { size: self.size, out: self.out, stride: self.stride, rows: self.rows.clone(), slots: &self.slots, units: &self.units } + Geometry { + size: self.size, + out: self.out, + stride: self.stride, + in_data_window: self.in_data_window, + rows: self.rows.clone(), + slots: &self.slots, + units: &self.units, + } + } +} + +fn request_window(index: &Index, request: &Request) -> Result { + if let Some(part) = request.data_window { + if request.channels.iter().any(|(p, _)| *p != part) { + return Err(malformed("every channel in a data-window request must belong to that part")); + } + index.parts.get(part).map(|p| p.data_window).ok_or_else(|| malformed("no such data window part")) + } else { + Ok(index.display) } } @@ -830,7 +864,9 @@ impl Plan { fn plan(index: &Index, request: &Request) -> Result { let level = request.level.min(16); let stride = 1i64 << level; - let (w, h) = (index.display.width as usize, index.display.height as usize); + let window = request_window(index, request)?; + let (w, h) = (window.width as usize, window.height as usize); + let in_data_window = request.data_window.is_some(); let out = level_size((w, h), level); // Per part and channel: the request slots that name it. let mut slots: Vec>> = index.parts.iter().map(|p| vec![Vec::new(); p.channels.len()]).collect(); @@ -872,7 +908,7 @@ fn plan(index: &Index, request: &Request) -> Result { // (both ends inside the display window, so an empty or reversed range at either end of i64 // stays empty instead of overflowing when aligned to the level's grid) let rows = rows.start.clamp(0, h as i64)..rows.end.clamp(0, h as i64); - let geometry = Geometry { size: (w, h), out, stride, rows: rows.clone(), slots: &slots, units: &units }; + let geometry = Geometry { size: (w, h), out, stride, in_data_window, rows: rows.clone(), slots: &slots, units: &units }; // What the request delivers: the rows read, at the level, of every requested channel. let need = plane_bytes((out.0, geometry.rows_read()), request.channels.len()); if need > request.max_bytes { @@ -888,7 +924,7 @@ fn plan(index: &Index, request: &Request) -> Result { continue; } for c in &part.chunks { - let top = (c.y as i64).saturating_add(part.offset.1); + let top = (c.y as i64).saturating_add(geometry.offset(part).1); if !geometry.any_wanted(top, top.saturating_add(c.rows as i64)) { continue; } @@ -914,7 +950,7 @@ fn plan(index: &Index, request: &Request) -> Result { // (no more threads than chunks can be in flight: two pieces) let workers = request.workers.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, usize::from)).min(jobs.len()).min(2 * PIECE_CHUNKS); - Ok(Plan { slots, size: (w, h), out, stride, rows, jobs, workers, units }) + Ok(Plan { slots, size: (w, h), out, stride, in_data_window, rows, jobs, workers, units }) } impl Index { @@ -1188,7 +1224,8 @@ fn next_result(results: &Receiver<(usize, Decoded)>, cancel: &dyn Fn() -> bool) /// is [`Error::OutOfMemory`], not an abort), so the cost is known before the first chunk is /// read. pub fn read_planes(source: &mut R, index: &Index, request: &Request, cancel: &dyn Fn() -> bool) -> Result { - let (w, h) = (index.display.width as usize, index.display.height as usize); + let window = request_window(index, request)?; + let (w, h) = (window.width as usize, window.height as usize); let (ow, oh) = level_size((w, h), request.level.min(16)); let n = ow.checked_mul(oh).ok_or_else(|| Error::LimitExceeded("display window".into()))?; let need = plane_bytes((ow, oh), request.channels.len()); @@ -1451,12 +1488,13 @@ fn chunk_bands(index: &Index, pi: usize, expected: &ChunkRef, buf: &[u8], g: &Ge let slots = g.slots.get(pi).map_or(&[][..], Vec::as_slice); let lines = block.index.pixel_size.1; let ((lw, lh), (w, h)) = (part.size, g.size); + let (offset_x, offset_y) = g.offset(part); let (ow, _) = g.out; // The output rows of the block: its data-window rows that land in the display window on a // wanted row. They are consecutive in the output grid (wanted rows are every stride-th). let (by, bh) = (block.index.pixel_position.1, block.index.pixel_size.1); let out_rows: Vec = (by..by.saturating_add(bh)) - .filter_map(|y| usize::try_from(y as i64 + part.offset.1).ok()) + .filter_map(|y| usize::try_from(y as i64 + offset_y).ok()) .filter(|ty| *ty < h && g.wanted(*ty as i64)) .map(|ty| ty / g.stride as usize) .collect(); @@ -1477,11 +1515,11 @@ fn chunk_bands(index: &Index, pi: usize, expected: &ChunkRef, buf: &[u8], g: &Ge if y >= lh || x0.checked_add(count).is_none_or(|end| end > lw) { continue; } - let Some(ty) = usize::try_from(y as i64 + part.offset.1).ok().filter(|ty| *ty < h) else { continue }; + let Some(ty) = usize::try_from(y as i64 + offset_y).ok().filter(|ty| *ty < h) else { continue }; if !g.wanted(ty as i64) { continue; } - let tx0 = x0 as i64 + part.offset.0; + let tx0 = x0 as i64 + offset_x; let skip = usize::try_from(-tx0).unwrap_or(0).min(count); let tx = usize::try_from(tx0.max(0)).unwrap_or(usize::MAX); let take = (count - skip).min(w.saturating_sub(tx)); diff --git a/crates/exr/src/seek_tests.rs b/crates/exr/src/seek_tests.rs index 0104922351..328e424e0a 100644 --- a/crates/exr/src/seek_tests.rs +++ b/crates/exr/src/seek_tests.rs @@ -89,6 +89,25 @@ fn only_the_requested_channels_are_returned_in_the_requested_order() { assert_eq!(read.planes, [whole[3].clone(), whole[0].clone()]); } +#[test] +fn reading_in_a_parts_data_window_keeps_off_display_tiles() { + let bytes = file( + vec![ + layer(Some("beauty"), (0, 0), (8, 6), &["R"], false, Compression::ZIP1), + layer(Some("paint"), (-2, -3), (9, 7), &["R"], true, Compression::ZIP1), + ], + (8, 6), + ); + let index = indexed(&bytes); + let request = Request { data_window: Some(1), ..Request::new(&[(1, 0)], usize::MAX) }; + let output = read_planes(&mut Cursor::new(&bytes), &index, &request, &never).unwrap(); + assert_eq!((output.width, output.height), (9, 7)); + assert_eq!(output.stats.chunks[0], 0); + assert_eq!(output.planes[0], (0..9 * 7).map(|i| value(i, 0)).collect::>()); + let wrong_part = Request { data_window: Some(1), ..Request::new(&[(0, 0)], usize::MAX) }; + assert!(index.estimate(&wrong_part).is_err()); +} + #[test] fn a_part_with_no_requested_channel_is_not_read() { let bytes = file( diff --git a/crates/exr/src/write.rs b/crates/exr/src/write.rs new file mode 100644 index 0000000000..e26a02405d --- /dev/null +++ b/crates/exr/src/write.rs @@ -0,0 +1,633 @@ +//! Incremental flat OpenEXR output (feature `decode`). +//! +//! [`write_scanlines`] asks for one typed channel row at a time. [`write_tiles`] asks for one +//! tile at a time. Both buffer a single compression block, with sample and codec scratch space, +//! metadata and one offset per chunk. + +use std::collections::HashSet; +use std::io::{Seek, Write}; +use std::ops::Range; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +use exr::block::writer::ChunksWriter; +use exr::block::{BlockIndex, UncompressedBlock, enumerate_ordered_header_block_indices}; +use exr::math::{RoundingMode, Vec2}; +use exr::meta::attribute::{ + AttributeValue, ChannelDescription, Chromaticities, IntegerBounds, LevelMode, LineOrder, SampleType as ExrSample, Text, TileDescription, +}; +use exr::meta::{BlockDescription, Headers, header::Header}; + +use crate::decode::{Compression, Error, Result, SampleType, Window, f16, to_exr_compression}; + +const MAX_PARTS: usize = 1024; +const MAX_CHANNELS: usize = 16_384; +const MAX_CHUNKS: usize = 1 << 20; +const MAX_BLOCK_BYTES: usize = 64 << 20; +const MAX_NAME_BYTES: usize = 255; +const MAX_HEADER_BYTES: usize = 8 << 20; +const MAX_TEXT_ATTRIBUTES: usize = 16_384; + +/// Name and stored sample type of a full-resolution channel. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Channel<'a> { + pub name: &'a str, + pub sample: SampleType, +} + +/// The window, channels and encoding of one flat part. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Part<'a> { + /// Required and unique in a multipart file. Optional in a single-part file. + pub name: Option<&'a str>, + pub data_window: Window, + pub channels: &'a [Channel<'a>], + /// Per-part compression. + pub compression: Compression, +} + +/// One flat tiled part with a single resolution level. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TilePart<'a> { + pub part: Part<'a>, + pub tile_width: u32, + pub tile_height: u32, +} + +/// Names and values of the `string` attributes of one part. +pub type TextAttributes<'a> = &'a [(&'a str, &'a str)]; + +/// Optional file and part attributes. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Metadata<'a> { + /// CIE xy for red, green, blue and white, shared by every part. + pub chromaticities: Option<[[f32; 2]; 4]>, + /// Text attributes by input part index. An empty slice supplies no attributes. The file + /// accepts at most 16,384 text attributes and 8 MiB of estimated headers. + pub text_attributes: &'a [TextAttributes<'a>], +} + +/// A buffer to fill in the channel's stored type. Tiles use a contiguous, row-major channel plane. +#[derive(Debug)] +pub enum RowSamples<'a> { + F16(&'a mut [f16]), + F32(&'a mut [f32]), + U32(&'a mut [u32]), +} + +impl RowSamples<'_> { + pub fn len(&self) -> usize { + match self { + Self::F16(row) => row.len(), + Self::F32(row) => row.len(), + Self::U32(row) => row.len(), + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + fn reborrow(&mut self) -> RowSamples<'_> { + match self { + Self::F16(row) => RowSamples::F16(row), + Self::F32(row) => RowSamples::F32(row), + Self::U32(row) => RowSamples::U32(row), + } + } + + fn clear(&mut self) { + match self { + Self::F16(row) => row.fill(f16::ZERO), + Self::F32(row) => row.fill(0.0), + Self::U32(row) => row.fill(0), + } + } + + fn append_to(&self, data: &mut Vec) { + match self { + Self::F16(row) => row.iter().for_each(|sample| data.extend_from_slice(&sample.to_bits().to_ne_bytes())), + Self::F32(row) => row.iter().for_each(|sample| data.extend_from_slice(&sample.to_ne_bytes())), + Self::U32(row) => row.iter().for_each(|sample| data.extend_from_slice(&sample.to_ne_bytes())), + } + } + + fn copy_range_to(&self, range: Range, data: &mut [u8]) -> Result<()> { + fn copy(samples: &[T], range: Range, data: &mut [u8], bytes: impl Fn(&T) -> [u8; N]) -> Result<()> { + let samples = samples.get(range).ok_or_else(|| encode("invalid tile sample range"))?; + let (destinations, remainder) = data.as_chunks_mut::(); + if !remainder.is_empty() || destinations.len() != samples.len() { + return Err(encode("invalid tile channel byte length")); + } + for (sample, dest) in samples.iter().zip(destinations) { + *dest = bytes(sample); + } + Ok(()) + } + match self { + Self::F16(samples) => copy(samples, range, data, |sample| sample.to_bits().to_ne_bytes()), + Self::F32(samples) => copy(samples, range, data, |sample| sample.to_ne_bytes()), + Self::U32(samples) => copy(samples, range, data, |sample| sample.to_ne_bytes()), + } + } +} + +/// Writes one or more flat scan-line parts with a common `display_window`. +/// +/// `fill_row(part, row, channel, samples)` fills the given buffer and returns the number of +/// samples supplied. `part` and `channel` are indices into the supplied descriptors. Parts +/// follow input order and rows increase from `0` at each part's data-window top. Within a row, +/// channels are requested in file name order. A callback error stops writing and is returned. +/// +/// Pass a fresh seekable output positioned at byte zero. The caller owns buffering, truncation +/// and cleanup of partial output after an I/O or callback error. Invalid descriptors are rejected +/// before output begins. Maximums are 1,024 parts, 16,384 channels across all parts, 1,048,576 +/// chunks across all parts and 64 MiB of uncompressed samples per chunk. +pub fn write_scanlines( + out: &mut W, + display_window: Window, + parts: &[Part<'_>], + fill_row: impl FnMut(usize, usize, usize, RowSamples<'_>) -> Result, +) -> Result<()> { + write_scanlines_with_metadata(out, display_window, parts, &Metadata::default(), fill_row) +} + +/// [`write_scanlines`] with optional file and part attributes. +pub fn write_scanlines_with_metadata( + out: &mut W, + display_window: Window, + parts: &[Part<'_>], + metadata: &Metadata<'_>, + mut fill_row: impl FnMut(usize, usize, usize, RowSamples<'_>) -> Result, +) -> Result<()> { + let (headers, channel_orders) = prepare_headers(display_window, parts.iter().map(|&part| (part, Storage::ScanLines)), metadata)?; + let mut rows = SampleBuffers::new(&headers, |header| header.layer_size.0)?; + write_blocks(out, headers, |index, header| { + let order = channel_orders.get(index.layer).ok_or_else(|| encode("invalid scan-line block part"))?; + fill_block(index, header, order, &mut rows, &mut fill_row) + }) +} + +/// Writes one or more flat tiled parts with a common display window and one resolution level. +/// +/// `fill_tile(part, window, writer)` is called once per tile and supplies each channel once +/// through [`TileWriter::fill_channel`]. `part` is the input part index. `window` gives the +/// tile's absolute coordinates and its actual size, clipped to its part's data window at edges. +/// Parts follow input order and tiles are requested left to right, then top to bottom. +/// The output and block limits are as for [`write_scanlines`], with the uncompressed block +/// limit applied to the nominal tile dimensions. +pub fn write_tiles( + out: &mut W, + display_window: Window, + parts: &[TilePart<'_>], + metadata: &Metadata<'_>, + mut fill_tile: impl FnMut(usize, Window, &mut TileWriter<'_>) -> Result<()>, +) -> Result<()> { + let layouts = parts.iter().map(|part| (part.part, Storage::Tiles(part.tile_width, part.tile_height))); + let (headers, channel_orders) = prepare_headers(display_window, layouts, metadata)?; + let mut planes = SampleBuffers::new(&headers, |header| { + let Vec2(w, h) = header.max_block_pixel_size(); + w.min(header.layer_size.0).saturating_mul(h.min(header.layer_size.1)) + })?; + let layouts: Vec<_> = headers.iter().zip(&channel_orders).map(|(header, order)| tile_layout(header, order)).collect::>()?; + let mut supplied = vec![false; layouts.iter().map(Vec::len).max().unwrap_or_default()]; + write_blocks(out, headers, |index, header| { + let layout = layouts.get(index.layer).ok_or_else(|| encode("invalid tile part"))?; + let supplied = supplied.get_mut(..layout.len()).ok_or_else(|| encode("invalid tile channel count"))?; + supplied.fill(false); + let window = tile_window(index, header)?; + let bytes = block_bytes(index, header)?; + let mut data = block_buffer(bytes)?; + data.resize(bytes, 0); + let Vec2(width, height) = index.pixel_size; + let mut writer = + TileWriter { width, height, bytes_per_pixel: header.channels.bytes_per_pixel, layout, supplied, data: &mut data, planes: &mut planes }; + fill_tile(index.layer, window, &mut writer)?; + if let Some(channel) = writer.supplied.iter().position(|&supplied| !supplied) { + return Err(encode(format_args!("part {}, tile at ({}, {}): missing channel {channel}", index.layer, window.x, window.y))); + } + Ok(data) + }) +} + +/// Receives the channel planes of one tile in the caller's channel order. +pub struct TileWriter<'a> { + width: usize, + height: usize, + bytes_per_pixel: usize, + layout: &'a [TileChannel], + supplied: &'a mut [bool], + data: &'a mut [u8], + planes: &'a mut SampleBuffers, +} + +impl TileWriter<'_> { + /// Fills a typed, row-major channel plane containing one sample per pixel. The callback + /// returns the number of samples it supplied. + pub fn fill_channel(&mut self, channel: usize, fill: impl FnOnce(RowSamples<'_>) -> Result) -> Result<()> { + let layout = self.layout.get(channel).ok_or_else(|| encode(format_args!("unknown tile channel {channel}")))?; + let supplied = self.supplied.get_mut(channel).ok_or_else(|| encode("invalid tile channel bookkeeping"))?; + if *supplied { + return Err(encode(format_args!("duplicate tile channel {channel}"))); + } + let len = self.width.checked_mul(self.height).ok_or_else(|| encode("tile sample count overflow"))?; + let mut plane = self.planes.get(layout.sample, len)?; + plane.clear(); + let count = fill(plane.reborrow())?; + if count != len { + return Err(encode(format_args!("tile channel {channel}: expected {len} samples, got {count}"))); + } + let stride = self.width * self.bytes_per_pixel; + let start = self.width * layout.offset; + let end = start + self.width * layout.sample.bytes_per_sample(); + for (y, row) in self.data.chunks_exact_mut(stride).enumerate() { + let dest = row.get_mut(start..end).ok_or_else(|| encode("invalid tile channel byte range"))?; + plane.copy_range_to(y * self.width..(y + 1) * self.width, dest)?; + } + *supplied = true; + Ok(()) + } +} + +#[derive(Clone, Copy)] +struct TileChannel { + sample: ExrSample, + // Width-independent byte count of the channels preceding this one in file order. + offset: usize, +} + +fn tile_layout(header: &Header, order: &[usize]) -> Result> { + let mut channels = vec![TileChannel { sample: ExrSample::F16, offset: 0 }; order.len()]; + let mut offset = 0; + for (&input, channel) in order.iter().zip(&header.channels.list) { + let entry = channels.get_mut(input).ok_or_else(|| encode("invalid tile channel order"))?; + *entry = TileChannel { sample: channel.sample_type, offset }; + offset += channel.sample_type.bytes_per_sample(); + } + Ok(channels) +} + +fn tile_window(index: BlockIndex, header: &Header) -> Result { + let position = |start: i32, offset: usize| { + i32::try_from(offset).ok().and_then(|offset| start.checked_add(offset)).ok_or_else(|| encode("tile coordinate overflow")) + }; + let origin = header.own_attributes.layer_position; + Ok(Window { + x: position(origin.0, index.pixel_position.0)?, + y: position(origin.1, index.pixel_position.1)?, + width: u32::try_from(index.pixel_size.0).map_err(encode)?, + height: u32::try_from(index.pixel_size.1).map_err(encode)?, + }) +} + +fn write_blocks( + out: &mut W, + headers: Headers, + mut read_block: impl FnMut(BlockIndex, &Header) -> Result>, +) -> Result<()> { + if out.stream_position().map_err(encode)? != 0 { + return Err(encode("output must start at byte zero")); + } + let mut block_error = None; + let written = catch_unwind(AssertUnwindSafe(|| { + exr::block::write(&mut *out, headers, true, |meta, writer| { + for (chunk_index, index) in enumerate_ordered_header_block_indices(&meta.headers) { + let data = + meta.headers.get(index.layer).ok_or_else(|| encode("invalid block part")).and_then(|header| read_block(index, header)).map_err( + |error| { + block_error = Some(error); + exr::error::Error::Aborted + }, + )?; + let chunk = UncompressedBlock { index, data }.compress_to_chunk(&meta.headers)?; + writer.write_chunk(chunk_index, chunk)?; + } + Ok(()) + }) + })); + if let Some(error) = block_error { + return Err(error); + } + written.map_err(|_| encode("block writer panicked"))?.map_err(encode)?; + out.flush().map_err(encode) +} + +#[derive(Clone, Copy)] +enum Storage { + ScanLines, + Tiles(u32, u32), +} + +impl Storage { + fn describe(self, size: Vec2, compression: exr::compression::Compression) -> Result<(BlockDescription, Vec2, usize)> { + match self { + Self::ScanLines => { + let rows = compression.scan_lines_per_block(); + Ok((BlockDescription::ScanLines, Vec2(size.0, rows), size.1.div_ceil(rows))) + } + Self::Tiles(width, height) => { + let dimension = |n| usize::try_from(n).ok().filter(|&n| n > 0 && n <= MAX_BLOCK_BYTES); + let (w, h) = dimension(width).zip(dimension(height)).ok_or_else(|| encode("invalid tile dimensions"))?; + let chunks = size.0.div_ceil(w).checked_mul(size.1.div_ceil(h)).ok_or_else(|| encode("tile count overflow"))?; + let tile_size = Vec2(w, h); + let tiles = TileDescription { tile_size, level_mode: LevelMode::Singular, rounding_mode: RoundingMode::Down }; + Ok((BlockDescription::Tiles(tiles), tile_size, chunks)) + } + } + } +} + +fn prepare_headers<'a>( + display_window: Window, + parts: impl ExactSizeIterator, Storage)>, + metadata: &Metadata<'_>, +) -> Result<(Headers, Vec>)> { + let part_count = parts.len(); + if part_count == 0 || part_count > MAX_PARTS { + return Err(encode("expected 1 to 1,024 parts")); + } + if !metadata.text_attributes.is_empty() && metadata.text_attributes.len() != part_count { + return Err(encode("text attributes must have one entry per part")); + } + if metadata.text_attributes.iter().map(|attributes| attributes.len()).fold(0usize, usize::saturating_add) > MAX_TEXT_ATTRIBUTES { + return Err(encode(format_args!("more than {MAX_TEXT_ATTRIBUTES} text attributes"))); + } + let chromaticities = metadata.chromaticities.map(checked_chromaticities).transpose()?; + let display = window_bounds(display_window)?; + let mut headers = Headers::new(); + let mut channel_orders = Vec::with_capacity(part_count); + let mut part_names = HashSet::new(); + let (mut channel_count, mut chunk_count) = (0usize, 0usize); + let mut max_file_bytes = 16usize; // Magic, version and header-list terminator. + let mut header_bytes = 16usize; + for (index, (part, storage)) in parts.enumerate() { + let name = part.name.map(|name| checked_name(name, "part")).transpose()?; + if let Some(name) = &name { + if !part_names.insert(name.clone()) { + return Err(encode(format_args!("duplicate part name {name}"))); + } + } else if part_count > 1 { + return Err(encode(format_args!("multipart part {index} needs a name"))); + } + + let data = window_bounds(part.data_window)?; + let (width, height) = (data.size.0, data.size.1); + channel_count = channel_count.saturating_add(part.channels.len()); + if part.channels.is_empty() || channel_count > MAX_CHANNELS { + return Err(encode(format_args!("part {index} needs channels and the file supports up to {MAX_CHANNELS} channels"))); + } + + let compression = to_exr_compression(part.compression); + let (blocks, Vec2(block_width, block_height), chunks) = storage.describe(data.size, compression)?; + chunk_count = chunk_count.saturating_add(chunks); + if chunk_count > MAX_CHUNKS { + return Err(encode(format_args!("more than {MAX_CHUNKS} blocks"))); + } + + let mut channels = Vec::with_capacity(part.channels.len()); + for (channel_index, channel) in part.channels.iter().enumerate() { + let name = checked_name(channel.name, "channel")?; + let sample = match channel.sample { + SampleType::F16 => ExrSample::F16, + SampleType::F32 => ExrSample::F32, + SampleType::U32 => ExrSample::U32, + }; + channels.push((channel_index, ChannelDescription::named(name, sample))); + } + channels.sort_unstable_by(|(_, a), (_, b)| a.name.cmp(&b.name)); + if let Some([(_, a), _]) = channels.windows(2).find(|pair| matches!(pair, [(_, a), (_, b)] if a.name == b.name)) { + return Err(encode(format_args!("duplicate channel name {} in part {index}", a.name))); + } + + let bytes_per_pixel: usize = channels.iter().map(|(_, channel)| channel.sample_type.bytes_per_sample()).sum(); + let bounded_height = if matches!(storage, Storage::ScanLines) { block_height.min(height) } else { block_height }; + if block_width.saturating_mul(bounded_height).saturating_mul(bytes_per_pixel) > MAX_BLOCK_BYTES { + return Err(encode(format_args!("a block in part {index} exceeds {MAX_BLOCK_BYTES} uncompressed bytes"))); + } + // The codec uses usize for the nominal block size and output offsets. Allow space + // beyond raw samples for standard attributes, channel entries, and chunk prefixes/offsets. + if block_width.checked_mul(block_height).and_then(|n| n.checked_mul(bytes_per_pixel)).is_none() { + return Err(encode(format_args!("a block in part {index} exceeds the codec's addressable size"))); + } + let header_estimate = 1024 + channels.iter().map(|(_, channel)| channel.name.bytes().len() + 32).sum::(); + header_bytes = header_bytes.saturating_add(header_estimate); + let attributes = metadata.text_attributes.get(index).copied().unwrap_or_default(); + let extra_bytes = text_bytes(attributes, &mut header_bytes)?; + let overhead = header_estimate + extra_bytes + chunks * 32; + max_file_bytes = width + .checked_mul(height) + .and_then(|pixels| pixels.checked_mul(bytes_per_pixel)) + .and_then(|samples| samples.checked_add(overhead)) + .and_then(|part_bytes| max_file_bytes.checked_add(part_bytes)) + .ok_or_else(|| encode("file may exceed the codec's addressable size"))?; + + let (order, descriptions) = channels.into_iter().unzip(); + let mut header = Header::new(Text::from_slice_unchecked(b""), data.size, descriptions) + .with_display_window(display) + .with_position(data.position) + .with_encoding(compression, blocks, LineOrder::Increasing); + header.own_attributes.layer_name = name; + header.shared_attributes.chromaticities = chromaticities; + set_text_attributes(&mut header, attributes)?; + headers.push(header); + channel_orders.push(order); + } + Ok((headers, channel_orders)) +} + +fn checked_name(name: &str, kind: &str) -> Result { + // exr::Text stores one byte per character. Check the character count before allocating it. + if name.is_empty() || name.chars().take(MAX_NAME_BYTES + 1).count() > MAX_NAME_BYTES || name.bytes().any(|byte| byte == 0) { + return Err(encode(format_args!("invalid {kind} name: expected 1 to {MAX_NAME_BYTES} OpenEXR bytes without NUL"))); + } + Text::new_or_none(name).ok_or_else(|| encode(format_args!("invalid {kind} name: unsupported characters"))) +} + +fn checked_chromaticities(points: [[f32; 2]; 4]) -> Result { + if points.iter().flatten().any(|value| !value.is_finite()) { + return Err(encode("chromaticities must be finite")); + } + let [red, green, blue, white] = points.map(|[x, y]| Vec2(x, y)); + Ok(Chromaticities { red, green, blue, white }) +} + +fn text_bytes(attributes: TextAttributes<'_>, header_bytes: &mut usize) -> Result { + let start = *header_bytes; + if start > MAX_HEADER_BYTES { + return Err(encode("OpenEXR headers exceed 8 MiB")); + } + for &(key, value) in attributes { + *header_bytes = header_bytes.saturating_add(key.len()).saturating_add(value.len()).saturating_add(16); + if *header_bytes > MAX_HEADER_BYTES { + return Err(encode("OpenEXR headers exceed 8 MiB")); + } + } + Ok(*header_bytes - start) +} + +fn set_text_attributes(header: &mut Header, attributes: TextAttributes<'_>) -> Result<()> { + let mut seen = HashSet::new(); + for &(name, value) in attributes { + let key = checked_name(name, "attribute")?; + if !seen.insert(name) { + return Err(encode(format_args!("duplicate attribute {name}"))); + } + let value = Text::new_or_none(value).ok_or_else(|| encode(format_args!("invalid string attribute {name}: unsupported characters")))?; + if value.bytes().contains(&0) { + return Err(encode(format_args!("invalid string attribute {name}: contains NUL"))); + } + let attrs = &mut header.own_attributes; + let field = match name { + "owner" => &mut attrs.owner, + "comments" => &mut attrs.comments, + "capDate" => &mut attrs.capture_date, + "wrapmodes" => &mut attrs.wrap_mode_name, + "view" => &mut attrs.view_name, + "software" => &mut attrs.software_name, + "renderingTransform" => &mut attrs.rendering_transform_name, + "lookModTransform" => &mut attrs.look_modification_transform_name, + "channels" + | "compression" + | "dataWindow" + | "displayWindow" + | "lineOrder" + | "pixelAspectRatio" + | "screenWindowCenter" + | "screenWindowWidth" + | "name" + | "type" + | "version" + | "chunkCount" + | "tiles" + | "maxSamplesPerPixel" + | "chromaticities" + | "timeCode" + | "preview" + | "whiteLuminance" + | "adoptedNeutral" + | "xDensity" + | "utcOffset" + | "longitude" + | "latitude" + | "altitude" + | "focus" + | "expTime" + | "aperture" + | "isoSpeed" + | "envmap" + | "keyCode" + | "framesPerSecond" + | "multiView" + | "worldToCamera" + | "worldToNDC" + | "deepImageState" + | "originalDataWindow" + | "nearClipPlane" + | "farClipPlane" + | "horizontalFieldOfView" + | "verticalFieldOfView" => { + return Err(encode(format_args!("reserved attribute {name}"))); + } + _ => { + attrs.other.insert(key, AttributeValue::Text(value)); + continue; + } + }; + *field = Some(value); + } + Ok(()) +} + +fn window_bounds(window: Window) -> Result { + let axis = |position: i32, size: u32| { + // The codec works with inclusive and exclusive ends and negates the origin in i32. + let size = i32::try_from(size).ok().filter(|&size| size > 0)?; + position.checked_neg()?; + position.checked_add(size)?; + usize::try_from(size).ok() + }; + let size = axis(window.x, window.width).zip(axis(window.y, window.height)).ok_or_else(|| encode("invalid OpenEXR window dimensions"))?; + Ok(IntegerBounds::new((window.x, window.y), size)) +} + +struct SampleBuffers { + half: Vec, + float: Vec, + uint: Vec, +} + +impl SampleBuffers { + fn new(headers: &[Header], samples: impl Fn(&Header) -> usize) -> Result { + let mut lengths = (0, 0, 0); + for header in headers { + for channel in &header.channels.list { + let len = match channel.sample_type { + ExrSample::F16 => &mut lengths.0, + ExrSample::F32 => &mut lengths.1, + ExrSample::U32 => &mut lengths.2, + }; + *len = (*len).max(samples(header)); + } + } + fn zeroed(width: usize) -> Result> { + let mut samples = Vec::new(); + samples.try_reserve_exact(width).map_err(|_| encode("could not allocate sample buffer"))?; + samples.resize(width, T::default()); + Ok(samples) + } + Ok(Self { half: zeroed(lengths.0)?, float: zeroed(lengths.1)?, uint: zeroed(lengths.2)? }) + } + + fn get(&mut self, sample: ExrSample, width: usize) -> Result> { + match sample { + ExrSample::F16 => self.half.get_mut(..width).map(RowSamples::F16), + ExrSample::F32 => self.float.get_mut(..width).map(RowSamples::F32), + ExrSample::U32 => self.uint.get_mut(..width).map(RowSamples::U32), + } + .ok_or_else(|| encode("sample buffer has the wrong size")) + } +} + +fn fill_block( + index: BlockIndex, + header: &Header, + order: &[usize], + rows: &mut SampleBuffers, + fill_row: &mut impl FnMut(usize, usize, usize, RowSamples<'_>) -> Result, +) -> Result> { + let part = index.layer; + let Vec2(width, height) = index.pixel_size; + let mut data = block_buffer(block_bytes(index, header)?)?; + let first = index.pixel_position.1; + let end = first.checked_add(height).ok_or_else(|| encode("scan-line row index overflow"))?; + for row in first..end { + for (&channel, description) in order.iter().zip(&header.channels.list) { + let mut samples = rows.get(description.sample_type, width)?; + samples.clear(); + let count = fill_row(part, row, channel, samples.reborrow())?; + if count != width { + return Err(encode(format_args!("part {part}, channel {channel}, row {row}: expected {width} samples, got {count}"))); + } + samples.append_to(&mut data); + } + } + Ok(data) +} + +fn block_bytes(index: BlockIndex, header: &Header) -> Result { + let Vec2(width, height) = index.pixel_size; + width + .checked_mul(height) + .and_then(|pixels| pixels.checked_mul(header.channels.bytes_per_pixel)) + .filter(|&bytes| (1..=MAX_BLOCK_BYTES).contains(&bytes)) + .ok_or_else(|| encode("invalid block size")) +} + +fn block_buffer(bytes: usize) -> Result> { + let mut data = Vec::new(); + data.try_reserve_exact(bytes).map_err(|_| encode("could not allocate block buffer"))?; + Ok(data) +} + +fn encode(message: impl std::fmt::Display) -> Error { + Error::Encode(message.to_string()) +} diff --git a/crates/exr/src/write_tests.rs b/crates/exr/src/write_tests.rs new file mode 100644 index 0000000000..fe19a80ba7 --- /dev/null +++ b/crates/exr/src/write_tests.rs @@ -0,0 +1,344 @@ +use std::cell::Cell; +use std::io::{self, Cursor, Seek, SeekFrom, Write}; + +use crate::decode::{self, Compression, Error, Limits, SampleType, Samples, Window, f16}; +use crate::seek::{Index, Request, read_planes}; +use crate::write::{Channel, Metadata, Part, RowSamples, TilePart, TileWriter, write_scanlines, write_scanlines_with_metadata, write_tiles}; + +const WINDOW: Window = Window { x: -3, y: -5, width: 64, height: 35 }; +const HALF: Channel<'_> = Channel { name: "R", sample: SampleType::F16 }; +const FLOAT: Channel<'_> = Channel { name: "Z", sample: SampleType::F32 }; +const UINT: Channel<'_> = Channel { name: "ID", sample: SampleType::U32 }; + +fn half_value(row: usize, channel: usize, x: usize) -> f16 { + f16::from_f32((row * 8 + channel * 32 + x / 8) as f32 / 16.0) +} + +fn depth_value(row: usize, x: usize) -> f32 { + f32::from_bits(0x3f80_0001 + (row * 8 + x / 8) as u32) +} + +fn id_value(row: usize, x: usize) -> u32 { + u32::MAX - (row * 8 + x / 8) as u32 +} + +fn sample_row(_: usize, row: usize, channel: usize, mut samples: RowSamples<'_>) -> decode::Result { + match &mut samples { + RowSamples::F16(values) => values.iter_mut().enumerate().for_each(|(x, value)| *value = half_value(row, channel, x)), + RowSamples::F32(values) => values.iter_mut().enumerate().for_each(|(x, value)| *value = depth_value(row, x)), + RowSamples::U32(values) => values.iter_mut().enumerate().for_each(|(x, value)| *value = id_value(row, x)), + } + Ok(samples.len()) +} + +fn whole_plane(window: Window, sample: impl Fn(usize, usize) -> T) -> Vec { + (0..window.height as usize).flat_map(|row| (0..window.width as usize).map(move |x| (row, x))).map(|(row, x)| sample(row, x)).collect() +} + +fn fill_tile(part: TilePart<'_>, window: Window, tile: &mut TileWriter<'_>) -> decode::Result<()> { + let x0 = (window.x - part.part.data_window.x) as usize; + let y0 = (window.y - part.part.data_window.y) as usize; + let width = window.width as usize; + // Supply in reverse descriptor order to exercise channel placement independent of callback order. + for channel in (0..part.part.channels.len()).rev() { + tile.fill_channel(channel, |mut samples| { + let at = |i: usize| (y0 + i / width, x0 + i % width); + match &mut samples { + RowSamples::F16(values) => values.iter_mut().enumerate().for_each(|(i, value)| { + let (y, x) = at(i); + *value = half_value(y, channel, x); + }), + RowSamples::F32(values) => values.iter_mut().enumerate().for_each(|(i, value)| { + let (y, x) = at(i); + *value = depth_value(y, x); + }), + RowSamples::U32(values) => values.iter_mut().enumerate().for_each(|(i, value)| { + let (y, x) = at(i); + *value = id_value(y, x); + }), + } + Ok(samples.len()) + })?; + } + Ok(()) +} + +#[test] +fn tiled_lossless_round_trips_all_sample_types_and_clips_edge_tiles() { + for (compression, name) in [ + (Compression::None, "Uncompressed"), + (Compression::Rle, "RLE"), + (Compression::Zip1, "ZIP1"), + (Compression::Zip16, "ZIP16"), + (Compression::Piz, "PIZ"), + ] { + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT, HALF, UINT], compression }; + let tiled = TilePart { part, tile_width: 30, tile_height: 18 }; + let mut out = Cursor::new(Vec::new()); + let mut windows = Vec::new(); + write_tiles(&mut out, WINDOW, &[tiled], &Metadata::default(), |part, window, tile| { + assert_eq!(part, 0); + windows.push(window); + fill_tile(tiled, window, tile) + }) + .unwrap(); + assert_eq!(windows.len(), 6); + assert_eq!(windows[0], Window { width: 30, height: 18, ..WINDOW }); + assert_eq!(windows[5], Window { x: WINDOW.x + 60, y: WINDOW.y + 18, width: 4, height: 17 }); + + let decoded = decode::decode_part(out.get_ref(), 0, &|_| true, &Limits::default()).unwrap(); + assert!(decoded.info.tiled); + assert_eq!(decoded.info.compression, name); + assert_eq!(decoded.info.data_window, WINDOW); + assert_eq!(decoded.channel("Z").unwrap().samples, Samples::F32(whole_plane(WINDOW, depth_value))); + assert_eq!(decoded.channel("R").unwrap().samples, Samples::F16(whole_plane(WINDOW, |y, x| half_value(y, 1, x)))); + assert_eq!(decoded.channel("ID").unwrap().samples, Samples::U32(whole_plane(WINDOW, id_value))); + } +} + +#[test] +fn tiled_multipart_keeps_distinct_tile_sizes_and_metadata() { + let depth = Part { name: Some("Depth"), data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let beauty = Part { name: Some("Beauty"), data_window: WINDOW, channels: &[HALF], compression: Compression::Piz }; + let parts = [TilePart { part: depth, tile_width: 16, tile_height: 14 }, TilePart { part: beauty, tile_width: 31, tile_height: 20 }]; + let chromaticities = [[0.64, 0.33], [0.3, 0.6], [0.15, 0.06], [0.3127, 0.329]]; + let text = [&[("craftLayerStack", "{\"version\":1}"), ("comments", "Preview")][..], &[("passLabel", "Beauty")][..]]; + let metadata = Metadata { chromaticities: Some(chromaticities), text_attributes: &text }; + let mut out = Cursor::new(Vec::new()); + write_tiles(&mut out, WINDOW, &parts, &metadata, |part, window, tile| fill_tile(parts[part], window, tile)).unwrap(); + let mut source = Cursor::new(out.into_inner()); + let index = Index::build(&mut source, &Limits::default(), &|| false).unwrap(); + let info = index.parts(); + assert_eq!(info[0].name.as_deref(), Some("Depth")); + assert_eq!(info[1].name.as_deref(), Some("Beauty")); + assert!(info.iter().all(|part| part.tiled)); + assert_eq!(info[0].text("craftLayerStack"), Some("{\"version\":1}")); + assert_eq!(info[1].text("craftLayerStack"), None); + assert_eq!(info[1].text("passLabel"), Some("Beauty")); + let headers = exr::meta::MetaData::read_from_buffered(Cursor::new(source.get_ref()), true).unwrap().headers; + assert_eq!(headers[0].own_attributes.comments.as_ref().unwrap().to_string(), "Preview"); + for header in &headers { + let c = header.shared_attributes.chromaticities.unwrap(); + assert_eq!([[c.red.0, c.red.1], [c.green.0, c.green.1], [c.blue.0, c.blue.1], [c.white.0, c.white.1]], chromaticities); + } + let requested_row = 31; + let request = Request { rows: Some(requested_row..requested_row + 1), ..Request::new(&[(0, 0), (1, 0)], usize::MAX) }; + let read = read_planes(&mut source, &index, &request, &|| false).unwrap(); + assert_eq!(read.stats.chunks, [4, 3]); + let requested_row = requested_row as usize; + assert_eq!(read.planes[0], whole_plane(WINDOW, |y, x| if y == requested_row { depth_value(y, x) } else { 0.0 })); + assert_eq!(read.planes[1], whole_plane(WINDOW, |y, x| if y == requested_row { half_value(y, 0, x).to_f32() } else { 0.0 })); +} + +#[test] +fn scanline_metadata_round_trips_a_custom_string() { + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let text = [&[("cryptomatte/abc1234/name", "CryptoObject")][..]]; + let metadata = Metadata { text_attributes: &text, ..Metadata::default() }; + let mut out = Cursor::new(Vec::new()); + write_scanlines_with_metadata(&mut out, WINDOW, &[part], &metadata, sample_row).unwrap(); + let parts = decode::parts(out.get_ref(), &Limits::default()).unwrap(); + assert_eq!(parts[0].text("cryptomatte/abc1234/name"), Some("CryptoObject")); +} + +#[test] +fn invalid_tile_dimensions_and_metadata_fail_before_output() { + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let tiled = TilePart { part, tile_width: 16, tile_height: 16 }; + let no_metadata = Metadata::default(); + let duplicate = [&[("pass", "Z"), ("pass", "depth")][..]]; + let reserved = [&[("tiles", "unexpected")][..]]; + let invalid_chromaticities = Metadata { chromaticities: Some([[f32::NAN; 2]; 4]), ..no_metadata }; + for (part, metadata) in [ + (TilePart { tile_width: 0, ..tiled }, no_metadata), + (TilePart { tile_width: 16_384, tile_height: 16_384, ..tiled }, no_metadata), + (tiled, invalid_chromaticities), + (tiled, Metadata { text_attributes: &duplicate, ..no_metadata }), + (tiled, Metadata { text_attributes: &reserved, ..no_metadata }), + ] { + let mut out = Cursor::new(Vec::new()); + let result = write_tiles(&mut out, WINDOW, &[part], &metadata, |_, _, _| panic!("invalid descriptors reached callback")); + assert!(matches!(result, Err(Error::Encode(_))), "{result:?}"); + assert!(out.get_ref().is_empty()); + } +} + +#[test] +fn incomplete_tiles_are_rejected() { + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let tiled = TilePart { part, tile_width: 4, tile_height: 5 }; + let result = write_tiles(&mut Cursor::new(Vec::new()), WINDOW, &[tiled], &Metadata::default(), |_, _, _| Ok(())); + assert!(matches!(result, Err(Error::Encode(message)) if message.contains("missing channel 0"))); + + let short = write_tiles(&mut Cursor::new(Vec::new()), WINDOW, &[tiled], &Metadata::default(), |_, _, tile| { + tile.fill_channel(0, |plane| Ok(plane.len() - 1)) + }); + assert!(matches!(short, Err(Error::Encode(message)) if message.contains("expected 20 samples, got 19"))); + + let duplicate = write_tiles(&mut Cursor::new(Vec::new()), WINDOW, &[tiled], &Metadata::default(), |_, _, tile| { + tile.fill_channel(0, |plane| Ok(plane.len()))?; + tile.fill_channel(0, |plane| Ok(plane.len())) + }); + assert!(matches!(duplicate, Err(Error::Encode(message)) if message.contains("duplicate tile channel 0"))); +} + +#[test] +fn single_part_lossless_round_trips_all_sample_types() { + for (compression, name) in [ + (Compression::None, "Uncompressed"), + (Compression::Rle, "RLE"), + (Compression::Zip1, "ZIP1"), + (Compression::Zip16, "ZIP16"), + (Compression::Piz, "PIZ"), + ] { + let mut out = Cursor::new(Vec::new()); + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT, HALF, UINT], compression }; + write_scanlines(&mut out, WINDOW, &[part], sample_row).unwrap(); + let limits = Limits::default(); + let bytes = out.get_ref(); + assert_eq!(decode::parts(bytes, &limits).unwrap().len(), 1); + let decoded = decode::decode_part(bytes, 0, &|_| true, &limits).unwrap(); + assert_eq!(decoded.info.name, None); + assert_eq!(decoded.info.compression, name); + assert_eq!(decoded.info.data_window, WINDOW); + assert_eq!(decoded.channel("Z").unwrap().samples, Samples::F32(whole_plane(WINDOW, depth_value))); + assert_eq!(decoded.channel("R").unwrap().samples, Samples::F16(whole_plane(WINDOW, |row, x| half_value(row, 1, x)))); + assert_eq!(decoded.channel("ID").unwrap().samples, Samples::U32(whole_plane(WINDOW, id_value))); + } +} + +#[test] +fn lossy_encodings_preserve_integer_ids() { + for compression in [Compression::Pxr24, Compression::B44, Compression::B44a, Compression::Dwaa, Compression::Dwab] { + let mut out = Cursor::new(Vec::new()); + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT, HALF, UINT], compression }; + write_scanlines(&mut out, WINDOW, &[part], sample_row).unwrap(); + let decoded = decode::decode_part(out.get_ref(), 0, &|_| true, &Limits::default()).unwrap(); + assert_eq!(decoded.channel("ID").unwrap().samples, Samples::U32(whole_plane(WINDOW, id_value)), "{compression:?}"); + } +} + +#[test] +fn named_parts_round_trip_and_support_selective_reads() { + let beauty = [HALF, Channel { name: "G", ..HALF }, Channel { name: "B", ..HALF }, Channel { name: "A", ..HALF }]; + let depth_window = Window { x: WINDOW.x + 1, y: WINDOW.y + 2, width: WINDOW.width - 1, height: WINDOW.height - 2 }; + let parts = [ + Part { name: Some("Depth"), data_window: depth_window, channels: &[FLOAT], compression: Compression::Zip1 }, + Part { name: Some("Beauty"), data_window: WINDOW, channels: &beauty, compression: Compression::Zip16 }, + ]; + let mut out = Cursor::new(Vec::new()); + write_scanlines(&mut out, WINDOW, &parts, sample_row).unwrap(); + let limits = Limits::default(); + let mut source = Cursor::new(out.into_inner()); + let index = Index::build(&mut source, &limits, &|| false).unwrap(); + let headers = index.parts(); + assert_eq!(headers.iter().map(|part| part.name.as_deref().unwrap()).collect::>(), ["Depth", "Beauty"]); + assert_eq!(decode::pick_part(headers), Some(1)); + assert_eq!((&*headers[0].compression, &*headers[1].compression), ("ZIP1", "ZIP16")); + assert_eq!(headers[0].data_window, depth_window); + assert!(headers.iter().all(|part| part.display_window == WINDOW)); + let beauty = &headers[1].channels; + assert_eq!(beauty.iter().map(|channel| channel.name.as_str()).collect::>(), ["A", "B", "G", "R"]); + assert!(beauty.iter().all(|channel| channel.sample == SampleType::F16)); + assert_eq!(headers[0].channels[0].sample, SampleType::F32); + let depth = decode::decode_part(source.get_ref(), 0, &|_| true, &limits).unwrap(); + assert_eq!(depth.channel("Z").unwrap().samples, Samples::F32(whole_plane(depth_window, depth_value))); + + let row = 17; + let request = Request { rows: Some(row..row + 1), fill: &[-1.0, -2.0], ..Request::new(&[(1, 3), (0, 0)], usize::MAX) }; + let read = read_planes(&mut source, &index, &request, &|| false).unwrap(); + assert_eq!(read.stats.chunks, [1, 1]); + let row = row as usize; + for (plane, expected) in [ + (&read.planes[0], whole_plane(WINDOW, |y, x| if y == row { half_value(y, 0, x).to_f32() } else { -1.0 })), + (&read.planes[1], whole_plane(WINDOW, |y, x| if y == row && x > 0 { depth_value(y - 2, x - 1) } else { -2.0 })), + ] { + assert_eq!(plane, &expected); + } +} + +#[test] +fn bad_descriptors_fail_before_writing_or_requesting_rows() { + let part = Part { name: Some("Depth"), data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let duplicate = [FLOAT, FLOAT]; + let bad_channel = [Channel { name: "Z\0hidden", ..FLOAT }]; + let long_name = "Z".repeat(256); + let long_channel = [Channel { name: &long_name, ..FLOAT }]; + let empty_name = [Channel { name: "", ..FLOAT }]; + for parts in [ + vec![], + vec![part, part], + vec![part, Part { name: None, ..part }], + vec![Part { name: Some("🎞"), ..part }], + vec![Part { channels: &duplicate, ..part }], + vec![Part { channels: &bad_channel, ..part }], + vec![Part { channels: &long_channel, ..part }], + vec![Part { channels: &empty_name, ..part }], + vec![Part { channels: &[], ..part }], + vec![Part { data_window: Window { width: 0, ..WINDOW }, ..part }], + vec![Part { data_window: Window { x: i32::MAX, ..WINDOW }, ..part }], + vec![Part { data_window: Window { width: 1 << 27, ..WINDOW }, ..part }], + vec![Part { data_window: Window { height: 1 << 21, ..WINDOW }, compression: Compression::Zip1, ..part }], + ] { + let mut out = Cursor::new(Vec::new()); + let result = write_scanlines(&mut out, WINDOW, &parts, |_, _, _, _| panic!("invalid descriptors reached callback")); + assert!(matches!(result, Err(Error::Encode(_))), "{parts:?}: {result:?}"); + assert!(out.get_ref().is_empty()); + } +} + +#[test] +fn short_rows_and_callback_errors_stop_writing() { + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let mut calls = 0; + let short = write_scanlines(&mut Cursor::new(Vec::new()), WINDOW, &[part], |_, _, _, row| { + calls += 1; + Ok(row.len() - 1) + }); + assert!(matches!(short, Err(Error::Encode(message)) if message.contains("expected 64 samples, got 63"))); + assert_eq!(calls, 1); + + let stopped = Error::Encode("source became unavailable".into()); + let result = write_scanlines(&mut Cursor::new(Vec::new()), WINDOW, &[part], |_, _, _, _| Err(stopped.clone())); + assert_eq!(result, Err(stopped)); +} + +struct LimitedOutput<'a> { + cursor: Cursor>, + limit: &'a Cell, +} + +impl Write for LimitedOutput<'_> { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if self.cursor.position() + bytes.len() as u64 > self.limit.get() { + return Err(io::Error::other("synthetic full disk")); + } + self.cursor.write(bytes) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl Seek for LimitedOutput<'_> { + fn seek(&mut self, position: SeekFrom) -> io::Result { + self.cursor.seek(position) + } +} + +#[test] +fn chunks_are_written_before_requesting_more_rows() { + let limit = Cell::new(u64::MAX); + let mut out = LimitedOutput { cursor: Cursor::new(Vec::new()), limit: &limit }; + let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; + let mut rows = 0; + let result = write_scanlines(&mut out, WINDOW, &[part], |_, _, _, row| { + rows += 1; + // Let the header and offset placeholders through, then fail the first block write. + limit.set(0); + Ok(row.len()) + }); + assert!(matches!(result, Err(Error::Encode(message)) if message.contains("synthetic full disk"))); + assert!(rows > 0 && rows < WINDOW.height, "received {rows} rows before first block write"); +} From 56754df0815820c7a07fb7924dc69c9b8089ac81 Mon Sep 17 00:00:00 2001 From: vangel76 <271991477+vangel76@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:05:54 +0100 Subject: [PATCH 053/130] fix(exr): preserve layered exchange metadata --- crates/exr/src/layer_stack.rs | 86 ++++++++++++++++++++++++++++++----- crates/exr/src/seek.rs | 5 +- crates/exr/src/seek_tests.rs | 25 +++++++++- crates/exr/src/write.rs | 22 ++++++++- crates/exr/src/write_tests.rs | 33 ++++++++++++++ 5 files changed, 155 insertions(+), 16 deletions(-) diff --git a/crates/exr/src/layer_stack.rs b/crates/exr/src/layer_stack.rs index e0664e8561..2e53f4d2c9 100644 --- a/crates/exr/src/layer_stack.rs +++ b/crates/exr/src/layer_stack.rs @@ -12,7 +12,7 @@ pub const ATTRIBUTE_NAME: &str = "craftLayerStack"; pub const MAX_ATTRIBUTE_BYTES: usize = 1 << 20; const VERSION: u64 = 1; const MAX_LAYERS: usize = 4096; -const MAX_ANCESTORS: usize = 64; +const MAX_GROUP_DEPTH: usize = 100; #[derive(Debug)] pub enum Error { @@ -39,6 +39,16 @@ pub struct LayerStack { /// The producer's original RGB compositing encoding. A portable profile ID or /// `icc:` describing an ICC profile. EXR chromaticities describe the stored pixels. pub original_blend_profile: Option, + /// The producer's document sample depth before conversion to EXR channels. + pub original_sample_depth: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SampleDepth { + U8, + U16, + F32, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -70,6 +80,7 @@ pub enum PixelRef { /// A named, flat EXR part. Use part names that are unique within the file. Part { name: String }, /// The exact prefix of the RGB(A) channels in the zero-based flat EXR part. + /// An empty prefix selects unprefixed channels such as `R`, `G` and `B`. ChannelGroup { part: u32, prefix: String }, } @@ -94,6 +105,7 @@ struct Input { version: u64, layers: Vec, original_blend_profile: Option, + original_sample_depth: Option, } #[derive(Serialize)] @@ -103,6 +115,8 @@ struct Output<'a> { layers: &'a [Layer], #[serde(skip_serializing_if = "Option::is_none")] original_blend_profile: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + original_sample_depth: Option, } impl LayerStack { @@ -119,11 +133,11 @@ impl LayerStack { if version != VERSION { return Ok(None); } - let Input { version, layers, original_blend_profile } = serde_json::from_str(text).map_err(Error::Json)?; + let Input { version, layers, original_blend_profile, original_sample_depth } = serde_json::from_str(text).map_err(Error::Json)?; if version != VERSION { return Ok(None); } - let stack = Self { layers, original_blend_profile }; + let stack = Self { layers, original_blend_profile, original_sample_depth }; stack.validate()?; Ok(Some(stack)) } @@ -132,9 +146,13 @@ impl LayerStack { /// header ASCII-safe. pub fn to_attribute(&self) -> Result { self.validate()?; - let json = - serde_json::to_string(&Output { version: VERSION, layers: &self.layers, original_blend_profile: self.original_blend_profile.as_deref() }) - .map_err(Error::Json)?; + let json = serde_json::to_string(&Output { + version: VERSION, + layers: &self.layers, + original_blend_profile: self.original_blend_profile.as_deref(), + original_sample_depth: self.original_sample_depth, + }) + .map_err(Error::Json)?; if json.len() > MAX_ATTRIBUTE_BYTES { return Err(Error::Limit("attribute is too large")); } @@ -180,11 +198,11 @@ impl LayerStack { } text_bytes = text_bytes.saturating_add(layer.name.len()).saturating_add(layer.blend.len()); if let LayerContent::Raster { pixels, .. } = &layer.content { - let (name, max) = match pixels { - PixelRef::Part { name } => (name, 255), - PixelRef::ChannelGroup { prefix, .. } => (prefix, 253), + let (name, min, max) = match pixels { + PixelRef::Part { name } => (name, 1, 255), + PixelRef::ChannelGroup { prefix, .. } => (prefix, 0, 253), }; - if name.is_empty() || name.chars().count() > max || name.chars().any(|c| c.is_control() || u32::from(c) > 255) { + if !(min..=max).contains(&name.chars().count()) || name.chars().any(|c| c.is_control() || u32::from(c) > 255) { return Err(Error::Malformed("invalid EXR part or channel group name")); } text_bytes = text_bytes.saturating_add(name.len()); @@ -205,7 +223,7 @@ impl LayerStack { return Err(Error::Malformed("cyclic layer hierarchy")); } depth += 1; - if depth > MAX_ANCESTORS { + if depth > MAX_GROUP_DEPTH { return Err(Error::Limit("layer hierarchy is too deep")); } at = ancestor; @@ -262,6 +280,7 @@ mod tests { }, ], original_blend_profile: Some("icc:AAE=".into()), + original_sample_depth: None, } } @@ -273,6 +292,51 @@ mod tests { assert_eq!(LayerStack::parse(&encoded).unwrap(), Some(stack)); } + #[test] + fn original_sample_depth_is_optional_in_version_one() { + let old = r#"{"version":1,"layers":[]}"#; + let stack = LayerStack::parse(old).unwrap().unwrap(); + assert_eq!(stack.original_sample_depth, None); + assert_eq!(stack.to_attribute().unwrap(), old); + + for (depth, wire) in [(SampleDepth::U8, "u8"), (SampleDepth::U16, "u16"), (SampleDepth::F32, "f32")] { + let stack = LayerStack { original_sample_depth: Some(depth), ..stack.clone() }; + let text = format!(r#"{{"version":1,"layers":[],"originalSampleDepth":"{wire}"}}"#); + assert_eq!(stack.to_attribute().unwrap(), text); + assert_eq!(LayerStack::parse(&text).unwrap(), Some(stack)); + } + assert!(LayerStack::parse(r#"{"version":1,"layers":[],"originalSampleDepth":"f16"}"#).is_err()); + } + + #[test] + fn empty_channel_group_prefix_round_trips_but_empty_part_name_is_invalid() { + let mut stack = stack(); + stack.layers[0].content = + LayerContent::Raster { pixels: PixelRef::ChannelGroup { part: 0, prefix: String::new() }, sampling: PixelSampling::Raw }; + let text = stack.to_attribute().unwrap(); + assert_eq!(LayerStack::parse(&text).unwrap(), Some(stack.clone())); + + stack.layers[0].content = LayerContent::Raster { pixels: PixelRef::Part { name: String::new() }, sampling: PixelSampling::Raw }; + assert!(matches!(stack.to_attribute(), Err(Error::Malformed(_)))); + } + + #[test] + fn supports_a_raster_inside_one_hundred_groups() { + let mut stack = stack(); + let group = stack.layers[1].clone(); + stack.layers.truncate(1); + stack.layers[0].parent = Some(100); + for id in 1..=100 { + stack.layers.push(Layer { id, parent: (id > 1).then_some(id - 1), ..group.clone() }); + } + let text = stack.to_attribute().unwrap(); + assert_eq!(LayerStack::parse(&text).unwrap(), Some(stack.clone())); + + stack.layers.push(Layer { id: 101, parent: Some(100), ..group }); + stack.layers[0].parent = Some(101); + assert!(matches!(stack.to_attribute(), Err(Error::Limit(_)))); + } + #[test] fn supports_flat_image_fallback_for_unknown_versions_and_rejects_bad_v1() { assert!(LayerStack::parse(r#"{"version":2,"layout":{"different":true}}"#).unwrap().is_none()); diff --git a/crates/exr/src/seek.rs b/crates/exr/src/seek.rs index 4b18bf8809..f01349bd30 100644 --- a/crates/exr/src/seek.rs +++ b/crates/exr/src/seek.rs @@ -293,9 +293,10 @@ impl Index { self.display } - /// Stored RGB primaries and white point (red, green, blue, white in CIE xy). + /// Stored RGB primaries and white point (red, green, blue, white in CIE xy), from the first + /// part that supplies the shared chromaticities attribute. pub fn chromaticities(&self) -> Option<[[f32; 2]; 4]> { - let c = self.meta.headers.first()?.shared_attributes.chromaticities.as_ref()?; + let c = self.meta.headers.iter().find_map(|header| header.shared_attributes.chromaticities.as_ref())?; Some([c.red, c.green, c.blue, c.white].map(|v| [v.0, v.1])) } diff --git a/crates/exr/src/seek_tests.rs b/crates/exr/src/seek_tests.rs index 328e424e0a..e1df9d6a97 100644 --- a/crates/exr/src/seek_tests.rs +++ b/crates/exr/src/seek_tests.rs @@ -14,7 +14,7 @@ use exr::prelude::{ WritableImage, }; -use super::decode::{Limits, decode_display_part}; +use super::decode::{Limits, Window, decode_display_part}; use super::seek::*; fn value(i: usize, k: usize) -> f32 { @@ -52,6 +52,29 @@ fn indexed(bytes: &[u8]) -> Index { Index::build(&mut Cursor::new(bytes), &Limits::default(), &never).unwrap() } +#[test] +fn index_finds_chromaticities_in_a_later_part_header() { + let window = Window { x: 0, y: 0, width: 1, height: 1 }; + let channels = [crate::write::Channel { name: "Y", sample: crate::decode::SampleType::F32 }]; + let first = crate::write::Part { name: Some("First"), data_window: window, channels: &channels, compression: crate::decode::Compression::None }; + let second = crate::write::Part { name: Some("Second"), ..first }; + let chromaticities = [[0.64, 0.33], [0.3, 0.6], [0.15, 0.06], [0.3127, 0.329]]; + let metadata = crate::write::Metadata { chromaticities: Some(chromaticities), ..Default::default() }; + let mut out = Cursor::new(Vec::new()); + crate::write::write_scanlines_with_metadata(&mut out, window, &[first, second], &metadata, |_, _, _, row| Ok(row.len())).unwrap(); + let mut bytes = out.into_inner(); + + // Rename the first header's attribute without shifting the second header or any offsets. + let attr = b"chromaticities\0chromaticities\0"; + let positions: Vec<_> = bytes.windows(attr.len()).enumerate().filter_map(|(offset, bytes)| (bytes == attr).then_some(offset)).collect(); + assert_eq!(positions.len(), 2); + bytes[positions[0]] = b'x'; + let headers = exr::meta::MetaData::read_from_buffered(Cursor::new(&bytes), false).unwrap().headers; + assert!(headers[0].shared_attributes.chromaticities.is_none()); + assert!(headers[1].shared_attributes.chromaticities.is_some()); + assert_eq!(indexed(&bytes).chromaticities(), Some(chromaticities)); +} + /// What the whole-part decoder places in the display window for each channel of part `part`. fn oracle(bytes: &[u8], part: usize, fill: f32) -> Vec> { decode_display_part(bytes, part, &|_| true, &|_| fill, &Limits::default()).unwrap().channels.into_iter().map(|c| c.samples).collect() diff --git a/crates/exr/src/write.rs b/crates/exr/src/write.rs index e26a02405d..035a77b78a 100644 --- a/crates/exr/src/write.rs +++ b/crates/exr/src/write.rs @@ -5,7 +5,7 @@ //! metadata and one offset per chunk. use std::collections::HashSet; -use std::io::{Seek, Write}; +use std::io::{Seek, SeekFrom, Write}; use std::ops::Range; use std::panic::{AssertUnwindSafe, catch_unwind}; @@ -24,6 +24,8 @@ const MAX_CHANNELS: usize = 16_384; const MAX_CHUNKS: usize = 1 << 20; const MAX_BLOCK_BYTES: usize = 64 << 20; const MAX_NAME_BYTES: usize = 255; +const SHORT_NAME_BYTES: usize = 31; +const VERSION_WORD_OFFSET: u64 = 4; const MAX_HEADER_BYTES: usize = 8 << 20; const MAX_TEXT_ATTRIBUTES: usize = 16_384; @@ -280,16 +282,24 @@ fn tile_window(index: BlockIndex, header: &Header) -> Result { } fn write_blocks( - out: &mut W, + mut out: &mut W, headers: Headers, mut read_block: impl FnMut(BlockIndex, &Header) -> Result>, ) -> Result<()> { if out.stream_position().map_err(encode)? != 0 { return Err(encode("output must start at byte zero")); } + let has_long_names = headers.iter().any(|header| { + header.own_attributes.layer_name.as_ref().is_some_and(|name| name.bytes().len() > SHORT_NAME_BYTES) + || header.channels.list.iter().any(|channel| channel.name.bytes().len() > SHORT_NAME_BYTES) + }); + let mut version_update = None; let mut block_error = None; let written = catch_unwind(AssertUnwindSafe(|| { exr::block::write(&mut *out, headers, true, |meta, writer| { + if has_long_names && !meta.requirements.has_long_names { + version_update = Some(exr::meta::Requirements { has_long_names: true, ..meta.requirements }); + } for (chunk_index, index) in enumerate_ordered_header_block_indices(&meta.headers) { let data = meta.headers.get(index.layer).ok_or_else(|| encode("invalid block part")).and_then(|header| read_block(index, header)).map_err( @@ -308,6 +318,14 @@ fn write_blocks( return Err(error); } written.map_err(|_| encode("block writer panicked"))?.map_err(encode)?; + // The codec can omit bit 10 when inferring requirements from channel names. Update the + // OpenEXR v2 version word in place, preserving the codec's other flags and all chunk offsets. + if let Some(requirements) = version_update { + let position = out.stream_position().map_err(encode)?; + out.seek(SeekFrom::Start(VERSION_WORD_OFFSET)).map_err(encode)?; + requirements.write(&mut out).map_err(encode)?; + out.seek(SeekFrom::Start(position)).map_err(encode)?; + } out.flush().map_err(encode) } diff --git a/crates/exr/src/write_tests.rs b/crates/exr/src/write_tests.rs index fe19a80ba7..f0eb4696ea 100644 --- a/crates/exr/src/write_tests.rs +++ b/crates/exr/src/write_tests.rs @@ -141,6 +141,39 @@ fn scanline_metadata_round_trips_a_custom_string() { assert_eq!(parts[0].text("cryptomatte/abc1234/name"), Some("CryptoObject")); } +#[test] +fn channel_names_set_the_long_name_flag_at_the_openexr_byte_boundary() { + let window = Window { width: 1, height: 1, ..WINDOW }; + for len in [31, 32, 255] { + let name = "Z".repeat(len); + let part = Part { name: None, data_window: window, channels: &[Channel { name: &name, ..FLOAT }], compression: Compression::None }; + let mut out = Cursor::new(Vec::new()); + write_scanlines(&mut out, window, &[part], sample_row).unwrap(); + assert_eq!(u32::from_le_bytes(out.get_ref()[4..8].try_into().unwrap()), 2 | if len > 31 { 0x400 } else { 0 }); + assert_eq!(decode::parts(out.get_ref(), &Limits::default()).unwrap()[0].channels[0].name, name); + + let tiled = TilePart { part, tile_width: 1, tile_height: 1 }; + let mut out = Cursor::new(Vec::new()); + write_tiles(&mut out, window, &[tiled], &Metadata::default(), |_, window, tile| fill_tile(tiled, window, tile)).unwrap(); + assert_eq!(u32::from_le_bytes(out.get_ref()[4..8].try_into().unwrap()), 0x202 | if len > 31 { 0x400 } else { 0 }); + let decoded = decode::decode_part(out.get_ref(), 0, &|_| true, &Limits::default()).unwrap(); + assert_eq!(decoded.channel(&name).unwrap().samples, Samples::F32(vec![depth_value(0, 0)])); + } +} + +#[test] +fn long_part_names_set_the_flag_in_multipart_files() { + let window = Window { width: 1, height: 1, ..WINDOW }; + let part = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::None }; + for len in [31, 32, 255] { + let name = "P".repeat(len); + let mut out = Cursor::new(Vec::new()); + write_scanlines(&mut out, window, &[part, Part { name: Some(&name), ..part }], sample_row).unwrap(); + assert_eq!(u32::from_le_bytes(out.get_ref()[4..8].try_into().unwrap()), 0x1002 | if len > 31 { 0x400 } else { 0 }); + assert_eq!(decode::parts(out.get_ref(), &Limits::default()).unwrap()[1].name.as_deref(), Some(name.as_str())); + } +} + #[test] fn invalid_tile_dimensions_and_metadata_fail_before_output() { let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; From d7b37a2f1139c3956e37f1d5326b12c4f5545f69 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 12:08:23 -0800 Subject: [PATCH 054/130] Apply repository import ordering to control fixture --- crates/control/src/client_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/control/src/client_tests.rs b/crates/control/src/client_tests.rs index 7a6ed5782e..e20bada163 100644 --- a/crates/control/src/client_tests.rs +++ b/crates/control/src/client_tests.rs @@ -1,9 +1,9 @@ //! The client against the shared server ([`crate::server::Hub`]) on an ephemeral loopback port. use super::*; -use socket2::{Domain, Socket, Type}; use crate::ControlRequest; use crate::server::{Hub, Protocol, Stop, Summary, Waits as ServerWaits}; +use socket2::{Domain, Socket, Type}; use std::ffi::OsString; use std::net::TcpListener; use std::path::PathBuf; From 6fc1ccd24058b2e8818fab4a9f7db6cf7aa6b8e7 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 17:58:21 -0800 Subject: [PATCH 055/130] update: preserve detach stderr for the busy retry policy --- crates/update/src/install.rs | 77 +++++++++++++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 2 deletions(-) diff --git a/crates/update/src/install.rs b/crates/update/src/install.rs index 03d93d780b..c8a091bc42 100644 --- a/crates/update/src/install.rs +++ b/crates/update/src/install.rs @@ -1983,11 +1983,84 @@ pub mod macos { return Ok(()); } let m = mount.to_str().ok_or("unusual characters in the mount point's path")?; - process::run(HDIUTIL, &["detach", m, "-quiet"], Duration::from_secs(60)) - .or_else(|_| process::run(HDIUTIL, &["detach", m, "-force", "-quiet"], Duration::from_secs(60))) + detach_with(m, process::run) + } + + /// Keeps the helper's stderr: `-quiet` would hide the busy reply that cleanup retries. + fn detach_with(mount: &str, run: impl Fn(&str, &[&str], Duration) -> Result) -> Result<(), String> { + run(HDIUTIL, &["detach", mount], Duration::from_secs(60)) + .or_else(|_| run(HDIUTIL, &["detach", mount, "-force"], Duration::from_secs(60))) .map(drop) } + #[cfg(test)] + #[test] + fn detach_stderr_reaches_the_busy_retry_policy() { + // Model hdiutil's documented -quiet behavior, then use the real process reader and + // retry classifier instead of injecting an already classified error string. + let script = r#" +state=$1 +scenario=$2 +shift 2 +count=0 +if [ -f "$state" ]; then read -r count < "$state"; fi +count=$((count + 1)) +printf '%s\n' "$count" > "$state" +quiet=false +for arg do + if [ "$arg" = -quiet ]; then quiet=true; fi +done +case "$scenario:$count" in + success:*|busy:3) exit 0 ;; + busy:*) reason='hdiutil: detach failed - Resource busy' ;; + permanent:*) reason='hdiutil: detach failed - Permission denied' ;; + *) exit 64 ;; +esac +if [ "$quiet" = false ]; then printf '%s\n' "$reason" >&2; fi +exit 16 +"#; + for (scenario, expected_calls, expected_waits) in [("busy", 3, 1), ("success", 1, 0), ("permanent", 2, 0)] { + let dir = tempfile::tempdir().unwrap(); + let state = dir.path().join("attempts"); + let calls = std::cell::RefCell::new(Vec::new()); + let waits = std::cell::RefCell::new(Vec::new()); + let mount = "/Volumes/PhotoCraft test"; + let result = super::retry_busy_detach_with_elapsed( + || { + detach_with(mount, |program, args, timeout| { + assert_eq!(program, "/usr/bin/hdiutil"); + assert_eq!(timeout, std::time::Duration::from_secs(60)); + calls.borrow_mut().push(args.iter().map(|s| (*s).to_string()).collect::>()); + let mut cmd = process::command("/bin/sh"); + cmd.args(["-c", script, "hdiutil-fixture"]).arg(&state).arg(scenario).args(args); + process::run_command(cmd, program, timeout) + }) + }, + |delay| waits.borrow_mut().push(delay), + || std::time::Duration::ZERO, + ); + if scenario == "permanent" { + assert_eq!(result, Err("hdiutil: detach failed - Permission denied".into())); + } else { + assert_eq!(result, Ok(()), "{scenario}"); + } + let calls = calls.into_inner(); + assert_eq!(calls.len(), expected_calls, "{scenario}"); + assert_eq!(calls[0], ["detach", mount]); + if expected_calls > 1 { + assert_eq!(calls[1], ["detach", mount, "-force"]); + } + if scenario == "busy" { + assert_eq!(calls[2], ["detach", mount], "the preserved busy error must reach another ordinary attempt"); + } + let waits = waits.into_inner(); + assert_eq!(waits.len(), expected_waits, "{scenario}"); + if scenario == "busy" { + assert_eq!(waits, [std::time::Duration::from_millis(500)]); + } + } + } + /// Detaches the image file `dmg` where it is attached with no volume mounted, which a failed /// attach can leave. An attachment with a mounted volume is left alone: another install may /// be using it. So is every attachment while a program started with `dmg` in its arguments From d5b68c0c216c6545013089163ed0fd1ed0b071a7 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 18:55:33 -0800 Subject: [PATCH 056/130] openpgp: exercise per-key check budgets with small inputs --- crates/openpgp/src/keys.rs | 32 ++++++++++++- crates/openpgp/src/keys_tests.rs | 78 +++++++++++++++++++++++--------- 2 files changed, 88 insertions(+), 22 deletions(-) diff --git a/crates/openpgp/src/keys.rs b/crates/openpgp/src/keys.rs index c3b083162e..720abd63af 100644 --- a/crates/openpgp/src/keys.rs +++ b/crates/openpgp/src/keys.rs @@ -27,6 +27,36 @@ const MAX_USER_ID: usize = 4 * 1024; /// checked, so a real key needs a handful). Room for two copies of the largest key kept, merged: /// two self-signatures for each User ID, and two with a back-signature each for each subkey. const MAX_CHECKS: usize = 512; + +#[cfg(not(test))] +pub(super) fn max_checks() -> usize { + MAX_CHECKS +} + +#[cfg(test)] +std::thread_local! { + static TEST_MAX_CHECKS: std::cell::Cell = const { std::cell::Cell::new(MAX_CHECKS) }; +} + +#[cfg(test)] +pub(super) fn max_checks() -> usize { + TEST_MAX_CHECKS.with(std::cell::Cell::get) +} + +#[cfg(test)] +pub(super) fn with_max_checks(limit: usize, run: impl FnOnce() -> T) -> T { + struct Restore(usize); + + impl Drop for Restore { + fn drop(&mut self) { + TEST_MAX_CHECKS.with(|value| value.set(self.0)); + } + } + + let _restore = Restore(TEST_MAX_CHECKS.with(|value| value.replace(limit))); + run() +} + /// How many packets one block is read for before it is given up on. const MAX_PACKETS: usize = 4_096; @@ -298,7 +328,7 @@ impl PublicKey { return None; } let primary = &key.primary_key; - let mut local = Budget::new(MAX_CHECKS); + let mut local = Budget::new(max_checks()); let mut revocations = Budget::new(MAX_REVOCATION_CHECKS); let spend = |budget: &mut Budget, total: &mut Budget| budget.spend() && total.spend(); diff --git a/crates/openpgp/src/keys_tests.rs b/crates/openpgp/src/keys_tests.rs index 3cc53b0bcd..7418d159e1 100644 --- a/crates/openpgp/src/keys_tests.rs +++ b/crates/openpgp/src/keys_tests.rs @@ -7,7 +7,7 @@ use pgp::ser::Serialize; use pgp::types::{Duration, Password, Tag}; use crate::fixtures::*; -use crate::keys::Budget; +use crate::keys::{Budget, max_checks, with_max_checks}; use crate::{CantCheck, Fingerprint, KeyRing, NotVerified, Outcome, PublicKey, verify}; const ALICE: &str = "Alice "; @@ -255,26 +255,62 @@ fn a_copy_with_junk_subkey_bindings_from_the_future_never_pushes_out_the_real_on fn a_copy_that_costs_more_checks_than_a_key_may_is_refused_not_cut_short() { let alice = secret(ALICE, Make { subkey: true, ..Make::default() }); let mallory = secret("Mallory ", Make { seed: 6, ..Make::default() }); - let mut copy = SignedPublicKey::from(alice.clone()); - // Junk User IDs with junk certifications before the subkey: checking them all would leave - // no checks for the subkey's binding. - for n in 0..5 { - let id = pgp::packet::UserId::from_str(Default::default(), format!("Alice {n} ")).unwrap(); - let sigs = (0..110) - .map(|i| { - forged(&alice, &mallory, SignatureType::CertPositive, made(&alice) + i, vec![]) - .sign_certification(&mallory.primary_key, ©.primary_key, &Password::empty(), Tag::UserId, &id) - .unwrap() - }) - .collect(); - copy.details.users.push(pgp::types::SignedUser::new(id, sigs)); - } - let junk = copy.to_bytes().unwrap(); - assert!(PublicKey::parse(&junk).is_err(), "a key not checked whole is no key"); - let mut keys = KeyRing::new(); - keys.insert(public(&alice)); - offer(&mut keys, &junk); - assert!(matches!(outcome(&signed_at(&alice, made(&alice) + 10), ALICE, &keys), Outcome::Verified(_))); + assert_eq!(max_checks(), 512); + let real = public(&alice); + let message = signed_at(&alice, made(&alice) + 10); + let nine_checks = with_max_checks(8, || { + assert_eq!(max_checks(), 8); + let mut copy = SignedPublicKey::from(alice.clone()); + assert_eq!(copy.details.users.len(), 1); + assert_eq!(copy.public_subkeys.len(), 1); + // Junk User IDs with junk certifications before the subkey: checking them all would leave + // no checks for the subkey's binding. Five users with two forged certs need 13 slots, + // including the real user's certification, the subkey binding and its back-signature. + for n in 0..5 { + let id = pgp::packet::UserId::from_str(Default::default(), format!("Alice {n} ")).unwrap(); + let sigs = (0..2) + .map(|i| { + forged(&alice, &mallory, SignatureType::CertPositive, made(&alice) + i, vec![]) + .sign_certification(&mallory.primary_key, ©.primary_key, &Password::empty(), Tag::UserId, &id) + .unwrap() + }) + .collect(); + copy.details.users.push(pgp::types::SignedUser::new(id, sigs)); + } + let junk = copy.to_bytes().unwrap(); + assert!(PublicKey::parse(&junk).is_err(), "a key not checked whole is no key"); + let mut keys = KeyRing::new(); + keys.insert(public(&alice)); + offer(&mut keys, &junk); + assert!(matches!(outcome(&signed_at(&alice, made(&alice) + 10), ALICE, &keys), Outcome::Verified(_))); + + // Reuse one actual forged packet per junk user: five unsuccessful checks plus the + // genuine key's three checks must still reach and verify the signing subkey. + let mut exact = SignedPublicKey::from(alice.clone()); + for user in copy.details.users.iter().skip(1) { + assert_eq!(user.signatures.len(), 2); + exact.details.users.push(pgp::types::SignedUser::new(user.id.clone(), vec![user.signatures[0].clone()])); + } + let accepted = PublicKey::parse(&exact.to_bytes().unwrap()).unwrap(); + assert_eq!(accepted.len(), 1); + assert_eq!(accepted[0].to_bytes(), real.to_bytes(), "discard only the forged certifications"); + let keys: KeyRing = accepted.into_iter().collect(); + assert!(matches!(outcome(&message, ALICE, &keys), Outcome::Verified(_))); + + // A sixth existing forged packet costs the last slot needed by the back-signature: + // refuse the whole key, rather than returning one with an unusable signing subkey. + exact.details.users[1].signatures.push(copy.details.users[1].signatures[1].clone()); + let nine = exact.to_bytes().unwrap(); + assert!(PublicKey::parse(&nine).is_err(), "nine checks do not fit an eight-check key budget"); + nine + }); + // Leaving the scope restores the real default, through both its getter and its consumer. + assert_eq!(max_checks(), 512); + let restored = PublicKey::parse(&nine_checks).unwrap(); + assert_eq!(restored.len(), 1); + assert_eq!(restored[0].to_bytes(), real.to_bytes()); + let keys: KeyRing = restored.into_iter().collect(); + assert!(matches!(outcome(&message, ALICE, &keys), Outcome::Verified(_))); } #[test] From 5cdb115518c046700cdaa3f3f54a5ce9acfa0c6f Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:53:16 +0100 Subject: [PATCH 057/130] craft-doc-binary: a Word 97 built-in style takes its built-in name (#1805) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A .doc saved by a non-English Word stores its built-in styles under that language's names (Обычный, Kop 1). Word reads a built-in style by its sti and names it from the reserved names in [MS-OE376] Part 4 §2.7.3.9, so the document's own Normal is Normal. The Word 97 reader ignored sti and kept the stored name, so these documents had no Normal. - stsh: one table of the built-in names for sti 0-266, from [MS-OE376]. The Word 97 reader names a built-in style from it; a user-defined style (0x0FFE) and any sti past the table keep the stored name. - word6: the Word 6.0/95 reader uses the same table instead of its own, which stopped at 106. - write: Plain Text is sti 90, not 91 (E-mail Signature). With the reader naming styles by sti, a Plain Text style would otherwise read back as E-mail Signature. --- crates/doc-binary/src/stsh.rs | 368 ++++++++++++++++++++++++++ crates/doc-binary/src/word6.rs | 117 +------- crates/doc-binary/src/write/styles.rs | 28 +- 3 files changed, 397 insertions(+), 116 deletions(-) diff --git a/crates/doc-binary/src/stsh.rs b/crates/doc-binary/src/stsh.rs index 3bd0328f32..a90fd250c1 100644 --- a/crates/doc-binary/src/stsh.rs +++ b/crates/doc-binary/src/stsh.rs @@ -32,6 +32,9 @@ pub(crate) struct StandardFonts { pub(crate) bidi: Option, } +/// `sti` of no style ([MS-DOC] `StdfBase`): read when the record is too short for one. +const STI_NIL: u16 = 0x0FFF; + /// `StshiLsd.cbLSD`: the size of a latent style's `LSD` ([MS-DOC] `StshiLsd`). const LSD_SIZE: u16 = 4; @@ -55,6 +58,287 @@ pub(crate) fn standard_fonts(table: &[u8], fc: u32, lcb: u32) -> StandardFonts { StandardFonts { ascii: at(12), east_asian: at(14), other: at(16), bidi } } +/// The names of Word's built-in styles by `sti`: the "Index within built-in styles" of the +/// reserved style names in [MS-OE376] (Part 4 §2.7.3.9, 0–266), which [MS-DOC]'s `StdfBase` says +/// `sti` is. Spelled as that table spells them. +const BUILT_IN_NAMES: [&str; 267] = [ + "Normal", + "heading 1", + "heading 2", + "heading 3", + "heading 4", + "heading 5", + "heading 6", + "heading 7", + "heading 8", + "heading 9", + "index 1", + "index 2", + "index 3", + "index 4", + "index 5", + "index 6", + "index 7", + "index 8", + "index 9", + "toc 1", + "toc 2", + "toc 3", + "toc 4", + "toc 5", + "toc 6", + "toc 7", + "toc 8", + "toc 9", + "Normal Indent", + "footnote text", + "annotation text", + "header", + "footer", + "index heading", + "caption", + "table of figures", + "envelope address", + "envelope return", + "footnote reference", + "annotation reference", + "line number", + "page number", + "endnote reference", + "endnote text", + "table of authorities", + "macro", + "toa heading", + "List", + "List Bullet", + "List Number", + "List 2", + "List 3", + "List 4", + "List 5", + "List Bullet 2", + "List Bullet 3", + "List Bullet 4", + "List Bullet 5", + "List Number 2", + "List Number 3", + "List Number 4", + "List Number 5", + "Title", + "Closing", + "Signature", + "Default Paragraph Font", + "Body Text", + "Body Text Indent", + "List Continue", + "List Continue 2", + "List Continue 3", + "List Continue 4", + "List Continue 5", + "Message Header", + "Subtitle", + "Salutation", + "Date", + "Body Text First Indent", + "Body Text First Indent 2", + "Note Heading", + "Body Text 2", + "Body Text 3", + "Body Text Indent 2", + "Body Text Indent 3", + "Block Text", + "Hyperlink", + "FollowedHyperlink", + "Strong", + "Emphasis", + "Document Map", + "Plain Text", + "E-mail Signature", + "HTML Top of Form", + "HTML Bottom of Form", + "Normal (Web)", + "HTML Acronym", + "HTML Address", + "HTML Cite", + "HTML Code", + "HTML Definition", + "HTML Keyboard", + "HTML Preformatted", + "HTML Sample", + "HTML Typewriter", + "HTML Variable", + "Normal Table", + "annotation subject", + "No List", + "Outline List 1", + "Outline List 2", + "Outline List 3", + "Table Simple 1", + "Table Simple 2", + "Table Simple 3", + "Table Classic 1", + "Table Classic 2", + "Table Classic 3", + "Table Classic 4", + "Table Colorful 1", + "Table Colorful 2", + "Table Colorful 3", + "Table Columns 1", + "Table Columns 2", + "Table Columns 3", + "Table Columns 4", + "Table Columns 5", + "Table Grid 1", + "Table Grid 2", + "Table Grid 3", + "Table Grid 4", + "Table Grid 5", + "Table Grid 6", + "Table Grid 7", + "Table Grid 8", + "Table List 1", + "Table List 2", + "Table List 3", + "Table List 4", + "Table List 5", + "Table List 6", + "Table List 7", + "Table List 8", + "Table 3D effects 1", + "Table 3D effects 2", + "Table 3D effects 3", + "Table Contemporary", + "Table Elegant", + "Table Professional", + "Table Subtle 1", + "Table Subtle 2", + "Table Web 1", + "Table Web 2", + "Table Web 3", + "Balloon Text", + "Table Grid", + "Table Theme", + "Placeholder Text", + "No Spacing", + "Light Shading", + "Light List", + "Light Grid", + "Medium Shading 1", + "Medium Shading 2", + "Medium List 1", + "Medium List 2", + "Medium Grid 1", + "Medium Grid 2", + "Medium Grid 3", + "Dark List", + "Colorful Shading", + "Colorful List", + "Colorful Grid", + "Light Shading Accent 1", + "Light List Accent 1", + "Light Grid Accent 1", + "Medium Shading 1 Accent 1", + "Medium Shading 2 Accent 1", + "Medium List 1 Accent 1", + "Revision", + "List Paragraph", + "Quote", + "Intense Quote", + "Medium List 2 Accent 1", + "Medium Grid 1 Accent 1", + "Medium Grid 2 Accent 1", + "Medium Grid 3 Accent 1", + "Dark List Accent 1", + "Colorful Shading Accent 1", + "Colorful List Accent 1", + "Colorful Grid Accent 1", + "Light Shading Accent 2", + "Light List Accent 2", + "Light Grid Accent 2", + "Medium Shading 1 Accent 2", + "Medium Shading 2 Accent 2", + "Medium List 1 Accent 2", + "Medium List 2 Accent 2", + "Medium Grid 1 Accent 2", + "Medium Grid 2 Accent 2", + "Medium Grid 3 Accent 2", + "Dark List Accent 2", + "Colorful Shading Accent 2", + "Colorful List Accent 2", + "Colorful Grid Accent 2", + "Light Shading Accent 3", + "Light List Accent 3", + "Light Grid Accent 3", + "Medium Shading 1 Accent 3", + "Medium Shading 2 Accent 3", + "Medium List 1 Accent 3", + "Medium List 2 Accent 3", + "Medium Grid 1 Accent 3", + "Medium Grid 2 Accent 3", + "Medium Grid 3 Accent 3", + "Dark List Accent 3", + "Colorful Shading Accent 3", + "Colorful List Accent 3", + "Colorful Grid Accent 3", + "Light Shading Accent 4", + "Light List Accent 4", + "Light Grid Accent 4", + "Medium Shading 1 Accent 4", + "Medium Shading 2 Accent 4", + "Medium List 1 Accent 4", + "Medium List 2 Accent 4", + "Medium Grid 1 Accent 4", + "Medium Grid 2 Accent 4", + "Medium Grid 3 Accent 4", + "Dark List Accent 4", + "Colorful Shading Accent 4", + "Colorful List Accent 4", + "Colorful Grid Accent 4", + "Light Shading Accent 5", + "Light List Accent 5", + "Light Grid Accent 5", + "Medium Shading 1 Accent 5", + "Medium Shading 2 Accent 5", + "Medium List 1 Accent 5", + "Medium List 2 Accent 5", + "Medium Grid 1 Accent 5", + "Medium Grid 2 Accent 5", + "Medium Grid 3 Accent 5", + "Dark List Accent 5", + "Colorful Shading Accent 5", + "Colorful List Accent 5", + "Colorful Grid Accent 5", + "Light Shading Accent 6", + "Light List Accent 6", + "Light Grid Accent 6", + "Medium Shading 1 Accent 6", + "Medium Shading 2 Accent 6", + "Medium List 1 Accent 6", + "Medium List 2 Accent 6", + "Medium Grid 1 Accent 6", + "Medium Grid 2 Accent 6", + "Medium Grid 3 Accent 6", + "Dark List Accent 6", + "Colorful Shading Accent 6", + "Colorful List Accent 6", + "Colorful Grid Accent 6", + "Subtle Emphasis", + "Intense Emphasis", + "Subtle Reference", + "Intense Reference", + "Book Title", + "Bibliography", + "TOC Heading", +]; + +/// The built-in name of a style whose `sti` is `sti`. Word names a built-in style by its `sti`, +/// whatever name the file stores (a non-English Word stores "Обычный" or "Kop 1"): `None` for a +/// user-defined style (0x0FFE), the null 0x0FFF, and anything else past the table, which keep the +/// stored name. +pub(crate) fn built_in_name(sti: u16) -> Option<&'static str> { + BUILT_IN_NAMES.get(usize::from(sti)).copied() +} + /// Parse the `STSH` at `table[fc..fc+lcb]`. pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result, DocbinError> { let fc = fc as usize; @@ -95,6 +379,7 @@ pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result, Do // StdfBase ([MS-DOC] §2.9.260, 10 bytes): sti(12)+flags(4); stk(4)+istdBase(12); // cupx(4)+istdNext(12); bchUpe(16) (= cbStd); grfstd(16). istdBase is a zero-based // index into the stylesheet, 0x0FFF meaning "no parent". + let sti = stdf.get(0..2).map_or(STI_NIL, |b| u16::from_le_bytes([b[0], b[1]]) & 0x0FFF); let stk = (stdf.get(2).copied().unwrap_or(1) & 0x0F).max(1); let w1 = stdf.get(2..4).map(|b| u16::from_le_bytes([b[0], b[1]])).unwrap_or(0xFFF1); let istd_base = w1 >> 4; @@ -135,6 +420,8 @@ pub(crate) fn parse(table: &[u8], fc: u32, lcb: u32) -> Result, Do { chpx = u.clone(); } + // A built-in style goes by its built-in name ("Normal", "heading 1"), as in Word. + let name = built_in_name(sti).map_or(name, str::to_owned); out.push(RawStyle { stk, istd_base, name, papx, chpx }); } Ok(out) @@ -192,3 +479,84 @@ pub(crate) fn fonts(table: &[u8], fc: u32, lcb: u32) -> Vec { /// Bytes of an FFN before its primary name ([MS-DOC] §2.9.82). const FFN_HEADER: usize = 39; + +#[cfg(test)] +mod tests { + use super::*; + + /// One Word 97 STD ([MS-DOC] §2.9.260, `cbSTDBaseInFile` 10) with this `sti`, `stk` and + /// stored name, and empty UPXs. + fn std_record(sti: u16, stk: u16, name: &str) -> Vec { + let cupx: u16 = if stk == 1 { 2 } else { 1 }; + let mut v = Vec::new(); + v.extend_from_slice(&sti.to_le_bytes()); + v.extend_from_slice(&(stk | 0x0FFF << 4).to_le_bytes()); // stk, istdBase none + v.extend_from_slice(&(cupx | 0x0FFF << 4).to_le_bytes()); // cupx, istdNext none + v.extend_from_slice(&[0; 4]); // bchUpe, grfstd + let units: Vec = name.encode_utf16().collect(); + v.extend_from_slice(&(units.len() as u16).to_le_bytes()); + v.extend(units.iter().flat_map(|u| u.to_le_bytes())); + v.extend_from_slice(&[0, 0]); + if stk == 1 { + v.extend_from_slice(&[2, 0, 0, 0]); // UpxPapx: istd 0, no sprms + } + v.extend_from_slice(&[0, 0]); // UpxChpx: no sprms + [(v.len() as u16).to_le_bytes().to_vec(), v].concat() + } + + /// An STSH holding these STDs. + fn stsh(stds: &[Vec]) -> Vec { + let mut v = vec![4, 0]; + v.extend_from_slice(&(stds.len() as u16).to_le_bytes()); + v.extend_from_slice(&10u16.to_le_bytes()); + v.extend(stds.iter().flatten()); + v + } + + fn names(stds: &[Vec]) -> Vec { + let t = stsh(stds); + parse(&t, 0, t.len() as u32).expect("STSH").into_iter().map(|s| s.name).collect() + } + + /// #1805: a non-English Word stores its built-in styles under its own names; Word reads them + /// by `sti`, under the built-in names. + #[test] + fn built_in_styles_take_their_built_in_names() { + let read = names(&[ + std_record(0, 1, "Обычный"), + std_record(1, 1, "Kop 1"), + std_record(65, 2, "Fuente de párrafo predeter."), + std_record(153, 1, "Sprechblasentext"), + std_record(154, 3, "表 (格子)"), + std_record(266, 1, "Inhaltsverzeichnisüberschrift"), + ]); + assert_eq!(read, ["Normal", "heading 1", "Default Paragraph Font", "Balloon Text", "Table Grid", "TOC Heading"]); + } + + /// #1805: a user-defined style (0x0FFE), and an `sti` past the table, keep the stored name. + #[test] + fn other_styles_keep_their_stored_names() { + assert_eq!( + names(&[std_record(0x0FFE, 1, "Mijn stijl"), std_record(267, 2, "Later"), std_record(0x0FFF, 1, "Nil")]), + ["Mijn stijl", "Later", "Nil"] + ); + } + + /// #1805: the document's own Normal is the model's `Normal`, and a heading is a heading. + #[test] + fn a_localized_normal_is_the_models_normal() { + let t = stsh(&[std_record(0, 1, "Standaard"), std_record(1, 1, "Kop 1")]); + let sheet = crate::fmt::stylesheet(&parse(&t, 0, t.len() as u32).expect("STSH"), &[], StandardFonts::default()); + assert!(sheet.get("Normal").is_some()); + let h = sheet.styles.iter().find(|s| s.name == "Heading 1").expect("Heading 1"); + assert_eq!(h.para.outline_level, Some(0)); + } + + #[test] + fn the_table_has_every_sti_of_ms_oe376() { + assert_eq!(BUILT_IN_NAMES.len(), 267); + assert_eq!(built_in_name(106), Some("annotation subject")); + assert_eq!(built_in_name(107), Some("No List")); + assert_eq!(built_in_name(0x0FFE), None); + } +} diff --git a/crates/doc-binary/src/word6.rs b/crates/doc-binary/src/word6.rs index e9fab2d740..f293fd4fbf 100644 --- a/crates/doc-binary/src/word6.rs +++ b/crates/doc-binary/src/word6.rs @@ -389,119 +389,6 @@ fn stylesheet(word: &[u8], fc: u32, lcb: u32) -> (Vec, Vec (styles, facts) } -/// The names of the built-in styles by sti: the "Index within built-in styles" of the reserved -/// style names in [MS-OE376] (Part 4 §2.7.3.9), which [MS-DOC]'s StdfBase says sti is. 0x0FFE -/// (user-defined) and anything past the table keep the name stored in the file. -const BUILT_IN_NAMES: [&str; 107] = [ - "Normal", - "heading 1", - "heading 2", - "heading 3", - "heading 4", - "heading 5", - "heading 6", - "heading 7", - "heading 8", - "heading 9", - "index 1", - "index 2", - "index 3", - "index 4", - "index 5", - "index 6", - "index 7", - "index 8", - "index 9", - "toc 1", - "toc 2", - "toc 3", - "toc 4", - "toc 5", - "toc 6", - "toc 7", - "toc 8", - "toc 9", - "Normal Indent", - "footnote text", - "annotation text", - "header", - "footer", - "index heading", - "caption", - "table of figures", - "envelope address", - "envelope return", - "footnote reference", - "annotation reference", - "line number", - "page number", - "endnote reference", - "endnote text", - "table of authorities", - "macro", - "toa heading", - "List", - "List Bullet", - "List Number", - "List 2", - "List 3", - "List 4", - "List 5", - "List Bullet 2", - "List Bullet 3", - "List Bullet 4", - "List Bullet 5", - "List Number 2", - "List Number 3", - "List Number 4", - "List Number 5", - "Title", - "Closing", - "Signature", - "Default Paragraph Font", - "Body Text", - "Body Text Indent", - "List Continue", - "List Continue 2", - "List Continue 3", - "List Continue 4", - "List Continue 5", - "Message Header", - "Subtitle", - "Salutation", - "Date", - "Body Text First Indent", - "Body Text First Indent 2", - "Note Heading", - "Body Text 2", - "Body Text 3", - "Body Text Indent 2", - "Body Text Indent 3", - "Block Text", - "Hyperlink", - "FollowedHyperlink", - "Strong", - "Emphasis", - "Document Map", - "Plain Text", - "E-mail Signature", - "HTML Top of Form", - "HTML Bottom of Form", - "Normal (Web)", - "HTML Acronym", - "HTML Address", - "HTML Cite", - "HTML Code", - "HTML Definition", - "HTML Keyboard", - "HTML Preformatted", - "HTML Sample", - "HTML Typewriter", - "HTML Variable", - "Normal Table", - "annotation subject", -]; - /// One style entry (`None` for an empty slot or one too short for its fixed part and name). fn style(std: &[u8], cb_base: usize) -> Option<(RawStyle, StyleFacts)> { let u16_at = |at: usize| std.get(at..at + 2).map(|x| u16::from_le_bytes([x[0], x[1]])); @@ -515,8 +402,8 @@ fn style(std: &[u8], cb_base: usize) -> Option<(RawStyle, StyleFacts)> { // ("Default" or "Обычный" for Normal). Other names are 8-bit, as Word shows them // (Windows-1252: names it couldn't store read back with '?'). let stored = std.get(cb_base + 1..cb_base + 1 + len)?; - let name: String = match BUILT_IN_NAMES.get(usize::from(sti)) { - Some(built_in) => (*built_in).to_owned(), + let name: String = match crate::stsh::built_in_name(sti) { + Some(built_in) => built_in.to_owned(), None => stored.iter().map(|&b| craft_codepage::cp1252(b)).collect(), }; let mut upxs: Vec<&[u8]> = Vec::new(); diff --git a/crates/doc-binary/src/write/styles.rs b/crates/doc-binary/src/write/styles.rs index d1d6a6649a..6286d5ade0 100644 --- a/crates/doc-binary/src/write/styles.rs +++ b/crates/doc-binary/src/write/styles.rs @@ -72,7 +72,7 @@ const BUILTIN: &[(&str, u16)] = &[ ("FollowedHyperlink", 86), ("Strong", 87), ("Emphasis", 88), - ("Plain Text", 91), + ("Plain Text", 90), ("Normal (Web)", 94), ("Normal Table", 105), ("No List", 107), @@ -397,4 +397,30 @@ mod tests { let t = font_table(&names); assert_eq!(crate::stsh::fonts(&t, 0, t.len() as u32), names); } + + /// #1805: the reader names a built-in style by its `sti`, so each one the writer gives must be + /// the one [MS-OE376] lists for the name it writes (Plain Text is 90; 91 is E-mail Signature). + #[test] + fn every_built_in_sti_names_the_style_written() { + for &(name, sti) in BUILTIN { + assert_eq!(crate::stsh::built_in_name(sti), Some(name), "sti {sti}"); + } + } + + /// #1805: a built-in style the writer gives an `sti` reads back under its own name. + #[test] + fn a_plain_text_style_reads_back_as_plain_text() { + let mut d = craft_wordmodel::Document::new(); + std::sync::Arc::make_mut(&mut d.styles).styles.push(Style { + id: "PlainText".into(), + name: "Plain Text".into(), + kind: StyleKind::Paragraph, + based_on: Some("Normal".into()), + ..Default::default() + }); + d.body = vec![craft_wordmodel::para_block(craft_wordmodel::para::Paragraph::with_text("x", CharProps::default()).styled("PlainText"))]; + let r = crate::read(&crate::write(&d).expect("write")).expect("read back"); + let style = r.body[0].as_para().and_then(|p| p.props.style.clone()).and_then(|id| r.styles.get(&id).map(|s| s.name.clone())); + assert_eq!(style.as_deref(), Some("Plain Text")); + } } From 89ba00e62818c124411a6f5c72761d1147cdf758 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 21 Nov 2026 09:10:21 -0800 Subject: [PATCH 058/130] audio: skip unused diagnostics in extreme Opus test --- crates/audio/tests/codecs/opusenc/modes.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/audio/tests/codecs/opusenc/modes.rs b/crates/audio/tests/codecs/opusenc/modes.rs index 2638585603..156d1e85d4 100644 --- a/crates/audio/tests/codecs/opusenc/modes.rs +++ b/crates/audio/tests/codecs/opusenc/modes.rs @@ -266,9 +266,7 @@ fn extreme_inputs_stay_decodable() { let (enc, packets) = encode(OpusEncoder::with_mode(c as u8, rate * c as u32, mode, bw).unwrap(), &planar); assert!(packets.iter().all(|p| p.len() >= 3 && p.len() <= 1276), "{name} {mode:?}: packet sizes"); let dec = decode(&enc.opus_head(), &packets); - let peak = dec.iter().flatten().fold(0f32, |m, v| m.max(v.abs())); - let snr = if name == "nan" { f64::NAN } else { snr_search(&planar[0], &dec[0], 2).0 }; - eprintln!("{name} {mode:?}/{bw:?} {c} ch: peak {peak:.2}, SNR {snr:.1} dB, {:.1} kb/s", bitrate(&packets) / 1000.0); + assert_eq!(dec.len(), c, "{name} {mode:?}/{bw:?} {c} ch: decoded channels"); assert!(dec.iter().all(|ch| ch.iter().all(|v| v.is_finite() && v.abs() <= 4.0)), "{name} {mode:?}/{bw:?} {c} ch: bad output"); } } From 995fda32caa2e933196bb6fd10193ccfa5310781 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 21 Nov 2026 13:02:25 -0800 Subject: [PATCH 059/130] craft-text: share outline font embedding permissions Port VectorCraft's Embedding::from_fs_type and its original permission table, preserving its existing interpretation. Make the module available without language features and cover combined no-subsetting restrictions. Source: storytold/vectorcraft@fa3dcab4110f39ee91d3e471ec4e03aefb5a169e Co-authored-by: bflatastic --- crates/text/src/embed.rs | 50 ++++++++++++++++++++++++++++++++++++++++ crates/text/src/lib.rs | 6 ++++- 2 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 crates/text/src/embed.rs diff --git a/crates/text/src/embed.rs b/crates/text/src/embed.rs new file mode 100644 index 0000000000..8291737f1b --- /dev/null +++ b/crates/text/src/embed.rs @@ -0,0 +1,50 @@ +//! Outline-font embedding permissions from raw OS/2 `fsType` flags. +//! +//! This classifies flags for outline embedding; it does not parse font data. + +// Ported from VectorCraft by bflatastic, fa3dcab4110f39ee91d3e471ec4e03aefb5a169e. + +/// What a font's licence lets a document do with it (OS/2 `fsType`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Embedding { + /// The font may be embedded, as a subset. + Subset, + /// The font may be embedded whole only (no subsetting). + Whole, + /// Restricted licence, or bitmap embedding only: the outlines may not be embedded. + Forbidden, +} + +impl Embedding { + /// The permission an OS/2 `fsType` value grants. Bits 0–3 are the usage permissions (none: + /// installable; 2: restricted; 4: preview and print; 8: editable), the most permissive one + /// winning when several are set; bit 8 forbids subsetting and bit 9 allows bitmaps only. + pub fn from_fs_type(fs: u16) -> Self { + let restricted = fs & 0x0002 != 0 && fs & 0x000c == 0; + if restricted || fs & 0x0200 != 0 { + Self::Forbidden + } else if fs & 0x0100 != 0 { + Self::Whole + } else { + Self::Subset + } + } +} + +#[cfg(test)] +mod tests { + use super::Embedding; + + #[test] + fn fs_type_flags_decide_the_embedding() { + assert_eq!(Embedding::from_fs_type(0), Embedding::Subset, "installable"); + assert_eq!(Embedding::from_fs_type(0x0004), Embedding::Subset, "preview & print"); + assert_eq!(Embedding::from_fs_type(0x0008), Embedding::Subset, "editable"); + assert_eq!(Embedding::from_fs_type(0x0002), Embedding::Forbidden, "restricted"); + assert_eq!(Embedding::from_fs_type(0x0006), Embedding::Subset, "the most permissive bit wins"); + assert_eq!(Embedding::from_fs_type(0x0200), Embedding::Forbidden, "bitmaps only"); + assert_eq!(Embedding::from_fs_type(0x0108), Embedding::Whole, "no subsetting"); + assert_eq!(Embedding::from_fs_type(0x0102), Embedding::Forbidden, "restricted before no subsetting"); + assert_eq!(Embedding::from_fs_type(0x0308), Embedding::Forbidden, "bitmaps only before no subsetting"); + } +} diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 62e8d0eb7b..016faf3cde 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -3,7 +3,9 @@ //! Shared text processing for the Craft apps. It sits below the composer: layout code calls it on //! plain text and a language before it shapes and places glyphs. //! -//! Modules, each behind the cargo feature of the same name: +//! [`embed`] is always available and classifies raw OS/2 `fsType` flags for outline embedding. +//! +//! Feature-gated modules, each behind the cargo feature of the same name: //! - [`hyphen`] (default): hyphenation points, with bundled US English data and optional //! hypher patterns for 47 more languages (Slovak, under the GPL, only with `slovak-gpl`). //! - [`segment`] (default): line-break opportunities (UAX #14 with kinsoku), and word breaks for @@ -15,6 +17,8 @@ //! Language features (`spanish`, `german`, …, `all-languages`) add data for that language and //! turn on the modules that use it. +pub mod embed; + #[cfg(feature = "positioned")] pub mod positioned; From 3cc61480e373ccde1d29e142d606ecf68ad32c03 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 21 Nov 2026 15:37:48 -0800 Subject: [PATCH 060/130] svg: cover CSS pixel unit casing --- crates/svg/src/transform_compat.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/svg/src/transform_compat.rs b/crates/svg/src/transform_compat.rs index 6b5c9b269b..5e8a441998 100644 --- a/crates/svg/src/transform_compat.rs +++ b/crates/svg/src/transform_compat.rs @@ -154,5 +154,15 @@ mod tests { assert_eq!(css_transform_to_svg("translate(50%, 0)"), None); assert_eq!(css_transform_to_svg("rotate3d(1, 0, 0, 45deg)"), None); assert_eq!(css_transform_to_svg("translate(1px"), None); + // CSS Values3 section4.4: unit identifiers are ASCII case-insensitive. + // https://www.w3.org/TR/css-values-3/#dimensions + for unit in ["px", "PX", "Px", "pX"] { + let input = format!("translateX(5{unit}) scale(2)"); + assert_eq!( + css_transform_to_svg(&input).map(|svg| parse_transform(&svg) * kurbo::Point::new(1.0, 2.0)), + Some(kurbo::Point::new(7.0, 4.0)), + "{input}", + ); + } } } From 90341115976e0873b3a124d374b16265ac14a0ed Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 21 Nov 2026 15:44:05 -0800 Subject: [PATCH 061/130] svg: accept mixed-case CSS pixel units --- crates/svg/src/transform_compat.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/transform_compat.rs b/crates/svg/src/transform_compat.rs index 5e8a441998..a09aab3c46 100644 --- a/crates/svg/src/transform_compat.rs +++ b/crates/svg/src/transform_compat.rs @@ -83,7 +83,8 @@ pub fn css_transform_to_svg(value: &str) -> Option { /// A CSS transform length in user units: `px` or unitless. fn css_length(a: &str) -> Option { - let n = a.strip_suffix("px").unwrap_or(a).parse::().ok()?; + let a = a.to_ascii_lowercase(); + let n = a.strip_suffix("px").unwrap_or(&a).parse::().ok()?; n.is_finite().then_some(n) } From 91c9e50399ebdedb3109b628f250d370a30f7b81 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 21 Nov 2026 16:53:07 -0800 Subject: [PATCH 062/130] svg: cover CSS declaration unit casing --- crates/svg/src/doc_style.rs | 118 ++++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/crates/svg/src/doc_style.rs b/crates/svg/src/doc_style.rs index f07aaad3fc..8f2b0dbb77 100644 --- a/crates/svg/src/doc_style.rs +++ b/crates/svg/src/doc_style.rs @@ -470,6 +470,124 @@ mod tests { assert_eq!(d.get("fill").map(String::as_str), Some("blue")); assert_eq!(d.get("stroke").map(String::as_str), Some("red")); assert!(!d.contains_key("transform")); + + // SVG1.1 length syntax distinguishes CSS unit case from raw attributes: + // https://www.w3.org/TR/SVG11/types.html#DataTypeLength + let primary = roxmltree::Document::parse( + r#""#, + ) + .unwrap(); + for id in ["lower", "upper"] { + let node = primary.descendants().find(|n| n.attribute("id") == Some(id)).unwrap(); + let mut st = Style::default(); + cascade(node, &StyleSheet::default(), &mut st, 200.0, 100.0, |_| true); + assert_eq!(st.stroke_width, 16.0, "{id}: CSS unit case must not change stroke width"); + } + + let close = |actual: f64, expected: f64| { + assert!((actual - expected).abs() <= 1e-12 * expected.abs().max(1.0), "{actual} != {expected}"); + }; + // Every supported suffix, through both CSS origins and every length property. + // Absolute factors are CSS px/unit; relative factors use the inherited font. + let units = [ + ("px", "pX", 1.0, 0.0), + ("pt", "Pt", 4.0 / 3.0, 0.0), + ("pc", "pC", 16.0, 0.0), + ("mm", "Mm", 96.0 / 25.4, 0.0), + ("cm", "cM", 96.0 / 2.54, 0.0), + ("in", "In", 96.0, 0.0), + ("em", "eM", 0.0, 1.0), + ("ex", "Ex", 0.0, 0.5), + ]; + for (unit, mixed, absolute, relative) in units { + for inline in [false, true] { + let separator = if inline { " " } else { "\t" }; + let values = format!( + "font-size:2{mixed};stroke-width:3{mixed};stroke-dasharray:1E1{mixed},{separator}+2.5{mixed};stroke-dashoffset:-5e-1{mixed}" + ); + let inline_style = if inline { format!(" style=\"{values}\"") } else { String::new() }; + let xml = format!( + "" + ); + let doc = roxmltree::Document::parse(&xml).unwrap(); + let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let mut css = StyleSheet::default(); + let rule = if inline { ".a { stroke-width:1px; font-size:1px; }".to_owned() } else { format!(".a {{ {values} }}") }; + parse_css(&rule, &mut css).unwrap(); + css.index(); + let d = declared(rect, &css, |_| true); + assert_eq!(d.get("font-size"), Some(&format!("2{unit}"))); + assert_eq!(d.get("stroke-width"), Some(&format!("3{unit}"))); + assert_eq!(d.get("stroke-dasharray"), Some(&format!("1E1{unit},{separator}+2.5{unit}"))); + assert_eq!(d.get("stroke-dashoffset"), Some(&format!("-5e-1{unit}"))); + let factor = |font| if relative == 0.0 { absolute } else { font * relative }; + let font = 2.0 * factor(20.0); + let mut st = Style { font_size: 20.0, ..Style::default() }; + cascade(rect, &css, &mut st, 200.0, 100.0, |_| true); + close(st.font_size, font); + close(st.stroke_width, 3.0 * factor(font)); + let dash = st.dash.as_ref().unwrap(); + assert_eq!(dash.len(), 2); + close(dash[0], 10.0 * factor(font)); + close(dash[1], 2.5 * factor(font)); + close(st.dash_offset, -0.5 * factor(font)); + } + } + + let raw = roxmltree::Document::parse( + r#""#, + ) + .unwrap(); + let rect = raw.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let d = declared(rect, &StyleSheet::default(), |_| true); + assert_eq!(d.get("stroke-width").map(String::as_str), Some("12PT")); + assert_eq!(d.get("font-size").map(String::as_str), Some("2EM")); + let mut st = Style { font_size: 20.0, ..Style::default() }; + cascade(rect, &StyleSheet::default(), &mut st, 200.0, 100.0, |_| true); + assert_eq!((st.font_size, st.stroke_width, st.dash_offset), (2.0, 12.0, 3.0)); + assert_eq!(st.dash, Some(vec![1.0, 2.0])); + assert_eq!(attr_len(rect, "width", 'x', &st, 200.0, 100.0), 12.0); + assert_eq!(length("12FURLONG", 'x', 20.0, 200.0, 100.0), Some(12.0)); + assert_eq!(length_strict("12PT", 100.0), None); + assert_eq!(parse_font_size("2EM", 20.0, 100.0), None); + assert_eq!(parse_dash_array("1PT 2PT", 100.0), None); + + let opaque = roxmltree::Document::parse( + r##""##, + ) + .unwrap(); + let rect = opaque.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let d = declared(rect, &StyleSheet::default(), |_| true); + for (key, value) in [ + ("stroke-width", "var(--Case)"), + ("font-size", "1e999PT"), + ("stroke-dasharray", "NaNPT, 2qU"), + ("stroke-dashoffset", "12FURLONG"), + ("fill", "url(#PaintID)"), + ("font-family", "MiXeD"), + ] { + assert_eq!(d.get(key).map(String::as_str), Some(value)); + } + let opaque_dash = opaque.descendants().find(|n| n.attribute("id") == Some("opaque-dash")).unwrap(); + let d = declared(opaque_dash, &StyleSheet::default(), |_| true); + assert_eq!(d.get("stroke-dasharray").map(String::as_str), Some("var(--Case, 12PT )")); + + // A normal matching rule is charged once, before its values are merged. + let mut css = StyleSheet::default(); + parse_css(".a { stroke-width:12PT; }", &mut css).unwrap(); + css.index(); + let doc = roxmltree::Document::parse( + r#""#, + ) + .unwrap(); + let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let mut charges = Vec::new(); + let d = declared(rect, &css, |cost| { + charges.push(cost); + true + }); + assert_eq!(charges, [1, 1, 1, 1]); + assert_eq!(d.get("stroke-width").map(String::as_str), Some("5px")); } #[test] From bc46729e36a05cd9026f95a14bff452e2d203398 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 21 Nov 2026 16:55:59 -0800 Subject: [PATCH 063/130] svg: normalize CSS declaration length units --- crates/svg/src/doc_style.rs | 51 ++++++++++++++++++++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/doc_style.rs b/crates/svg/src/doc_style.rs index 8f2b0dbb77..1b467c4255 100644 --- a/crates/svg/src/doc_style.rs +++ b/crates/svg/src/doc_style.rs @@ -138,8 +138,51 @@ pub const STYLE_PROPS: &[&str] = &[ "stop-opacity", ]; +/// Normalize only numeric CSS length-unit suffixes in the properties this cascade resolves. +/// Raw SVG attributes and opaque CSS values keep their existing spelling and compatibility. +fn css_length_units(property: &str, value: String) -> String { + if !matches!(property, "font-size" | "stroke-width" | "stroke-dasharray" | "stroke-dashoffset") { + return value; + } + let separator = |c: char| c == ',' || c.is_whitespace(); + let finite = |number: &str| number.parse::().ok().is_some_and(f64::is_finite); + let supported = |unit: &str| matches!(unit.to_ascii_lowercase().as_str(), "px" | "pt" | "pc" | "mm" | "cm" | "in" | "em" | "ex"); + let numeric_length = |token: &str| { + finite(token.strip_suffix('%').unwrap_or(token)) + || token.len().checked_sub(2).is_some_and(|split| token.get(..split).is_some_and(finite) && token.get(split..).is_some_and(supported)) + }; + let eligible = if property == "stroke-dasharray" { + value.split(separator).filter(|token| !token.is_empty()).all(numeric_length) + } else { + numeric_length(value.trim()) + }; + if !eligible { + return value; + } + let mut out = String::with_capacity(value.len()); + for part in value.split_inclusive(separator) { + let token = part.trim_end_matches(separator); + if let Some(split) = token.len().checked_sub(2) + && let (Some(number), Some(unit)) = (token.get(..split), token.get(split..)) + && number.parse::().ok().is_some_and(f64::is_finite) + { + let unit = unit.to_ascii_lowercase(); + if matches!(unit.as_str(), "px" | "pt" | "pc" | "mm" | "cm" | "in" | "em" | "ex") { + out.push_str(number); + out.push_str(&unit); + out.push_str(&part[token.len()..]); + continue; + } + } + out.push_str(part); + } + out +} + /// Collect the declared properties of an element: presentation attributes, then CSS rules /// (by specificity and source order, bounded by `charge_css`), then the inline `style` attribute. +/// Supported numeric length-unit suffixes are normalized only for CSS declarations; raw +/// presentation attributes retain their existing spelling and length compatibility. pub fn declared(n: roxmltree::Node, css: &StyleSheet, charge_css: impl FnMut(usize) -> bool) -> HashMap { let mut out = HashMap::new(); for a in n.attributes() { @@ -147,9 +190,15 @@ pub fn declared(n: roxmltree::Node, css: &StyleSheet, charge_css: impl FnMut(usi out.insert(a.name().to_string(), a.value().to_string()); } } - css.apply(n.tag_name().name(), n.attribute("id"), n.attribute("class").unwrap_or_default(), &mut out, charge_css); + let mut css_values = HashMap::new(); + css.apply(n.tag_name().name(), n.attribute("id"), n.attribute("class").unwrap_or_default(), &mut css_values, charge_css); + out.extend(css_values.into_iter().map(|(k, v)| { + let v = css_length_units(&k, v); + (k, v) + })); if let Some(st) = n.attribute("style") { for (k, v) in declarations(st) { + let v = css_length_units(&k, v); out.insert(k, v); } } From d06b3282415b54b79fa29e829411c0ea08c16a37 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 21 Nov 2026 19:13:32 -0800 Subject: [PATCH 064/130] svg: cover zero-size basic-shape eligibility --- crates/svg/src/paths.rs | 96 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/crates/svg/src/paths.rs b/crates/svg/src/paths.rs index 9bd450594c..21c17af911 100644 --- a/crates/svg/src/paths.rs +++ b/crates/svg/src/paths.rs @@ -1984,6 +1984,102 @@ mod tests { fails("", "invalid XML"); } + #[test] + fn zero_sized_basic_shapes_are_not_imported() { + // Original examples from SVG 1.1 basic-shape zero-size rules, sections 9.2-9.4. + // These shapes are not drawable; a line/path with a zero-area bbox is different. + let mut retained = Vec::new(); + for (label, shape) in [ + ("rect width=0", r#""#), + ("rect height=0", r#""#), + ("circle r=0", r#""#), + ("ellipse rx=0", r#""#), + ("ellipse ry=0", r#""#), + ("default-zero dimensions", r#""#), + ] { + let got = read(&format!(r#"{shape}"#)); + assert!(got.warnings.is_empty()); + if !got.shapes.is_empty() { + retained.push(label); + } + } + + // Keep ordinary positive shapes and exact-zero (not epsilon) eligibility. + let positive = read( + r#""#, + ); + assert_eq!(positive.shapes.len(), 3); + for (i, expected) in + [kurbo::Rect::new(1.0, 2.0, 5.0, 8.0), kurbo::Rect::new(8.0, 8.0, 12.0, 12.0), kurbo::Rect::new(7.0, 8.0, 13.0, 12.0)].iter().enumerate() + { + let actual = bounds(&positive, i); + assert!(near(actual.x0, expected.x0) && near(actual.y0, expected.y0)); + assert!(near(actual.x1, expected.x1) && near(actual.y1, expected.y1)); + } + let near_positive = read(r#""#); + assert_eq!(near_positive.shapes.len(), 3); + for shape in &near_positive.shapes { + let bbox = shape.path.bounding_box(); + assert!(bbox.width() > 0.0 && bbox.height() > 0.0); + } + let square = read(r#""#); + assert_eq!(square.shapes.len(), 1); + assert_eq!(square.shapes[0].path.elements().len(), 5); + assert!(!square.shapes[0].path.elements().iter().any(|e| matches!(e, PathEl::CurveTo(..)))); + + // A vertical/horizontal/point line and a raw path keep their exact geometry. + let lines = read( + r#""#, + ); + assert_eq!(lines.shapes.len(), 4); + for (shape, (from, to)) in lines.shapes.iter().zip([ + (Point::new(2.0, 1.0), Point::new(2.0, 9.0)), + (Point::new(1.0, 2.0), Point::new(9.0, 2.0)), + (Point::new(3.0, 4.0), Point::new(3.0, 4.0)), + (Point::new(5.0, 6.0), Point::new(5.0, 10.0)), + ]) { + assert_eq!(shape.path.elements(), &[PathEl::MoveTo(from), PathEl::LineTo(to)]); + } + + // Referenced geometry goes through the same eligibility rule as direct geometry. + let uses = read( + r##""##, + ); + if uses.shapes.iter().any(|shape| shape.label == r#""#) { + retained.push("use zero rect"); + } + let positive_use = uses.shapes.iter().find(|shape| shape.label == r#""#).unwrap(); + assert_eq!(positive_use.path.bounding_box(), kurbo::Rect::new(2.0, 3.0, 5.0, 7.0)); + + // Invalid ordinary attributes still fail even if another dimension is zero. + for (shape, message) in [ + (r#""#, "width/height cannot be negative"), + (r#""#, "corner radii cannot be negative"), + (r#""#, "invalid ry"), + (r#""#, "radius cannot be negative"), + (r#""#, "invalid cx"), + (r#""#, "radii cannot be negative"), + (r#""#, "invalid cy"), + ] { + let error = import::<()>(&format!("{shape}"), "zero.svg").unwrap_err(); + assert!(error.0.contains(message), "{}", error.0); + } + + let clipped = read( + r##""##, + ); + assert_eq!(clipped.shapes.len(), 1); + assert_eq!(clipped.clips.len(), 1); + assert!(clipped.warnings.is_empty()); + if !clipped.clips[0].pieces.is_empty() { + // Record the baseline defect without sending degenerate pieces to boolean clipping. + retained.push("clip pieces"); + } else { + assert!(clipped.clipped_path(&clipped.shapes[0]).unwrap().elements().is_empty()); + } + assert!(retained.is_empty(), "zero-sized basic shapes retained: {retained:?}"); + } + #[test] fn reads_all_common_basic_shapes() { let got = read( From e144926bc88f602a26d611ea1690bf3958166705 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 21 Nov 2026 19:23:06 -0800 Subject: [PATCH 065/130] svg: omit zero-size basic shapes from path import --- crates/svg/src/paths.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/svg/src/paths.rs b/crates/svg/src/paths.rs index 21c17af911..9b8d0c9662 100644 --- a/crates/svg/src/paths.rs +++ b/crates/svg/src/paths.rs @@ -942,7 +942,7 @@ fn geometry_for(node: roxmltree::Node<'_, '_>, path_name: &str) -> Result

    {}\n", lines.join("
    "))); - let next_start = active_cues.get(i + 1).map(|(n, _)| tick_to_ms(n.start)); + let next_start = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s); if next_start != Some(end_ms) { out.push_str(&format!("

     \n")); } @@ -291,4 +297,27 @@ mod tests { assert_eq!(parsed.cues[0].end, ms_to_tick(101)); assert_eq!(parsed.cues[1].start, ms_to_tick(500)); } + + #[test] + fn adjacent_short_cues_do_not_collide_after_rounding() { + let t100 = ms_to_tick(100); + let t100_1 = Tick(t100.0 + crate::TICKS_PER_MS / 10); + let t200 = ms_to_tick(200); + let doc = Document { + cues: vec![ + Cue { start: t100, end: t100_1, text: "First".into(), ..Default::default() }, + Cue { start: t100_1, end: t200, text: "Second".into(), ..Default::default() }, + ], + ..Default::default() + }; + let encoded = write(&doc); + let back = parse(&encoded).unwrap(); + assert_eq!(back.cues.len(), 2); + assert_eq!(back.cues[0].text, "First"); + assert_eq!(tick_to_ms(back.cues[0].start), 100); + assert_eq!(tick_to_ms(back.cues[0].end), 101); + assert_eq!(back.cues[1].text, "Second"); + assert_eq!(tick_to_ms(back.cues[1].start), 101); + assert_eq!(tick_to_ms(back.cues[1].end), 200); + } } diff --git a/crates/captions/src/subviewer.rs b/crates/captions/src/subviewer.rs index fada039b24..96b97ef6d2 100644 --- a/crates/captions/src/subviewer.rs +++ b/crates/captions/src/subviewer.rs @@ -83,14 +83,7 @@ pub fn parse(text: &str) -> Result { if parse_timing(l).is_some() { break; } - out.extend(split_br(l).into_iter().map(str::trim).filter(|p| !p.is_empty()).map(|p| { - let p = if p.contains('\u{ff0c}') && parse_timing(&p.replacen('\u{ff0c}', ",", 1)).is_some() { - p.replacen('\u{ff0c}', ",", 1) - } else { - p.to_string() - }; - escape_markup(&p) - })); + out.extend(split_br(l).into_iter().map(str::trim).filter(|p| !p.is_empty()).map(escape_markup)); i += 1; } if end <= start || out.is_empty() { @@ -192,7 +185,14 @@ mod tests { assert!(written.contains("00:00:01.00,00:00:02.00")); let parsed = parse(&written).unwrap(); assert_eq!(parsed.cues.len(), 2); - assert_eq!(parsed.cues[0].text, "00:00:01.00,00:00:02.00"); + assert_eq!(parsed.cues[0].text, "00:00:01.00\u{ff0c}00:00:02.00"); assert_eq!(parsed.cues[1].text, "Second cue"); } + + #[test] + fn literal_fullwidth_comma_preserved_on_read() { + let raw = "[INFORMATION]\n[SUBTITLE]\n00:00:01.00,00:00:02.00\n00:00:01.00\u{ff0c}00:00:02.00\n\n"; + let doc = parse(raw).unwrap(); + assert_eq!(doc.cues[0].text, "00:00:01.00\u{ff0c}00:00:02.00"); + } } From a48fb1dd5f2e02c3db8086db0ee88c7faa62235c Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Mon, 23 Nov 2026 21:08:57 +0530 Subject: [PATCH 090/130] craft-raw: add preview fallback and bounded dimensions guard --- crates/raw/src/cr2.rs | 69 +++++++++++++++++++++++++++------ crates/raw/src/cr2/sraw.rs | 24 ++++++++++-- crates/raw/src/dng.rs | 66 +++++++++++++++++++++---------- crates/raw/src/orf.rs | 7 +++- crates/raw/src/preview.rs | 8 +++- crates/raw/src/preview/tests.rs | 43 ++++++++++++++++++++ 6 files changed, 178 insertions(+), 39 deletions(-) diff --git a/crates/raw/src/cr2.rs b/crates/raw/src/cr2.rs index 5f8f8f04f2..3347bcbd41 100644 --- a/crates/raw/src/cr2.rs +++ b/crates/raw/src/cr2.rs @@ -276,20 +276,29 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result = match &slices { Some(s) => { let n = s[0].min(64) as usize; - let mut v = vec![s[1] as usize; n]; - v.push(s[2] as usize); + let (Some(w0), Some(w1)) = (usize::try_from(s[1]).ok(), usize::try_from(s[2]).ok()) else { + return Err(RawError::Corrupt("CR2 slice width exceeds address space".into())); + }; + let mut v = vec![w0; n]; + v.push(w1); v } None => { - let w = (fw as u64).checked_mul(nc as u64).ok_or_else(|| RawError::Corrupt("bad CR2 frame size".into()))?; - vec![w as usize] + let w = (fw as u64) + .checked_mul(nc as u64) + .and_then(|v| usize::try_from(v).ok()) + .ok_or_else(|| RawError::Corrupt("bad CR2 frame size".into()))?; + vec![w] } }; - let width: usize = widths.iter().sum(); + let width: usize = widths.iter().try_fold(0usize, |acc, &w| acc.checked_add(w)).ok_or(RawError::Limit("CR2 slice widths overflow"))?; if width == 0 || total % width != 0 { return Err(RawError::Corrupt(format!("CR2 slices ({width}) do not divide the frame ({total} samples)"))); } let height = total / width; + if width > u32::MAX as usize || height > u32::MAX as usize { + return Err(RawError::Limit("CR2 dimensions exceed u32::MAX")); + } let mut data = Vec::new(); if let Some(frame) = &frame { data = vec![0u16; total]; @@ -297,7 +306,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result Result= 9) { - let (l, tp, r, b) = (si[5] as usize, si[6] as usize, si[7] as usize, si[8] as usize); - if r > l && b > tp && r < width && b < height { - active = Rect::new(l, tp, r - l + 1, b - tp + 1); - // `AspectInfo` is measured from the image area's origin, so it only applies when that area is known. - let image = Rect::new(0, 0, active.width, active.height); - crop = crate::shared::aspect_crop(mn.as_ref().map(|m| &m.ifd), image).unwrap_or(image); + let coords = [si[5], si[6], si[7], si[8]].map(|v| usize::try_from(v).ok()); + if let [Some(l), Some(tp), Some(r), Some(b)] = coords + && r > l + && b > tp + && r < width + && b < height + { + let cw = r - l + 1; + let ch = b - tp + 1; + if cw <= width - l && ch <= height - tp { + active = Rect::new(l, tp, cw, ch); + // `AspectInfo` is measured from the image area's origin, so it only applies when that area is known. + let image = Rect::new(0, 0, active.width, active.height); + crop = crate::shared::aspect_crop(mn.as_ref().map(|m| &m.ifd), image).unwrap_or(image); + } } } + if active.width == 0 || active.height == 0 { + active = Rect::new(0, 0, width, height); + } + if crop.width == 0 || crop.height == 0 { + crop = Rect::new(0, 0, active.width, active.height); + } let color_data = mn.as_ref().and_then(|m| m.ifd.value(COLOR_BALANCE).map(|v| words(v, m.order))); let kelvin_presets = color_data.as_deref().and_then(kelvin_presets_from_color_data); let wb = color_data.as_deref().and_then(wb_from_color_balance).or_else(|| wb_from_wb_info(mn.as_ref()?)); @@ -867,4 +893,23 @@ pub(crate) mod tests { let image = decode_with_note(&[(crate::shared::ASPECT_INFO, 4, aspect)]); assert_eq!((image.active_area, image.crop), (Rect::new(0, 0, 64, 10), Rect::new(0, 0, 64, 10))); } + + /// Active sensor area dimensions that are missing, zero-sized or inverted fall back to the full sensor frame. + #[test] + fn active_area_fallback_on_missing_or_corrupt_sensor_info() { + let (w, h) = (68, 50); + // Zero-sized: right == left + let si_zero: Vec = [68u16, 50, 0, 0, 0, 4, 2, 4, 49].iter().flat_map(|v| v.to_le_bytes()).collect(); + let img = decode_sized_with_note(w, h, &[(SENSOR_INFO, 3, si_zero)]); + assert_eq!((img.active_area, img.crop), (Rect::new(0, 0, w, h), Rect::new(0, 0, w, h))); + + // Inverted borders: right < left + let si_inv: Vec = [68u16, 50, 0, 0, 0, 10, 2, 4, 49].iter().flat_map(|v| v.to_le_bytes()).collect(); + let img = decode_sized_with_note(w, h, &[(SENSOR_INFO, 3, si_inv)]); + assert_eq!((img.active_area, img.crop), (Rect::new(0, 0, w, h), Rect::new(0, 0, w, h))); + + // Without SensorInfo: falls back to full sensor frame + let img = decode_sized_with_note(w, h, &[]); + assert_eq!((img.active_area, img.crop), (Rect::new(0, 0, w, h), Rect::new(0, 0, w, h))); + } } diff --git a/crates/raw/src/cr2/sraw.rs b/crates/raw/src/cr2/sraw.rs index e3c7c74aee..9e2577004f 100644 --- a/crates/raw/src/cr2/sraw.rs +++ b/crates/raw/src/cr2/sraw.rs @@ -89,6 +89,9 @@ impl Layout { } let rows = samples / row; let (width, height) = (row / mcu * 2, rows * vertical); + if width == 0 || height == 0 || width > u32::MAX as usize || height > u32::MAX as usize { + return Err(RawError::Limit("sRAW dimensions exceed u32::MAX")); + } if width.checked_mul(height).and_then(|p| p.checked_mul(3)).is_none_or(|s| s > limits.samples()) { return Err(RawError::Limit("sRAW image too large")); } @@ -347,13 +350,28 @@ pub(super) fn decode(bytes: &[u8], tiff: &Tiff, raw: &Ifd, mode: Mode, limits: & let mn = tiff.exif().and_then(|e| e.get(t::MAKER_NOTE)).and_then(|e| makernote::parse_makernote(bytes, e.offset, e.count() as u64, tiff.order, &make)); let (w, h) = (layout.width, layout.height); + if w > u32::MAX as usize || h > u32::MAX as usize { + return Err(RawError::Limit("sRAW dimensions exceed u32::MAX")); + } let mut active = Rect::new(0, 0, w, h); if let Some(si) = mn.as_ref().and_then(|m| m.ifd.u64s(SENSOR_INFO)).filter(|v| v.len() >= 9) { - let (l, tp, r, b) = (si[5] as usize, si[6] as usize, si[7] as usize, si[8] as usize); - if r > l && b > tp && r < w && b < h { - active = Rect::new(l, tp, r - l + 1, b - tp + 1); + let coords = [si[5], si[6], si[7], si[8]].map(|v| usize::try_from(v).ok()); + if let [Some(l), Some(tp), Some(r), Some(b)] = coords + && r > l + && b > tp + && r < w + && b < h + { + let cw = r - l + 1; + let ch = b - tp + 1; + if cw <= w - l && ch <= h - tp { + active = Rect::new(l, tp, cw, ch); + } } } + if active.width == 0 || active.height == 0 { + active = Rect::new(0, 0, w, h); + } let colour_data = mn.as_ref().and_then(|m| m.ifd.value(COLOR_BALANCE).map(|v| words(v, m.order))); let black_counts = colour_data.as_deref().and_then(colour_data_black); // 1.0 = a CFA CR2 of the same body at full 14-bit scale; see LUMA_GAIN diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rs index 9589f5d4d0..7bf42b43f4 100644 --- a/crates/raw/src/dng.rs +++ b/crates/raw/src/dng.rs @@ -371,30 +371,18 @@ fn decode_ifd(bytes: &[u8], tiff: &Tiff, pixels: &Ifd, main: &Ifd, mode: Mode, f let (full_w, full_h) = if std::ptr::eq(pixels, raw) { (w, h) } else { - (raw.u64(t::IMAGE_WIDTH).unwrap_or(0) as usize, raw.u64(t::IMAGE_LENGTH).unwrap_or(0) as usize) + ( + raw.u64(t::IMAGE_WIDTH).and_then(|v| usize::try_from(v).ok()).unwrap_or(0), + raw.u64(t::IMAGE_LENGTH).and_then(|v| usize::try_from(v).ok()).unwrap_or(0), + ) }; if full_w == 0 || full_h == 0 { return Err(RawError::Corrupt("raw image IFD without a size".into())); } - let active_area = match raw.u64s(t::ACTIVE_AREA).as_deref() { - Some([top, left, bottom, right]) if bottom > top && right > left && (*bottom as usize) <= full_h && (*right as usize) <= full_w => { - Rect::new(*left as usize, *top as usize, (*right - *left) as usize, (*bottom - *top) as usize) - } - _ => Rect::new(0, 0, full_w, full_h), - }; - let (crop, default_crop_adjusted) = default_crop(raw, active_area, full_w, full_h); - let (active_area, crop) = if (full_w, full_h) == (w, h) { - (active_area, crop) - } else { - let (sx, sy) = (w as f64 / full_w as f64, h as f64 / full_h as f64); - let scale = |r: Rect| { - let (x, y) = ((r.x as f64 * sx).round() as usize, (r.y as f64 * sy).round() as usize); - let (x1, y1) = (((r.x + r.width) as f64 * sx).round() as usize, ((r.y + r.height) as f64 * sy).round() as usize); - Rect::new(x, y, x1.saturating_sub(x).max(1), y1.saturating_sub(y).max(1)) - }; - let area = scale(active_area).clipped(w, h); - (area, scale(crop).clipped(area.width, area.height)) - }; + if w > u32::MAX as usize || h > u32::MAX as usize || full_w > u32::MAX as usize || full_h > u32::MAX as usize { + return Err(RawError::Limit("DNG dimensions exceed u32::MAX")); + } + let (active_area, crop, default_crop_adjusted) = active_area_and_crop(raw, w, h, full_w, full_h); let mut assumed_cfa = false; let cfa = if info.photometric == photometric::CFA { @@ -557,6 +545,44 @@ fn extend_understated_strip(bytes: &[u8], info: &mut ImageInfo, raw: &Ifd) { } } +fn active_area_and_crop(raw: &Ifd, w: usize, h: usize, full_w: usize, full_h: usize) -> (Rect, Rect, bool) { + let active_area = match raw.u64s(t::ACTIVE_AREA).as_deref() { + Some(&[top, left, bottom, right]) => { + let coords = [top, left, bottom, right].map(|v| usize::try_from(v).ok()); + match coords { + [Some(top), Some(left), Some(bottom), Some(right)] + if bottom > top && right > left && top <= full_h && left <= full_w && bottom <= full_h && right <= full_w => + { + Rect::new(left, top, right - left, bottom - top) + } + _ => Rect::new(0, 0, full_w, full_h), + } + } + _ => Rect::new(0, 0, full_w, full_h), + }; + let active_area = if active_area.width == 0 || active_area.height == 0 { Rect::new(0, 0, full_w, full_h) } else { active_area }; + let (crop, default_crop_adjusted) = default_crop(raw, active_area, full_w, full_h); + if (full_w, full_h) == (w, h) { + (active_area, crop, default_crop_adjusted) + } else { + let (sx, sy) = (w as f64 / full_w as f64, h as f64 / full_h as f64); + let scale = |r: Rect| { + let (x, y) = ((r.x as f64 * sx).round() as usize, (r.y as f64 * sy).round() as usize); + let (x1, y1) = (((r.x + r.width) as f64 * sx).round() as usize, ((r.y + r.height) as f64 * sy).round() as usize); + Rect::new(x, y, x1.saturating_sub(x).max(1), y1.saturating_sub(y).max(1)) + }; + let mut area = scale(active_area).clipped(w, h); + if area.width == 0 || area.height == 0 { + area = Rect::new(0, 0, w, h); + } + let mut c = scale(crop).clipped(area.width, area.height); + if c.width == 0 || c.height == 0 { + c = Rect::new(0, 0, area.width, area.height); + } + (area, c, default_crop_adjusted) + } +} + /// The default crop is relative to ActiveArea. DNG 1.7.1 defines independent /// defaults: origin (0, 0), size ImageWidth/ImageLength. An unusable optional crop /// preserves the entire active image. Valid partly overlapping rectangles retain the diff --git a/crates/raw/src/orf.rs b/crates/raw/src/orf.rs index d1eccceb99..857ca35a8a 100644 --- a/crates/raw/src/orf.rs +++ b/crates/raw/src/orf.rs @@ -206,6 +206,9 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result u32::MAX as usize || h > u32::MAX as usize { + return Err(RawError::Limit("ORF dimensions exceed u32::MAX")); + } let n = w.checked_mul(h).filter(|n| *n > 0 && *n <= limits.samples()).ok_or(RawError::Limit("image too large"))?; // A partial TIFF directory is damage, not evidence of an unsupported compressed layout. // Do not infer packing from an absent strip table or from clipped sensor bytes. @@ -233,7 +236,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result 0).ok_or_else(|| RawError::Corrupt("bad ORF row stride".into()))?; if src.len() as u64 != total || src.len() / stride != h { return Err(RawError::Corrupt("ORF strip shorter than its rows".into())); } @@ -257,7 +260,7 @@ pub(crate) fn decode(bytes: &[u8], mode: Mode, limits: &Limits) -> Result 0).ok_or_else(|| RawError::Corrupt("bad ORF row stride".into()))?; let mut d = vec![0u16; n]; d.par_chunks_mut(w).enumerate().for_each(|(y, row)| unpack_row_le32_msb(&src[y * stride..(y + 1) * stride], 12, row)); d diff --git a/crates/raw/src/preview.rs b/crates/raw/src/preview.rs index 00b36965ce..2321972178 100644 --- a/crates/raw/src/preview.rs +++ b/crates/raw/src/preview.rs @@ -410,9 +410,13 @@ fn preview_covering(bytes: &[u8], min_edge: Option, jpeg_only: bool) -> Opt .or(largest) .map(|s| if is_jxl(s) { s.to_vec() } else { trim_eoi(s).to_vec() }); // a TIFF raw whose preview no tag points to: one we can't decode (Leaf MOS), or Epson ERF (in its maker note) - // ORF capability must not remove the scan fallback for unsupported modes and damaged preview pointers. + // Container capability must not remove the scan fallback for unsupported modes and damaged preview pointers. let best = best.or_else(|| { - format.filter(|f| !f.is_supported() || matches!(f, crate::RawFormat::Erf | crate::RawFormat::Orf)).and_then(|_| scan_for_jpeg(bytes)) + format + .filter(|f| { + !f.is_supported() || matches!(f, crate::RawFormat::Erf | crate::RawFormat::Orf | crate::RawFormat::Cr2 | crate::RawFormat::Dng) + }) + .and_then(|_| scan_for_jpeg(bytes)) }); // Hasselblad 3FR / FFF carry no JPEG, only uncompressed RGB images: one wrapped as a baseline TIFF #[cfg(feature = "hasselblad")] diff --git a/crates/raw/src/preview/tests.rs b/crates/raw/src/preview/tests.rs index be0d6fbd75..0973ae5258 100644 --- a/crates/raw/src/preview/tests.rs +++ b/crates/raw/src/preview/tests.rs @@ -974,3 +974,46 @@ fn supported_orf_keeps_unreferenced_jpeg_fallback() { assert_eq!(embedded_preview(&file).as_deref(), Some(jpeg.as_slice())); assert_eq!(embedded_preview_covering(&file, 1).as_deref(), Some(jpeg.as_slice())); } + +#[cfg(feature = "cr2")] +/// CR2 capability reporting must not disable preview scanning when preview tags are missing or damaged. +#[test] +fn supported_cr2_keeps_unreferenced_jpeg_fallback() { + let mut ifd = IfdBuilder::new(); + ifd.set(t::IMAGE_WIDTH, Value::Long(vec![64])); + ifd.set(t::IMAGE_LENGTH, Value::Long(vec![64])); + ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![16])); + ifd.set(t::COMPRESSION, Value::Short(vec![1])); + let raw_tiff = TiffWriter::default().write(&[ifd]).unwrap(); + let mut file = Vec::new(); + file.extend_from_slice(b"II*\0\x10\0\0\0CR\x02\0\0\0\0\0"); + file.extend_from_slice(&raw_tiff[8..]); + let jpeg = scan_jpeg(3, 900); + file.extend_from_slice(&jpeg); + let format = crate::probe(&file).unwrap(); + assert_eq!(format, crate::RawFormat::Cr2); + assert!(format.is_supported()); + assert_eq!(embedded_preview(&file).as_deref(), Some(jpeg.as_slice())); + assert_eq!(embedded_preview_covering(&file, 1).as_deref(), Some(jpeg.as_slice())); +} + +#[cfg(feature = "dng")] +/// DNG capability reporting must not disable preview scanning when preview tags are missing or damaged. +#[test] +fn supported_dng_keeps_unreferenced_jpeg_fallback() { + let mut ifd = IfdBuilder::new(); + ifd.set(t::DNG_VERSION, Value::Byte(vec![1, 4, 0, 0])); + ifd.set(t::IMAGE_WIDTH, Value::Long(vec![64])); + ifd.set(t::IMAGE_LENGTH, Value::Long(vec![64])); + ifd.set(t::BITS_PER_SAMPLE, Value::Short(vec![16])); + ifd.set(t::COMPRESSION, Value::Short(vec![1])); + ifd.set_image(ImageData::Strips { rows_per_strip: 64, strips: vec![vec![0; 16]] }); + let mut file = TiffWriter::default().write(&[ifd]).unwrap(); + let jpeg = scan_jpeg(3, 900); + file.extend_from_slice(&jpeg); + let format = crate::probe(&file).unwrap(); + assert_eq!(format, crate::RawFormat::Dng); + assert!(format.is_supported()); + assert_eq!(embedded_preview(&file).as_deref(), Some(jpeg.as_slice())); + assert_eq!(embedded_preview_covering(&file, 1).as_deref(), Some(jpeg.as_slice())); +} From 0a394e3eaf4f7ec9d83f380775f589642e9d5ef7 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Mon, 23 Nov 2026 21:09:19 +0530 Subject: [PATCH 091/130] craft-metafile: distinguish opcode budget exhaustion from premature EOF in PICT reader --- crates/metafile/src/lib.rs | 4 +++- crates/metafile/src/pict.rs | 26 +++++++++++++++++---- crates/metafile/src/tests/limits.rs | 35 +++++++++++++++++++++++++++++ crates/metafile/tests/it/pict.rs | 7 +++++- 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index a8732562a9..45e77b483c 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -48,7 +48,7 @@ use bytes::Bytes; use canvas::Raw; pub use eof::ends_early; use geom::{Op, P}; -pub use pict::{is_pict, parse as parse_pict}; +pub use pict::{TruncationReason, is_pict, parse as parse_pict}; pub use place::{MAX_BITMAP_SIDE, PlacedClip, PlacedItem, bez_path, crop_window}; pub use size::size; pub use text::{Font, HAlign, SYMBOL_CHARSET, Text, VAlign}; @@ -86,6 +86,8 @@ pub struct Picture { /// the picture holds what came before. The limits that cut one path, string, region or dash /// pattern short do not set it. pub truncated: bool, + /// Granular reason why decoding halted early, distinguishing premature EOF from safety budget exhaustion. + pub truncation_reason: Option, /// Images the file asks to draw that the reader did not read: bitmaps past a size, item, byte or /// decode limit or in a form the reader cannot decode, EMF+ metafile images that do not parse or /// are nested deeper than 3 levels, and pattern or texture brushes whose bitmap was not read, a diff --git a/crates/metafile/src/pict.rs b/crates/metafile/src/pict.rs index 41cf6653be..341c01ca67 100644 --- a/crates/metafile/src/pict.rs +++ b/crates/metafile/src/pict.rs @@ -16,10 +16,17 @@ use crate::geom::Op; use crate::text::{Font, HAlign, Text, VAlign}; use crate::{Cap, Error, Frame, Join, LineStyle, MAX_BYTES, MAX_ITEMS, MAX_PIXELS, Picture, clip, dib, f}; +/// Why a picture's decode stopped early. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TruncationReason { + PrematureEof, + OpcodeLimitExceeded, +} + /// The application data before the picture in a PICT file. const FILE_HEADER: usize = 512; /// Most opcodes one picture plays (a small file can't keep the reader busy for minutes). -const MAX_OPS: usize = 1 << 22; +pub const MAX_OPS: usize = 1 << 22; /// Most rectangles one region breaks into. const MAX_RECTS: usize = 1 << 16; /// Steps the regions of one picture may take to read (each inversion point and band costs some). @@ -624,6 +631,7 @@ struct Pict { pending_pen: Option<([u8; 3], f64)>, skipped_records: u32, truncated: bool, + truncation_reason: Option, dropped_images: u32, ignored_clips: u32, unplayed_raster_ops: u32, @@ -661,6 +669,7 @@ impl Pict { pending_pen: None, skipped_records: 0, truncated: false, + truncation_reason: None, dropped_images: 0, ignored_clips: 0, unplayed_raster_ops: 0, @@ -1448,24 +1457,32 @@ pub(crate) fn parse_nested(bytes: &[u8]) -> Result { let h = find(bytes).ok_or(Error::NotPict)?; let mut q = Pict::new(h.frame); let mut r = Be::new(bytes, h.ops); - let mut stopped_early = true; + let mut reached_end = false; + let mut reason = None; for _ in 0..MAX_OPS { if h.v2 && r.pos % 2 == 1 && r.skip(1).is_none() { + reason = Some(TruncationReason::PrematureEof); break; } let Some(op) = (if h.v2 { r.u16() } else { r.u8().map(u16::from) }) else { + reason = Some(TruncationReason::PrematureEof); break; }; if op == 0x00FF { - stopped_early = false; + reached_end = true; break; } if q.op(op, &mut r).is_none() { + reason = Some(TruncationReason::PrematureEof); break; } } - if stopped_early { + if !reached_end && reason.is_none() { + reason = Some(TruncationReason::OpcodeLimitExceeded); + } + if reason.is_some() { q.truncated = true; + q.truncation_reason = reason; } q.flush(); let pic = @@ -1473,6 +1490,7 @@ pub(crate) fn parse_nested(bytes: &[u8]) -> Result { Ok(Picture { skipped_records: q.skipped_records.saturating_add(pic.skipped_records), truncated: q.truncated || pic.truncated, + truncation_reason: q.truncation_reason.or(pic.truncation_reason), dropped_images: q.dropped_images.saturating_add(pic.dropped_images), ignored_clips: q.ignored_clips.saturating_add(pic.ignored_clips), unplayed_raster_ops: q.unplayed_raster_ops.saturating_add(pic.unplayed_raster_ops), diff --git a/crates/metafile/src/tests/limits.rs b/crates/metafile/src/tests/limits.rs index 6b88c4284e..741a8c5537 100644 --- a/crates/metafile/src/tests/limits.rs +++ b/crates/metafile/src/tests/limits.rs @@ -312,3 +312,38 @@ fn masking_a_bitmap_to_a_clip_stops_at_the_work_cap() { assert!(side(fits)); assert!(!side(fits + 2)); } + +#[test] +fn pict_truncated_halfway_through_rectangle_reports_premature_eof() { + let mut pict = vec![0xA5; 512]; + pict.extend([0, 0]); + pict.extend([0, 0, 0, 0, 0, 10, 0, 10]); + pict.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + pict.extend([-1i16, 0].iter().flat_map(|x| x.to_be_bytes())); + pict.extend([0; 20]); + // Truncated halfway through a rectangle opcode (paintRect 0x0031): + // Rectangle opcode expects 8 bytes [top, left, bottom, right], but only 4 bytes are provided. + pict.extend([0x00, 0x31]); + pict.extend([0, 0, 0, 5]); + + let p = crate::parse(&pict).unwrap(); + assert!(p.truncated); + assert_eq!(p.truncation_reason, Some(crate::TruncationReason::PrematureEof)); +} + +#[test] +fn pict_records_exceeding_max_opcode_budget_reports_opcode_limit_exceeded() { + let mut pict = vec![0xA5; 512]; + pict.extend([0, 0]); + pict.extend([0, 0, 0, 0, 0, 10, 0, 10]); + pict.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + pict.extend([-1i16, 0].iter().flat_map(|x| x.to_be_bytes())); + pict.extend([0; 20]); + // Valid records exceeding MAX_OPS budget (e.g. NOP opcodes 0x0000): + pict.resize(pict.len() + 2 * (crate::pict::MAX_OPS + 1), 0); + pict.extend([0x00, 0xFF]); + + let p = crate::parse(&pict).unwrap(); + assert!(p.truncated); + assert_eq!(p.truncation_reason, Some(crate::TruncationReason::OpcodeLimitExceeded)); +} diff --git a/crates/metafile/tests/it/pict.rs b/crates/metafile/tests/it/pict.rs index dcfb2822c9..99e2729598 100644 --- a/crates/metafile/tests/it/pict.rs +++ b/crates/metafile/tests/it/pict.rs @@ -4,7 +4,7 @@ use kurbo::{Rect, Shape}; -use craft_metafile::{Item, bez_path, parse_pict}; +use craft_metafile::{Item, TruncationReason, bez_path, parse_pict}; /// Big-endian words. fn be(v: &[i16]) -> Vec { @@ -355,13 +355,17 @@ fn pictures_cut_short_keep_what_came_before() { let p = parse_pict(cut).unwrap(); assert_eq!(p.items.len(), 1); assert!(p.truncated); + assert_eq!(p.truncation_reason, Some(TruncationReason::PrematureEof)); let p = parse_pict(&v2([0, 0, 50, 50], &[(0x31, rect(0, 0, 10, 10)), (0xA1, be(&[100, 5000]))])).unwrap(); assert_eq!(p.items.len(), 1); assert!(p.truncated); + assert_eq!(p.truncation_reason, Some(TruncationReason::PrematureEof)); let p = parse_pict(&v2([0, 0, 50, 50], &[(0xA0, be(&[100]))])).unwrap(); assert!(p.items.is_empty()); + assert!(!p.truncated); + assert_eq!(p.truncation_reason, None); } #[test] @@ -389,6 +393,7 @@ fn a_picture_that_never_ends_stops_at_the_opcode_limit() { let p = parse_pict(&b).unwrap(); assert_eq!(p.items.len(), 1); assert!(p.truncated); + assert_eq!(p.truncation_reason, Some(TruncationReason::OpcodeLimitExceeded)); } #[test] From c59c4c7d3a37827745125645925683e856299f6a Mon Sep 17 00:00:00 2001 From: el-j Date: Mon, 23 Nov 2026 16:43:04 +0100 Subject: [PATCH 092/130] Reject unsupported bit depths in SMPTE 302M header frame_bytes --- crates/audio/src/s302m.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/audio/src/s302m.rs b/crates/audio/src/s302m.rs index f5e6cd790f..205741c529 100644 --- a/crates/audio/src/s302m.rs +++ b/crates/audio/src/s302m.rs @@ -51,13 +51,13 @@ pub struct Header { } impl Header { - /// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` overflow. + /// Bytes of one frame (one sample of every channel), or 0 if `channels` or `bits` are unsupported or overflow. pub fn frame_bytes(&self) -> usize { let pair_bytes = match self.bits { 16 => 5, 20 => 6, 24 => 7, - b => ((b as usize).saturating_add(4) * 2) / 8, + _ => return 0, }; (self.channels / 2).checked_mul(pair_bytes).unwrap_or(0) } @@ -242,4 +242,16 @@ mod tests { let h = Header { channels: usize::MAX, channel_id: 0, bits: 24, alignment: 0, audio_bytes: 0 }; assert_eq!(h.frame_bytes(), 0); } + + #[test] + fn header_frame_bytes_rejects_unsupported_depth() { + let h_max = Header { channels: 2, channel_id: 0, bits: u32::MAX, alignment: 0, audio_bytes: 0 }; + assert_eq!(h_max.frame_bytes(), 0); + + let h_unsupported = Header { channels: 2, channel_id: 0, bits: 18, alignment: 0, audio_bytes: 0 }; + assert_eq!(h_unsupported.frame_bytes(), 0); + + let h_zero = Header { channels: 2, channel_id: 0, bits: 0, alignment: 0, audio_bytes: 0 }; + assert_eq!(h_zero.frame_bytes(), 0); + } } From 2d62bcaaa6d4aed95917e0ee0182f4473b5f156b Mon Sep 17 00:00:00 2001 From: el-j Date: Mon, 23 Nov 2026 16:44:40 +0100 Subject: [PATCH 093/130] Remove yuv2 from Yuyv layout documentation aliases --- crates/video/src/rawvideo/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/video/src/rawvideo/mod.rs b/crates/video/src/rawvideo/mod.rs index 8402df8eae..e8d9088377 100644 --- a/crates/video/src/rawvideo/mod.rs +++ b/crates/video/src/rawvideo/mod.rs @@ -4,7 +4,7 @@ //! | [`Layout`] | Samples | Packing | //! |---|---|---| //! | `Uyvy` | 8-bit 4:2:2 | `U Y0 V Y1` per two pixels (QuickTime `2vuy`, `UYVY`) | -//! | `Yuyv` | 8-bit 4:2:2 | `Y0 U Y1 V` (`YUY2`, `yuv2`, `YUYV`) | +//! | `Yuyv` | 8-bit 4:2:2 | `Y0 U Y1 V` (`YUY2`, `YUYV`) | //! | `Yvyu` | 8-bit 4:2:2 | `Y0 V Y1 U` (`YVYU`) | //! | `V210` | 10-bit 4:2:2 | six pixels in four little-endian 32-bit words (`Cb0 Y0 Cr0`, `Y1 Cb1 Y2`, `Cr1 Y3 Cb2`, `Y4 Cr2 Y5`, ten bits each, the low field first); rows padded to a multiple of 128 bytes | //! | `R210` | 10-bit RGB | one big-endian 32-bit word per pixel, `R` in bits 29-20, `G` in 19-10, `B` in 9-0; rows padded to a multiple of 256 bytes | From 7902882094354ffe69e909d8747a8bfa17fefbc2 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Mon, 23 Nov 2026 21:20:47 +0530 Subject: [PATCH 094/130] craft-metafile: assign PrematureEof only when reads fail on EOF --- crates/metafile/src/pict.rs | 23 ++++++++++++++++++----- crates/metafile/src/tests/limits.rs | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/crates/metafile/src/pict.rs b/crates/metafile/src/pict.rs index 341c01ca67..58ee8e8507 100644 --- a/crates/metafile/src/pict.rs +++ b/crates/metafile/src/pict.rs @@ -50,15 +50,22 @@ const FLAT: u32 = 0x200; struct Be<'a> { data: &'a [u8], pos: usize, + eof: bool, } impl<'a> Be<'a> { fn new(data: &'a [u8], pos: usize) -> Self { - Self { data, pos } + Self { data, pos, eof: false } } fn bytes(&mut self, n: usize) -> Option<&'a [u8]> { let end = self.pos.checked_add(n)?; - let b = self.data.get(self.pos..end)?; + let b = match self.data.get(self.pos..end) { + Some(b) => b, + None => { + self.eof = true; + return None; + } + }; self.pos = end; Some(b) } @@ -72,6 +79,7 @@ impl<'a> Be<'a> { self.pos = end; Some(()) } else { + self.eof = true; None } } @@ -1458,6 +1466,7 @@ pub(crate) fn parse_nested(bytes: &[u8]) -> Result { let mut q = Pict::new(h.frame); let mut r = Be::new(bytes, h.ops); let mut reached_end = false; + let mut halted_for_record_error = false; let mut reason = None; for _ in 0..MAX_OPS { if h.v2 && r.pos % 2 == 1 && r.skip(1).is_none() { @@ -1473,14 +1482,18 @@ pub(crate) fn parse_nested(bytes: &[u8]) -> Result { break; } if q.op(op, &mut r).is_none() { - reason = Some(TruncationReason::PrematureEof); + if r.eof { + reason = Some(TruncationReason::PrematureEof); + } else { + halted_for_record_error = true; + } break; } } - if !reached_end && reason.is_none() { + if !reached_end && !halted_for_record_error && reason.is_none() { reason = Some(TruncationReason::OpcodeLimitExceeded); } - if reason.is_some() { + if !reached_end { q.truncated = true; q.truncation_reason = reason; } diff --git a/crates/metafile/src/tests/limits.rs b/crates/metafile/src/tests/limits.rs index 741a8c5537..258b206771 100644 --- a/crates/metafile/src/tests/limits.rs +++ b/crates/metafile/src/tests/limits.rs @@ -347,3 +347,26 @@ fn pict_records_exceeding_max_opcode_budget_reports_opcode_limit_exceeded() { assert!(p.truncated); assert_eq!(p.truncation_reason, Some(crate::TruncationReason::OpcodeLimitExceeded)); } + +#[test] +fn pict_invalid_zero_height_bitmap_does_not_report_premature_eof() { + let mut pict = vec![0xA5; 512]; + pict.extend([0, 0]); + pict.extend([0, 0, 0, 0, 0, 10, 0, 10]); + pict.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + pict.extend([-1i16, 0].iter().flat_map(|x| x.to_be_bytes())); + pict.extend([0; 20]); + // Complete BitsRect (0x0090) with zero-height bounds, followed by EndPic (0x00FF): + pict.extend([0x00, 0x90]); + pict.extend([0x00, 0x02]); // row_bytes + pict.extend([0, 0, 0, 0, 0, 0, 0, 10]); // bounds (top=0, left=0, bottom=0, right=10; height=0) + pict.extend([0, 0, 0, 0, 0, 0, 0, 10]); // src + pict.extend([0, 0, 0, 0, 0, 0, 0, 10]); // dst + pict.extend([0x00, 0x00]); // mode + pict.extend([0x00, 0xFF]); // EndPic + + let p = crate::parse(&pict).unwrap(); + assert!(p.truncated); + assert_ne!(p.truncation_reason, Some(crate::TruncationReason::PrematureEof)); + assert_eq!(p.truncation_reason, None); +} From 96833a150abb4eaa3b48297954984c1c5707e6bd Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Mon, 23 Nov 2026 21:31:15 +0530 Subject: [PATCH 095/130] craft-raw: reset crop to replacement area on DNG active area fallback --- crates/raw/src/dng.rs | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/crates/raw/src/dng.rs b/crates/raw/src/dng.rs index 7bf42b43f4..409462ccdc 100644 --- a/crates/raw/src/dng.rs +++ b/crates/raw/src/dng.rs @@ -561,7 +561,7 @@ fn active_area_and_crop(raw: &Ifd, w: usize, h: usize, full_w: usize, full_h: us _ => Rect::new(0, 0, full_w, full_h), }; let active_area = if active_area.width == 0 || active_area.height == 0 { Rect::new(0, 0, full_w, full_h) } else { active_area }; - let (crop, default_crop_adjusted) = default_crop(raw, active_area, full_w, full_h); + let (crop, mut default_crop_adjusted) = default_crop(raw, active_area, full_w, full_h); if (full_w, full_h) == (w, h) { (active_area, crop, default_crop_adjusted) } else { @@ -572,13 +572,18 @@ fn active_area_and_crop(raw: &Ifd, w: usize, h: usize, full_w: usize, full_h: us Rect::new(x, y, x1.saturating_sub(x).max(1), y1.saturating_sub(y).max(1)) }; let mut area = scale(active_area).clipped(w, h); - if area.width == 0 || area.height == 0 { + let area_fell_back = area.width == 0 || area.height == 0; + if area_fell_back { area = Rect::new(0, 0, w, h); } - let mut c = scale(crop).clipped(area.width, area.height); + let scaled_crop = scale(crop); + let mut c = if area_fell_back { Rect::new(0, 0, area.width, area.height) } else { scaled_crop.clipped(area.width, area.height) }; if c.width == 0 || c.height == 0 { c = Rect::new(0, 0, area.width, area.height); } + if (raw.contains(t::DEFAULT_CROP_ORIGIN) || raw.contains(t::DEFAULT_CROP_SIZE)) && (area_fell_back || c != scaled_crop) { + default_crop_adjusted = true; + } (area, c, default_crop_adjusted) } } @@ -746,6 +751,28 @@ mod tests { let mut hostile = RawData::U16(image); assert!(deinterleave(&mut hostile, 8, 6, 1, 1 << 20, 1).is_err()); } + + #[test] + fn scaled_active_area_fallback_resets_crop_to_full_replacement_area() { + use craft_tiff::Entry; + let raw = Ifd { entries: vec![Entry { tag: t::ACTIVE_AREA, offset: 0, value: Value::Long(vec![63, 63, 64, 64]) }], ..Default::default() }; + let (area, crop, adjusted) = active_area_and_crop(&raw, 8, 8, 64, 64); + assert_eq!(area, Rect::new(0, 0, 8, 8)); + assert_eq!(crop, Rect::new(0, 0, 8, 8)); + assert!(!adjusted); + + let mut entries = vec![ + Entry { tag: t::ACTIVE_AREA, offset: 0, value: Value::Long(vec![63, 63, 64, 64]) }, + Entry { tag: t::DEFAULT_CROP_ORIGIN, offset: 0, value: Value::Rational(vec![(0, 1), (0, 1)]) }, + Entry { tag: t::DEFAULT_CROP_SIZE, offset: 0, value: Value::Rational(vec![(1, 1), (1, 1)]) }, + ]; + entries.sort_by_key(|e| e.tag); + let explicit_crop_raw = Ifd { entries, ..Default::default() }; + let (area, crop, adjusted) = active_area_and_crop(&explicit_crop_raw, 8, 8, 64, 64); + assert_eq!(area, Rect::new(0, 0, 8, 8)); + assert_eq!(crop, Rect::new(0, 0, 8, 8)); + assert!(adjusted); + } } #[cfg(all(test, feature = "hasselblad"))] From 44238ee2a2eb546727d2dbaffd3f60236cca43e4 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Mon, 23 Nov 2026 21:43:55 +0530 Subject: [PATCH 096/130] craft-metafile: halt with PrematureEof when record parsing encounters EOF --- crates/metafile/src/pict.rs | 4 ++++ crates/metafile/src/tests/limits.rs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/crates/metafile/src/pict.rs b/crates/metafile/src/pict.rs index 58ee8e8507..e3b8ea04a9 100644 --- a/crates/metafile/src/pict.rs +++ b/crates/metafile/src/pict.rs @@ -1489,6 +1489,10 @@ pub(crate) fn parse_nested(bytes: &[u8]) -> Result { } break; } + if r.eof { + reason = Some(TruncationReason::PrematureEof); + break; + } } if !reached_end && !halted_for_record_error && reason.is_none() { reason = Some(TruncationReason::OpcodeLimitExceeded); diff --git a/crates/metafile/src/tests/limits.rs b/crates/metafile/src/tests/limits.rs index 258b206771..059dba415a 100644 --- a/crates/metafile/src/tests/limits.rs +++ b/crates/metafile/src/tests/limits.rs @@ -370,3 +370,21 @@ fn pict_invalid_zero_height_bitmap_does_not_report_premature_eof() { assert_ne!(p.truncation_reason, Some(crate::TruncationReason::PrematureEof)); assert_eq!(p.truncation_reason, None); } + +#[test] +fn pict_truncated_region_payload_stops_with_premature_eof() { + let mut pict = vec![0xA5; 512]; + pict.extend([0, 0]); + pict.extend([0, 0, 0, 0, 0, 10, 0, 10]); + pict.extend([0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00]); + pict.extend([-1i16, 0].iter().flat_map(|x| x.to_be_bytes())); + pict.extend([0; 20]); + // Opcode 0x0080 (frameRgn) claiming 16 bytes for region, followed by EOF before body finishes: + pict.extend([0x00, 0x80]); + pict.extend([0x00, 0x10]); + pict.extend([0x00, 0xFF]); + + let p = crate::parse(&pict).unwrap(); + assert!(p.truncated); + assert_eq!(p.truncation_reason, Some(crate::TruncationReason::PrematureEof)); +} From 0d2bb58a55a275c63e616eb3614a78ef68393da0 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 23 Nov 2026 09:06:43 -0800 Subject: [PATCH 097/130] test(sketch): pin production truncation with sparse points --- crates/sketch/src/rest/tests.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/sketch/src/rest/tests.rs b/crates/sketch/src/rest/tests.rs index e080f3df1e..42fcdb231b 100644 --- a/crates/sketch/src/rest/tests.rs +++ b/crates/sketch/src/rest/tests.rs @@ -207,6 +207,18 @@ fn a_path_past_the_point_cap_is_cut() { assert!(out.warnings.iter().any(|w| w == "paths with more than 100000 points were cut"), "{:?}", out.warnings); assert!(out.warnings.iter().any(|w| w == "path points that couldn't be read were skipped"), "{:?}", out.warnings); assert!(out.networks.is_empty()); + + // Pin truncation at the ordinary entry point's production boundary with only three readable points. + let mut points = vec![Value::Null; 100_001]; + points[0] = json!({"point": "{0, 0}"}); + points[99_999] = json!({"point": "{0.5, 0.5}"}); + points[100_000] = json!({"point": "{1, 1}"}); + let mut path = shape_path("L", 0.0, 0.0, 10.0, 10.0, &[], false); + path["points"] = Value::Array(points); + let z = sketch_zip("50.2", 103, document(&["P"]), &[page("P", "P", vec![path])], &[]); + let out = map(&z); + assert_eq!(out.networks[0].as_ref().map(|n| n.vertices.len()), Some(2)); + assert!(out.warnings.iter().any(|w| w == "paths with more than 100000 points were cut"), "{:?}", out.warnings); } #[test] From f3020eb43265afcd0516171a92f6b7b4c1a6d957 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 23 Nov 2026 09:08:12 -0800 Subject: [PATCH 098/130] text: clarify embedding flag compatibility contract --- crates/text/src/embed.rs | 27 ++++++++++++++++++--------- crates/text/src/lib.rs | 4 +++- 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/crates/text/src/embed.rs b/crates/text/src/embed.rs index 8291737f1b..9599b78f55 100644 --- a/crates/text/src/embed.rs +++ b/crates/text/src/embed.rs @@ -1,24 +1,33 @@ -//! Outline-font embedding permissions from raw OS/2 `fsType` flags. +//! Outline-font embedding classification from supplied OS/2 `fsType` flags. //! -//! This classifies flags for outline embedding; it does not parse font data. +//! This preserves VectorCraft's compatibility policy for outline embedding. It accepts flags, +//! not font data or an OS/2 table version, and does not apply the version-specific rules in the +//! [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/os2#fstype). +//! Callers remain responsible for selecting and interpreting the appropriate table data. // Ported from VectorCraft by bflatastic, fa3dcab4110f39ee91d3e471ec4e03aefb5a169e. -/// What a font's licence lets a document do with it (OS/2 `fsType`). +/// An outline-font embedding classification under [`Embedding::from_fs_type`]'s compatibility policy. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Embedding { - /// The font may be embedded, as a subset. + /// This policy allows subset embedding of the outlines. Subset, - /// The font may be embedded whole only (no subsetting). + /// This policy allows whole-font embedding only (no subsetting). Whole, - /// Restricted licence, or bitmap embedding only: the outlines may not be embedded. + /// This policy forbids outline embedding for restricted or bitmap-only flags. Forbidden, } impl Embedding { - /// The permission an OS/2 `fsType` value grants. Bits 0–3 are the usage permissions (none: - /// installable; 2: restricted; 4: preview and print; 8: editable), the most permissive one - /// winning when several are set; bit 8 forbids subsetting and bit 9 allows bitmaps only. + /// Classify supplied OS/2 `fsType` flags using VectorCraft's compatibility policy. + /// + /// The restricted flag (`0x0002`) forbids outlines unless preview/print (`0x0004`) or + /// editable (`0x0008`) is also set. Bitmap-only (`0x0200`) forbids outlines regardless of + /// those usage flags. Otherwise, no-subsetting (`0x0100`) selects whole-font embedding; + /// the remaining values select subset embedding. + /// + /// No OS/2 table version is supplied, so this does not apply version-specific OpenType + /// rules. The caller remains responsible for selecting and interpreting the table data. pub fn from_fs_type(fs: u16) -> Self { let restricted = fs & 0x0002 != 0 && fs & 0x000c == 0; if restricted || fs & 0x0200 != 0 { diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index 016faf3cde..4d0dbd2e82 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -3,7 +3,9 @@ //! Shared text processing for the Craft apps. It sits below the composer: layout code calls it on //! plain text and a language before it shapes and places glyphs. //! -//! [`embed`] is always available and classifies raw OS/2 `fsType` flags for outline embedding. +//! [`embed`] is always available and classifies supplied OS/2 `fsType` flags using VectorCraft's +//! outline-embedding compatibility policy. See its documentation for the caller's table-data +//! responsibilities. //! //! Feature-gated modules, each behind the cargo feature of the same name: //! - [`hyphen`] (default): hyphenation points, with bundled US English data and optional From 2b511bc9f35ce91d6a9a46b49168dcbb8a8c83f5 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Mon, 23 Nov 2026 21:24:22 +0530 Subject: [PATCH 099/130] craft-sniff: add OpenRaster (.ora) and Silhouette Studio (.studio) signatures --- crates/sniff/src/detect.rs | 81 ++++++++++++++++++++++- crates/sniff/src/kind.rs | 10 ++- crates/sniff/src/tests.rs | 131 ++++++++++++++++++++++++++++++++++++- 3 files changed, 219 insertions(+), 3 deletions(-) diff --git a/crates/sniff/src/detect.rs b/crates/sniff/src/detect.rs index d97baf1269..510d6de0c6 100644 --- a/crates/sniff/src/detect.rs +++ b/crates/sniff/src/detect.rs @@ -54,7 +54,8 @@ fn leading(b: &[u8]) -> Option { (b"Kaydara FBX Binary ", Kind::Fbx), (b"ply\n", Kind::Ply), (b"ply\r", Kind::Ply), - (b"PK\x03\x04", Kind::Zip), + (b"silhouette04;", Kind::Studio), + (b"silhouette05;", Kind::Studio), (b"PK\x05\x06", Kind::Zip), (b"7z\xbc\xaf\x27\x1c", Kind::SevenZip), (b"Rar!\x1a\x07\x00", Kind::Rar), @@ -89,6 +90,7 @@ fn checked(b: &[u8]) -> Option { return Some(dos(b)); } match b.get(..4)? { + b"PK\x03\x04" => Some(zip(b)), [0xca, 0xfe, 0xba, 0xbe] => Some(if be32(b, 4)? <= MAX_FAT_ARCHES { Kind::MachOFat } else { Kind::JavaClass }), b"II*\0" | b"MM\0*" | b"II+\0" | b"MM\0+" => Some(Kind::Tiff), b"8BPS" => matches!(be16(b, 4)?, 1 | 2).then_some(Kind::Psd), @@ -99,6 +101,83 @@ fn checked(b: &[u8]) -> Option { } } +/// `PK\x03\x04`: an OpenRaster archive when the first entry is a stored `mimetype` holding +/// `image/openraster`, otherwise [`Kind::Zip`]. +fn zip(b: &[u8]) -> Kind { + if is_ora(b) { Kind::Ora } else { Kind::Zip } +} + +fn is_ora(b: &[u8]) -> bool { + if le16(b, 8) != Some(0) { + return false; + } + let Some(flags) = le16(b, 6) else { + return false; + }; + let Some(name_len) = le16(b, 26).map(usize::from) else { + return false; + }; + let Some(extra_len) = le16(b, 28).map(usize::from) else { + return false; + }; + if name_len != 8 || b.get(30..38) != Some(b"mimetype") { + return false; + } + let Some(start) = 38usize.checked_add(extra_len) else { + return false; + }; + + let raw_size = le32(b, 18); + let size = if raw_size == Some(0xffff_ffff) { b.get(38..start).and_then(zip64_size) } else { raw_size.and_then(|s| usize::try_from(s).ok()) }; + + let streamed = (flags & 0x0008) != 0 && (raw_size == Some(0) || (raw_size == Some(0xffff_ffff) && size == Some(0))); + if streamed { + let Some(payload_end) = start.checked_add(16) else { + return false; + }; + if b.get(start..payload_end) != Some(b"image/openraster") { + return false; + } + let Some(rest) = b.get(payload_end..) else { + return false; + }; + return validate_descriptor(rest); + } + + let Some(sz) = size else { + return false; + }; + let Some(end) = start.checked_add(sz) else { + return false; + }; + b.get(start..end) == Some(b"image/openraster") +} + +fn zip64_size(mut extra: &[u8]) -> Option { + while extra.len() >= 4 { + let id = u16::from_le_bytes(extra.get(..2)?.try_into().ok()?); + let len = usize::from(u16::from_le_bytes(extra.get(2..4)?.try_into().ok()?)); + let next = 4usize.checked_add(len)?; + let data = extra.get(4..next)?; + if id == 1 { + let size = u64::from_le_bytes(data.get(..8)?.try_into().ok()?); + return usize::try_from(size).ok(); + } + extra = extra.get(next..)?; + } + None +} + +fn validate_descriptor(desc: &[u8]) -> bool { + let d = if desc.starts_with(b"PK\x07\x08") { desc.get(4..).unwrap_or(desc) } else { desc }; + if le32(d, 4) == Some(16) && le32(d, 8) == Some(16) { + return true; + } + let comp64 = d.get(4..12).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(u64::from_le_bytes) == Some(16); + let uncomp64 = d.get(12..20).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(u64::from_le_bytes) == Some(16); + comp64 && uncomp64 +} + /// `MZ`: a PE file when `e_lfanew` (at 0x3C) points at `PE\0\0` within the bytes given. fn dos(b: &[u8]) -> Kind { let pe = le32(b, 0x3c) diff --git a/crates/sniff/src/kind.rs b/crates/sniff/src/kind.rs index da98b15dcb..da35efaa9e 100644 --- a/crates/sniff/src/kind.rs +++ b/crates/sniff/src/kind.rs @@ -47,6 +47,8 @@ pub enum Kind { Psd, Qoi, OpenExr, + /// OpenRaster layered image (`.ora`). + Ora, // Audio. /// MPEG-1/2 Audio Layer III, with or without an ID3v2 tag. Mp3, @@ -128,11 +130,13 @@ pub enum Kind { BinaryPlist, // Documents. Pdf, + /// Silhouette Studio cutting document (`.studio`, `.studio3`). + Studio, } impl Kind { /// Every kind, in the order [`identify`](crate::identify) documents them. - pub const ALL: [Kind; 56] = [ + pub const ALL: [Kind; 58] = [ Kind::Png, Kind::Jpeg, Kind::Gif, @@ -146,6 +150,7 @@ impl Kind { Kind::Psd, Kind::Qoi, Kind::OpenExr, + Kind::Ora, Kind::Mp3, Kind::Aac, Kind::Flac, @@ -189,6 +194,7 @@ impl Kind { Kind::Sqlite, Kind::BinaryPlist, Kind::Pdf, + Kind::Studio, ]; /// The media type to send or store with the file: the IANA registration where one exists, @@ -223,6 +229,7 @@ impl Kind { Kind::Psd => ("image/vnd.adobe.photoshop", "psd", Image), Kind::Qoi => ("image/qoi", "qoi", Image), Kind::OpenExr => ("image/x-exr", "exr", Image), + Kind::Ora => ("image/openraster", "ora", Image), Kind::Mp3 => ("audio/mpeg", "mp3", Audio), Kind::Aac => ("audio/aac", "aac", Audio), Kind::Flac => ("audio/flac", "flac", Audio), @@ -265,6 +272,7 @@ impl Kind { Kind::Sqlite => ("application/vnd.sqlite3", "sqlite", Database), Kind::BinaryPlist => ("application/x-bplist", "plist", Database), Kind::Pdf => ("application/pdf", "pdf", Document), + Kind::Studio => ("application/x-silhouette-studio", "studio", Document), } } } diff --git a/crates/sniff/src/tests.rs b/crates/sniff/src/tests.rs index 2c5d2da8d3..3771990725 100644 --- a/crates/sniff/src/tests.rs +++ b/crates/sniff/src/tests.rs @@ -46,6 +46,25 @@ fn ebml(doc_type: &[u8]) -> Vec { bytes } +/// A ZIP local file header whose first entry is `mimetype`. +fn ora(mimetype: &[u8], compression: u16) -> Vec { + let mut bytes = b"PK\x03\x04".to_vec(); + bytes.extend_from_slice(&20u16.to_le_bytes()); + bytes.extend_from_slice(&0u16.to_le_bytes()); + bytes.extend_from_slice(&compression.to_le_bytes()); + bytes.extend_from_slice(&0u16.to_le_bytes()); + bytes.extend_from_slice(&0u16.to_le_bytes()); + bytes.extend_from_slice(&0u32.to_le_bytes()); + let len = u32::try_from(mimetype.len()).unwrap(); + bytes.extend_from_slice(&len.to_le_bytes()); + bytes.extend_from_slice(&len.to_le_bytes()); + bytes.extend_from_slice(&8u16.to_le_bytes()); + bytes.extend_from_slice(&0u16.to_le_bytes()); + bytes.extend_from_slice(b"mimetype"); + bytes.extend_from_slice(mimetype); + bytes +} + #[test] fn names_fixed_prefixes() { let cases: &[(&[u8], Kind)] = &[ @@ -67,6 +86,8 @@ fn names_fixed_prefixes() { (b"Kaydara FBX Binary \0\x1a\0", Kind::Fbx), (b"ply\nformat ascii 1.0\n", Kind::Ply), (b"ply\r\nformat binary_little_endian 1.0\r\n", Kind::Ply), + (b"silhouette04;\x01\x04\0\0\0", Kind::Studio), + (b"silhouette05;\x01\x04\0\0\0", Kind::Studio), (b"PK\x03\x04\x14\0", Kind::Zip), (b"PK\x05\x06\0\0\0\0", Kind::Zip), (b"7z\xbc\xaf\x27\x1c\0\x04", Kind::SevenZip), @@ -260,9 +281,111 @@ fn reads_only_the_head() { assert_eq!(identify(&png), Some(Kind::Png)); } +#[test] +fn names_openraster_and_silhouette_studio() { + // Silhouette Studio: v2 (.studio) and v3 (.studio3). + assert_eq!(identify(b"silhouette04;\x01\x04\0\0\0"), Some(Kind::Studio)); + assert_eq!(identify(b"silhouette05;\x01\x04\0\0\0"), Some(Kind::Studio)); + // Truncated Studio magic bytes return None. + assert_eq!(identify(b"silhouette04"), None); + assert_eq!(identify(b"silhouette"), None); + assert_eq!(identify(b"sil"), None); + // Modified Studio magic bytes return None. + assert_eq!(identify(b"silhouette03;\x01"), None); + assert_eq!(identify(b"silhouette06;\x01"), None); + assert_eq!(identify(b"silhouette04:\x01"), None); + + // OpenRaster (.ora): ZIP archive with stored "mimetype" entry holding "image/openraster". + let valid_ora = ora(b"image/openraster", 0); + assert_eq!(identify(&valid_ora), Some(Kind::Ora)); + // Non-zero compression: deflated (method 8) is not stored -> falls back to Zip. + assert_eq!(identify(&ora(b"image/openraster", 8)), Some(Kind::Zip)); + // Different mimetype -> falls back to Zip. + assert_eq!(identify(&ora(b"image/png", 0)), Some(Kind::Zip)); + // Truncated ORA mimetype inside ZIP: + assert_eq!(identify(&ora(b"image/openraste", 0)), Some(Kind::Zip)); + // Truncated magic bytes return None. + assert_eq!(identify(b"PK"), None); + assert_eq!(identify(b"PK\x03"), None); + // Modified magic bytes return None. + assert_eq!(identify(b"PK\x03\x05"), None); + assert_eq!(identify(b"image/openraster"), None); + + // OpenRaster with ZIP64 extra field (sizes 0xffffffff): + let mut zip64_ora = b"PK\x03\x04".to_vec(); + zip64_ora.extend_from_slice(&45u16.to_le_bytes()); + zip64_ora.extend_from_slice(&0u16.to_le_bytes()); + zip64_ora.extend_from_slice(&0u16.to_le_bytes()); + zip64_ora.extend_from_slice(&0u16.to_le_bytes()); + zip64_ora.extend_from_slice(&0u16.to_le_bytes()); + zip64_ora.extend_from_slice(&0u32.to_le_bytes()); + zip64_ora.extend_from_slice(&0xffff_ffffu32.to_le_bytes()); + zip64_ora.extend_from_slice(&0xffff_ffffu32.to_le_bytes()); + zip64_ora.extend_from_slice(&8u16.to_le_bytes()); + zip64_ora.extend_from_slice(&20u16.to_le_bytes()); + zip64_ora.extend_from_slice(b"mimetype"); + zip64_ora.extend_from_slice(&1u16.to_le_bytes()); + zip64_ora.extend_from_slice(&16u16.to_le_bytes()); + zip64_ora.extend_from_slice(&16u64.to_le_bytes()); + zip64_ora.extend_from_slice(&16u64.to_le_bytes()); + zip64_ora.extend_from_slice(b"image/openraster"); + assert_eq!(identify(&zip64_ora), Some(Kind::Ora)); + + // OpenRaster with general-purpose bit 3 and following data descriptor: + let mut descriptor_ora = b"PK\x03\x04".to_vec(); + descriptor_ora.extend_from_slice(&20u16.to_le_bytes()); + descriptor_ora.extend_from_slice(&8u16.to_le_bytes()); + descriptor_ora.extend_from_slice(&0u16.to_le_bytes()); + descriptor_ora.extend_from_slice(&0u16.to_le_bytes()); + descriptor_ora.extend_from_slice(&0u16.to_le_bytes()); + descriptor_ora.extend_from_slice(&0u32.to_le_bytes()); + descriptor_ora.extend_from_slice(&0u32.to_le_bytes()); + descriptor_ora.extend_from_slice(&0u32.to_le_bytes()); + descriptor_ora.extend_from_slice(&8u16.to_le_bytes()); + descriptor_ora.extend_from_slice(&0u16.to_le_bytes()); + descriptor_ora.extend_from_slice(b"mimetype"); + descriptor_ora.extend_from_slice(b"image/openraster"); + descriptor_ora.extend_from_slice(b"PK\x07\x08"); + descriptor_ora.extend_from_slice(&0u32.to_le_bytes()); + descriptor_ora.extend_from_slice(&16u32.to_le_bytes()); + descriptor_ora.extend_from_slice(&16u32.to_le_bytes()); + assert_eq!(identify(&descriptor_ora), Some(Kind::Ora)); + + // Streamed ZIP64 OpenRaster (bit 3 set, 0xffffffff local sizes, zero ZIP64 extra sizes, and 64-bit descriptor): + let mut zip64_desc_ora = b"PK\x03\x04".to_vec(); + zip64_desc_ora.extend_from_slice(&45u16.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&8u16.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&0u16.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&0u16.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&0u16.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&0u32.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&0xffff_ffffu32.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&0xffff_ffffu32.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&8u16.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&20u16.to_le_bytes()); + zip64_desc_ora.extend_from_slice(b"mimetype"); + zip64_desc_ora.extend_from_slice(&1u16.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&16u16.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&0u64.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&0u64.to_le_bytes()); + zip64_desc_ora.extend_from_slice(b"image/openraster"); + zip64_desc_ora.extend_from_slice(b"PK\x07\x08"); + zip64_desc_ora.extend_from_slice(&0u32.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&16u64.to_le_bytes()); + zip64_desc_ora.extend_from_slice(&16u64.to_le_bytes()); + assert_eq!(identify(&zip64_desc_ora), Some(Kind::Ora)); +} + #[test] fn every_prefix_of_every_sample_is_safe() { - let mut samples = vec![ftyp(b"mif1", &[b"avif"]), ebml(b"webm"), ogg(b"OpusHead"), riff(b"RIFF", b"WAVE")]; + let mut samples = vec![ + ftyp(b"mif1", &[b"avif"]), + ebml(b"webm"), + ogg(b"OpusHead"), + riff(b"RIFF", b"WAVE"), + ora(b"image/openraster", 0), + b"silhouette04;\x01\x04\0\0\0".to_vec(), + ]; samples.push(padded(b"MZ", 0x100)); samples.push((0..=255).collect()); for sample in &samples { @@ -308,4 +431,10 @@ fn media_types_apps_send() { assert_eq!(Kind::Elf.family(), Family::Executable); assert_eq!(Kind::Sqlite.family(), Family::Database); assert_eq!(Kind::Pdf.family(), Family::Document); + assert_eq!(Kind::Ora.mime_type(), "image/openraster"); + assert_eq!(Kind::Ora.extension(), "ora"); + assert_eq!(Kind::Ora.family(), Family::Image); + assert_eq!(Kind::Studio.mime_type(), "application/x-silhouette-studio"); + assert_eq!(Kind::Studio.extension(), "studio"); + assert_eq!(Kind::Studio.family(), Family::Document); } From be8e501ffc05f18e83f9bb658c11958d09f3e915 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:00:17 +0100 Subject: [PATCH 100/130] craft-docx: read and write w16du:dateUtc on tracked changes (#3206) Word writes a tracked change's w:date in local wall-clock time, so two changes an hour apart in the hour the clocks go back over get one w:date, and the reader, which groups revisions by kind, author and date, read them back as one change. Revision now keeps the change's UTC time (MS-DOCX 2.12.2.1 dateUtc): the reader reads it and groups by it too, and the writer writes it beside w:date (dropped with Remove date and time). The w16du namespace is declared on body parts and listed in mc:Ignorable. --- crates/docx/src/read.rs | 2 +- crates/docx/src/read/parts.rs | 7 +- crates/docx/src/write/props.rs | 6 ++ crates/docx/src/write/story.rs | 2 +- crates/docx/src/write/story/blocks.rs | 12 +-- crates/docx/src/write/story/para.rs | 42 ++++----- crates/docx/src/xml.rs | 4 +- crates/docx/tests/it/privacy.rs | 14 +-- crates/docx/tests/it/roundtrip.rs | 93 +++++++++++++++++-- .../tests/it/section_metadata_preservation.rs | 2 +- crates/docx/tests/it/wordml2003_write.rs | 2 +- crates/wordmodel/src/review.rs | 6 +- 12 files changed, 137 insertions(+), 55 deletions(-) diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 18c9ea47a0..518f3e6b47 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -73,7 +73,7 @@ pub(crate) struct Reader<'p> { file_orders: craft_wordmodel::para::FileOrders, pub doc: Document, pub pc: PropCtx, - revs: HashMap<(u8, String, String, Option), u32>, + revs: HashMap<(u8, String, String, Option, Option), u32>, /// Move ranges (`w:moveFromRangeStart` …) seen so far. pub moves: MoveCtx, media_by_path: HashMap, diff --git a/crates/docx/src/read/parts.rs b/crates/docx/src/read/parts.rs index 79bdacb890..a62a482752 100644 --- a/crates/docx/src/read/parts.rs +++ b/crates/docx/src/read/parts.rs @@ -74,17 +74,20 @@ impl Reader<'_> { pub(super) fn revision_named(&mut self, kind: RevisionKind, e: &El, move_name: Option) -> u32 { let author = e.attr("w:author").unwrap_or("").chars().take(256).collect::(); let date = e.attr("w:date").unwrap_or("").chars().take(64).collect::(); + let date_utc = e.attr("w16du:dateUtc").filter(|d| !d.is_empty()).map(|d| d.chars().take(64).collect::()); let k = match kind { RevisionKind::Insert => 0, RevisionKind::Delete => 1, RevisionKind::Format => 2, }; - let key = (k, author.clone(), date.clone(), move_name.clone()); + // Two changes with one local `w:date` (the hour the clocks go back over) are told apart + // by their UTC time. + let key = (k, author.clone(), date.clone(), move_name.clone(), date_utc.clone()); if let Some(i) = self.revs.get(&key) { return *i; } let i = self.doc.revisions.len() as u32; - self.doc.revisions.push(Revision { kind, author, date, move_name }); + self.doc.revisions.push(Revision { kind, author, date, move_name, date_utc }); self.revs.insert(key, i); i } diff --git a/crates/docx/src/write/props.rs b/crates/docx/src/write/props.rs index 497ffc412e..086d0cad5a 100644 --- a/crates/docx/src/write/props.rs +++ b/crates/docx/src/write/props.rs @@ -225,6 +225,12 @@ pub fn open_change(w: &mut W, tag: &str, a: &ChangeAttrs) { w.open(tag, &refs); } +/// [`open_change`] for an empty element. +pub fn empty_change(w: &mut W, tag: &str, a: &ChangeAttrs) { + let refs: Vec<(&str, &str)> = a.iter().map(|(k, v)| (*k, v.as_str())).collect(); + w.empty(tag, &refs); +} + /// A tracked change element holding the properties before the change: `…`. fn change_el(w: &mut W, tag: &str, inner: &str, a: &ChangeAttrs, body: impl FnOnce(&mut W)) { open_change(w, tag, a); diff --git a/crates/docx/src/write/story.rs b/crates/docx/src/write/story.rs index 26f1f2a449..377abc75c4 100644 --- a/crates/docx/src/write/story.rs +++ b/crates/docx/src/write/story.rs @@ -8,7 +8,7 @@ use craft_wordmodel::section::{LineNumberRestart, NoteProps, SectionProps, Secti use craft_wordmodel::table::Table; use craft_wordmodel::{Block, Blocks, InlineObject, Paragraph, RevisionKind}; -use super::props::{ChangeAttrs, borders, open_change, ppr_inner, rpr, rpr_inner, tblpr, tcpr, trpr}; +use super::props::{ChangeAttrs, borders, empty_change, open_change, ppr_inner, rpr, rpr_inner, tblpr, tcpr, trpr}; use super::{PartRels, Writer}; use crate::package::rt; use crate::units::{emu, n, twips}; diff --git a/crates/docx/src/write/story/blocks.rs b/crates/docx/src/write/story/blocks.rs index bdb2fb5427..c65fc734fc 100644 --- a/crates/docx/src/write/story/blocks.rs +++ b/crates/docx/src/write/story/blocks.rs @@ -1,5 +1,5 @@ use super::toc::written_toc_span; -use super::{Block, Blocks, CharProps, MAX_DEPTH, PartRels, Table, W, Writer, tblpr, tcpr, trpr, twips}; +use super::{Block, Blocks, CharProps, MAX_DEPTH, PartRels, Table, W, Writer, empty_change, tblpr, tcpr, trpr, twips}; impl Writer<'_> { fn write_trailing_para(&mut self, w: &mut W, depth: usize) { @@ -77,13 +77,11 @@ impl Writer<'_> { continue; } let name = self.doc.move_name(Some(rev)).unwrap_or("").to_string(); - let (id, author, date) = self.rev_attrs(rev); + let mut a = self.change_attrs(rev); + let id = a.first().map(|(_, id)| id.clone()).unwrap_or_default(); + a.insert(1, ("w:name", name)); let tag = if to { "w:moveToRangeStart" } else { "w:moveFromRangeStart" }; - if date.is_empty() { - w.empty(tag, &[("w:id", &id), ("w:name", &name), ("w:author", &author)]); - } else { - w.empty(tag, &[("w:id", &id), ("w:name", &name), ("w:author", &author), ("w:date", &date)]); - } + empty_change(w, tag, &a); self.open_moves.push((rev, id, to)); } } diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index babed9de51..624ce32381 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -1,5 +1,6 @@ use super::{ - ChangeAttrs, CharProps, InlineObject, Paragraph, PartRels, Piece, PropChange, RevisionKind, W, Writer, open_change, ppr_inner, rpr, rpr_inner, rt, + ChangeAttrs, CharProps, InlineObject, Paragraph, PartRels, Piece, PropChange, RevisionKind, W, Writer, empty_change, open_change, ppr_inner, rpr, + rpr_inner, rt, }; impl Writer<'_> { @@ -37,12 +38,8 @@ impl Writer<'_> { fn write_mark_rpr(&mut self, w: &mut W, mark: &CharProps, mark_revs: &[(u32, &str)]) { w.open("w:rPr", &[]); for (idx, tag) in mark_revs { - let (id, author, date) = self.rev_attrs(*idx); - if date.is_empty() { - w.empty(tag, &[("w:id", &id), ("w:author", &author)]); - } else { - w.empty(tag, &[("w:id", &id), ("w:author", &author), ("w:date", &date)]); - } + let a = self.change_attrs(*idx); + empty_change(w, tag, &a); } rpr_inner(w, mark); if let Some(ch) = mark.fmt_change.as_deref() { @@ -300,21 +297,20 @@ impl Writer<'_> { } } - pub(super) fn rev_attrs(&mut self, idx: u32) -> (String, String, String) { + /// `w:id`, `w:author`, `w:date` and `w16du:dateUtc` of a tracked change by revision `idx`. + pub(crate) fn change_attrs(&mut self, idx: u32) -> ChangeAttrs { self.next_rev_id += 1; let r = self.doc.revisions.get(idx as usize); let author = crate::write::annotation_author(self.doc, r.map_or("", |r| r.author.as_str())).to_string(); - // Remove date and time (§17.15.1.69): tracked changes are saved without `w:date`. - let date = if self.doc.settings.remove_date_time { String::new() } else { r.map(|r| r.date.clone()).unwrap_or_default() }; - (self.next_rev_id.to_string(), author, date) - } - - /// `w:id`, `w:author` and `w:date` of a tracked change by revision `idx`. - pub(crate) fn change_attrs(&mut self, idx: u32) -> ChangeAttrs { - let (id, author, date) = self.rev_attrs(idx); - let mut a = vec![("w:id", id), ("w:author", author)]; - if !date.is_empty() { - a.push(("w:date", date)); + let mut a = vec![("w:id", self.next_rev_id.to_string()), ("w:author", author)]; + // Remove date and time (§17.15.1.69): tracked changes are saved without their dates. + if let Some(r) = r.filter(|_| !self.doc.settings.remove_date_time) { + if !r.date.is_empty() { + a.push(("w:date", r.date.clone())); + } + if let Some(utc) = r.date_utc.as_ref().filter(|d| !d.is_empty()) { + a.push(("w16du:dateUtc", utc.clone())); + } } a } @@ -344,12 +340,8 @@ impl Writer<'_> { continue; } let tag = self.rev_tag(idx, tag); - let (id, author, date) = self.rev_attrs(idx); - if date.is_empty() { - w.open(tag, &[("w:id", &id), ("w:author", &author)]); - } else { - w.open(tag, &[("w:id", &id), ("w:author", &author), ("w:date", &date)]); - } + let a = self.change_attrs(idx); + open_change(w, tag, &a); } } diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index 46da6911d4..378bcbe2a8 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -49,6 +49,8 @@ pub const NAMESPACES: &[(&str, &str)] = &[ ("cx6", "http://schemas.microsoft.com/office/drawing/2016/5/12/chartex"), ("cx7", "http://schemas.microsoft.com/office/drawing/2016/5/13/chartex"), ("cx8", "http://schemas.microsoft.com/office/drawing/2016/5/14/chartex"), + // A tracked change's UTC time (`w16du:dateUtc`). + ("w16du", "http://schemas.microsoft.com/office/word/2023/wordml/word16du"), ]; /// The `a:ext` URI under which a drawing is marked decorative ([MS-ODRAWXML]), and the @@ -531,7 +533,7 @@ impl W { /// `xmlns:` declarations for the body-part namespaces, plus `mc:Ignorable`. pub fn body_ns() -> Vec<(String, String)> { let mut v: Vec<(String, String)> = NAMESPACES.iter().map(|(p, u)| (format!("xmlns:{p}"), (*u).to_string())).collect(); - v.push(("mc:Ignorable".into(), "w14 w15 wp14".into())); + v.push(("mc:Ignorable".into(), "w14 w15 wp14 w16du".into())); v } diff --git a/crates/docx/tests/it/privacy.rs b/crates/docx/tests/it/privacy.rs index 6429cc4f70..1ee2ef7169 100644 --- a/crates/docx/tests/it/privacy.rs +++ b/crates/docx/tests/it/privacy.rs @@ -5,6 +5,7 @@ use std::collections::BTreeMap; use std::io::{Cursor, Read, Write}; const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#; +const W16DU_NS: &str = r#"xmlns:w16du="http://schemas.microsoft.com/office/word/2023/wordml/word16du""#; const RT: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"; fn zip(entries: &[(&str, String)]) -> Vec { @@ -29,11 +30,11 @@ fn unzip(bytes: &[u8]) -> BTreeMap { parts } -/// A package with two named commenters, a tracked insertion and deletion, the document -/// properties' creator and last-modified-by, and `settings` inside `w:settings`. +/// A package with two named commenters, a tracked insertion (with its UTC time) and deletion, the +/// document properties' creator and last-modified-by, and `settings` inside `w:settings`. fn fixture(settings: &str) -> Vec { let body = r#"Clause one. -AddedRemoved"#; +AddedRemoved"#; let comments = format!( r#"Check this.Agreed."# ); @@ -46,7 +47,7 @@ fn fixture(settings: &str) -> Vec { ); zip(&[ ("_rels/.rels", root_rels), - ("word/document.xml", format!(r#"{body}"#)), + ("word/document.xml", format!(r#"{body}"#)), ("word/_rels/document.xml.rels", doc_rels), ("word/comments.xml", comments), ("word/settings.xml", format!(r#"{settings}"#)), @@ -77,7 +78,7 @@ fn remove_personal_information_and_dates_on_save() { for name in NAMES { assert!(!all.contains(name), "{name} saved"); } - assert!(!all.contains("w:date="), "annotation date saved"); + assert!(!all.contains("w:date=") && !all.contains("dateUtc="), "annotation date saved"); assert!(!all.contains("2026-03-0"), "annotation date saved"); let comments = &parts["word/comments.xml"]; assert_eq!(comments.matches(r#"w:author="Author""#).count(), 2, "{comments}"); @@ -103,7 +104,7 @@ fn each_privacy_setting_works_alone() { // Dates only: names stay. let doc = craft_docx::read(&fixture("")).unwrap(); let (parts, all) = saved(&doc); - assert!(!all.contains("w:date=")); + assert!(!all.contains("w:date=") && !all.contains("dateUtc=")); assert!(all.contains("Quill Ramsey") && all.contains("Ona Vettel")); assert!(parts["docProps/core.xml"].contains("Quill Ramsey")); assert!(!parts["word/settings.xml"].contains("removePersonalInformation")); @@ -121,6 +122,7 @@ fn each_privacy_setting_works_alone() { let (parts, all) = saved(&doc); assert!(all.contains("Quill Ramsey") && all.contains(r#"w:initials="OV""#)); assert_eq!(all.matches("w:date=").count(), 4); + assert!(all.contains(r#"w16du:dateUtc="2026-03-04T13:06:07Z""#), "the insertion keeps its UTC time"); assert!(parts["docProps/core.xml"].contains("Ona Vettel")); assert!(!parts["word/settings.xml"].contains("removeDateAndTime")); } diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 4927cd09c8..801b64e24e 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -976,8 +976,20 @@ fn toc_field_skips_nested_stories() { #[test] fn tracked_changes_round_trip() { let mut d = Document::new(); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None }); - d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None }); + d.revisions.push(Revision { + kind: RevisionKind::Insert, + author: "Alice".into(), + date: "2026-05-01T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); + d.revisions.push(Revision { + kind: RevisionKind::Delete, + author: "Bob".into(), + date: "2026-05-02T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); d.settings.track_changes = true; let ins = CharProps { ins: Some(0), ..Default::default() }; let del = CharProps { del: Some(1), bold: Some(true), ..Default::default() }; @@ -1001,12 +1013,51 @@ fn tracked_changes_round_trip() { assert!(r.settings.track_changes); } +/// Two changes by one author with one local `w:date` (the hour the clocks go back over) stay two +/// changes across a save, told apart by their UTC time (`w16du:dateUtc`). +#[test] +fn tracked_changes_with_one_local_date_stay_apart_by_their_utc_time() { + let mut d = Document::new(); + for utc in ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"] { + let mut r = Revision::new(RevisionKind::Insert, "Ada", "2026-11-01T01:30:00Z"); + r.date_utc = Some(utc.into()); + d.revisions.push(r); + } + d.settings.track_changes = true; + let p = para_runs(&[ + ("Draft.", CharProps::default()), + (" One", CharProps { ins: Some(0), ..Default::default() }), + (" Two", CharProps { ins: Some(1), ..Default::default() }), + ]); + d.body = vec![para_block(p.clone())]; + let r = rt(&d); + assert_eq!(r.revisions, d.revisions); + assert_eq!(paras(&r)[0].runs, p.runs); + // Without their UTC times, the file can't tell them apart. + for r in &mut d.revisions { + r.date_utc = None; + } + assert_eq!(rt(&d).revisions.len(), 1, "one author, kind and date is one change"); +} + #[test] fn tracked_equations_round_trip() { // Issue #6011: equations saved with tracked revision marks (w:ins / w:del) around math. let mut d = Document::new(); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None }); - d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None }); + d.revisions.push(Revision { + kind: RevisionKind::Insert, + author: "Alice".into(), + date: "2026-05-01T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); + d.revisions.push(Revision { + kind: RevisionKind::Delete, + author: "Bob".into(), + date: "2026-05-02T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); d.settings.track_changes = true; let ins = CharProps { ins: Some(0), ..Default::default() }; let del = CharProps { del: Some(1), ..Default::default() }; @@ -1061,8 +1112,20 @@ fn tracked_equations_round_trip() { fn nested_omath_para_revisions_read() { // Defensive reader check: w:ins and w:del nested inside m:oMathPara. let mut d = Document::new(); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None }); - d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Charles".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None }); + d.revisions.push(Revision { + kind: RevisionKind::Insert, + author: "Ada".into(), + date: "2026-05-01T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); + d.revisions.push(Revision { + kind: RevisionKind::Delete, + author: "Charles".into(), + date: "2026-05-02T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); let doc_xml = r#"x+1y-1"#; let base = craft_docx::write(&d).unwrap(); let bytes = replace_part(&base, "word/document.xml", doc_xml.as_bytes()); @@ -1080,8 +1143,20 @@ fn tracked_paragraph_marks_round_trip() { // Issue #229: an inserted / deleted paragraph mark is `w:ins` / `w:del` in the mark's // `w:rPr` (ECMA-376 §17.13.5.16, §17.13.5.15), alone or with mark formatting. let mut d = Document::new(); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Alice".into(), date: "2026-05-01T10:00:00Z".into(), move_name: None }); - d.revisions.push(Revision { kind: RevisionKind::Delete, author: "Bob".into(), date: "2026-05-02T10:00:00Z".into(), move_name: None }); + d.revisions.push(Revision { + kind: RevisionKind::Insert, + author: "Alice".into(), + date: "2026-05-01T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); + d.revisions.push(Revision { + kind: RevisionKind::Delete, + author: "Bob".into(), + date: "2026-05-02T10:00:00Z".into(), + move_name: None, + date_utc: None, + }); let mut split = Paragraph::with_text("Owned ALPHA ", CharProps::default()); split.mark.ins = Some(0); let mut joined = Paragraph::with_text("Owned BETA", CharProps::default()); @@ -1821,7 +1896,7 @@ fn kitchen_sink() -> Document { let f = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Note", CharProps::default()))]); let c = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment", CharProps::default()))]); d.comments.insert(3, Comment { author: "X".into(), part: c, ..Default::default() }); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None }); + d.revisions.push(Revision { kind: RevisionKind::Insert, author: "A".into(), date: String::new(), move_name: None, date_utc: None }); d.last_section.headers.default = Some(h); let mut blocks: Blocks = Vec::new(); let mut p = para_runs(&[ diff --git a/crates/docx/tests/it/section_metadata_preservation.rs b/crates/docx/tests/it/section_metadata_preservation.rs index 7e83d46877..67cce5a338 100644 --- a/crates/docx/tests/it/section_metadata_preservation.rs +++ b/crates/docx/tests/it/section_metadata_preservation.rs @@ -41,7 +41,7 @@ fn section_metadata_survives_native_json_and_two_docx_save_reopen_cycles() { assert!(xml.contains(r#""#), "cycle {cycle}: {xml}"); assert!(xml.contains(r#"w:chapStyle="1" w:chapSep="hyphen""#), "cycle {cycle}: {xml}"); assert!(xml.contains(r#"w:chapStyle="10" w:chapSep="colon""#), "cycle {cycle}: {xml}"); - assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14\""), "cycle {cycle}: {xml}"); + assert!(xml.contains("xmlns:w15=") && xml.contains("mc:Ignorable=\"w14 w15 wp14 w16du\""), "cycle {cycle}: {xml}"); document = craft_docx::read(&bytes).unwrap(); let json = serde_json::to_vec(&document).unwrap(); document = serde_json::from_slice(&json).unwrap(); diff --git a/crates/docx/tests/it/wordml2003_write.rs b/crates/docx/tests/it/wordml2003_write.rs index 6256c6b91a..f68662b3d1 100644 --- a/crates/docx/tests/it/wordml2003_write.rs +++ b/crates/docx/tests/it/wordml2003_write.rs @@ -37,7 +37,7 @@ fn sample() -> Document { let foot = d.add_part(PartKind::Footnote, vec![para_block(Paragraph::with_text("Sown in May.", CharProps::default()))]); let com = d.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Too short?", CharProps::default()))]); d.comments.insert(3, Comment { author: "Bo".into(), part: com, ..Default::default() }); - d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None }); + d.revisions.push(Revision { kind: RevisionKind::Insert, author: "Ada".into(), date: String::new(), move_name: None, date_utc: None }); d.last_section.headers.default = Some(head); let mut p = Paragraph::new(); diff --git a/crates/wordmodel/src/review.rs b/crates/wordmodel/src/review.rs index de960b117a..516d72285a 100644 --- a/crates/wordmodel/src/review.rs +++ b/crates/wordmodel/src/review.rs @@ -42,11 +42,15 @@ pub struct Revision { /// insertion or deletion. #[serde(skip_serializing_if = "Option::is_none")] pub move_name: Option, + /// The change's UTC timestamp (`w16du:dateUtc`, MS-DOCX 2.12.2.1), where `date` is the local + /// time Word writes in `w:date`. `None` when the file doesn't give it. + #[serde(skip_serializing_if = "Option::is_none")] + pub date_utc: Option, } impl Revision { pub fn new(kind: RevisionKind, author: impl Into, date: impl Into) -> Revision { - Revision { kind, author: author.into(), date: date.into(), move_name: None } + Revision { kind, author: author.into(), date: date.into(), move_name: None, date_utc: None } } } From ffbbfcabfabdeaae91553157cd71a60d4027ca82 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:03:02 +0100 Subject: [PATCH 101/130] docx: only a dateUtc in Word's namespace is a tracked change's UTC time The reader looked `w16du:dateUtc` up with `El::attr`, which falls back to an unqualified attribute with the same local name. A bare `dateUtc` then told revisions apart and was saved under Word's namespace. It now reads the canonical name only (`El::attr_exact`); other attributes keep the fallback. Co-Authored-By: Claude Opus 5.5 --- crates/docx/src/read/parts.rs | 4 +++- crates/docx/src/xml.rs | 9 ++++++-- crates/docx/tests/it/fixtures.rs | 36 ++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 3 deletions(-) diff --git a/crates/docx/src/read/parts.rs b/crates/docx/src/read/parts.rs index a62a482752..5c0d8ed9bc 100644 --- a/crates/docx/src/read/parts.rs +++ b/crates/docx/src/read/parts.rs @@ -74,7 +74,9 @@ impl Reader<'_> { pub(super) fn revision_named(&mut self, kind: RevisionKind, e: &El, move_name: Option) -> u32 { let author = e.attr("w:author").unwrap_or("").chars().take(256).collect::(); let date = e.attr("w:date").unwrap_or("").chars().take(64).collect::(); - let date_utc = e.attr("w16du:dateUtc").filter(|d| !d.is_empty()).map(|d| d.chars().take(64).collect::()); + // Only the Word namespace's `dateUtc`: a bare one would be saved under that namespace + // without having come from it. + let date_utc = e.attr_exact("w16du:dateUtc").filter(|d| !d.is_empty()).map(|d| d.chars().take(64).collect::()); let k = match kind { RevisionKind::Insert => 0, RevisionKind::Delete => 1, diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index 378bcbe2a8..a6d8794fb6 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -203,15 +203,20 @@ impl El { /// Attribute by canonical name (`w:val`); falls back to an unqualified attribute with the /// same local name (some producers omit the prefix). pub fn attr(&self, name: &str) -> Option<&str> { - if let Some((_, v)) = self.attrs.iter().find(|(k, _)| k == name) { + if let Some(v) = self.attr_exact(name) { return Some(v); } let local = name.rsplit(':').next().unwrap_or(name); if local != name { - return self.attrs.iter().find(|(k, _)| k == local).map(|(_, v)| v.as_str()); + return self.attr_exact(local); } None } + /// Attribute by canonical name only, for one whose namespace carries meaning an unqualified + /// attribute can't claim. + pub fn attr_exact(&self, name: &str) -> Option<&str> { + self.attrs.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str()) + } /// Child elements. pub fn els(&self) -> impl Iterator { self.kids.iter().filter_map(|n| match n { diff --git a/crates/docx/tests/it/fixtures.rs b/crates/docx/tests/it/fixtures.rs index 4f2b9de277..e58fb3e0a7 100644 --- a/crates/docx/tests/it/fixtures.rs +++ b/crates/docx/tests/it/fixtures.rs @@ -2706,6 +2706,42 @@ fn move_revisions_round_trip() { check(&craft_docx::read(&out).unwrap()); } +/// Two insertions by one author with one local `w:date`, told apart (or not) by `dateUtc`. +fn two_insertions_at_one_local_time(utc: [&str; 2]) -> String { + let ins = |id: u32, utc: &str, text: &str| { + format!(r#"{text}"#) + }; + format!("{}{}", ins(1, utc[0], " One"), ins(2, utc[1], " Two")) +} + +/// Issue #3206: a tracked change's `dateUtc` is read under any prefix bound to Word's namespace +/// for it, and saved under that namespace. +#[test] +fn a_tracked_change_utc_time_is_read_under_any_prefix_for_its_namespace() { + let du = r#"xmlns:du="http://schemas.microsoft.com/office/word/2023/wordml/word16du""#; + let body = two_insertions_at_one_local_time([ + &format!(r#"{du} du:dateUtc="2026-11-01T05:30:00Z""#), + &format!(r#"{du} du:dateUtc="2026-11-01T06:30:00Z""#), + ]); + let d = read_body(&body); + let utc: Vec<_> = d.revisions.iter().map(|r| r.date_utc.as_deref()).collect(); + assert_eq!(utc, [Some("2026-11-01T05:30:00Z"), Some("2026-11-01T06:30:00Z")]); + let xml = text(&unzip(&craft_docx::write(&d).unwrap()), "word/document.xml"); + assert_eq!(attr_values(&xml, "w:ins", "w16du:dateUtc"), ["2026-11-01T05:30:00Z", "2026-11-01T06:30:00Z"]); +} + +/// Issue #3206: an unqualified `dateUtc` doesn't say it's Word's UTC time, so it neither tells +/// changes apart nor is saved under Word's namespace. +#[test] +fn an_unqualified_date_utc_is_not_a_tracked_change_utc_time() { + let body = two_insertions_at_one_local_time([r#"dateUtc="2026-11-01T05:30:00Z""#, r#"dateUtc="2026-11-01T06:30:00Z""#]); + let d = read_body(&body); + assert_eq!(d.revisions.len(), 1, "one author, kind and local date is one change"); + assert_eq!(d.revisions[0].date_utc, None); + let xml = text(&unzip(&craft_docx::write(&d).unwrap()), "word/document.xml"); + assert!(!xml.contains("dateUtc="), "{xml}"); +} + /// A document's own footnote separators and continuation notice are kept (ECMA-376 §17.11), and /// written back as Word numbers them: -1, 0 and 1, the notes after them. #[test] From ee8e7a1683faa02dfc6effd98e69a6dce4df15fc Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:38:10 +0000 Subject: [PATCH 102/130] craft-csv: add conservative short-row fallback to sniff_csv_delimiter --- crates/csv/README.md | 2 +- crates/csv/src/lib.rs | 96 ++++++++++++++++++++++++++++++++++++++----- 2 files changed, 86 insertions(+), 12 deletions(-) diff --git a/crates/csv/README.md b/crates/csv/README.md index a11d4a8ab2..91390ac744 100644 --- a/crates/csv/README.md +++ b/crates/csv/README.md @@ -12,7 +12,7 @@ mapping a SYLK sheet onto a document are the caller's work. |---|---| | `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 | | `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a sample of the first 65,536 characters (empty or whitespace-only quoted records are blank); when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | -| `sniff_csv_delimiter(text, quote)` | same scan as `sniff_delimiter`, but for `.csv`-named text prefers comma when comma has coherent quoted fields and separates every sampled record with text, or separates the first such record while neither tab nor semicolon coherently separates every sampled record | +| `sniff_csv_delimiter(text, quote)` | same scan as `sniff_delimiter`, but for `.csv`-named text prefers comma when comma coherently separates every sampled record with text; when no candidate coherently separates every sampled record, falls back to a coherent candidate whose header and at least one later record share a positive delimiter count with strictly more than half of the sampled records having 1 to that many delimiters (preferring comma, then tab over semicolon), or else comma if comma coherently separates the first sampled record with text | | `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text | | `records(text, delim, quote, max_records, max_fields)` | the same, collected | | `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing | diff --git a/crates/csv/src/lib.rs b/crates/csv/src/lib.rs index 683250b023..fa5aed71f3 100644 --- a/crates/csv/src/lib.rs +++ b/crates/csv/src/lib.rs @@ -53,9 +53,15 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { /// separates the sampled records. /// /// Uses the same bounded character sample, quote-boundary coherence rules and fallback ranking -/// as [`sniff_delimiter`], except that when comma has coherent quoted fields it is chosen if -/// it separates every sampled record with text, or if it separates the first such record and -/// neither tab nor semicolon coherently separates every sampled record with text. +/// as [`sniff_delimiter`], with two `.csv`-specific rules: +/// - When comma has coherent quoted fields and separates every sampled record with text, comma +/// wins even if tab or semicolon also separates them. +/// - When no candidate coherently separates every sampled record with text, a coherent candidate +/// whose first record and at least one later record share the same positive delimiter count +/// (and where strictly more than half of the sampled records with text contain between one and +/// that many delimiters) is chosen — preferring comma, then the most matching records, higher +/// header count and total, then tab over semicolon. If none matches, comma still wins when it +/// has coherent quoted fields and separates the first sampled record with text. pub fn sniff_csv_delimiter(text: &str, quote: char) -> u8 { sniff_delimiter_inner(text, quote, true) } @@ -116,19 +122,52 @@ fn separates_coherently(scan: &DelimiterScan) -> bool { scan.coherent && scan.counts.iter().min().is_some_and(|&min| min > 0) } -fn csv_prefers_comma([tab, comma, semi]: &[DelimiterScan; 3]) -> bool { - if !comma.coherent || comma.counts.is_empty() { - return false; +/// Scores a coherent candidate whose first record and at least one later record share the same +/// positive delimiter count, and where strictly more than half of the sampled records with text +/// contain between one and that many delimiters (allowing occasional short rows). +fn header_short_row_score(scan: &DelimiterScan) -> Option<(usize, usize, usize)> { + if !scan.coherent { + return None; } - if comma.counts.iter().min().is_some_and(|&min| min > 0) { - return true; + let &header = scan.counts.first()?; + if header == 0 { + return None; } - comma.counts.first().is_some_and(|&first| first > 0) && !separates_coherently(tab) && !separates_coherently(semi) + let exact_matches = scan.counts.iter().filter(|&&count| count == header).count(); + let in_range = scan.counts.iter().filter(|&&count| (1..=header).contains(&count)).count(); + if exact_matches < 2 || in_range * 2 <= scan.counts.len() { + return None; + } + Some((exact_matches, header, scan.counts.iter().sum())) +} + +fn pick_csv_delimiter(scans: &[DelimiterScan; 3]) -> Option { + let [tab, comma, semi] = scans; + if separates_coherently(comma) { + return Some(b','); + } + if separates_coherently(tab) || separates_coherently(semi) { + return None; + } + if header_short_row_score(comma).is_some() { + return Some(b','); + } + if let Some((delimiter, _)) = [tab, semi] + .into_iter() + .filter_map(|scan| header_short_row_score(scan).map(|score| (scan.delimiter, score))) + .reduce(|best, candidate| if candidate.1 > best.1 { candidate } else { best }) + { + return Some(delimiter); + } + if comma.coherent && comma.counts.first().is_some_and(|&first| first > 0) { + return Some(b','); + } + None } fn pick_delimiter(scans: [DelimiterScan; 3], prefer_comma: bool) -> u8 { - if prefer_comma && csv_prefers_comma(&scans) { - return b','; + if prefer_comma && let Some(delimiter) = pick_csv_delimiter(&scans) { + return delimiter; } let with_text = scans.each_ref().map(|scan| (scan.delimiter, scan.counts.as_slice(), scan.coherent)); // Records of delimiters alone have no quotes, so they are coherent. @@ -587,6 +626,41 @@ mod tests { assert_eq!(sniff_csv_delimiter(&format!("{};7\n", ";\n".repeat(40_000)), '"'), b';'); } + #[test] + fn csv_delimiter_sniffing_handles_short_rows_conservatively() { + // Tab- and semicolon-delimited CSVs with a short row recover when the header and a later + // full row agree across a majority of sampled records. + for (text, expected) in [ + ("Name\tCity\nAda\nGrace\tParis\n", b'\t'), + ("Name;City\nAda\nGrace;Paris\n", b';'), + ("Name\tCity\tRole\nAda\nGrace\tParis\tLead\n", b'\t'), + ("Name;City;Role\nAda\nGrace;Paris;Lead\n", b';'), + ("Name\tCity\nAda\tLondon\nGrace\n", b'\t'), + ("Name;City\nAda;London\nGrace\n", b';'), + ("Last, First\tCity\nAda\nGrace\tParis\n", b'\t'), + ("Last, First;City\nAda\nGrace;Paris\n", b';'), + ("\"\"\nName\tCity\nAda\nGrace\tParis\n", b'\t'), + ("\"Name\"\t\"City;Region\"\nAda;X\nGrace\tParis;Y\n", b'\t'), + ] { + assert_eq!(sniff_csv_delimiter(text, '"'), expected, "{text:?}"); + } + + // Comma preference and conservative single-column fallbacks stay comma. + for text in [ + "Name,Note;Tag\nAda\nGrace,Hello;2\n", + "Name,Note\tTag\nAda\nGrace,Hello\t2\n", + "\"Name\",\"Note;Tag\"\nAda;Team\n", + "alpha;beta\r\ngamma\r\n", + "alpha\tbeta\r\ngamma\r\n", + "alpha;beta\r\ngamma\r\ndelta\r\n", + "Notes\r\nalpha;beta\r\ngamma;delta\r\n", + "a;b\nc\nd\ne;f\n", + "Title: a;b\nline\nx;y;z\nline\nc;d\n", + ] { + assert_eq!(sniff_csv_delimiter(text, '"'), b',', "{text:?}"); + } + } + #[test] fn parser_stops_collecting_fields_at_the_cap() { let (max, extra) = (16_384usize, 50); From bce6dc09a6bb067cea2366e099d68571ccf09fc5 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 24 Nov 2026 18:37:54 +0530 Subject: [PATCH 103/130] fix(dxf): preserve invalid/non-finite numeric values as Value::Invalid (#3265) --- crates/dxf/src/lib.rs | 111 ++++++++++++++++++++++++++++++++-- crates/dxf/tests/hardening.rs | 23 ++++++- 2 files changed, 128 insertions(+), 6 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index dcffaf3962..f63c73d3d8 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -48,12 +48,14 @@ pub enum Value { Bool(bool), /// Binary chunk (310–319, 1004) as hex text. Hex(String), + /// Non-finite or malformed numeric group value preserved as raw text. + Invalid(String), } impl Value { pub fn as_str(&self) -> String { match self { - Value::Str(s) | Value::Hex(s) => s.clone(), + Value::Str(s) | Value::Hex(s) | Value::Invalid(s) => s.clone(), Value::Real(r) => format_real(*r), Value::Int(i) => i.to_string(), Value::Bool(b) => i64::from(*b).to_string(), @@ -84,6 +86,17 @@ impl Value { _ => 0, } } + /// Whether this value represents a malformed or non-finite numeric group. + pub fn is_invalid(&self) -> bool { + matches!(self, Value::Invalid(_)) + } + /// The raw text of the invalid value, if this is [`Value::Invalid`]. + pub fn invalid_str(&self) -> Option<&str> { + match self { + Value::Invalid(s) => Some(s), + _ => None, + } + } } #[derive(Clone, Debug, PartialEq)] @@ -105,6 +118,9 @@ impl Tag { pub fn i(code: i32, v: i64) -> Self { Tag { code, value: Value::Int(v) } } + pub fn invalid(code: i32, v: impl Into) -> Self { + Tag { code, value: Value::Invalid(v.into()) } + } pub fn str(&self) -> String { self.value.as_str() } @@ -121,6 +137,12 @@ impl Tag { pub fn i64(&self) -> i64 { self.value.as_i64() } + pub fn is_invalid(&self) -> bool { + self.value.is_invalid() + } + pub fn invalid_str(&self) -> Option<&str> { + self.value.invalid_str() + } } /// The value type for a group code (DXF Reference, "Group Code Value Types"). @@ -151,7 +173,10 @@ pub fn kind_of(code: i32) -> Kind { fn typed(code: i32, text: &str) -> Value { let t = text.trim(); match kind_of(code) { - Kind::Real => t.parse::().ok().filter(|v| v.is_finite()).map_or(Value::Real(0.0), Value::Real), + Kind::Real => match t.parse::() { + Ok(v) if v.is_finite() => Value::Real(v), + _ => Value::Invalid(t.to_string()), + }, Kind::Int16 | Kind::Int32 | Kind::Int64 => { // A float spelling ("1e3", "12.0") is accepted when finite, clamped to what the // group's width holds, signed or unsigned (files write 16-bit flags up to 65535, as @@ -570,7 +595,14 @@ fn parse_binary_pass(b: &[u8], max_tags: usize, text: &mut codepage::BinaryText) }; let v = match kind_of(code) { Kind::Str => Value::Str(unescape_unicode(&text.string(code, c.cstr()?))), - Kind::Real => Value::Real(Some(c.f64()?).filter(|v| v.is_finite()).unwrap_or(0.0)), + Kind::Real => { + let r = c.f64()?; + if r.is_finite() { + Value::Real(r) + } else { + Value::Invalid(r.to_string()) + } + } Kind::Int16 => Value::Int(i64::from(c.i16()?)), Kind::Int32 => Value::Int(i64::from(c.i32()?)), Kind::Int64 => Value::Int(c.i64()?), @@ -766,6 +798,7 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec { out.extend_from_slice(chunk.as_bytes()); } } + Value::Invalid(s) => push_string(s, strings, &mut out), } out.extend_from_slice(b"\r\n"); } @@ -809,7 +842,11 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { } Kind::Real => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&t.value.as_f64().to_le_bytes()); + let r = match &t.value { + Value::Invalid(s) => s.parse::().unwrap_or_else(|_| t.value.as_f64()), + _ => t.value.as_f64(), + }; + out.extend_from_slice(&r.to_le_bytes()); } Kind::Int16 => { out.extend_from_slice(&code_bytes); @@ -1324,6 +1361,72 @@ mod tests { b.extend_from_slice(b"EOF\0"); assert_eq!(parse(&b).unwrap()[0].str(), "图号"); } + + #[test] + fn invalid_numeric_values_produce_value_invalid_and_preserve_compatibility() { + let val = Value::Invalid("not_a_number".into()); + assert!(val.is_invalid()); + assert_eq!(val.invalid_str(), Some("not_a_number")); + assert_eq!(val.as_str(), "not_a_number"); + assert_eq!(val.as_f64(), 0.0); + assert_eq!(val.as_i64(), 0); + + let tag = Tag::invalid(10, "NaN"); + assert!(tag.is_invalid()); + assert_eq!(tag.invalid_str(), Some("NaN")); + assert_eq!(tag.str(), "NaN"); + assert_eq!(tag.str_ref(), None); + assert_eq!(tag.f64(), 0.0); + assert_eq!(tag.i64(), 0); + } + + #[test] + fn parse_ascii_invalid_and_non_finite_reals() { + let text = "10\nNaN\n20\ninf\n30\n-inf\n40\ngarbage\n50\n 12.34.56 \n0\nEOF\n"; + let tags = parse(text.as_bytes()).unwrap(); + assert_eq!(tags.len(), 6); + + assert_eq!(tags[0], Tag::invalid(10, "NaN")); + assert!(tags[0].is_invalid()); + assert_eq!(tags[0].f64(), 0.0); + + assert_eq!(tags[1], Tag::invalid(20, "inf")); + assert!(tags[1].is_invalid()); + assert_eq!(tags[1].f64(), 0.0); + + assert_eq!(tags[2], Tag::invalid(30, "-inf")); + assert!(tags[2].is_invalid()); + assert_eq!(tags[2].f64(), 0.0); + + assert_eq!(tags[3], Tag::invalid(40, "garbage")); + assert!(tags[3].is_invalid()); + assert_eq!(tags[3].f64(), 0.0); + + assert_eq!(tags[4], Tag::invalid(50, "12.34.56")); + assert!(tags[4].is_invalid()); + assert_eq!(tags[4].f64(), 0.0); + } + + #[test] + fn invalid_reals_roundtrip_in_ascii_and_binary() { + let tags = vec![ + Tag::invalid(10, "NaN"), + Tag::invalid(20, "inf"), + Tag::invalid(30, "malformed"), + Tag::s(0, "EOF"), + ]; + let ascii_out = write_ascii(&tags); + let back_ascii = parse(ascii_out.as_bytes()).unwrap(); + assert_eq!(back_ascii[0], Tag::invalid(10, "NaN")); + assert_eq!(back_ascii[1], Tag::invalid(20, "inf")); + assert_eq!(back_ascii[2], Tag::invalid(30, "malformed")); + + let bin_out = write_binary(&tags, true); + let back_bin = parse(&bin_out).unwrap(); + assert_eq!(back_bin[0], Tag::invalid(10, "NaN")); + assert_eq!(back_bin[1], Tag::invalid(20, "inf")); + assert_eq!(back_bin[2], Tag::f(30, 0.0)); + } } #[cfg(test)] diff --git a/crates/dxf/tests/hardening.rs b/crates/dxf/tests/hardening.rs index 4d013f1f4f..8fed323ef5 100644 --- a/crates/dxf/tests/hardening.rs +++ b/crates/dxf/tests/hardening.rs @@ -13,17 +13,36 @@ fn bin_with(f: impl FnOnce(&mut Vec)) -> Vec { } #[test] -fn binary_reals_that_are_not_finite_become_zero() { +fn binary_reals_that_are_not_finite_become_invalid() { for bits in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { let b = bin_with(|b| { b.extend_from_slice(&10i16.to_le_bytes()); b.extend_from_slice(&bits.to_le_bytes()); }); let tags = parse(&b).unwrap(); - assert_eq!(tags[0], Tag::f(10, 0.0), "{bits}"); + assert_eq!(tags[0], Tag::invalid(10, bits.to_string()), "{bits}"); + assert_eq!(tags[0].f64(), 0.0, "backward compatibility for f64: {bits}"); + assert_eq!(tags[0].i64(), 0, "backward compatibility for i64: {bits}"); + assert!(tags[0].is_invalid()); } } +#[test] +fn malformed_path_coordinates_are_invalid_and_do_not_silently_snap_to_origin() { + // Malformed line entity coordinates (groups 10, 20, 11, 21) + let dxf = b"0\nSECTION\n2\nENTITIES\n0\nLINE\n10\n100.0\n20\nNaN\n11\ncorrupted\n21\n200.0\n0\nENDSEC\n0\nEOF\n"; + let tags = parse(dxf).unwrap(); + let y0 = tags.iter().find(|t| t.code == 20).unwrap(); + let x1 = tags.iter().find(|t| t.code == 11).unwrap(); + assert_eq!(y0.value, Value::Invalid("NaN".into())); + assert_eq!(x1.value, Value::Invalid("corrupted".into())); + assert!(y0.is_invalid()); + assert!(x1.is_invalid()); + // Legacy callers still get 0.0 + assert_eq!(y0.f64(), 0.0); + assert_eq!(x1.f64(), 0.0); +} + #[test] fn ascii_accepts_bom_and_cr_only_line_ends() { let want = vec![Tag::s(0, "SECTION"), Tag::s(2, "ENTITIES"), Tag::s(0, "ENDSEC"), Tag::s(0, "EOF")]; From dca616ff73c75651dce2ed05090fe6817df5d86a Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 24 Nov 2026 18:59:46 +0530 Subject: [PATCH 104/130] style(dxf): apply cargo fmt formatting --- crates/dxf/src/lib.rs | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index f63c73d3d8..522a0046c6 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -597,11 +597,7 @@ fn parse_binary_pass(b: &[u8], max_tags: usize, text: &mut codepage::BinaryText) Kind::Str => Value::Str(unescape_unicode(&text.string(code, c.cstr()?))), Kind::Real => { let r = c.f64()?; - if r.is_finite() { - Value::Real(r) - } else { - Value::Invalid(r.to_string()) - } + if r.is_finite() { Value::Real(r) } else { Value::Invalid(r.to_string()) } } Kind::Int16 => Value::Int(i64::from(c.i16()?)), Kind::Int32 => Value::Int(i64::from(c.i32()?)), @@ -1409,12 +1405,7 @@ mod tests { #[test] fn invalid_reals_roundtrip_in_ascii_and_binary() { - let tags = vec![ - Tag::invalid(10, "NaN"), - Tag::invalid(20, "inf"), - Tag::invalid(30, "malformed"), - Tag::s(0, "EOF"), - ]; + let tags = vec![Tag::invalid(10, "NaN"), Tag::invalid(20, "inf"), Tag::invalid(30, "malformed"), Tag::s(0, "EOF")]; let ascii_out = write_ascii(&tags); let back_ascii = parse(ascii_out.as_bytes()).unwrap(); assert_eq!(back_ascii[0], Tag::invalid(10, "NaN")); From 9efbe4517a35b47a2f056f88637152ff9587b2d6 Mon Sep 17 00:00:00 2001 From: el-j Date: Tue, 24 Nov 2026 14:51:56 +0100 Subject: [PATCH 105/130] craft-video: Theora encoder checks chroma samples from the rounded-down start to the rounded-up end of the crop --- crates/video/src/theora/encoder.rs | 43 +++++++++++++++-------------- crates/video/tests/theora.rs | 44 ++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 20 deletions(-) diff --git a/crates/video/src/theora/encoder.rs b/crates/video/src/theora/encoder.rs index ec43310c96..407225e6e5 100644 --- a/crates/video/src/theora/encoder.rs +++ b/crates/video/src/theora/encoder.rs @@ -24,6 +24,28 @@ pub struct EncoderConfig { pub keyframe_distance: u32, } +impl EncoderConfig { + /// The part of plane `pli` the picture covers, as `(x, y, width, height)` in samples. A + /// subsampled plane takes every sample that lies under a visible luma sample, so the start + /// rounds down and the end (exclusive) rounds up: with an odd offset the first and last chroma + /// samples can each be shared with a luma sample outside the picture. + fn active_region(&self, pli: usize) -> (usize, usize, usize, usize) { + let (shift_x, shift_y) = match (pli, self.pixel_format) { + (0, _) | (_, PixelFormat::Yuv444) => (0, 0), + (_, PixelFormat::Yuv422) => (1, 0), + (_, PixelFormat::Yuv420) => (1, 1), + }; + let span = |origin: u32, size: u32, shift: u32| { + let start = (origin >> shift) as usize; + let end = (origin as usize + size as usize).div_ceil(1 << shift); + (start, end.saturating_sub(start)) + }; + let (x, w) = span(self.pic_x, self.pic_width, shift_x); + let (y, h) = span(self.pic_y, self.pic_height, shift_y); + (x, y, w, h) + } +} + impl Default for EncoderConfig { fn default() -> Self { Self { @@ -268,26 +290,7 @@ impl Encoder { _ => (&pic.y, pic.y_stride), }; - let (active_w, active_h, active_x, active_y) = match pli { - 0 => (self.config.pic_width as usize, self.config.pic_height as usize, self.config.pic_x as usize, self.config.pic_y as usize), - _ => match self.config.pixel_format { - PixelFormat::Yuv420 => ( - (self.config.pic_width as usize).div_ceil(2), - (self.config.pic_height as usize).div_ceil(2), - (self.config.pic_x as usize) / 2, - (self.config.pic_y as usize) / 2, - ), - PixelFormat::Yuv422 => ( - (self.config.pic_width as usize).div_ceil(2), - self.config.pic_height as usize, - (self.config.pic_x as usize) / 2, - self.config.pic_y as usize, - ), - PixelFormat::Yuv444 => { - (self.config.pic_width as usize, self.config.pic_height as usize, self.config.pic_x as usize, self.config.pic_y as usize) - } - }, - }; + let (active_x, active_y, active_w, active_h) = self.config.active_region(pli); // Read 8x8 block from source picture (origin at lower-left!) // Note: In Theora coordinates, row 0 is at the bottom of the plane. diff --git a/crates/video/tests/theora.rs b/crates/video/tests/theora.rs index 720286bade..2c57b510e6 100644 --- a/crates/video/tests/theora.rs +++ b/crates/video/tests/theora.rs @@ -633,3 +633,47 @@ fn test_theora_yuv444_chroma_motion_vector_half_pixel() { // (If quarter-pixel units were used erroneously, it would have averaged ref_cb[0] and ref_cb[1] giving (0 + 200)/2 = 100) assert_eq!(pred[0][0], 200); } + +/// With an odd picture offset the chroma samples under the visible luma are counted from the +/// rounded-down start to the rounded-up end, so a missing edge sample is an error and a missing +/// sample outside the visible crop is not. +#[test] +fn test_theora_odd_crop_checks_the_chroma_edge_samples() { + let cfg = EncoderConfig { + width: 32, + height: 32, + pic_width: 2, + pic_height: 2, + pic_x: 1, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv422, + color_space: ColorSpace::Undefined, + quality: 40, + keyframe_distance: 64, + }; + let mut enc = Encoder::new(cfg).expect("encoder"); + let mut pic = test_picture(32, 32); + pic.pixel_format = PixelFormat::Yuv422; + pic.pic_width = 2; + pic.pic_height = 2; + pic.pic_x = 1; + pic.uv_stride = 16; + pic.u = vec![128; 16 * 32]; + pic.v = vec![128; 16 * 32]; + assert!(enc.encode_frame(&pic, true).is_ok()); + // Luma x = 1 and x = 2 sit over chroma columns 0 and 1; row 1, column 1 is the last one needed. + let needed = 16 + 2; + let mut short = pic.clone(); + short.u.truncate(needed - 1); + assert!(matches!(enc.encode_frame(&short, true), Err(Error::DimensionMismatch(_)))); + let mut short = pic.clone(); + short.v.truncate(needed - 1); + assert!(matches!(enc.encode_frame(&short, true), Err(Error::DimensionMismatch(_)))); + // Everything past the crop may be missing. + let mut trimmed = pic.clone(); + trimmed.u.truncate(needed); + trimmed.v.truncate(needed); + assert!(enc.encode_frame(&trimmed, true).is_ok()); +} From 6454a33c83309170b2904ef184d374915ef562fb Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Tue, 24 Nov 2026 19:38:04 +0530 Subject: [PATCH 106/130] fix(dxf): write non-finite NaN sentinel for unparseable invalid text in binary DXF --- crates/dxf/src/lib.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 522a0046c6..7fbcc3ef73 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -839,7 +839,7 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { Kind::Real => { out.extend_from_slice(&code_bytes); let r = match &t.value { - Value::Invalid(s) => s.parse::().unwrap_or_else(|_| t.value.as_f64()), + Value::Invalid(s) => s.parse::().unwrap_or(f64::NAN), _ => t.value.as_f64(), }; out.extend_from_slice(&r.to_le_bytes()); @@ -1416,7 +1416,11 @@ mod tests { let back_bin = parse(&bin_out).unwrap(); assert_eq!(back_bin[0], Tag::invalid(10, "NaN")); assert_eq!(back_bin[1], Tag::invalid(20, "inf")); - assert_eq!(back_bin[2], Tag::f(30, 0.0)); + // Invalid text that cannot be parsed as a float is preserved in binary DXF as NaN, + // so it remains invalid rather than silently converting to genuine zero. + assert_eq!(back_bin[2], Tag::invalid(30, "NaN")); + assert_eq!(back_bin[2].f64(), 0.0); + assert!(back_bin[2].is_invalid()); } } From 7e63794b2d7fa41de4f3d79df71a1e7378096a0f Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 25 Nov 2026 00:33:29 +0530 Subject: [PATCH 107/130] fix(dxf): preserve invalid integers and non-finite Tag::f values (#3265) --- crates/dxf/src/lib.rs | 13 +++++++++---- crates/dxf/tests/hardening.rs | 22 +++++++++++++++++++--- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 7fbcc3ef73..158c4bc15f 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -113,7 +113,7 @@ impl Tag { Tag { code, value: Value::Str(v.into()) } } pub fn f(code: i32, v: f64) -> Self { - Tag { code, value: Value::Real(if v.is_finite() { v } else { 0.0 }) } + Tag { code, value: if v.is_finite() { Value::Real(v) } else { Value::Invalid(v.to_string()) } } } pub fn i(code: i32, v: i64) -> Self { Tag { code, value: Value::Int(v) } @@ -180,14 +180,19 @@ fn typed(code: i32, text: &str) -> Value { Kind::Int16 | Kind::Int32 | Kind::Int64 => { // A float spelling ("1e3", "12.0") is accepted when finite, clamped to what the // group's width holds, signed or unsigned (files write 16-bit flags up to 65535, as - // the integer spelling reads them); NaN, inf and text become 0. + // the integer spelling reads them); NaN, inf and non-numeric text become Value::Invalid. let (lo, hi) = match kind_of(code) { Kind::Int16 => (i64::from(i16::MIN), i64::from(u16::MAX)), Kind::Int32 => (i64::from(i32::MIN), i64::from(u32::MAX)), _ => (i64::MIN, i64::MAX), }; - t.parse::() - .map_or_else(|_| Value::Int(t.parse::().ok().filter(|f| f.is_finite()).map_or(0, |f| (f as i64).clamp(lo, hi))), Value::Int) + match t.parse::() { + Ok(i) => Value::Int(i), + Err(_) => match t.parse::() { + Ok(f) if f.is_finite() => Value::Int((f as i64).clamp(lo, hi)), + _ => Value::Invalid(t.to_string()), + }, + } } Kind::Bool => Value::Bool(t.parse::().unwrap_or(0) != 0), Kind::Hex => Value::Hex(normalize_hex(t)), diff --git a/crates/dxf/tests/hardening.rs b/crates/dxf/tests/hardening.rs index 8fed323ef5..eb9ca6c896 100644 --- a/crates/dxf/tests/hardening.rs +++ b/crates/dxf/tests/hardening.rs @@ -126,19 +126,35 @@ fn trailing_spaces_keep_sections_and_eof() { #[test] fn integer_groups_reject_non_finite_and_clamp() { let t = parse(b"70\ninf\n70\nNaN\n70\n1e30\n70\n-1e30\n90\n1e30\n160\n1e30\n160\n-inf\n62\n12.0\n0\nEOF\n").unwrap(); - assert_eq!(t[0], Tag::i(70, 0)); - assert_eq!(t[1], Tag::i(70, 0)); + assert_eq!(t[0], Tag::invalid(70, "inf")); + assert_eq!(t[0].i64(), 0); + assert_eq!(t[1], Tag::invalid(70, "NaN")); + assert_eq!(t[1].i64(), 0); // Clamped to what the group's width holds, unsigned values included (the binary writer // keeps up to 65535 and 4294967295 as their bit patterns). assert_eq!(t[2], Tag::i(70, i64::from(u16::MAX))); assert_eq!(t[3], Tag::i(70, i64::from(i16::MIN))); assert_eq!(t[4], Tag::i(90, i64::from(u32::MAX))); assert_eq!(t[5], Tag::i(160, i64::MAX)); - assert_eq!(t[6], Tag::i(160, 0)); + assert_eq!(t[6], Tag::invalid(160, "-inf")); + assert_eq!(t[6].i64(), 0); assert_eq!(t[7], Tag::i(62, 12)); assert_eq!(Value::Str("inf".into()).as_i64(), 0); } +#[test] +fn tag_f_non_finite_creates_invalid() { + let nan_tag = Tag::f(10, f64::NAN); + assert!(nan_tag.is_invalid()); + assert_eq!(nan_tag.f64(), 0.0); + assert_eq!(nan_tag.invalid_str(), Some("NaN")); + + let inf_tag = Tag::f(20, f64::INFINITY); + assert!(inf_tag.is_invalid()); + assert_eq!(inf_tag.f64(), 0.0); + assert_eq!(inf_tag.invalid_str(), Some("inf")); +} + /// An unsigned value spelled as a float reads as the same spelled as an integer (#1026 review): /// `65535.0` is 65535 like `65535`, not 32767. #[test] From 97ce4a2bea13080a38a49e42ad82f4747db69e18 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:36:30 +0100 Subject: [PATCH 108/130] fix(exr): hold the writer to the reader's per-header attribute limit The writer counted text attributes across the file only, so a part with more than 4,096 attributes in all saved but did not reopen. One shared constant now bounds a header in the writer and both readers, and the writer counts every attribute it emits for a part, standard ones included. --- crates/exr/src/decode.rs | 4 ++ crates/exr/src/seek.rs | 10 ++--- crates/exr/src/stream.rs | 8 ++-- crates/exr/src/write.rs | 13 +++++- crates/exr/src/write_tests.rs | 78 ++++++++++++++++++++++++++++++++++- 5 files changed, 101 insertions(+), 12 deletions(-) diff --git a/crates/exr/src/decode.rs b/crates/exr/src/decode.rs index bd7aca975e..ca97651776 100644 --- a/crates/exr/src/decode.rs +++ b/crates/exr/src/decode.rs @@ -65,6 +65,10 @@ fn map_exr(e: exr::error::Error) -> Error { } } +/// The most attributes one header may hold, standard ones included. The readers refuse a header +/// above it and the writer refuses to produce one. +pub(crate) const MAX_HEADER_ATTRIBUTES: usize = 4096; + /// Caps on what a file may ask the reader to allocate. `#[non_exhaustive]`: start from /// [`Limits::default`] and set the fields you change. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/exr/src/seek.rs b/crates/exr/src/seek.rs index f01349bd30..0bccc7dad0 100644 --- a/crates/exr/src/seek.rs +++ b/crates/exr/src/seek.rs @@ -60,7 +60,7 @@ use exr::meta::MetaData; use exr::meta::attribute::SampleType as ExrSample; use exr::meta::header::Header; -use crate::decode::{Limits, PartInfo, Window, check_previews, part_info}; +use crate::decode::{Limits, MAX_HEADER_ATTRIBUTES, PartInfo, Window, check_previews, part_info}; /// Why a read failed. More kinds may be added: a `match` needs a catch-all arm. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] @@ -119,10 +119,10 @@ fn exr_error(e: exr::error::Error) -> Error { } const MAGIC: [u8; 4] = [0x76, 0x2f, 0x31, 0x01]; -/// Headers of all parts together: at most this many bytes, parts, and attributes per part. +/// Headers of all parts together: at most this many bytes and parts. Attributes per header are +/// bounded by `MAX_HEADER_ATTRIBUTES`. const META_BYTES: usize = 8 << 20; const MAX_PARTS: usize = 1024; -const MAX_ATTRIBUTES: usize = 4096; /// The most chunks all parts of a file may have together. The offset tables and the index hold /// a few bytes per chunk, so a header declaring billions of tiny tiles (whose tables a short file /// can't hold anyway) is refused before anything is sized by it. 16 million chunks is a 64K × @@ -393,8 +393,8 @@ fn read_headers(r: &mut R, cancel: &dyn Fn() -> bool) -> Resul break; } attributes += 1; - if attributes > MAX_ATTRIBUTES { - return Err(Error::LimitExceeded("more than 4096 attributes in a header".into())); + if attributes > MAX_HEADER_ATTRIBUTES { + return Err(Error::LimitExceeded(format!("more than {MAX_HEADER_ATTRIBUTES} attributes in a header"))); } read_name(r, &mut prefix, None)?; let mut size = [0u8; 4]; diff --git a/crates/exr/src/stream.rs b/crates/exr/src/stream.rs index c3d942e947..6f9ab3ef3d 100644 --- a/crates/exr/src/stream.rs +++ b/crates/exr/src/stream.rs @@ -1,6 +1,6 @@ //! Bounded block-by-block reading of one flat scan-line part (feature `decode`): a reader that //! never sizes a buffer by the whole picture. [`Decoder::new`] reads the headers (at most 8 MiB -//! and 4096 attributes) and the offset table through `Read + Seek`; [`Decoder::next_band`] then +//! and 4,096 attributes) and the offset table through `Read + Seek`; [`Decoder::next_band`] then //! returns one compression block at a time as interleaved f32 samples. A caller that writes bands //! into tiled storage can open pictures larger than memory. //! @@ -21,7 +21,7 @@ use exr::{ }; use crate::channels::{ColorLayout, color_channels}; -use crate::decode::{Error, Result}; +use crate::decode::{Error, MAX_HEADER_ATTRIBUTES, Result}; const META_BYTES: usize = 8 << 20; const BLOCK_BYTES: usize = 64 << 20; @@ -73,8 +73,8 @@ fn metadata(r: &mut impl Read, cancel: &dyn Fn() -> bool) -> Result> { break; } attributes += 1; - if attributes > 4096 { - return Err(limit("EXR metadata exceeds 4096 attributes")); + if attributes > MAX_HEADER_ATTRIBUTES { + return Err(limit(&format!("EXR metadata exceeds {MAX_HEADER_ATTRIBUTES} attributes"))); } string(r, &mut prefix)?; let length = read::<4>(r)?; diff --git a/crates/exr/src/write.rs b/crates/exr/src/write.rs index 035a77b78a..0e2daba2a4 100644 --- a/crates/exr/src/write.rs +++ b/crates/exr/src/write.rs @@ -17,7 +17,7 @@ use exr::meta::attribute::{ }; use exr::meta::{BlockDescription, Headers, header::Header}; -use crate::decode::{Compression, Error, Result, SampleType, Window, f16, to_exr_compression}; +use crate::decode::{Compression, Error, MAX_HEADER_ATTRIBUTES, Result, SampleType, Window, f16, to_exr_compression}; const MAX_PARTS: usize = 1024; const MAX_CHANNELS: usize = 16_384; @@ -64,7 +64,10 @@ pub struct Metadata<'a> { /// CIE xy for red, green, blue and white, shared by every part. pub chromaticities: Option<[[f32; 2]; 4]>, /// Text attributes by input part index. An empty slice supplies no attributes. The file - /// accepts at most 16,384 text attributes and 8 MiB of estimated headers. + /// accepts at most 16,384 text attributes and 8 MiB of estimated headers. A part's header + /// holds at most 4,096 attributes, so its text attributes leave room for the standard + /// attributes the writer adds (channels, windows, compression and the like, plus the part + /// name and type in a multipart file). pub text_attributes: &'a [TextAttributes<'a>], } @@ -446,6 +449,12 @@ fn prepare_headers<'a>( header.own_attributes.layer_name = name; header.shared_attributes.chromaticities = chromaticities; set_text_attributes(&mut header, attributes)?; + let header_attributes = header.all_named_attributes().count(); + if header_attributes > MAX_HEADER_ATTRIBUTES { + return Err(encode(format_args!( + "part {index} has {header_attributes} attributes, standard ones included, and a header holds at most {MAX_HEADER_ATTRIBUTES}" + ))); + } headers.push(header); channel_orders.push(order); } diff --git a/crates/exr/src/write_tests.rs b/crates/exr/src/write_tests.rs index f0eb4696ea..a9c2737441 100644 --- a/crates/exr/src/write_tests.rs +++ b/crates/exr/src/write_tests.rs @@ -1,7 +1,7 @@ use std::cell::Cell; use std::io::{self, Cursor, Seek, SeekFrom, Write}; -use crate::decode::{self, Compression, Error, Limits, SampleType, Samples, Window, f16}; +use crate::decode::{self, Compression, Error, Limits, MAX_HEADER_ATTRIBUTES, SampleType, Samples, Window, f16}; use crate::seek::{Index, Request, read_planes}; use crate::write::{Channel, Metadata, Part, RowSamples, TilePart, TileWriter, write_scanlines, write_scanlines_with_metadata, write_tiles}; @@ -196,6 +196,82 @@ fn invalid_tile_dimensions_and_metadata_fail_before_output() { } } +// Chunk count, channels, compression, line order, display and data windows, pixel aspect ratio, +// screen window centre and width, block type and part name +const MULTIPART_SCANLINE_ATTRIBUTES: usize = 11; + +fn numbered_attributes(count: usize) -> Vec<(String, String)> { + (0..count).map(|n| (format!("pass{n}"), format!("value{n}"))).collect() +} + +fn borrowed(attributes: &[(String, String)]) -> Vec<(&str, &str)> { + attributes.iter().map(|(name, value)| (name.as_str(), value.as_str())).collect() +} + +#[test] +fn multipart_header_at_the_attribute_limit_round_trips() { + let window = Window { width: 2, height: 2, ..WINDOW }; + let beauty = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::Zip16 }; + let depth = Part { name: Some("Depth"), ..beauty }; + let user_attributes = numbered_attributes(MAX_HEADER_ATTRIBUTES - MULTIPART_SCANLINE_ATTRIBUTES); + let borrowed_attributes = borrowed(&user_attributes); + let text = [&borrowed_attributes[..], &[("passLabel", "Depth")][..]]; + let metadata = Metadata { text_attributes: &text, ..Metadata::default() }; + let mut out = Cursor::new(Vec::new()); + + write_scanlines_with_metadata(&mut out, window, &[beauty, depth], &metadata, sample_row).unwrap(); + + let index = Index::build(&mut out, &Limits::default(), &|| false).unwrap(); + let last = user_attributes.len() - 1; + assert_eq!(index.parts()[0].text("pass0"), Some("value0")); + assert_eq!(index.parts()[0].text(&format!("pass{last}")), Some(format!("value{last}").as_str())); + assert_eq!(index.parts()[1].text("passLabel"), Some("Depth")); +} + +#[test] +fn multipart_header_over_the_attribute_limit_is_refused_before_output() { + let window = Window { width: 2, height: 2, ..WINDOW }; + let beauty = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::Zip16 }; + let depth = Part { name: Some("Depth"), ..beauty }; + let user_attributes = numbered_attributes(MAX_HEADER_ATTRIBUTES - MULTIPART_SCANLINE_ATTRIBUTES + 1); + let borrowed_attributes = borrowed(&user_attributes); + let text = [&[][..], &borrowed_attributes[..]]; + let metadata = Metadata { text_attributes: &text, ..Metadata::default() }; + let mut out = Cursor::new(Vec::new()); + + let result = write_scanlines_with_metadata(&mut out, window, &[beauty, depth], &metadata, |_, _, _, _| panic!("reached callback")); + + assert!(matches!(&result, Err(Error::Encode(message)) if message.contains("part 1") && message.contains("4096")), "{result:?}"); + assert!(out.get_ref().is_empty()); +} + +#[test] +fn tiled_header_with_chromaticities_counts_them_against_the_attribute_limit() { + let window = Window { width: 2, height: 2, ..WINDOW }; + let part = Part { name: Some("Beauty"), data_window: window, channels: &[FLOAT], compression: Compression::Zip16 }; + let tiled = TilePart { part, tile_width: 2, tile_height: 2 }; + let chromaticities = Some([[0.64, 0.33], [0.3, 0.6], [0.15, 0.06], [0.3127, 0.329]]); + // The scan-line set plus the tile description and the shared chromaticities + let user_count = MAX_HEADER_ATTRIBUTES - MULTIPART_SCANLINE_ATTRIBUTES - 2; + let user_attributes = numbered_attributes(user_count); + let borrowed_attributes = borrowed(&user_attributes); + let text = [&borrowed_attributes[..]]; + let metadata = Metadata { chromaticities, text_attributes: &text }; + let mut out = Cursor::new(Vec::new()); + + write_tiles(&mut out, window, &[tiled], &metadata, |_, window, tile| fill_tile(tiled, window, tile)).unwrap(); + + Index::build(&mut out, &Limits::default(), &|| false).unwrap(); + let over_attributes = numbered_attributes(user_count + 1); + let borrowed_over = borrowed(&over_attributes); + let over_text = [&borrowed_over[..]]; + let over = Metadata { chromaticities, text_attributes: &over_text }; + let mut refused = Cursor::new(Vec::new()); + let result = write_tiles(&mut refused, window, &[tiled], &over, |_, _, _| panic!("reached callback")); + assert!(matches!(result, Err(Error::Encode(_))), "{result:?}"); + assert!(refused.get_ref().is_empty()); +} + #[test] fn incomplete_tiles_are_rejected() { let part = Part { name: None, data_window: WINDOW, channels: &[FLOAT], compression: Compression::Zip16 }; From ec4247be6a96e736cafe7211a4f705910cfbc64b Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 25 Nov 2026 01:54:25 +0100 Subject: [PATCH 109/130] fix(odf): a sublist's header written from the model stays in its parent item Co-Authored-By: Claude Opus 5.5 --- crates/odf/src/text/tests_more/lists.rs | 51 +++++++++++++ crates/odf/src/text/writer.rs | 97 +++++++++++-------------- 2 files changed, 94 insertions(+), 54 deletions(-) diff --git a/crates/odf/src/text/tests_more/lists.rs b/crates/odf/src/text/tests_more/lists.rs index b9bb69148f..115914ea02 100644 --- a/crates/odf/src/text/tests_more/lists.rs +++ b/crates/odf/src/text/tests_more/lists.rs @@ -428,3 +428,54 @@ fn zero_indent_multi_paragraph_header_survives_model_export() { assert!(p.props.numbering.is_none()); } } + +/// A sublist's header, written from the model, stays with the sublist's items in the item the +/// sublist is in: alone or of several paragraphs, below another header, and before the item goes +/// on after the sublist. +#[test] +fn a_sublists_header_written_from_the_model_stays_in_its_parent_item() { + let styles = format!( + r#""# + ); + // The lists of `xml`, without attributes. + let lists = |xml: &str| -> String { + let (from, to) = (xml.find("").unwrap()); + let mut out = String::new(); + for part in xml.get(from..to).unwrap().split('<').skip(1) { + let (tag, text) = part.split_once('>').unwrap(); + out.push_str(&format!("<{}>{text}", tag.split(' ').next().unwrap())); + } + out + "" + }; + let head = "Sub header"; + let sub = "Sub"; + for inner in [ + format!("{head}{sub}Sub two"), + format!( + "MoreSub headerSecond line{sub}" + ), + format!("{head}Parent again"), + "Sub headerDeeperDeepest".to_string(), + ] { + let list = |parent: &str, attrs: &str| { + format!( + "{parent}{inner}Next" + ) + }; + let content = format!( + "{}", + list("Parent", r#" text:style-name="L""#) + ); + let mut d = import(&package(&content, Some(&styles))).unwrap(); + // Edited, so the list is written from the model. + let i = d.body.iter().position(|b| b.as_para().is_some_and(|p| p.text == "Parent")).unwrap(); + d.insert_text(&craft_wordmodel::Pos::body(i, 0), "Edited ", &Default::default()).unwrap(); + let out = export(&d).unwrap(); + assert_eq!(lists(&crate::text::tests::content_of(&out)), list("Edited Parent", "")); + let rows = |d: &Document| { + let paras = d.body.iter().filter_map(|b| b.as_para()); + paras.map(|p| (p.text.clone(), p.props.numbering.map(|n| n.level), p.props.list_item)).collect::>() + }; + assert_eq!(rows(&import(&out).unwrap()), rows(&d)); + } +} diff --git a/crates/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index 84d0374477..bc268d786c 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -107,16 +107,13 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9 let mut kinds = [first; 9]; let mut seen = [false; 9]; let mut i = start; - // The level of the last item: an item's further paragraph goes in an item still open. - let mut last = usize::from(p.item.unwrap_or(0).min(8)); while let Some(FBlock::Para(q)) = blocks.get(i) { let Some(li) = q.list else { // A section it opens or closes ends the run, as an item's does. let wrap = q.wrap.as_deref().filter(|_| wraps); - match model::continues_list(blocks, i).map(usize::from) { - Some(lv) if lv <= last && (i == start || !wrap.is_some_and(|w| !w.0.is_empty())) => { - // The items below it are closed. - last = lv; + match model::continues_list(blocks, i) { + // (One below the last item is the header of a sublist in it.) + Some(_) if i == start || !wrap.is_some_and(|w| !w.0.is_empty()) => { i += 1; if wrap.is_some_and(|w| w.1 > 0) { break; @@ -127,7 +124,6 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9 } }; let l = li.level.min(8) as usize; - last = l; let list_id = *id.get_or_insert(li.list); if li.list != list_id || (list_id == 0 && l == 0 && seen[0] && kinds[0].ordered != li.ordered) { break; @@ -150,21 +146,36 @@ fn list_run(blocks: &[FBlock], start: usize, wraps: bool) -> (usize, [ListOut; 9 (i.max(start + 1), kinds, id.unwrap_or(0)) } -/// Close nested items and lists down to the requested open depth. -fn close_lists(out: &mut String, stack: &mut Vec, depth: usize) { - while stack.len() > depth { - if stack.pop() == Some(true) { - out.push_str(""); - } - out.push_str(""); - } +/// What is open in a list being written. +#[derive(Clone, Copy, PartialEq)] +enum ListPart { + None, + Item, + Header, } -/// Open or close the single leading header without splitting its consecutive paragraphs. -fn list_header(out: &mut String, is_open: &mut bool, open: bool) { - if *is_open != open { - out.push_str(if open { "" } else { "" }); - *is_open = open; +/// Close the open part of the innermost list, then open `part`. +fn list_part(out: &mut String, stack: &mut [ListPart], part: ListPart) { + let Some(top) = stack.last_mut() else { return }; + out.push_str(match top { + ListPart::None => "", + ListPart::Item => "", + ListPart::Header => "", + }); + out.push_str(match part { + ListPart::None => "", + ListPart::Item => "", + ListPart::Header => "", + }); + *top = part; +} + +/// Close nested items and lists down to the requested open depth. +fn close_lists(out: &mut String, stack: &mut Vec, depth: usize) { + while stack.len() > depth { + list_part(out, stack, ListPart::None); + stack.pop(); + out.push_str(""); } } @@ -976,30 +987,15 @@ impl Writer { self.list_styles.push(kinds); let lname = format!("{}L{}", self.prefix, self.list_styles.len()); let id_of_list = id; - // Open lists: per level, whether a list-item is open. - let mut stack: Vec = Vec::new(); - let mut header_open = false; + // Open lists: per level, what is open in it. + let mut stack: Vec = Vec::new(); for (qi, q) in blocks.get(start..i).unwrap_or(&[]).iter().enumerate() { let FBlock::Para(q) = q else { continue }; - if q.list.is_none() && stack.get(usize::from(q.item.unwrap_or(0).min(8))).copied() == Some(true) { - // An item's further paragraph (`list_run` took it only below an open - // item at its level): in that item, its sublists ended first. - let lv = q.item.map_or(0, |l| l.min(8) as usize); - close_lists(out, &mut stack, lv + 1); - self.para_in(q, chain(start + qi), out); - continue; - } - if q.list.is_some() { - list_header(out, &mut header_open, false); - } let lv = usize::from(q.list.map(|l| l.level).or(q.item).unwrap_or(0).min(8)); close_lists(out, &mut stack, lv + 1); while stack.len() < lv + 1 { - if let Some(top) = stack.last_mut() - && !*top - { - out.push_str(""); - *top = true; + if stack.last() == Some(&ListPart::None) { + list_part(out, &mut stack, ListPart::Item); } if stack.is_empty() { let id = format!("{}lst{}", self.prefix, self.list_styles.len()); @@ -1026,25 +1022,18 @@ impl Writer { } else { out.push_str(""); } - stack.push(false); + stack.push(ListPart::None); } - // Leading unnumbered paragraphs belong to one list header, not to - // the document body. Keep that membership when original markup is gone. - if q.list.is_none() { - list_header(out, &mut header_open, true); - self.para_in(q, chain(start + qi), out); - continue; + // An unnumbered paragraph goes in the item or header open at its level (its + // sublists ended first); a list's leading ones are its header's. Keep that + // membership when original markup is gone. + if q.list.is_some() { + list_part(out, &mut stack, ListPart::Item); + } else if stack.last() == Some(&ListPart::None) { + list_part(out, &mut stack, ListPart::Header); } - if let Some(top) = stack.last_mut() { - if *top { - out.push_str(""); - } - *top = true; - } - out.push_str(""); self.para_in(q, chain(start + qi), out); } - list_header(out, &mut header_open, false); close_lists(out, &mut stack, 0); self.close_wrap(closes.as_ref(), 0, out); out.push('\n'); From 65c5bdd66be6c7e2e9bb416fb3e0a4b68b86816e Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 25 Nov 2026 08:48:25 +0530 Subject: [PATCH 110/130] fix(dxf): provide checked conversion, unescape invalid ascii, and document binary integer loss (#3265) --- crates/dxf/src/lib.rs | 57 ++++++++++++++++++++++++++++++----- crates/dxf/tests/hardening.rs | 29 ++++++++++++++++++ 2 files changed, 78 insertions(+), 8 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 158c4bc15f..6b9d5ccde9 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -86,6 +86,26 @@ impl Value { _ => 0, } } + /// Return the finite float value, or `None` if this value is non-finite or represents an invalid numeric group. + pub fn checked_f64(&self) -> Option { + match self { + Value::Real(r) if r.is_finite() => Some(*r), + Value::Int(i) => Some(*i as f64), + Value::Str(s) => s.trim().parse::().ok().filter(|v| v.is_finite()), + Value::Bool(b) => Some(f64::from(u8::from(*b))), + _ => None, + } + } + /// Return the integer value, or `None` if this value represents an invalid numeric group or cannot be converted to `i64`. + pub fn checked_i64(&self) -> Option { + match self { + Value::Int(i) => Some(*i), + Value::Real(r) if r.is_finite() => Some(*r as i64), + Value::Str(s) => s.trim().parse::().ok().or_else(|| s.trim().parse::().ok().filter(|f| f.is_finite()).map(|f| f as i64)), + Value::Bool(b) => Some(i64::from(*b)), + _ => None, + } + } /// Whether this value represents a malformed or non-finite numeric group. pub fn is_invalid(&self) -> bool { matches!(self, Value::Invalid(_)) @@ -137,6 +157,14 @@ impl Tag { pub fn i64(&self) -> i64 { self.value.as_i64() } + /// Return the finite float value, or `None` if this tag's value is non-finite or invalid. + pub fn checked_f64(&self) -> Option { + self.value.checked_f64() + } + /// Return the integer value, or `None` if this tag's value is invalid or cannot be converted to `i64`. + pub fn checked_i64(&self) -> Option { + self.value.checked_i64() + } pub fn is_invalid(&self) -> bool { self.value.is_invalid() } @@ -231,8 +259,9 @@ pub use codepage::decode_code_page; /// /// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair, /// truncated binary data, or more group codes than the limit returned by [`max_tags()`], which is -/// [`MAX_TAGS`] by default. For ASCII input, invalid numeric text becomes `0.0` for real values or -/// `0` for integer values, and an EOF tag is not required. +/// [`MAX_TAGS`] by default. For ASCII input, invalid numeric text is preserved as [`Value::Invalid`], +/// and an EOF tag is not required. Numeric accessors ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or +/// `0` for backward compatibility. pub fn parse(bytes: &[u8]) -> Result> { parse_with_limit(bytes, max_tags()) } @@ -285,7 +314,8 @@ fn count_ascii_pairs(bytes: &[u8]) -> usize { /// /// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair, /// truncated binary data, or more than `max_tags` group codes. For ASCII input, invalid numeric -/// text becomes `0.0` for real values or `0` for integer values, and an EOF tag is not required. +/// text is preserved as [`Value::Invalid`], and an EOF tag is not required. Numeric accessors +/// ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or `0` for backward compatibility. pub fn parse_with_limit(bytes: &[u8], max_tags: usize) -> Result> { if let Some(body) = bytes.strip_prefix(BINARY_SENTINEL) { return parse_binary_with_limit(body, max_tags); @@ -434,7 +464,8 @@ fn byte_lines(mut rest: &[u8]) -> impl Iterator { /// # Errors /// /// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair, -/// or too many tags. Invalid numeric text becomes `0.0` for real values or `0` for integer values. +/// or too many tags. Invalid numeric text is preserved as [`Value::Invalid`]. Numeric accessors +/// ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or `0` for backward compatibility. /// A complete tag stream does not require an EOF tag. pub fn parse_ascii(text: &str) -> Result> { parse_ascii_counted(text, max_tags(), 0) @@ -480,6 +511,7 @@ fn ascii_tags(text: &str, max_tags: usize, expected: usize, recover: bool) -> Re let v = match typed(code, val) { // Only text with a backslash can hold an escape; the rest moves in as it is. Value::Str(s) => Value::Str(unescape_owned(s)), + Value::Invalid(s) => Value::Invalid(unescape_owned(s)), o => o, }; let eof = code == 0 && matches!(&v, Value::Str(s) if s.trim_end() == "EOF"); @@ -813,6 +845,10 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec { /// several groups of the same code). Strings are UTF-8 when `utf8` (R2007+), otherwise escaped as /// in [`write_ascii`]. A tag's value is converted to its code's kind, so a number written as text /// is stored as a number; a code outside the 16-bit range is skipped. +/// +/// Invalid real values ([`Value::Invalid`]) are preserved across binary serialization using +/// `f64::NAN`. Because binary integer representations have no non-finite sentinel, invalid +/// integer groups are encoded as `0`. pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec { binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }) } @@ -845,21 +881,26 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { out.extend_from_slice(&code_bytes); let r = match &t.value { Value::Invalid(s) => s.parse::().unwrap_or(f64::NAN), - _ => t.value.as_f64(), + _ => t.value.checked_f64().unwrap_or(0.0), }; out.extend_from_slice(&r.to_le_bytes()); } Kind::Int16 => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&wrap_i16(t.value.as_i64())); + // Binary DXF integer fields have no IEEE-754 non-finite / NaN marker. + // Value::Invalid explicitly loses invalidity and converts to 0 via checked_i64. + let i = t.value.checked_i64().unwrap_or(0); + out.extend_from_slice(&wrap_i16(i)); } Kind::Int32 => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&wrap_i32(t.value.as_i64())); + let i = t.value.checked_i64().unwrap_or(0); + out.extend_from_slice(&wrap_i32(i)); } Kind::Int64 => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&t.value.as_i64().to_le_bytes()); + let i = t.value.checked_i64().unwrap_or(0); + out.extend_from_slice(&i.to_le_bytes()); } Kind::Bool => { out.extend_from_slice(&code_bytes); diff --git a/crates/dxf/tests/hardening.rs b/crates/dxf/tests/hardening.rs index eb9ca6c896..a01b123d13 100644 --- a/crates/dxf/tests/hardening.rs +++ b/crates/dxf/tests/hardening.rs @@ -147,14 +147,43 @@ fn tag_f_non_finite_creates_invalid() { let nan_tag = Tag::f(10, f64::NAN); assert!(nan_tag.is_invalid()); assert_eq!(nan_tag.f64(), 0.0); + assert_eq!(nan_tag.checked_f64(), None); + assert_eq!(nan_tag.checked_i64(), None); assert_eq!(nan_tag.invalid_str(), Some("NaN")); let inf_tag = Tag::f(20, f64::INFINITY); assert!(inf_tag.is_invalid()); assert_eq!(inf_tag.f64(), 0.0); + assert_eq!(inf_tag.checked_f64(), None); + assert_eq!(inf_tag.checked_i64(), None); assert_eq!(inf_tag.invalid_str(), Some("inf")); } +#[test] +fn invalid_numbers_with_dxf_escapes_roundtrip_through_ascii_write_and_parse() { + let tags = + vec![Tag::invalid(10, "12.34\\U+0020xyz"), Tag::invalid(20, "bad\\U+005Cpath"), Tag::invalid(70, "corrupted\\U+0041"), Tag::s(0, "EOF")]; + let ascii_out = write_ascii(&tags); + let back = parse(ascii_out.as_bytes()).unwrap(); + assert_eq!(back[0], Tag::invalid(10, "12.34\\U+0020xyz")); + assert_eq!(back[1], Tag::invalid(20, "bad\\U+005Cpath")); + assert_eq!(back[2], Tag::invalid(70, "corrupted\\U+0041")); +} + +#[test] +fn binary_integer_writer_makes_invalid_loss_explicit() { + let invalid_int_tag = Tag::invalid(70, "corrupted"); + assert!(invalid_int_tag.is_invalid()); + assert_eq!(invalid_int_tag.checked_i64(), None); + assert_eq!(invalid_int_tag.i64(), 0); + + // Binary DXF integer groups have no NaN marker, so invalid integers explicitly encode as 0 + let bin = write_binary(&[invalid_int_tag, Tag::s(0, "EOF")], true); + let back = parse(&bin).unwrap(); + assert_eq!(back[0], Tag::i(70, 0)); + assert_eq!(back[0].checked_i64(), Some(0)); +} + /// An unsigned value spelled as a float reads as the same spelled as an integer (#1026 review): /// `65535.0` is 65535 like `65535`, not 32767. #[test] From 6a01305271a8f0a2a3080918b955daf1c9c31352 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 25 Nov 2026 09:05:18 +0530 Subject: [PATCH 111/130] craft-sniff: document OpenRaster HEAD contract exception and add boundary regression --- crates/sniff/src/detect.rs | 11 +++++- crates/sniff/src/lib.rs | 9 ++++- crates/sniff/src/tests.rs | 76 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 4 deletions(-) diff --git a/crates/sniff/src/detect.rs b/crates/sniff/src/detect.rs index 510d6de0c6..793041a163 100644 --- a/crates/sniff/src/detect.rs +++ b/crates/sniff/src/detect.rs @@ -2,7 +2,9 @@ use crate::Kind; -/// How many leading bytes [`identify`] reads at most. Every signature it knows lies within them. +/// How many leading bytes [`identify`] reads at most. Every signature it knows lies within them, +/// except for container formats like OpenRaster whose distinguishing payload may be pushed past +/// this window by variable-length ZIP extra fields (which fall back to [`Kind::Zip`]). pub const HEAD: usize = 4096; /// The largest universal Mach-O architecture count taken as Mach-O rather than a Java class. @@ -25,6 +27,11 @@ const TS_SYNC: u8 = 0x47; /// headers, MPEG transport stream packets), so a file is never named by a weak signature when a /// strong one matches. /// +/// OpenRaster (`.ora`) archives require an uncompressed `mimetype` entry as their first file, +/// but permit variable-length ZIP extra fields. If ZIP metadata pushes the `image/openraster` +/// payload beyond [`HEAD`] bytes, `identify` falls back to [`Kind::Zip`] as an intentionally +/// bounded format hint rather than reading an unbounded stream. +/// /// `CAFEBABE` starts both a universal Mach-O and a Java class file. The next big-endian 32-bit /// value is a Mach-O architecture count or a class file's version: up to 44 is taken as /// [`Kind::MachOFat`], 45 and over as [`Kind::JavaClass`]. A caller that knows the file name @@ -102,7 +109,7 @@ fn checked(b: &[u8]) -> Option { } /// `PK\x03\x04`: an OpenRaster archive when the first entry is a stored `mimetype` holding -/// `image/openraster`, otherwise [`Kind::Zip`]. +/// `image/openraster` within [`HEAD`], otherwise [`Kind::Zip`]. fn zip(b: &[u8]) -> Kind { if is_ora(b) { Kind::Ora } else { Kind::Zip } } diff --git a/crates/sniff/src/lib.rs b/crates/sniff/src/lib.rs index b95e11591a..c62bb405ab 100644 --- a/crates/sniff/src/lib.rs +++ b/crates/sniff/src/lib.rs @@ -15,9 +15,14 @@ //! Which kinds an app supports, and what it does when the name and the bytes disagree, stay //! with the app. //! -//! [`HEAD`] bytes are enough for every signature; passing more changes nothing, passing fewer +//! [`HEAD`] bytes are enough for almost every signature; passing more changes nothing, passing fewer //! only loses the signatures that sit further in (TAR's at byte 257, MPEG transport streams' -//! third packet). Any input is fine: nothing here allocates, panics or reads past the slice. +//! third packet). An exception is OpenRaster ([`Kind::Ora`]): the OpenRaster specification requires +//! an uncompressed `mimetype` entry as the first file in the ZIP archive, but permits variable-length +//! ZIP extra fields. If ordinary ZIP metadata pushes the `image/openraster` payload beyond [`HEAD`] +//! bytes, [`identify`] safely falls back to [`Kind::Zip`] even if the full file was supplied. +//! Downstream callers can distinguish an intentionally bounded format hint from an exhaustive +//! format guarantee. Any input is fine: nothing here allocates, panics or reads past the slice. //! //! Written from the formats' public specifications and registrations (IANA media types, ISO/IEC //! 14496-12 brands, the EBML and Matroska specifications, RIFF, the ELF, PE and Mach-O headers). diff --git a/crates/sniff/src/tests.rs b/crates/sniff/src/tests.rs index 3771990725..dd980c8cfd 100644 --- a/crates/sniff/src/tests.rs +++ b/crates/sniff/src/tests.rs @@ -376,6 +376,82 @@ fn names_openraster_and_silhouette_studio() { assert_eq!(identify(&zip64_desc_ora), Some(Kind::Ora)); } +#[test] +fn openraster_extra_fields_boundary_and_zip_fallback() { + // OpenRaster specifies that the first entry must be an uncompressed "mimetype" file, + // but permits arbitrary ZIP extra fields. + // When extra fields push the "image/openraster" payload past HEAD bytes (4096), + // identify safely falls back to Kind::Zip even when the complete file is supplied. + + fn ora_with_extra(mime: &[u8], extra: &[u8]) -> Vec { + let mut b = b"PK\x03\x04".to_vec(); + b.extend_from_slice(&20u16.to_le_bytes()); + b.extend_from_slice(&0u16.to_le_bytes()); + b.extend_from_slice(&0u16.to_le_bytes()); + b.extend_from_slice(&0u16.to_le_bytes()); + b.extend_from_slice(&0u16.to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); + let len = u32::try_from(mime.len()).unwrap_or(0); + b.extend_from_slice(&len.to_le_bytes()); + b.extend_from_slice(&len.to_le_bytes()); + b.extend_from_slice(&8u16.to_le_bytes()); + let extra_len = u16::try_from(extra.len()).unwrap_or(0); + b.extend_from_slice(&extra_len.to_le_bytes()); + b.extend_from_slice(b"mimetype"); + b.extend_from_slice(extra); + b.extend_from_slice(mime); + b + } + + fn make_ordinary_extra(total_len: usize) -> Vec { + let mut extra = Vec::with_capacity(total_len); + // Ordinary Info-ZIP Extended Timestamp (0x5455): flag (1 byte) + modtime (4 bytes) + if total_len >= 9 { + extra.extend_from_slice(&0x5455u16.to_le_bytes()); + extra.extend_from_slice(&5u16.to_le_bytes()); + extra.push(1); + extra.extend_from_slice(&1_700_000_000u32.to_le_bytes()); + } + // Fill remaining extra field space with ordinary Info-ZIP Unix metadata (0x7875) + while extra.len() < total_len { + let remaining = total_len.saturating_sub(extra.len()); + if remaining >= 4 { + let data_len = remaining.saturating_sub(4).min(u16::MAX as usize); + let data_u16 = u16::try_from(data_len).unwrap_or(u16::MAX); + extra.extend_from_slice(&0x7875u16.to_le_bytes()); + extra.extend_from_slice(&data_u16.to_le_bytes()); + extra.resize(extra.len().saturating_add(data_len), 0); + } else { + extra.resize(total_len, 0); + break; + } + } + extra + } + + // Header (30) + "mimetype" (8) = 38 bytes before extra fields. + // "image/openraster" = 16 bytes. + // Total before payload end = 38 + extra_len + 16 = 54 + extra_len. + // At HEAD = 4096: + // extra_len = 4096 - 54 = 4042: payload ends exactly at byte 4096 (inside HEAD). + let extra_at_boundary = make_ordinary_extra(4042); + let ora_at_boundary = ora_with_extra(b"image/openraster", &extra_at_boundary); + assert_eq!(ora_at_boundary.len(), HEAD); + assert_eq!(identify(&ora_at_boundary), Some(Kind::Ora)); + + // extra_len = 4043: payload ends at byte 4097 (crosses HEAD by 1 byte). + // Even when the full 4097 bytes are supplied, identify caps at HEAD and falls back to Zip. + let extra_past_boundary = make_ordinary_extra(4043); + let ora_past_boundary = ora_with_extra(b"image/openraster", &extra_past_boundary); + assert_eq!(ora_past_boundary.len(), HEAD + 1); + assert_eq!(identify(&ora_past_boundary), Some(Kind::Zip)); + + // extra_len = 4100: payload starts at byte 4138 (entirely beyond HEAD). + let extra_well_past = make_ordinary_extra(4100); + let ora_well_past = ora_with_extra(b"image/openraster", &extra_well_past); + assert_eq!(identify(&ora_well_past), Some(Kind::Zip)); +} + #[test] fn every_prefix_of_every_sample_is_safe() { let mut samples = vec![ From 5520a5bf73a9600566a30b222fe97299cde3bead Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 25 Nov 2026 09:18:05 +0530 Subject: [PATCH 112/130] fix(dxf): fail binary write on invalid integer, add checked_i64 bounds, and preserve raw numeric escapes (#3265) --- crates/dxf/src/lib.rs | 148 ++++++++++++++++++++++++---- crates/dxf/tests/audit_followups.rs | 4 +- crates/dxf/tests/binary_write.rs | 10 +- crates/dxf/tests/code_page_write.rs | 10 +- crates/dxf/tests/conformance.rs | 6 +- crates/dxf/tests/hardening.rs | 16 +-- crates/dxf/tests/hex_chunks.rs | 2 +- crates/dxf/tests/recovering.rs | 2 +- crates/dxf/tests/roundtrip.rs | 3 +- 9 files changed, 159 insertions(+), 42 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 6b9d5ccde9..2035945b66 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -35,6 +35,10 @@ pub enum DxfError { /// The memory for `tags` group codes couldn't be had: an error, not the process ending. #[error("not enough memory to read this drawing's {tags} DXF group codes")] OutOfMemory { tags: usize }, + /// An invalid integer value ([`Value::Invalid`]) cannot be encoded in binary DXF + /// because binary integer fields have no non-finite sentinel. + #[error("cannot encode invalid integer tag (group {code}) as binary DXF: `{text}`")] + InvalidInteger { code: i32, text: String }, } pub type Result = std::result::Result; @@ -52,6 +56,13 @@ pub enum Value { Invalid(String), } +const I64_MIN_F64: f64 = -9_223_372_036_854_775_808.0; +const I64_MAX_EXCLUSIVE_F64: f64 = 9_223_372_036_854_775_808.0; + +fn f64_to_i64_checked(r: f64) -> Option { + if r.is_finite() && (I64_MIN_F64..I64_MAX_EXCLUSIVE_F64).contains(&r) { Some(r as i64) } else { None } +} + impl Value { pub fn as_str(&self) -> String { match self { @@ -100,8 +111,8 @@ impl Value { pub fn checked_i64(&self) -> Option { match self { Value::Int(i) => Some(*i), - Value::Real(r) if r.is_finite() => Some(*r as i64), - Value::Str(s) => s.trim().parse::().ok().or_else(|| s.trim().parse::().ok().filter(|f| f.is_finite()).map(|f| f as i64)), + Value::Real(r) => f64_to_i64_checked(*r), + Value::Str(s) => s.trim().parse::().ok().or_else(|| s.trim().parse::().ok().and_then(f64_to_i64_checked)), Value::Bool(b) => Some(i64::from(*b)), _ => None, } @@ -479,6 +490,21 @@ fn parse_ascii_counted(text: &str, max_tags: usize, expected: usize) -> Result String { + let unescaped = unescape_owned(s.clone()); + if unescaped == s { + return s; + } + let becomes_valid_numeric = match kind_of(code) { + Kind::Real => unescaped.trim().parse::().ok().filter(|v| v.is_finite()).is_some(), + Kind::Int16 | Kind::Int32 | Kind::Int64 => { + unescaped.trim().parse::().is_ok() || unescaped.trim().parse::().ok().filter(|f| f.is_finite()).is_some() + } + _ => false, + }; + if becomes_valid_numeric { s } else { unescaped } +} + /// The tags of ASCII DXF text. With `recover`, a line that is no group code, or a group code /// with no value after it, ends the reading instead of failing it: the tags before it are /// returned with the 1-based number of that line. @@ -511,7 +537,7 @@ fn ascii_tags(text: &str, max_tags: usize, expected: usize, recover: bool) -> Re let v = match typed(code, val) { // Only text with a backslash can hold an escape; the rest moves in as it is. Value::Str(s) => Value::Str(unescape_owned(s)), - Value::Invalid(s) => Value::Invalid(unescape_owned(s)), + Value::Invalid(s) => Value::Invalid(unescape_invalid(code, s)), o => o, }; let eof = code == 0 && matches!(&v, Value::Str(s) if s.trim_end() == "EOF"); @@ -847,19 +873,34 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec { /// is stored as a number; a code outside the 16-bit range is skipped. /// /// Invalid real values ([`Value::Invalid`]) are preserved across binary serialization using -/// `f64::NAN`. Because binary integer representations have no non-finite sentinel, invalid -/// integer groups are encoded as `0`. -pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec { - binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }) +/// `f64::NAN`. +/// +/// # Errors +/// +/// Returns [`DxfError::InvalidInteger`] if any integer tag holds an invalid value ([`Value::Invalid`]), +/// because binary DXF integer representations have no IEEE-754 non-finite sentinel. Callers who +/// want invalid integers normalized to `0` can use [`write_binary_lossy`]. +pub fn write_binary(tags: &[Tag], utf8: bool) -> Result> { + binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }, false) } /// Write tags as pre-R2007 binary DXF with text in the code page `code_page` names, as /// [`write_ascii_in`] does. -pub fn write_binary_in(tags: &[Tag], code_page: &str) -> Vec { - binary(tags, Strings::Escaped(codepage::encoder(code_page))) +/// +/// # Errors +/// +/// Returns [`DxfError::InvalidInteger`] if any integer tag holds an invalid value ([`Value::Invalid`]). +pub fn write_binary_in(tags: &[Tag], code_page: &str) -> Result> { + binary(tags, Strings::Escaped(codepage::encoder(code_page)), false) } -fn binary(tags: &[Tag], strings: Strings) -> Vec { +/// Write tags as binary DXF, normalizing invalid integer tags ([`Value::Invalid`]) to `0` +/// instead of returning an error. +pub fn write_binary_lossy(tags: &[Tag], utf8: bool) -> Vec { + binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }, true).unwrap_or_default() +} + +fn binary(tags: &[Tag], strings: Strings, normalize_invalid_integers: bool) -> Result> { let mut out = Vec::with_capacity(BINARY_SENTINEL.len() + tags.len() * 12); out.extend_from_slice(BINARY_SENTINEL); for t in tags { @@ -887,19 +928,35 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { } Kind::Int16 => { out.extend_from_slice(&code_bytes); - // Binary DXF integer fields have no IEEE-754 non-finite / NaN marker. - // Value::Invalid explicitly loses invalidity and converts to 0 via checked_i64. - let i = t.value.checked_i64().unwrap_or(0); + let i = match t.value.checked_i64() { + Some(i) => i, + None if normalize_invalid_integers => 0, + None => { + return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() }); + } + }; out.extend_from_slice(&wrap_i16(i)); } Kind::Int32 => { out.extend_from_slice(&code_bytes); - let i = t.value.checked_i64().unwrap_or(0); + let i = match t.value.checked_i64() { + Some(i) => i, + None if normalize_invalid_integers => 0, + None => { + return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() }); + } + }; out.extend_from_slice(&wrap_i32(i)); } Kind::Int64 => { out.extend_from_slice(&code_bytes); - let i = t.value.checked_i64().unwrap_or(0); + let i = match t.value.checked_i64() { + Some(i) => i, + None if normalize_invalid_integers => 0, + None => { + return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() }); + } + }; out.extend_from_slice(&i.to_le_bytes()); } Kind::Bool => { @@ -921,7 +978,7 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { } } } - out + Ok(out) } /// Hex text cleaned up: only the hex digits are kept, and an odd trailing digit is padded with @@ -1156,7 +1213,7 @@ mod tests { let tags = vec![Tag::s(8, text)]; let back = parse_ascii(&write_ascii_as(&tags, utf8)).unwrap(); assert_eq!(back, tags, "utf8={utf8} {text}"); - let back = parse_binary(&write_binary(&tags, utf8)).unwrap(); + let back = parse_binary(&write_binary(&tags, utf8).unwrap()).unwrap(); assert_eq!(back[1..], tags[..], "binary utf8={utf8} {text}"); } } @@ -1458,7 +1515,7 @@ mod tests { assert_eq!(back_ascii[1], Tag::invalid(20, "inf")); assert_eq!(back_ascii[2], Tag::invalid(30, "malformed")); - let bin_out = write_binary(&tags, true); + let bin_out = write_binary(&tags, true).unwrap(); let back_bin = parse(&bin_out).unwrap(); assert_eq!(back_bin[0], Tag::invalid(10, "NaN")); assert_eq!(back_bin[1], Tag::invalid(20, "inf")); @@ -1468,6 +1525,61 @@ mod tests { assert_eq!(back_bin[2].f64(), 0.0); assert!(back_bin[2].is_invalid()); } + + #[test] + fn checked_i64_bounds_enforced_including_exclusive_upper_bound() { + // Inclusive lower bound: -2^63 fits + assert_eq!(Value::Real(-9_223_372_036_854_775_808.0).checked_i64(), Some(i64::MIN)); + assert_eq!(Value::Str("-9223372036854775808".into()).checked_i64(), Some(i64::MIN)); + + // Just below lower bound: does not fit + assert_eq!(Value::Real(-1e30).checked_i64(), None); + assert_eq!(Value::Str("-1e30".into()).checked_i64(), None); + + // Exclusive upper bound: 2^63 does not fit in i64 + assert_eq!(Value::Real(9_223_372_036_854_775_808.0).checked_i64(), None); + assert_eq!(Value::Str("9223372036854775808".into()).checked_i64(), None); + + // Just below exclusive upper bound: 2^63 - 2048 (largest representable f64 < 2^63) + assert_eq!(Value::Real(9_223_372_036_854_774_784.0).checked_i64(), Some(9_223_372_036_854_774_784)); + + // Normal values + assert_eq!(Value::Real(42.0).checked_i64(), Some(42)); + assert_eq!(Value::Int(42).checked_i64(), Some(42)); + assert_eq!(Value::Invalid("foo".into()).checked_i64(), None); + } + + #[test] + fn invalid_numeric_escape_does_not_decode_into_valid_numeric_spelling() { + let text = "10\n\\U+0030\n0\nEOF\n"; + let tags = parse(text.as_bytes()).unwrap(); + assert_eq!(tags[0], Tag::invalid(10, "\\U+0030")); + assert!(tags[0].is_invalid()); + + // Roundtrip in ASCII preserves raw invalid escape and signal + let ascii_out = write_ascii(&tags); + let back_ascii = parse(ascii_out.as_bytes()).unwrap(); + assert_eq!(back_ascii[0], Tag::invalid(10, "\\U+0030")); + assert!(back_ascii[0].is_invalid()); + + // Roundtrip in binary preserves invalid signal via NaN sentinel + let bin_out = write_binary(&tags, true).unwrap(); + let back_bin = parse(&bin_out).unwrap(); + assert_eq!(back_bin[0], Tag::invalid(10, "NaN")); + assert!(back_bin[0].is_invalid()); + } + + #[test] + fn binary_integer_writer_reports_error_unless_lossy_normalized() { + let tags = vec![Tag::invalid(70, "corrupted"), Tag::s(0, "EOF")]; + // Checked write_binary returns error for invalid integer tag + assert!(matches!(write_binary(&tags, true), Err(DxfError::InvalidInteger { code: 70, .. }))); + + // Explicit write_binary_lossy normalizes invalid integer to 0 + let lossy_bin = write_binary_lossy(&tags, true); + let back = parse(&lossy_bin).unwrap(); + assert_eq!(back[0], Tag::i(70, 0)); + } } #[cfg(test)] diff --git a/crates/dxf/tests/audit_followups.rs b/crates/dxf/tests/audit_followups.rs index de61bf175a..bd82631019 100644 --- a/crates/dxf/tests/audit_followups.rs +++ b/crates/dxf/tests/audit_followups.rs @@ -9,7 +9,7 @@ fn group_code_255_is_an_ordinary_code_in_binary_dxf() { // Code 255 used to be read as an R12 escape (`FF 00 `), so a file with that code could // not be read back. let tags = vec![Tag::s(255, "x"), Tag::s(0, "EOF")]; - let back = parse(&write_binary(&tags, true)).unwrap(); + let back = parse(&write_binary(&tags, true).unwrap()).unwrap(); assert_eq!(back.len(), 2); assert_eq!((back[0].code, back[0].str()), (255, "x".to_string())); } @@ -117,7 +117,7 @@ fn escapes_next_to_other_text_and_backslashes() { assert_eq!(parse(&file).unwrap()[0].str(), "éA\\ ü"); // And the writer keeps the literal text literal. let tags = [Tag::s(1, "é\\U+0041\\ ü"), Tag::s(0, "EOF")]; - assert_eq!(parse(&write_binary(&tags, true)).unwrap()[0].str(), "é\\U+0041\\ ü"); + assert_eq!(parse(&write_binary(&tags, true).unwrap()).unwrap()[0].str(), "é\\U+0041\\ ü"); } #[test] diff --git a/crates/dxf/tests/binary_write.rs b/crates/dxf/tests/binary_write.rs index 4ecaf17097..a899b4890f 100644 --- a/crates/dxf/tests/binary_write.rs +++ b/crates/dxf/tests/binary_write.rs @@ -25,14 +25,14 @@ fn sample() -> Vec { #[test] fn binary_roundtrips_every_value_kind() { for utf8 in [false, true] { - let bytes = write_binary(&sample(), utf8); + let bytes = write_binary(&sample(), utf8).unwrap(); assert!(is_binary(&bytes)); assert_eq!(parse(&bytes).unwrap(), sample(), "utf8 = {utf8}"); } // Pre-2007 strings are escaped to ASCII, 2007+ ones are UTF-8. - let old = write_binary(&sample(), false); + let old = write_binary(&sample(), false).unwrap(); assert!(old.windows(7).any(|w| w == b"\\U+56FE")); - let new = write_binary(&sample(), true); + let new = write_binary(&sample(), true).unwrap(); assert!(new.windows("图号".len()).any(|w| w == "图号".as_bytes())); } @@ -41,7 +41,7 @@ fn binary_converts_values_to_their_codes_kind() { // A number held as text at a numeric code, an out-of-range 16-bit value, a long chunk. let long = "AB".repeat(300); let tags = vec![Tag::s(70, "12"), Tag::i(62, 1 << 20), Tag::new(310, Value::Hex(long)), Tag::s(0, "EOF")]; - let back = parse(&write_binary(&tags, true)).unwrap(); + let back = parse(&write_binary(&tags, true).unwrap()).unwrap(); assert_eq!(back[0], Tag::i(70, 12)); assert_eq!(back[1], Tag::i(62, i64::from(i16::MAX))); let sizes: Vec = back.iter().filter(|t| t.code == 310).map(|t| t.str().len()).collect(); @@ -57,7 +57,7 @@ fn utf8_ascii_keeps_text_and_drops_line_breaks() { #[test] fn hostile_binary_input_never_panics() { - let good = write_binary(&sample(), true); + let good = write_binary(&sample(), true).unwrap(); // Every truncation, and every single-byte corruption of the body. for n in 0..good.len() { let _ = parse(good.get(..n).unwrap()); diff --git a/crates/dxf/tests/code_page_write.rs b/crates/dxf/tests/code_page_write.rs index 02e8a75d2b..35ce1ed457 100644 --- a/crates/dxf/tests/code_page_write.rs +++ b/crates/dxf/tests/code_page_write.rs @@ -43,7 +43,7 @@ fn text_is_written_in_the_code_page() { ]; for (cp, text, raw) in cases { let tags = file(cp, text); - for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] { assert!(contains(&bytes, raw), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); } @@ -60,7 +60,7 @@ fn unknown_ascii_and_utf8_code_pages_are_pure_ascii() { assert!(bytes.is_ascii(), "{cp}"); assert_eq!(bytes, write_ascii(&tags).into_bytes(), "{cp}"); assert!(contains(&bytes, b"A\\U+00E7\\U+00E3o fim"), "{cp}"); - assert!(write_binary_in(&tags, cp).iter().all(u8::is_ascii), "{cp} binary"); + assert!(write_binary_in(&tags, cp).unwrap().iter().all(u8::is_ascii), "{cp} binary"); } } @@ -74,7 +74,7 @@ fn code_page_bytes_that_are_valid_utf8_are_escaped_in_ascii() { assert!(ascii.is_ascii(), "{:?}", String::from_utf8_lossy(&ascii)); assert!(contains(&ascii, b"\\U+0421\\U+0406")); assert_eq!(parse(&ascii).unwrap()[10].str(), "СІ"); - let binary = write_binary_in(&tags, "ANSI_1251"); + let binary = write_binary_in(&tags, "ANSI_1251").unwrap(); assert!(contains(&binary, b"\xD1\xB2")); assert_eq!(parse(&binary).unwrap()[10].str(), "СІ"); // Bytes that are not valid UTF-8 stay as they are. @@ -111,7 +111,7 @@ fn literal_escapes_survive_code_page_text() { [("ANSI_1252", "Ação \\U+00E9 \\M+183A4F"), ("ANSI_1251", "Слой \\U+0041"), ("ANSI_1251", "СІ \\U+0041"), ("ANSI_932", "表 \\M+1")] { let tags = file(cp, text); - for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] { assert!(contains(&bytes, b"\\U+005C"), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); } @@ -132,7 +132,7 @@ fn a_trail_byte_backslash_never_starts_an_escape() { ]; for (cp, text, written, never) in cases { let tags = file(cp, text); - for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] { assert!(contains(&bytes, written), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); assert!(!contains(&bytes, never), "{cp} {what}: a trail byte starts an escape"); assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); diff --git a/crates/dxf/tests/conformance.rs b/crates/dxf/tests/conformance.rs index 2c09e28e81..8112a30758 100644 --- a/crates/dxf/tests/conformance.rs +++ b/crates/dxf/tests/conformance.rs @@ -42,7 +42,7 @@ fn writes_independently_specified_ascii_and_binary_bytes() { for utf8 in [false, true] { let tags = std::slice::from_ref(&tag); assert_eq!(write_ascii_as(tags, utf8).as_bytes(), ascii, "ASCII code {}", tag.code); - assert_eq!(write_binary(tags, utf8), [SENTINEL, binary].concat(), "binary code {}", tag.code); + assert_eq!(write_binary(tags, utf8).unwrap(), [SENTINEL, binary].concat(), "binary code {}", tag.code); } } } @@ -66,7 +66,7 @@ fn integer_code_ranges_have_independent_binary_widths() { let expected = [SENTINEL, &code_bytes, &value_bytes[..width]].concat(); let tags = [Tag::i(code, value)]; for utf8 in [false, true] { - assert_eq!(write_binary(&tags, utf8), expected, "code={code} value={value} utf8={utf8}"); + assert_eq!(write_binary(&tags, utf8).unwrap(), expected, "code={code} value={value} utf8={utf8}"); } assert_eq!(parse(&expected).unwrap(), tags, "code={code} value={value}"); } @@ -83,7 +83,7 @@ fn text_encoding_has_independent_wire_expectations() { let ascii = [b" 1\r\n".as_slice(), text, b"\r\n"].concat(); let binary = [SENTINEL, b"\x01\0", text, b"\0"].concat(); assert_eq!(write_ascii_as(&tags, unicode).as_bytes(), ascii, "utf8={unicode}"); - assert_eq!(write_binary(&tags, unicode), binary, "utf8={unicode}"); + assert_eq!(write_binary(&tags, unicode).unwrap(), binary, "utf8={unicode}"); assert_eq!(parse(&ascii).unwrap(), tags); assert_eq!(parse(&binary).unwrap(), tags); } diff --git a/crates/dxf/tests/hardening.rs b/crates/dxf/tests/hardening.rs index a01b123d13..c35067540a 100644 --- a/crates/dxf/tests/hardening.rs +++ b/crates/dxf/tests/hardening.rs @@ -171,15 +171,19 @@ fn invalid_numbers_with_dxf_escapes_roundtrip_through_ascii_write_and_parse() { } #[test] -fn binary_integer_writer_makes_invalid_loss_explicit() { +fn binary_integer_writer_reports_error_unless_lossy_normalized() { let invalid_int_tag = Tag::invalid(70, "corrupted"); assert!(invalid_int_tag.is_invalid()); assert_eq!(invalid_int_tag.checked_i64(), None); assert_eq!(invalid_int_tag.i64(), 0); - // Binary DXF integer groups have no NaN marker, so invalid integers explicitly encode as 0 - let bin = write_binary(&[invalid_int_tag, Tag::s(0, "EOF")], true); - let back = parse(&bin).unwrap(); + // Binary DXF integer groups have no NaN marker, so write_binary reports conversion error + let res = write_binary(&[invalid_int_tag.clone(), Tag::s(0, "EOF")], true); + assert!(matches!(res, Err(craft_dxf::DxfError::InvalidInteger { code: 70, .. }))); + + // Explicit write_binary_lossy normalizes invalid integer to 0 + let lossy_bin = craft_dxf::write_binary_lossy(&[invalid_int_tag, Tag::s(0, "EOF")], true); + let back = parse(&lossy_bin).unwrap(); assert_eq!(back[0], Tag::i(70, 0)); assert_eq!(back[0].checked_i64(), Some(0)); } @@ -203,7 +207,7 @@ fn hex_groups_pad_odd_digits_and_drop_junk() { assert_eq!(t[2].value, Value::Hex(String::new())); assert_eq!(t[3].value, Value::Hex("0aF0".into())); // The binary writer agrees with the reader: the odd digit is padded, nothing shifts. - let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true)).unwrap(); + let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true).unwrap()).unwrap(); assert_eq!(back[0].value, Value::Hex("ABC0".into())); } @@ -235,7 +239,7 @@ fn binary_sixteen_and_thirty_two_bit_values_wrap_in_range_and_clamp_outside() { Tag::i(90, -(1 << 40)), Tag::s(0, "EOF"), ]; - let back = parse(&write_binary(&tags, true)).unwrap(); + let back = parse(&write_binary(&tags, true).unwrap()).unwrap(); assert_eq!(back[0], Tag::i(70, -1)); assert_eq!(back[1], Tag::i(70, 40000 - 65536)); assert_eq!(back[2], Tag::i(70, i64::from(i16::MAX))); diff --git a/crates/dxf/tests/hex_chunks.rs b/crates/dxf/tests/hex_chunks.rs index 80e9e91933..e9f34fa0c4 100644 --- a/crates/dxf/tests/hex_chunks.rs +++ b/crates/dxf/tests/hex_chunks.rs @@ -52,7 +52,7 @@ fn check_ascii(code: i32, bytes: &[u8], utf8: bool) { } fn check_binary(code: i32, bytes: &[u8], utf8: bool) { - let wire = write_binary(&input(code, bytes), utf8); + let wire = write_binary(&input(code, bytes), utf8).unwrap(); let mut chunks = wire.strip_prefix(SENTINEL).unwrap().strip_suffix(FOLLOWING_BINARY).unwrap(); assert!(!chunks.is_empty(), "an empty payload must still have a tag"); let context = format!("binary code={code} bytes={} utf8={utf8}", bytes.len()); diff --git a/crates/dxf/tests/recovering.rs b/crates/dxf/tests/recovering.rs index 1dffd87f39..8df6a5231e 100644 --- a/crates/dxf/tests/recovering.rs +++ b/crates/dxf/tests/recovering.rs @@ -10,7 +10,7 @@ fn an_intact_file_reads_as_parse_reads_it() { assert_eq!(damaged, None); assert_eq!(tags, parse(WHOLE.as_bytes()).expect("reads")); // Binary files are read as before. - let binary = write_binary(&tags, true); + let binary = write_binary(&tags, true).unwrap(); assert_eq!(parse_recovering(&binary).expect("reads"), (tags, None)); } diff --git a/crates/dxf/tests/roundtrip.rs b/crates/dxf/tests/roundtrip.rs index 362bc725fa..0ab6c0dda5 100644 --- a/crates/dxf/tests/roundtrip.rs +++ b/crates/dxf/tests/roundtrip.rs @@ -23,7 +23,8 @@ fn check(case: &str, body: &[Tag]) { let mut current = original.clone(); for pass in 1..=2 { let context = format!("{case} · {version} · binary={binary} · pass={pass}"); - let bytes = if binary { write_binary(¤t, version.utf8()) } else { write_ascii_as(¤t, version.utf8()).into_bytes() }; + let bytes = + if binary { write_binary(¤t, version.utf8()).unwrap() } else { write_ascii_as(¤t, version.utf8()).into_bytes() }; assert_eq!(is_binary(&bytes), binary, "{context}"); let back = parse(&bytes).unwrap_or_else(|e| panic!("{context}: {e}")); assert_eq!(back.len(), original.len(), "{context}: tag count"); From 41bcc4d9f225dd9b984eae9d6883effa64723859 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 25 Nov 2026 09:51:05 +0530 Subject: [PATCH 113/130] fix(dxf): distinguish integer overflow from float syntax in checked_i64 (#3265) --- crates/dxf/src/lib.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 2035945b66..d8cb3f4463 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -112,7 +112,11 @@ impl Value { match self { Value::Int(i) => Some(*i), Value::Real(r) => f64_to_i64_checked(*r), - Value::Str(s) => s.trim().parse::().ok().or_else(|| s.trim().parse::().ok().and_then(f64_to_i64_checked)), + Value::Str(s) => match s.trim().parse::() { + Ok(i) => Some(i), + Err(err) if matches!(err.kind(), std::num::IntErrorKind::PosOverflow | std::num::IntErrorKind::NegOverflow) => None, + Err(_) => s.trim().parse::().ok().and_then(f64_to_i64_checked), + }, Value::Bool(b) => Some(i64::from(*b)), _ => None, } @@ -1532,17 +1536,28 @@ mod tests { assert_eq!(Value::Real(-9_223_372_036_854_775_808.0).checked_i64(), Some(i64::MIN)); assert_eq!(Value::Str("-9223372036854775808".into()).checked_i64(), Some(i64::MIN)); - // Just below lower bound: does not fit + // Adjacent decimal below lower bound: must not round to i64::MIN via float fallback + assert_eq!(Value::Str("-9223372036854775809".into()).checked_i64(), None); + + // Far below lower bound: does not fit assert_eq!(Value::Real(-1e30).checked_i64(), None); assert_eq!(Value::Str("-1e30".into()).checked_i64(), None); - // Exclusive upper bound: 2^63 does not fit in i64 + // Inclusive upper bound: 2^63 - 1 fits + assert_eq!(Value::Str("9223372036854775807".into()).checked_i64(), Some(i64::MAX)); + + // Exclusive upper bound / adjacent decimal above upper bound: does not fit assert_eq!(Value::Real(9_223_372_036_854_775_808.0).checked_i64(), None); assert_eq!(Value::Str("9223372036854775808".into()).checked_i64(), None); // Just below exclusive upper bound: 2^63 - 2048 (largest representable f64 < 2^63) assert_eq!(Value::Real(9_223_372_036_854_774_784.0).checked_i64(), Some(9_223_372_036_854_774_784)); + // Float syntax fallback still converts finite real strings within integer range + assert_eq!(Value::Str("12.0".into()).checked_i64(), Some(12)); + assert_eq!(Value::Str("-12.0".into()).checked_i64(), Some(-12)); + assert_eq!(Value::Str("1e3".into()).checked_i64(), Some(1000)); + // Normal values assert_eq!(Value::Real(42.0).checked_i64(), Some(42)); assert_eq!(Value::Int(42).checked_i64(), Some(42)); From 59dbd044fc179383c043ef48aa6b11d9abb71fe7 Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 25 Nov 2026 08:52:00 +0100 Subject: [PATCH 114/130] fix(video): Bink review findings in the docs, example, oracle test and probe scripts Docs: the README, the frame module and the crate docs said every decoder converts to VideoFrame; Bink's has no conversion. bink_binkdec creates its output as a new file, so no other name of the input (a hard link included) can be truncated. bink_oracle counts samples past the end of the shorter plane as differences. Decoder: a failed frame swaps the planes back instead of copying them, and a block without coefficient planes allocates no lists. Same output. Probe scripts: a failed or partial run no longer replaces a complete table (scans, trees2, dataset) or passes for a match (t8, fuzz_diff); bits read past the data are zeros in the probe as in the model (cmodel, rmodel); fit1 compares quantiser 0's rows only; cenc refuses magnitudes of more than 15 bits and pins the list order its self-check needs; dec3 clips scaled blocks to the plane; probe counts chroma rounded up; t1 and ac1 no longer import modules that are not here. fuzz_diff also follows the running DC, bounds each decoder's time and keeps its cases in a private directory. Co-Authored-By: Claude Opus 5.5 --- crates/video/README.md | 4 +-- crates/video/examples/bink_binkdec.rs | 12 +++---- crates/video/src/bink/decode.rs | 5 ++- crates/video/src/bink/mod.rs | 3 +- crates/video/src/frame/mod.rs | 3 +- crates/video/src/lib.rs | 2 +- crates/video/tests/bink_oracle.rs | 3 +- crates/video/tools/bink_probe/README.md | 4 +-- crates/video/tools/bink_probe/ac1.py | 2 +- crates/video/tools/bink_probe/cenc.py | 3 +- crates/video/tools/bink_probe/cmodel.py | 1 + crates/video/tools/bink_probe/dataset.py | 4 ++- crates/video/tools/bink_probe/dec3.py | 5 ++- crates/video/tools/bink_probe/fit1.py | 9 +++-- crates/video/tools/bink_probe/fuzz_diff.py | 39 ++++++++++++++-------- crates/video/tools/bink_probe/probe.py | 2 +- crates/video/tools/bink_probe/rmodel.py | 1 + crates/video/tools/bink_probe/scans.py | 1 + crates/video/tools/bink_probe/t1.py | 1 - crates/video/tools/bink_probe/t8.py | 3 +- crates/video/tools/bink_probe/trees2.py | 4 ++- 21 files changed, 69 insertions(+), 42 deletions(-) diff --git a/crates/video/README.md b/crates/video/README.md index ab4edc1be3..38a08f4f25 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -38,8 +38,8 @@ No codec feature is on by default. ## Decoded frames Each decoder returns its own picture type. `frame::VideoFrame` is a codec-agnostic form that -every decoder's output converts into with `VideoFrame::try_from` (always built; each conversion -comes with its codec's feature): +every decoder's output but Bink's converts into with `VideoFrame::try_from` (always built; each +conversion comes with its codec's feature): - Planes are `[Y, Cb, Cr]`, `[R, G, B]` or `[Y]` (`ColorFamily`), plus an optional alpha plane. DNx, VP9 and AV1 (identity matrix) store RGB as G, B, R; the conversion reorders them. diff --git a/crates/video/examples/bink_binkdec.rs b/crates/video/examples/bink_binkdec.rs index 1c6cb61a25..2fffbb9dfd 100644 --- a/crates/video/examples/bink_binkdec.rs +++ b/crates/video/examples/bink_binkdec.rs @@ -1,6 +1,7 @@ //! Decode the video of a Bink file to raw I420 (`binkdec in.bik out.yuv`), for comparison with //! other decoders. Prints `ok N` for each frame that decodes and `ERR N message` for each that -//! does not; a frame that fails writes no picture. +//! does not; a frame that fails writes no picture. The output must not exist yet, so it can't be the +//! input under another name. use std::io::Write; @@ -9,16 +10,11 @@ fn main() -> Result<(), Box> { let [_, input, output] = args.as_slice() else { return Err("usage: binkdec in.bik out.yuv".into()); }; - // creating the output truncates it: refuse when it is the input under another name - if let (Ok(a), Ok(b)) = (std::fs::canonicalize(input), std::fs::canonicalize(output)) - && a == b - { - return Err("the output would overwrite the input".into()); - } let file = std::fs::File::open(input)?; let bink = craft_media::bink::open(&file)?; let mut dec = craft_video::bink::Decoder::from_params(&bink.video_params())?; - let mut out = std::io::BufWriter::new(std::fs::File::create(output)?); + let out = std::fs::File::create_new(output).map_err(|e| format!("cannot create {output}: {e}"))?; + let mut out = std::io::BufWriter::new(out); for i in 0..bink.frames.len() { let frame = bink.read_frame(&file, i)?; match dec.decode(bink.split_frame(&frame)?.video) { diff --git a/crates/video/src/bink/decode.rs b/crates/video/src/bink/decode.rs index 08c8099c52..0a15871e9a 100644 --- a/crates/video/src/bink/decode.rs +++ b/crates/video/src/bink/decode.rs @@ -349,6 +349,9 @@ enum ListCoder { /// Reads the values of one block with the list coder: `top_plane + 1` planes for residue, /// `planes` planes for coefficients. `out` is indexed by row * 8 + column. fn read_list(bits: &mut Bits, coder: ListCoder, planes: u32, mut budget: u32, out: &mut [i32; 64]) -> Result<()> { + if planes == 0 { + return Ok(()); + } let mut list: Vec = Vec::with_capacity(80); list.extend([Entry::Parent(0, 2), Entry::Parent(2, 0), Entry::Parent(2, 2)]); match coder { @@ -356,7 +359,7 @@ fn read_list(bits: &mut Bits, coder: ListCoder, planes: u32, mut budget: u32, ou ListCoder::Residue => list.push(Entry::Group(0, 0)), } // positions in the order they became non-zero, for the residue refinement passes - let mut order: Vec = Vec::with_capacity(64); + let mut order: Vec = Vec::with_capacity(if coder == ListCoder::Residue { 64 } else { 0 }); let at = |r: u8, c: u8| usize::from(r) * 8 + usize::from(c); for plane in (0..planes).rev() { if coder == ListCoder::Residue { diff --git a/crates/video/src/bink/mod.rs b/crates/video/src/bink/mod.rs index 6fb2f7b562..6fe072387e 100644 --- a/crates/video/src/bink/mod.rs +++ b/crates/video/src/bink/mod.rs @@ -218,8 +218,9 @@ impl Decoder { p.cur.fill(0); } if let Err(e) = self.decode_planes(packet) { + // the last picture is current again; the failed one is cleared when the next frame starts for p in &mut self.planes { - p.cur.copy_from_slice(&p.prev); + std::mem::swap(&mut p.cur, &mut p.prev); } return Err(e); } diff --git a/crates/video/src/frame/mod.rs b/crates/video/src/frame/mod.rs index cf092f43f1..ffc77f8da0 100644 --- a/crates/video/src/frame/mod.rs +++ b/crates/video/src/frame/mod.rs @@ -3,7 +3,8 @@ //! Each decoder in this crate returns its own picture type. [`VideoFrame`] holds what they have in //! common: planar samples at their stored width (`u8` or `u16`), per-plane bit depth, chroma //! subsampling, an optional alpha plane, colour tags as ITU-T H.273 code points, and timing. -//! Every decoder output converts into it with `VideoFrame::try_from`, behind the codec's feature. +//! Every decoder output but Bink's converts into it with `VideoFrame::try_from`, behind the codec's +//! feature. //! A conversion moves the sample buffers; it does not copy or rescale samples. Paletted video is //! the exception: VMD's decoder holds palette indices, and converting it (`&vmd::Decoder`) writes //! new 8-bit R, G, B planes from its palette. diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index e9a2c33ee7..fb1d9cc9aa 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -27,7 +27,7 @@ //! The decoders bound the pictures they hold with a memory budget ([`budget`]). //! //! Each decoder returns its own picture type. [`frame::VideoFrame`] is the codec-agnostic form -//! they all convert into (`VideoFrame::try_from`). +//! they all convert into (`VideoFrame::try_from`), except Bink's, which has no conversion. //! //! `TrackDecoder` picks the decoder for a track from its `craft_media::CodecParams` and returns //! `VideoFrame`s, for H.264, HEVC, VP9, AV1, MPEG-2, ProRes, DNx, APV, FFV1 and VP8 diff --git a/crates/video/tests/bink_oracle.rs b/crates/video/tests/bink_oracle.rs index 9ddb1ddf7a..b8c73bc46b 100644 --- a/crates/video/tests/bink_oracle.rs +++ b/crates/video/tests/bink_oracle.rs @@ -76,7 +76,8 @@ fn real_files_decode_like_ffmpeg() { } let (y, rest) = theirs.split_at(w * h); let (u, v) = rest.split_at(cw * ch); - let diff = |a: &[u8], b: &[u8]| a.iter().zip(b).filter(|(x, y)| x != y).count(); + // samples past the end of the shorter plane differ too + let diff = |a: &[u8], b: &[u8]| a.iter().zip(b).filter(|(x, y)| x != y).count() + a.len().abs_diff(b.len()); let (dy, du, dv) = (diff(&pic.y, y), diff(&pic.u, u), diff(&pic.v, v)); if dy + du + dv != 0 { failed = Some(format!("frame {i}: {dy} luma, {du} Cb and {dv} Cr samples differ")); diff --git a/crates/video/tools/bink_probe/README.md b/crates/video/tools/bink_probe/README.md index 9c0975ed40..ab76fe37db 100644 --- a/crates/video/tools/bink_probe/README.md +++ b/crates/video/tools/bink_probe/README.md @@ -18,8 +18,8 @@ are not part of the build or the tests. 1184): `t8.py`, `t9.py`, `synth.py` and `trees2.py`, and through them `scans.py`. - `BINK_PROBE_DECODER` (`fuzz_diff.py`): the program that decodes a `.bik` file with the Rust decoder; by default the `bink_binkdec` example in the workspace's release target directory. -- `BINK_PROBE_CASES` (`fuzz_diff.py`): where differing cases are kept; by default - `bink_probe_cases` in the system's temporary directory. +- `BINK_PROBE_CASES` (`fuzz_diff.py`): the directory in which each run makes its own one for the + cases it keeps; by default the system's temporary directory. - `IF` and `REV` (`cmodel.py`): switch the coefficient model to variants that were tried and rejected (`IF=1`: members left at zero go next to their group instead of to the front of the list; `REV=0`: they keep their order). The defaults are the model that matches. diff --git a/crates/video/tools/bink_probe/ac1.py b/crates/video/tools/bink_probe/ac1.py index 86bb9c4995..983c58d0dd 100644 --- a/crates/video/tools/bink_probe/ac1.py +++ b/crates/video/tools/bink_probe/ac1.py @@ -1,7 +1,7 @@ import sys, os sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from synth2 import * -from dc2 import bitsof +def bitsof(v, n): return [(v >> i) & 1 for i in range(n)] def probe_inline(inline, dc=800, blocks=((5, 5), (6, 5))): bits = frame(lambda b: luma_plane(b, {p: 5 for p in blocks}, idc_bits=bitsof(len(blocks), 10) + bitsof(dc, 11) + ([0] * 4 if len(blocks) > 1 else []), inline=inline), extra_zero=400) cur, prev, msg = decode(bits) diff --git a/crates/video/tools/bink_probe/cenc.py b/crates/video/tools/bink_probe/cenc.py index 61e8871cac..bba28f638f 100644 --- a/crates/video/tools/bink_probe/cenc.py +++ b/crates/video/tools/bink_probe/cenc.py @@ -7,6 +7,7 @@ def encode_coefs(coefs): if not coefs: return 0, [] top = {k: abs(x).bit_length() - 1 for k, x in coefs.items()} v = max(top.values()) + 1 + if v > 15: raise ValueError('a coefficient of more than 15 bits: the plane count is a 4-bit field') out = [] def members(mode, r, c): if mode == 'S': return [(r, c)] @@ -40,7 +41,7 @@ def encode_coefs(coefs): return v, out if __name__ == '__main__': import random, cmodel - os.environ['IF'] = '0'; cmodel.OPT['insig_front'] = False + os.environ['IF'] = '0'; os.environ['REV'] = '1'; cmodel.OPT['insig_front'] = False # the order the encoder writes rnd = random.Random(5); bad = 0 for t in range(2000): n = rnd.randint(0, 20) diff --git a/crates/video/tools/bink_probe/cmodel.py b/crates/video/tools/bink_probe/cmodel.py index 0b96b11483..d80253c1c0 100644 --- a/crates/video/tools/bink_probe/cmodel.py +++ b/crates/video/tools/bink_probe/cmodel.py @@ -51,6 +51,7 @@ if __name__ == '__main__': cases = [one(k) for k in range(n)] def run(bits): coefs, L = decode_coefs(bits, v) + bits = bits + [0] * (L - len(bits)) # the model read zeros past the end F = ac5.est(bitsof(v, 4) + bits[:L] + bitsof(ac5.Q, 4) + [0] * 40) if F is None: return bits, coefs, L, 'ffmpeg error' if abs(F[0][0] - ac5.DC * ac5.QDC) > 6: return bits, coefs, L, 'length wrong (DC %d)' % round(F[0][0]) diff --git a/crates/video/tools/bink_probe/dataset.py b/crates/video/tools/bink_probe/dataset.py index 415dbedb9a..d62d674cd8 100644 --- a/crates/video/tools/bink_probe/dataset.py +++ b/crates/video/tools/bink_probe/dataset.py @@ -4,6 +4,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from idct1 import block from concurrent.futures import ThreadPoolExecutor rnd = random.Random(int(sys.argv[2])); n = int(sys.argv[1]); out = sys.argv[3]; qfix = int(sys.argv[4]) if len(sys.argv) > 4 else None +if qfix is not None and not 0 <= qfix <= 15: raise SystemExit('the quantiser is a 4-bit field: 0 to 15') cases = [] for i in range(n): kind = i % 4 @@ -18,4 +19,5 @@ def run(c): g = block(co, dc=dc, q=q) return {'dc': dc, 'q': q, 'coefs': [[r, cc, x] for (r, cc), x in co.items()], 'px': g} with ThreadPoolExecutor(8) as ex: rows = [r for r in ex.map(run, cases) if r['px']] -json.dump(rows, open(out, 'w')); print('saved', len(rows)) +if not rows: raise SystemExit('no probe decoded: %s is not written' % out) +json.dump(rows, open(out, 'w')); print('saved', len(rows), 'rejected', n - len(rows)) diff --git a/crates/video/tools/bink_probe/dec3.py b/crates/video/tools/bink_probe/dec3.py index 45d60b5881..0b68e3dac1 100644 --- a/crates/video/tools/bink_probe/dec3.py +++ b/crates/video/tools/bink_probe/dec3.py @@ -120,8 +120,8 @@ def decode_plane(pk, pos, bw, bh, log=None, w1=10, w2=11, prev=None, widths=None elif t == 1: if by & 1 == 0: st_ = sub.get(); HOLD['subs'].append((by, bx, st_)); px = blk(st_) - for y in range(16): - for x in range(16): img[by * 8 + y][bx * 8 + x] = px[(y // 2) * 8 + x // 2] + for y in range(min(16, (bh - by) * 8)): + for x in range(min(16, (bw - bx) * 8)): img[by * 8 + y][bx * 8 + x] = px[(y // 2) * 8 + x // 2] bx += 1 else: px = blk(t) @@ -139,7 +139,6 @@ def decode_frame(pk, w, h, prev=None, order='YVU', widths=None): for name in order: pw, ph = (w, h) if name == 'Y' else (cw, ch) bw, bh = (pw + 7) // 8, (ph + 7) // 8 - if name != 'Y' and bh & 1: img = [[0] * (bw * 8) for _ in range(bh * 8 + 8)] out[name], end = decode_plane(pk, pos, bw, bh, prev=prev[name] if prev else None, widths=widths or widths_for(bw)) pos = (end + 31) // 32 * 32 return out, pos diff --git a/crates/video/tools/bink_probe/fit1.py b/crates/video/tools/bink_probe/fit1.py index 5ad5195cc1..22ad470623 100644 --- a/crates/video/tools/bink_probe/fit1.py +++ b/crates/video/tools/bink_probe/fit1.py @@ -28,12 +28,17 @@ def make(cbits, qbits, qshift, final_bias, final_shift, order, qround, mround): return [[((cols[c][r] + final_bias) >> final_shift) & 255 for c in range(8)] for r in range(8)] return decode if __name__ == '__main__': - rows = json.load(open(sys.argv[1])) + # the table in make() is quantiser 0's (its scale is 1), so only its rows can be compared + rows = [r for r in json.load(open(sys.argv[1])) if r['q'] == 0] + if not rows: raise SystemExit('no row of quantiser 0: collect them with dataset.py and a fixed quantiser of 0') res = [] for cbits, qbits, order, qround, mround, fb in itertools.product((8, 11, 12, 13), (14, 16), ('cols', 'rows'), (0, 1), (0, 1), (0x7F, 0x80)): qshift = qbits - 5 dec = make(cbits, qbits, qshift, fb, 8, order, qround, mround) - bad = sum(dec(r['dc'], r['coefs'])[y][x] != r['px'][y][x] for r in rows for y in range(8) for x in range(8)) + bad = 0 + for r in rows: + got = dec(r['dc'], r['coefs']) + bad += sum(got[y][x] != r['px'][y][x] for y in range(8) for x in range(8)) res.append((bad, cbits, qbits, order, qround, mround, hex(fb))) res.sort() for r in res[:8]: print(r) diff --git a/crates/video/tools/bink_probe/fuzz_diff.py b/crates/video/tools/bink_probe/fuzz_diff.py index 9b2091a518..abe9eaf67e 100644 --- a/crates/video/tools/bink_probe/fuzz_diff.py +++ b/crates/video/tools/bink_probe/fuzz_diff.py @@ -8,13 +8,16 @@ The options dict narrows what is generated, for example {'w': 17, 'h': 8, 'sig': {'planes': [7, 8, 9]}, {'frames': 4, 'new16': 1, 'cover': 1}; see the opt.get calls. Use 'new16' with 'cover' so every block is drawn: where a 16x16 entry steps over blocks nothing drew, ffmpeg shows whatever its recycled buffer held, which differs from run to run of content. Cases that -differ are kept in the directory BINK_PROBE_CASES names (default: bink_probe_cases in the -system's temporary directory). BINK_PROBE_DECODER names the decoder program if it is not the +differ, or that a decoder doesn't finish, are kept in a new directory, made for the run in the one BINK_PROBE_CASES +names (default: the system's temporary directory) and printed at the end. BINK_PROBE_DECODER names the decoder program if it is not the example in the workspace's target directory.""" -import re, random, struct, subprocess, os, sys +import re, random, struct, subprocess, os, sys, tempfile S=os.path.dirname(os.path.abspath(__file__)) W=os.path.normpath(os.path.join(S,'..','..','..','..')) -CASES=os.environ.get('BINK_PROBE_CASES') or os.path.join(__import__('tempfile').gettempdir(),'bink_probe_cases') +PARENT=os.environ.get('BINK_PROBE_CASES') or None +if PARENT: os.makedirs(PARENT,exist_ok=True) +CASES=tempfile.mkdtemp(prefix='bink_probe_',dir=PARENT) # private to this user and this run +TIMEOUT=60 # seconds, for each decoder on one case DECODER=os.environ.get('BINK_PROBE_DECODER') or os.path.join(W,'target','release','examples','bink_binkdec') src=open(os.path.join(S,'..','..','src','bink','tables.rs')).read() blk=src[src.index('TREES'):src.index('RUN_SCANS')] @@ -135,6 +138,7 @@ def gen_plane(b,rnd,bw,bh,inter,opt,subn=None): if t==3: ib.put(rnd.randint(0,15),4); i=0 fixed=opt.get('runfixed') + assert fixed is None or fixed>0,'runfixed must be positive' while i<63: run=min(rnd.choice([1,1,2,3,5,8,12,16,16]),64-i) if fixed is None else min(fixed,64-i) run=min(run,16) @@ -255,7 +259,7 @@ def gen_plane(b,rnd,bw,bh,inter,opt,subn=None): if k=='idc' and not opt.get('dcwild'): if val-d<0: sg=0 elif val+d>2047: sg=1 - b.put(sg,1) + b.put(sg,1); val+=-d if sg else d cnt+=g elif k=='run': if len(set(v))==1 and rnd.random() Date: Wed, 25 Nov 2026 09:07:04 +0100 Subject: [PATCH 115/130] feat(video): Bink pictures convert into a VideoFrame The README, the frame module and the crate docs say every decoder's output converts; Bink's was the one that did not. The colour tags stay unspecified: nothing in the stream gives a matrix or range. Co-Authored-By: Claude Opus 5.5 --- crates/video/README.md | 4 ++-- crates/video/src/bink/README.md | 1 + crates/video/src/frame/convert.rs | 15 +++++++++++++++ crates/video/src/frame/mod.rs | 3 +-- crates/video/src/frame/tests.rs | 12 ++++++++++++ crates/video/src/lib.rs | 2 +- 6 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/video/README.md b/crates/video/README.md index 38a08f4f25..ab4edc1be3 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -38,8 +38,8 @@ No codec feature is on by default. ## Decoded frames Each decoder returns its own picture type. `frame::VideoFrame` is a codec-agnostic form that -every decoder's output but Bink's converts into with `VideoFrame::try_from` (always built; each -conversion comes with its codec's feature): +every decoder's output converts into with `VideoFrame::try_from` (always built; each conversion +comes with its codec's feature): - Planes are `[Y, Cb, Cr]`, `[R, G, B]` or `[Y]` (`ColorFamily`), plus an optional alpha plane. DNx, VP9 and AV1 (identity matrix) store RGB as G, B, R; the conversion reorders them. diff --git a/crates/video/src/bink/README.md b/crates/video/src/bink/README.md index 176fac4003..b150e9ccb3 100644 --- a/crates/video/src/bink/README.md +++ b/crates/video/src/bink/README.md @@ -37,6 +37,7 @@ for i in 0..file.frames.len() { Which frames are key frames, and the frame rate, come from the container. - A `Picture` holds the samples as coded. The decoder makes no statement about their colour matrix or range: nothing in the stream says, and comparing with ffmpeg cannot tell. + `VideoFrame::try_from(picture)` leaves them unspecified. - After an error the decoder keeps the last picture that decoded. - `reset()` forgets the previous picture, for decoding from a key frame after a seek. diff --git a/crates/video/src/frame/convert.rs b/crates/video/src/frame/convert.rs index 65eebc0e3b..bff53bd6e0 100644 --- a/crates/video/src/frame/convert.rs +++ b/crates/video/src/frame/convert.rs @@ -413,6 +413,21 @@ impl TryFrom for VideoFrame { } } +#[cfg(feature = "bink-decode")] +impl TryFrom for VideoFrame { + type Error = FrameError; + + /// An 8-bit 4:2:0 frame. Bink signals no colour description, and the picture carries no timing. + fn try_from(p: crate::bink::Picture) -> Result { + let planes = vec![ + Plane::packed(p.width, p.height, 8, Samples::U8(p.y))?, + Plane::packed(p.chroma_width, p.chroma_height, 8, Samples::U8(p.u))?, + Plane::packed(p.chroma_width, p.chroma_height, 8, Samples::U8(p.v))?, + ]; + VideoFrame::new(p.width, p.height, ColorFamily::YCbCr, Subsampling::S420, planes, None) + } +} + #[cfg(feature = "vmd-decode")] impl TryFrom<&crate::vmd::Decoder> for VideoFrame { type Error = FrameError; diff --git a/crates/video/src/frame/mod.rs b/crates/video/src/frame/mod.rs index ffc77f8da0..cf092f43f1 100644 --- a/crates/video/src/frame/mod.rs +++ b/crates/video/src/frame/mod.rs @@ -3,8 +3,7 @@ //! Each decoder in this crate returns its own picture type. [`VideoFrame`] holds what they have in //! common: planar samples at their stored width (`u8` or `u16`), per-plane bit depth, chroma //! subsampling, an optional alpha plane, colour tags as ITU-T H.273 code points, and timing. -//! Every decoder output but Bink's converts into it with `VideoFrame::try_from`, behind the codec's -//! feature. +//! Every decoder output converts into it with `VideoFrame::try_from`, behind the codec's feature. //! A conversion moves the sample buffers; it does not copy or rescale samples. Paletted video is //! the exception: VMD's decoder holds palette indices, and converting it (`&vmd::Decoder`) writes //! new 8-bit R, G, B planes from its palette. diff --git a/crates/video/src/frame/tests.rs b/crates/video/src/frame/tests.rs index 0a5e4c7bfe..a0e0e95505 100644 --- a/crates/video/src/frame/tests.rs +++ b/crates/video/src/frame/tests.rs @@ -336,6 +336,18 @@ fn vp8_picture_converts() { assert_eq!(f.pts, Some(1)); } +/// The planes keep their order and their rounded-up chroma size, and what Bink doesn't signal stays unspecified. +#[cfg(feature = "bink-decode")] +#[test] +fn bink_picture_converts() { + let p = crate::bink::Picture { width: 3, height: 5, chroma_width: 2, chroma_height: 3, y: vec![1; 15], u: vec![2; 6], v: vec![3; 6] }; + let f = VideoFrame::try_from(p).unwrap(); + assert_eq!((f.width(), f.height()), (3, 5)); + let planes: Vec<_> = f.planes().iter().map(|p| (p.width(), p.height(), p.row_u8(0).unwrap()[0])).collect(); + assert_eq!(planes, [(3, 5, 1), (2, 3, 2), (2, 3, 3)]); + assert_eq!((f.color, f.pts, f.sar), (ColorTags::UNSPECIFIED, None, None)); +} + #[cfg(feature = "prores")] #[test] fn prores_frame_converts() { diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index fb1d9cc9aa..e9a2c33ee7 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -27,7 +27,7 @@ //! The decoders bound the pictures they hold with a memory budget ([`budget`]). //! //! Each decoder returns its own picture type. [`frame::VideoFrame`] is the codec-agnostic form -//! they all convert into (`VideoFrame::try_from`), except Bink's, which has no conversion. +//! they all convert into (`VideoFrame::try_from`). //! //! `TrackDecoder` picks the decoder for a track from its `craft_media::CodecParams` and returns //! `VideoFrame`s, for H.264, HEVC, VP9, AV1, MPEG-2, ProRes, DNx, APV, FFV1 and VP8 From a5a72f1fe6faea5cb10cd09a3283ec8c166bbe10 Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 25 Nov 2026 12:01:31 +0100 Subject: [PATCH 116/130] hayro-interpret: a script that lists no vertical feature leaves the choice to the next The search for a face's vert lookups took the first script with a default language system, even one that lists no vert or vrt2: a kana that lists horizontal features only hid DFLT's vert, and the vertical CID drew its ordinary glyph. A script now counts only when it lists a vertical feature that has lookups; else DFLT's applies, else every one of the face. Co-Authored-By: Claude Opus 5.5 --- .../tests/interpretation/vertical_forms.rs | 54 ++++++++++++++----- vendor/README.craft-reader.md | 4 +- vendor/hayro-interpret/src/font/cid.rs | 20 ++++--- 3 files changed, 57 insertions(+), 21 deletions(-) diff --git a/crates/pdf/tests/interpretation/vertical_forms.rs b/crates/pdf/tests/interpretation/vertical_forms.rs index 74e1e18cf0..915344fafc 100644 --- a/crates/pdf/tests/interpretation/vertical_forms.rs +++ b/crates/pdf/tests/interpretation/vertical_forms.rs @@ -66,22 +66,30 @@ enum Subtable { /// system and replaces glyph `from` with glyph `to`. fn gsub(feature: &[u8; 4], from: u16, to: u16, subtable: Subtable) -> Vec { // No required feature (0xFFFF); one optional feature, feature 0. - gsub_listing(feature, from, to, subtable, &[0xFFFF, 1, 0]) + gsub_listing(feature, from, to, subtable, &[(b"DFLT", &[0xFFFF, 1, 0])]) } -/// [`gsub`] with the default language system's `requiredFeatureIndex`, `featureIndexCount` and -/// `featureIndices` given by `language`. -fn gsub_listing(feature: &[u8; 4], from: u16, to: u16, subtable: Subtable, language: &[u16]) -> Vec { - // DFLT script (offset 8); its default language system (offset 4, no other language systems; - // no lookup order) lists the features as `language` says. - let mut scripts = u16s(&[1]); - scripts.extend(b"DFLT"); - scripts.extend(u16s(&[8, 4, 0, 0])); - scripts.extend(u16s(language)); - // Feature 0: `feature`, lookup 0. - let mut features = u16s(&[1]); +/// [`gsub`] with a second feature, `zero`, which has no lookups, and with `scripts`: each one's +/// tag and its default language system's `requiredFeatureIndex`, `featureIndexCount` and +/// `featureIndices`. +fn gsub_listing(feature: &[u8; 4], from: u16, to: u16, subtable: Subtable, scripts: &[(&[u8; 4], &[u16])]) -> Vec { + // A script's default language system (offset 4, no other language systems; no lookup order) + // lists the features as `scripts` says. + let mut records = u16s(&[u16::try_from(scripts.len()).unwrap()]); + let mut tables = Vec::new(); + for (tag, language) in scripts { + records.extend(*tag); + records.extend(u16s(&[u16::try_from(2 + 6 * scripts.len() + tables.len()).unwrap()])); + tables.extend(u16s(&[4, 0, 0])); + tables.extend(u16s(language)); + } + let scripts = [records, tables].concat(); + // Feature 0: `feature`, lookup 0. Feature 1: `zero`. + let mut features = u16s(&[2]); features.extend(feature); - features.extend(u16s(&[8, 0, 1, 0])); + features.extend(u16s(&[14])); + features.extend(b"zero"); + features.extend(u16s(&[20, 0, 1, 0, 0, 0])); // Coverage of `from` only. let coverage = u16s(&[1, 1, from]); let single = match subtable { @@ -238,11 +246,29 @@ fn a_face_without_a_vertical_glyph_draws_the_ordinary_one() { fn a_vert_feature_the_language_system_requires_applies() { let (bracket, a) = (glyph('「'), glyph('A')); // Required feature 0, no optional features. - let required = with_table(TINY_GLYF, b"GSUB", Some(&gsub_listing(b"vert", bracket, a, Subtable::List, &[0, 0]))); + let required = with_table(TINY_GLYF, b"GSUB", Some(&gsub_listing(b"vert", bracket, a, Subtable::List, &[(b"DFLT", &[0, 0])]))); assert_eq!(glyphs(&pdf("UniJIS-UCS2-V", "300C"), &required), [u32::from(a)], "the required vert feature applies"); assert_eq!(glyphs(&pdf("UniJIS-UCS2-H", "300C"), &required), [u32::from(bracket)], "a horizontal CID keeps its glyph"); } +/// A script that exists but lists no vertical feature does not end the search: when `kana`, the +/// collection's script, lists another feature only, `DFLT`'s `vert` applies; when `DFLT` lists +/// none either, the `vert` of any script does. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn a_script_without_a_vertical_feature_leaves_it_to_the_next() { + let (bracket, a) = (glyph('「'), glyph('A')); + // Feature 0 is `vert`, feature 1 `zero`. + let (vert, zero): (&[u16], &[u16]) = (&[0xFFFF, 1, 0], &[0xFFFF, 1, 1]); + let only_dflt: &[(&[u8; 4], &[u16])] = &[(b"DFLT", vert), (b"kana", zero)]; + let only_another: &[(&[u8; 4], &[u16])] = &[(b"DFLT", zero), (b"kana", zero), (b"latn", vert)]; + for (scripts, which) in [(only_dflt, "only DFLT"), (only_another, "only a script other than kana and DFLT")] { + let face = with_table(TINY_GLYF, b"GSUB", Some(&gsub_listing(b"vert", bracket, a, Subtable::List, scripts))); + assert_eq!(glyphs(&pdf("UniJIS-UCS2-V", "300C"), &face), [u32::from(a)], "{which} lists vert: it applies"); + assert_eq!(glyphs(&pdf("UniJIS-UCS2-H", "300C"), &face), [u32::from(bracket)], "{which} lists vert: a horizontal CID keeps its glyph"); + } +} + /// Adobe-Japan1 gives “ (U+201C) CID 108 and its vertical form CID 8279 (0x2057), which only the /// older UCS-2 CMaps name: `UniJIS-UCS2-V` picks 8279 for U+201C, while `UniJIS-UTF16-V` keeps /// 108. 8279, through that CMap or as an `Identity-H` CID, is a vertical form; 108 is not. The diff --git a/vendor/README.craft-reader.md b/vendor/README.craft-reader.md index 4aca12573f..b4d7797b12 100644 --- a/vendor/README.craft-reader.md +++ b/vendor/README.craft-reader.md @@ -81,7 +81,9 @@ adapts its tests; a plate-mode test in `crates/pdf/tests/plates.rs` checks the c #7665 was open in PdfCraft when it was ported. Its comments keep the label `PdfCraft patch (107)`. Its tests are adapted in `crates/pdf/tests/interpretation/vertical_forms.rs`, with the fonts-build -fixture `Tiny-glyf.ttf` as the substitute instead of PdfCraft's bundled Inter. +fixture `Tiny-glyf.ttf` as the substitute instead of PdfCraft's bundled Inter. Two changes +are not in #7665: the UCS-2 CMaps alone decide when a resolver lacks the UTF-16 ones, and a script +that lists no vertical feature leaves the lookups to `DFLT`, then to every script of the face. A craft-libs patch, labeled `Craft patch (CMYK masks)` in code comments, takes a luminosity soft mask whose group is DeviceCMYK from the group's inks: ISO 32000-2 diff --git a/vendor/hayro-interpret/src/font/cid.rs b/vendor/hayro-interpret/src/font/cid.rs index b228918df2..d88d9ee095 100644 --- a/vendor/hayro-interpret/src/font/cid.rs +++ b/vendor/hayro-interpret/src/font/cid.rs @@ -797,6 +797,14 @@ fn vertical_lookups(gsub: &Gsub<'_>, script: Tag) -> Vec { let Ok(features) = gsub.feature_list() else { return Vec::new(); }; + let is_vertical = |index: u16| { + features + .feature_records() + .get(usize::from(index)) + .filter(|r| [Tag::new(b"vert"), Tag::new(b"vrt2")].contains(&r.feature_tag())) + .and_then(|r| r.feature(features.offset_data()).ok()) + .is_some_and(|f| !f.lookup_list_indices().is_empty()) + }; let listed: Option> = gsub.script_list().ok().and_then(|scripts| { [script, Tag::new(b"DFLT")].into_iter().find_map(|tag| { let record = scripts @@ -811,12 +819,12 @@ fn vertical_lookups(gsub: &Gsub<'_>, script: Tag) -> Vec { // The language system's required feature (0xFFFF: none) and its other features // (OpenType `LangSys`): a face may list `vert` as either. let required = Some(language.required_feature_index()).filter(|&i| i != 0xFFFF); - Some( - required - .into_iter() - .chain(language.feature_indices().iter().map(|i| i.get())) - .collect(), - ) + let listed: Vec = required + .into_iter() + .chain(language.feature_indices().iter().map(|i| i.get())) + .collect(); + // A script that lists no vertical feature leaves the choice to the next. + listed.iter().any(|&i| is_vertical(i)).then_some(listed) }) }); for tag in [Tag::new(b"vert"), Tag::new(b"vrt2")] { From 19114f32954a5c821b0c8a7d25289579120647fe Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 25 Nov 2026 12:07:56 +0100 Subject: [PATCH 117/130] craft-pdf: the vertical-form tests tell a script's own vert from the fallback's The fallback to the next script also finds a required vert that is ignored when only DFLT has one, so the required-feature test no longer caught that. Each feature of the test GSUB now has a lookup of its own: kana requires one vert and DFLT lists another, and the fallback test's kana lists hkna. Co-Authored-By: Claude Opus 5.5 --- .../tests/interpretation/vertical_forms.rs | 84 ++++++++++--------- 1 file changed, 46 insertions(+), 38 deletions(-) diff --git a/crates/pdf/tests/interpretation/vertical_forms.rs b/crates/pdf/tests/interpretation/vertical_forms.rs index 915344fafc..dd6511f6af 100644 --- a/crates/pdf/tests/interpretation/vertical_forms.rs +++ b/crates/pdf/tests/interpretation/vertical_forms.rs @@ -66,30 +66,41 @@ enum Subtable { /// system and replaces glyph `from` with glyph `to`. fn gsub(feature: &[u8; 4], from: u16, to: u16, subtable: Subtable) -> Vec { // No required feature (0xFFFF); one optional feature, feature 0. - gsub_listing(feature, from, to, subtable, &[(b"DFLT", &[0xFFFF, 1, 0])]) + gsub_listing(from, &[(feature, to)], subtable, &[(b"DFLT", &[0xFFFF, 1, 0])]) } -/// [`gsub`] with a second feature, `zero`, which has no lookups, and with `scripts`: each one's -/// tag and its default language system's `requiredFeatureIndex`, `featureIndexCount` and -/// `featureIndices`. -fn gsub_listing(feature: &[u8; 4], from: u16, to: u16, subtable: Subtable, scripts: &[(&[u8; 4], &[u16])]) -> Vec { - // A script's default language system (offset 4, no other language systems; no lookup order) - // lists the features as `scripts` says. - let mut records = u16s(&[u16::try_from(scripts.len()).unwrap()]); - let mut tables = Vec::new(); - for (tag, language) in scripts { - records.extend(*tag); - records.extend(u16s(&[u16::try_from(2 + 6 * scripts.len() + tables.len()).unwrap()])); - tables.extend(u16s(&[4, 0, 0])); - tables.extend(u16s(language)); +/// A GSUB table with `features`, each one's tag and the glyph its lookup replaces `from` with, and +/// `scripts`, each one's tag and its default language system's `requiredFeatureIndex`, +/// `featureIndexCount` and `featureIndices`. +fn gsub_listing(from: u16, features: &[(&[u8; 4], u16)], subtable: Subtable, scripts: &[(&[u8; 4], &[u16])]) -> Vec { + // The default language system at offset 4; no other language systems; no lookup order. + let script_list = list(scripts.iter().map(|(tag, language)| (tag.as_slice(), [u16s(&[4, 0, 0]), u16s(language)].concat()))); + // Feature n has one lookup, lookup n. + let feature_list = list(features.iter().zip(0..).map(|((tag, _), n)| (tag.as_slice(), u16s(&[0, 1, n])))); + let lookup_list = list(features.iter().map(|(_, to)| (&[][..], lookup(from, *to, subtable)))); + let script_offset = 10; + let feature_offset = script_offset + u16::try_from(script_list.len()).unwrap(); + let lookup_offset = feature_offset + u16::try_from(feature_list.len()).unwrap(); + [u16s(&[1, 0, script_offset, feature_offset, lookup_offset]), script_list, feature_list, lookup_list].concat() +} + +/// An OpenType list of `tables`: their count, each one's tag (a lookup has none) and offset, then +/// the tables. +fn list<'a>(tables: impl Iterator)>) -> Vec { + let tables: Vec<_> = tables.collect(); + let data = 2 + tables.iter().map(|(tag, _)| tag.len() + 2).sum::(); + let mut records = u16s(&[u16::try_from(tables.len()).unwrap()]); + let mut bodies = Vec::new(); + for (tag, table) in tables { + records.extend(tag); + records.extend(u16s(&[u16::try_from(data + bodies.len()).unwrap()])); + bodies.extend(table); } - let scripts = [records, tables].concat(); - // Feature 0: `feature`, lookup 0. Feature 1: `zero`. - let mut features = u16s(&[2]); - features.extend(feature); - features.extend(u16s(&[14])); - features.extend(b"zero"); - features.extend(u16s(&[20, 0, 1, 0, 0, 0])); + [records, bodies].concat() +} + +/// A lookup that replaces glyph `from` with glyph `to`. +fn lookup(from: u16, to: u16, subtable: Subtable) -> Vec { // Coverage of `from` only. let coverage = u16s(&[1, 1, from]); let single = match subtable { @@ -101,11 +112,7 @@ fn gsub_listing(feature: &[u8; 4], from: u16, to: u16, subtable: Subtable, scrip // Extension format 1: the type it holds, then a 32-bit offset to it. Subtable::DeltaInExtension => (7, [u16s(&[1, 1, 0, 8]), single].concat()), }; - let lookups = [u16s(&[1, 4, lookup_type, 0, 1, 8]), body].concat(); - let script_list = 10u16; - let feature_list = script_list + u16::try_from(scripts.len()).unwrap(); - let lookup_list = feature_list + u16::try_from(features.len()).unwrap(); - [u16s(&[1, 0, script_list, feature_list, lookup_list]), scripts, features, lookups].concat() + [u16s(&[lookup_type, 0, 1, 8]), body].concat() } /// A `cmap` table whose one subtable (Windows Unicode BMP, format 4) maps `character` to `glyph`. @@ -240,30 +247,31 @@ fn a_face_without_a_vertical_glyph_draws_the_ordinary_one() { } /// A language system may list `vert` only as its required feature (`requiredFeatureIndex`, with -/// no optional features): its lookups apply too. +/// no optional features): its lookups apply too, and `kana`'s before `DFLT`'s. #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[cfg_attr(not(target_arch = "wasm32"), test)] fn a_vert_feature_the_language_system_requires_applies() { - let (bracket, a) = (glyph('「'), glyph('A')); - // Required feature 0, no optional features. - let required = with_table(TINY_GLYF, b"GSUB", Some(&gsub_listing(b"vert", bracket, a, Subtable::List, &[(b"DFLT", &[0, 0])]))); + let (bracket, a, comma) = (glyph('「'), glyph('A'), glyph('、')); + // `kana` requires feature 1 and lists no optional features; `DFLT` lists feature 0. + let gsub = gsub_listing(bracket, &[(b"vert", comma), (b"vert", a)], Subtable::List, &[(b"DFLT", &[0xFFFF, 1, 0]), (b"kana", &[1, 0])]); + let required = with_table(TINY_GLYF, b"GSUB", Some(&gsub)); assert_eq!(glyphs(&pdf("UniJIS-UCS2-V", "300C"), &required), [u32::from(a)], "the required vert feature applies"); assert_eq!(glyphs(&pdf("UniJIS-UCS2-H", "300C"), &required), [u32::from(bracket)], "a horizontal CID keeps its glyph"); } /// A script that exists but lists no vertical feature does not end the search: when `kana`, the -/// collection's script, lists another feature only, `DFLT`'s `vert` applies; when `DFLT` lists -/// none either, the `vert` of any script does. +/// collection's script, lists a horizontal feature only, `DFLT`'s `vert` applies; when `DFLT` +/// lists none either, the `vert` of any script does. #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] #[cfg_attr(not(target_arch = "wasm32"), test)] fn a_script_without_a_vertical_feature_leaves_it_to_the_next() { - let (bracket, a) = (glyph('「'), glyph('A')); - // Feature 0 is `vert`, feature 1 `zero`. - let (vert, zero): (&[u16], &[u16]) = (&[0xFFFF, 1, 0], &[0xFFFF, 1, 1]); - let only_dflt: &[(&[u8; 4], &[u16])] = &[(b"DFLT", vert), (b"kana", zero)]; - let only_another: &[(&[u8; 4], &[u16])] = &[(b"DFLT", zero), (b"kana", zero), (b"latn", vert)]; + let (bracket, a, comma) = (glyph('「'), glyph('A'), glyph('、')); + let (hkna, vert): (&[u16], &[u16]) = (&[0xFFFF, 1, 0], &[0xFFFF, 1, 1]); + let only_dflt: &[(&[u8; 4], &[u16])] = &[(b"DFLT", vert), (b"kana", hkna)]; + let only_another: &[(&[u8; 4], &[u16])] = &[(b"DFLT", hkna), (b"kana", hkna), (b"latn", vert)]; for (scripts, which) in [(only_dflt, "only DFLT"), (only_another, "only a script other than kana and DFLT")] { - let face = with_table(TINY_GLYF, b"GSUB", Some(&gsub_listing(b"vert", bracket, a, Subtable::List, scripts))); + let gsub = gsub_listing(bracket, &[(b"hkna", comma), (b"vert", a)], Subtable::List, scripts); + let face = with_table(TINY_GLYF, b"GSUB", Some(&gsub)); assert_eq!(glyphs(&pdf("UniJIS-UCS2-V", "300C"), &face), [u32::from(a)], "{which} lists vert: it applies"); assert_eq!(glyphs(&pdf("UniJIS-UCS2-H", "300C"), &face), [u32::from(bracket)], "{which} lists vert: a horizontal CID keeps its glyph"); } From 98e696073fe6d1281ba41bfc6cc5c3f5aeef816e Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:38:01 +0100 Subject: [PATCH 118/130] craft-xfl: an unreadable edge command ends only its run (#3282) An unknown or malformed command in an edges attribute now ends only the run it is in: the run's valid prefix is kept and parsing resumes at the next `!`, instead of dropping every later run. parse_edges and Edge::parsed_edges also return how many runs were cut short, so a consumer can report the loss. Decimal coordinates accept a signed exponent (1e-3). --- crates/xfl/src/edges.rs | 119 +++++++++++++++++++++++++++++----------- crates/xfl/src/shape.rs | 7 ++- 2 files changed, 94 insertions(+), 32 deletions(-) diff --git a/crates/xfl/src/edges.rs b/crates/xfl/src/edges.rs index e58602e9d9..a819fb1534 100644 --- a/crates/xfl/src/edges.rs +++ b/crates/xfl/src/edges.rs @@ -5,8 +5,10 @@ //! Coordinates may be decimal or signed 24.8 fixed-point hexadecimal (`#A.8` is 10.5). //! //! This module returns neutral points and segments so consumers can map them to their own -//! geometry model. Like Animate files in the wild, a damaged suffix ends parsing while keeping -//! the valid prefix. The segment cap bounds output allocation. +//! geometry model. Each `!` starts a run that depends on nothing before it, so an unknown or +//! malformed command ends only its own run: the run's valid prefix is kept and parsing resumes +//! at the next `!`. [`parse_edges`] reports how many runs were cut short. The segment cap bounds +//! output allocation. /// Most segments parsed from one edge attribute. pub const MAX_EDGE_SEGMENTS: usize = 2_000_000; @@ -26,6 +28,15 @@ pub struct Segment { pub to: Point, } +/// Segments parsed from one edge attribute, with a count of the runs that were not read whole. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ParsedEdges { + pub segments: Vec, + /// Runs that ended early at an unknown or malformed command, or that the segment cap cut off + /// or left unread. A run's segments before the point where it ended are still in `segments`. + pub cut_runs: usize, +} + const TWIPS_PER_PIXEL: f32 = 20.0; fn number(input: &[u8], at: &mut usize) -> Option { @@ -58,8 +69,17 @@ fn number(input: &[u8], at: &mut usize) -> Option { if matches!(input.get(*at), Some(b'-' | b'+')) { *at += 1; } - while input.get(*at).is_some_and(|b| b.is_ascii_digit() || matches!(b, b'.' | b'e' | b'E')) { - *at += 1; + while let Some(&b) = input.get(*at) { + if b.is_ascii_digit() || b == b'.' { + *at += 1; + } else if matches!(b, b'e' | b'E') { + *at += 1; + if matches!(input.get(*at), Some(b'-' | b'+')) { + *at += 1; + } + } else { + break; + } } std::str::from_utf8(input.get(start..*at)?).ok()?.parse::().ok().filter(|v| v.is_finite()) } @@ -70,47 +90,63 @@ fn point(input: &[u8], at: &mut usize) -> Option { /// Parses an XFL `` attribute into pixel-coordinate line and quadratic segments. /// -/// Stops at the first unknown or malformed command, preserving the valid prefix. The current +/// An unknown or malformed command ends its run, keeping the run's valid prefix, and parsing +/// resumes at the next `!`; use [`parse_edges`] to learn how many runs were cut short. The current /// point starts at the origin. Move and selection commands do not produce segments. pub fn parse_edge_segments(source: &str) -> Vec { + parse_edges(source).segments +} + +/// Parses an XFL `` attribute like [`parse_edge_segments`], and also counts the +/// runs that were cut short, so a consumer can report that part of the edge is missing. +pub fn parse_edges(source: &str) -> ParsedEdges { let input = source.as_bytes(); let mut at = 0; let mut current = Point::default(); - let mut segments = Vec::new(); + let mut parsed = ParsedEdges::default(); while let Some(&command) = input.get(at) { at += 1; - match command { - b'!' => match point(input, &mut at) { - Some(p) => current = p, - None => break, - }, - b'|' | b'/' => match point(input, &mut at) { - Some(to) => { - segments.push(Segment { from: current, control: None, to }); - current = to; - } - None => break, - }, - b'[' | b']' => match (point(input, &mut at), point(input, &mut at)) { - (Some(control), Some(to)) => { - segments.push(Segment { from: current, control: Some(control), to }); - current = to; - } - _ => break, - }, + let read = match command { + b'!' => point(input, &mut at).map(|p| current = p), + b'|' | b'/' => point(input, &mut at).map(|to| { + parsed.segments.push(Segment { from: current, control: None, to }); + current = to; + }), + b'[' | b']' => point(input, &mut at).zip(point(input, &mut at)).map(|(control, to)| { + parsed.segments.push(Segment { from: current, control: Some(control), to }); + current = to; + }), b'S' => { while input.get(at).is_some_and(u8::is_ascii_digit) { at += 1; } + Some(()) } - b if b.is_ascii_whitespace() => {} - _ => break, + b if b.is_ascii_whitespace() => Some(()), + _ => None, + }; + if read.is_none() { + parsed.cut_runs += 1; + at = next_run(input, at); } - if segments.len() >= MAX_EDGE_SEGMENTS { + if parsed.segments.len() >= MAX_EDGE_SEGMENTS { + parsed.cut_runs += unread_runs(input.get(at..).unwrap_or_default()); break; } } - segments + parsed +} + +/// The index of the next run's `!` at or after `at`, or the end of the input. +fn next_run(input: &[u8], at: usize) -> usize { + input.get(at..).and_then(|rest| rest.iter().position(|&b| b == b'!')).map_or(input.len(), |offset| at + offset) +} + +/// Runs in `rest` that parsing will not reach: the current run if anything but whitespace is left +/// of it, and every later run. +fn unread_runs(rest: &[u8]) -> usize { + let current_run = rest.iter().take_while(|&&b| b != b'!').any(|b| !b.is_ascii_whitespace()); + usize::from(current_run) + rest.iter().filter(|&&b| b == b'!').count() } #[cfg(test)] @@ -142,11 +178,32 @@ mod tests { assert!(parse_edge_segments("!NaN 2|5 5").is_empty()); } + #[test] + fn unreadable_command_ends_only_its_run() { + let line = |from: (f32, f32), to: (f32, f32)| Segment { from: Point { x: from.0, y: from.1 }, control: None, to: Point { x: to.0, y: to.1 } }; + let parsed = parse_edges("!0 0|200 0?7|300 0!400 0|600 0"); + assert_eq!(parsed.segments, [line((0.0, 0.0), (10.0, 0.0)), line((20.0, 0.0), (30.0, 0.0))]); + assert_eq!(parsed.cut_runs, 1); + + let parsed = parse_edges("!x 0|200 0!0 20[1 2 nope|5 5!0 0|0 200"); + assert_eq!(parsed.segments, [line((0.0, 0.0), (0.0, 10.0))]); + assert_eq!(parsed.cut_runs, 2); + assert_eq!(parse_edges("!0 0|200 0S2 !0 0|0 200").cut_runs, 0); + } + + #[test] + fn decimal_coordinates_take_a_signed_exponent() { + let segments = parse_edge_segments("!0 0|2e+2 400E-1"); + assert_eq!(segments.len(), 1); + assert_eq!(segments[0].to, Point { x: 10.0, y: 2.0 }); + } + #[test] fn oversized_coordinate_numbers_and_segment_lists_are_bounded() { assert!(parse_edge_segments("!999999999999999999999999999999999999999999999999 0|1 1").is_empty()); let source = "|0 0".repeat(MAX_EDGE_SEGMENTS + 1); - let segments = parse_edge_segments(&source); - assert_eq!(segments.len(), MAX_EDGE_SEGMENTS); + let parsed = parse_edges(&source); + assert_eq!(parsed.segments.len(), MAX_EDGE_SEGMENTS); + assert_eq!(parsed.cut_runs, 1); } } diff --git a/crates/xfl/src/shape.rs b/crates/xfl/src/shape.rs index 173359a524..2c1c13d872 100644 --- a/crates/xfl/src/shape.rs +++ b/crates/xfl/src/shape.rs @@ -4,7 +4,7 @@ //! application's geometry, paint, or animation types. They work with `craft_xml::El` and with //! compatible borrowed element adapters implemented by consumers. -use crate::edges::{self, Segment}; +use crate::edges::{self, ParsedEdges, Segment}; use std::borrow::Cow; /// An element source used by the borrowed XFL schema views. @@ -529,6 +529,11 @@ impl Edge<'_, E> { pub fn segments(&self) -> Vec { self.encoded_segments().map(edges::parse_edge_segments).unwrap_or_default() } + + /// Parsed XFL path segments, with a count of the runs that were cut short. + pub fn parsed_edges(&self) -> ParsedEdges { + self.encoded_segments().map(edges::parse_edges).unwrap_or_default() + } } #[cfg(test)] From 2aa669b339e67a018fdd923dba4bb3de88bd5141 Mon Sep 17 00:00:00 2001 From: Stefan Pantic Date: Wed, 25 Nov 2026 16:12:59 -0500 Subject: [PATCH 119/130] scraft-format: declare v2 for sessions holding an instrument route --- crates/scraft-format/README.md | 9 ++++ crates/scraft-format/src/session.rs | 67 ++++++++++++++++++++++++++--- 2 files changed, 70 insertions(+), 6 deletions(-) diff --git a/crates/scraft-format/README.md b/crates/scraft-format/README.md index c2df56206b..9ddea451ab 100644 --- a/crates/scraft-format/README.md +++ b/crates/scraft-format/README.md @@ -11,5 +11,14 @@ fields, 256 MiB session byte limit, character limits, and duplicate/exhausted ID fields use `craft_time::soundcraft`, the exact sample-index time API retained by `craft-time`. MIDI sequence values use `craft-midi`'s serde representation. +## Format versions + +A session file declares the lowest `format_version` able to read it back, not the writer's own +version: `Session::to_json` writes 1 unless the document holds a `Route::Instrument` (an +instrument's auxiliary output bus, used as a track input), which serializes an enum tag v1 cannot +parse — those files declare 2. A reader refuses anything above `Session::FORMAT_VERSION` with +`SessionError::Version`, so an older build fails such files with the newer-version message rather +than a generic parse error. + The application still maps sessions to UI state, engine state, media paths and audio pools. The session schema and its format-specific parsing, writing, sanitization and validation live here. diff --git a/crates/scraft-format/src/session.rs b/crates/scraft-format/src/session.rs index 021cab8bcd..3d1a650f20 100644 --- a/crates/scraft-format/src/session.rs +++ b/crates/scraft-format/src/session.rs @@ -3,7 +3,7 @@ use crate::clip::{bound, bound_sequence}; use crate::soundcraft_time::{FrameRate, GridScale, GridValue, Range, SampleRate, Samples, TempoMap, TimeFormat}; use crate::{ - Bus, BusId, ChannelFormat, Clip, ClipId, Group, GroupId, MarkerId, MarkerKind, MemoryLocation, OutputPath, Source, SourceId, SourcePool, + Bus, BusId, ChannelFormat, Clip, ClipId, Group, GroupId, MarkerId, MarkerKind, MemoryLocation, OutputPath, Route, Source, SourceId, SourcePool, TRACK_COLORS, Track, TrackId, TrackKind, VideoSource, }; @@ -403,11 +403,17 @@ impl Default for Session { } impl Session { - pub const FORMAT_VERSION: u32 = 1; + /// Highest session version this build reads. Newer files get `SessionError::Version`, + /// not a parse error. + pub const FORMAT_VERSION: u32 = 2; + + /// The version a session declares when nothing in it needs a newer reader. Today only + /// `Route::Instrument` (an instrument's auxiliary output bus) is unreadable to v1. + const BASE_FORMAT_VERSION: u32 = 1; pub fn new(name: impl Into, sample_rate: SampleRate) -> Self { let mut s = Session { - format_version: Self::FORMAT_VERSION, + format_version: Self::BASE_FORMAT_VERSION, name: name.into(), sample_rate, bit_depth: BitDepthSetting::Int24, @@ -748,7 +754,30 @@ impl Session { // ---- persistence --------------------------------------------------------------------- pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(self).map_err(|e| SessionError::Format(e.to_string())) + let version = self.saved_format_version(); + if version == self.format_version { + serde_json::to_string_pretty(self).map_err(|e| SessionError::Format(e.to_string())) + } else { + let mut session = self.clone(); + session.format_version = version; + serde_json::to_string_pretty(&session).map_err(|e| SessionError::Format(e.to_string())) + } + } + + /// The lowest format version that can read this document back. `Route::Instrument` writes + /// an enum tag a v1 reader does not know, so a file holding one must declare v2: a v1 + /// reader then refuses it with `SessionError::Version` rather than a generic parse error. + fn saved_format_version(&self) -> u32 { + if self.uses_instrument_routes() { Self::FORMAT_VERSION } else { Self::BASE_FORMAT_VERSION } + } + + /// Any `Route::Instrument` on a track's input, output or send. + fn uses_instrument_routes(&self) -> bool { + self.tracks.iter().any(|t| { + matches!(t.mixer.input, Route::Instrument { .. }) + || matches!(t.mixer.output, Route::Instrument { .. }) + || t.mixer.sends.iter().flatten().any(|s| matches!(s.target, Route::Instrument { .. })) + }) } /// Parse a session; decoded audio must be attached separately (`pool`). @@ -1216,6 +1245,32 @@ mod tests { assert!(matches!(Session::from_json(&v.to_string()), Err(SessionError::Version(999)))); } + /// `Route::Instrument` writes an enum tag a v1 reader cannot parse, so a file holding one + /// declares v2: an older reader then refuses with `SessionError::Version`, not a generic + /// parse error. Sessions without one stay v1 and open in older builds. + #[test] + fn a_session_with_an_instrument_route_saves_as_v2_and_round_trips() { + let mut s = Session::default(); + let instrument_track = s.add_track(TrackKind::Instrument, ChannelFormat::Stereo, Some("Keys")); + let aux_track = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some("Keys Out")); + s.track_mut(aux_track).unwrap().mixer.input = Route::Instrument { track: instrument_track, bus: 1 }; + + let text = s.to_json().unwrap(); + let head: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(head["format_version"], serde_json::json!(Session::FORMAT_VERSION), "v2 so a v1 reader refuses by version"); + let back = Session::from_json(&text).unwrap(); + assert_eq!( + back.track(aux_track).map(|t| &t.mixer.input), + Some(&Route::Instrument { track: instrument_track, bus: 1 }), + "the route survives a full save/load" + ); + + let mut plain = Session::default(); + plain.add_track(TrackKind::Audio, ChannelFormat::Stereo, None); + let head: serde_json::Value = serde_json::from_str(&plain.to_json().unwrap()).unwrap(); + assert_eq!(head["format_version"], serde_json::json!(Session::BASE_FORMAT_VERSION), "nothing v2-only stays v1"); + } + #[test] fn the_version_is_checked_as_before() { // #892: the version is read without building the whole document as a tree; the errors @@ -1246,7 +1301,7 @@ mod tests { assert_eq!(format(t), want, "{t}"); } let mut v = serde_json::to_value(Session::default()).unwrap(); - for (ver, want) in [(serde_json::json!(2), 2), (serde_json::json!(1u64 << 40), u32::MAX)] { + for (ver, want) in [(serde_json::json!(3), 3), (serde_json::json!(1u64 << 40), u32::MAX)] { v["format_version"] = ver; assert_eq!(Session::from_json(&v.to_string()), Err(SessionError::Version(want))); } @@ -1257,7 +1312,7 @@ mod tests { // A newer version is refused even when the rest would not parse. assert_eq!(Session::from_json(r#"{"format_version":7,"tracks":5}"#), Err(SessionError::Version(7))); // An older or the current version loads as it did. - for ver in [0, 1] { + for ver in [0, 1, 2] { v["format_version"] = serde_json::json!(ver); assert_eq!(Session::from_json(&v.to_string()).map(|s| s.format_version), Ok(ver)); } From 4ad6744523dd12ef7a4892ca11cca3b428c57536 Mon Sep 17 00:00:00 2001 From: el-j Date: Thu, 26 Nov 2026 01:13:16 +0100 Subject: [PATCH 120/130] craft-captions: accept {0}{0} MicroDVD rate headers and prevent VPlayer adjacent cue collisions --- crates/captions/src/microdvd.rs | 13 ++++++--- crates/captions/src/vplayer.rs | 39 ++++++++++++++++++++----- crates/captions/tests/it/legacy_text.rs | 9 ++++++ 3 files changed, 50 insertions(+), 11 deletions(-) diff --git a/crates/captions/src/microdvd.rs b/crates/captions/src/microdvd.rs index a5b606367e..5816373712 100644 --- a/crates/captions/src/microdvd.rs +++ b/crates/captions/src/microdvd.rs @@ -5,9 +5,9 @@ //! {24}{72}First line|{y:i}second line in italics //! ``` //! -//! A line is `{first frame}{last frame}text`; `|` starts a new line. A first cue `{1}{1}` whose text -//! is a number gives the frame rate; without it the rate is 23.976 fps (the rate other readers -//! assume). Control codes `{y:i}` / `{y:b}` / `{y:u}` (italic, bold, underline; `i,b` together) +//! A line is `{first frame}{last frame}text`; `|` starts a new line. A first cue `{1}{1}` or `{0}{0}` +//! whose text is a number gives the frame rate; without it the rate is 23.976 fps (the rate other +//! readers assume). Control codes `{y:i}` / `{y:b}` / `{y:u}` (italic, bold, underline; `i,b` together) //! and `{c:$BBGGRR}` (colour) style the line they start; the capital forms `{Y:…}` and `{C:…}` //! style every later line of the cue too. Other controls (`{f:…}` font, `{s:…}` size, `{h:…}`, …) //! are dropped. Writing always starts with the `{1}{1}` rate line and styles a line only when @@ -143,7 +143,7 @@ pub fn parse(text: &str) -> Result { continue; } match split_cue(line) { - Some((1, 1, t)) if rows.is_empty() && !has_rate_line && header_rate(t).is_some() => { + Some((0, 0, t) | (1, 1, t)) if rows.is_empty() && !has_rate_line && header_rate(t).is_some() => { rate = header_rate(t).unwrap_or(rate); has_rate_line = true; } @@ -224,6 +224,11 @@ mod tests { fn rate_header() { let d = parse("{1}{1}25.000\n{25}{50}x\n").unwrap(); assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25)); + let d = parse("{0}{0}25.000\n{25}{50}x\n{50}{75}29.97\n").unwrap(); + assert_eq!(d.cues.len(), 2); + assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25)); + assert_eq!(d.cues[1].start, FrameRate::FPS_25.tick_of(50)); + assert_eq!(d.cues[1].text, "29.97"); let d = parse("{25}{50}x\n").unwrap(); assert_eq!(d.cues[0].start, DEFAULT_RATE.tick_of(25)); } diff --git a/crates/captions/src/vplayer.rs b/crates/captions/src/vplayer.rs index e1c42ba424..169e4f24a0 100644 --- a/crates/captions/src/vplayer.rs +++ b/crates/captions/src/vplayer.rs @@ -98,16 +98,20 @@ pub fn write(doc: &Document) -> String { }) .collect(); - for (i, (c, lines)) in active_cues.iter().enumerate() { - let start_cs = cs(c.start); + let mut resolved_cues: Vec<(i64, i64, &Vec)> = Vec::with_capacity(active_cues.len()); + let mut prev_end = 0i64; + for (c, lines) in &active_cues { + let start_cs = cs(c.start).max(prev_end); let end_cs = cs(c.end).max(start_cs + 1); + prev_end = end_cs; + resolved_cues.push((start_cs, end_cs, lines)); + } + + for (i, &(start_cs, end_cs, lines)) in resolved_cues.iter().enumerate() { out.push_str(&format!("{}={}\n", clock(start_cs), lines.join("|"))); - let next_start_cs = active_cues.get(i + 1).map(|(n, _)| cs(n.start)); + let next_start_cs = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s); if next_start_cs != Some(end_cs) { - let next_too_early = next_start_cs.is_some_and(|next| next <= start_cs); - if !next_too_early { - out.push_str(&format!("{}=\n", clock(end_cs))); - } + out.push_str(&format!("{}=\n", clock(end_cs))); } } out @@ -131,6 +135,27 @@ mod tests { assert_eq!(parsed.cues[0].end, ms_to_tick(10)); } + #[test] + fn adjacent_short_cues_do_not_collide_after_rounding() { + let doc = Document { + cues: vec![ + Cue { start: ms_to_tick(1000), end: ms_to_tick(1001), text: "First".to_string(), ..Default::default() }, + Cue { start: ms_to_tick(1001), end: ms_to_tick(1020), text: "Second".to_string(), ..Default::default() }, + ], + ..Default::default() + }; + let written = write(&doc); + assert_eq!(written, "00:00:01.00=First\n00:00:01.01=Second\n00:00:01.02=\n"); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 2); + assert_eq!(parsed.cues[0].text, "First"); + assert_eq!(parsed.cues[0].start, ms_to_tick(1000)); + assert_eq!(parsed.cues[0].end, ms_to_tick(1010)); + assert_eq!(parsed.cues[1].text, "Second"); + assert_eq!(parsed.cues[1].start, ms_to_tick(1010)); + assert_eq!(parsed.cues[1].end, ms_to_tick(1020)); + } + #[test] fn separators_and_ends() { let d = parse("00:00:01:Hello|world\n00:00:04.50=\n00:00:05 later\n").unwrap(); diff --git a/crates/captions/tests/it/legacy_text.rs b/crates/captions/tests/it/legacy_text.rs index 250a1d7307..1bfe11bfea 100644 --- a/crates/captions/tests/it/legacy_text.rs +++ b/crates/captions/tests/it/legacy_text.rs @@ -159,6 +159,15 @@ fn microdvd_counts_frames_at_the_given_rate() { assert_eq!(String::from_utf8(bytes.clone()).expect("utf8"), "{1}{1}25.000\n{50}{100}x\n"); let back = parse(&bytes, Format::MicroDvd).expect("parse"); assert_eq!((back.cues[0].start, back.cues[0].end), (Tick(2 * T), Tick(4 * T))); + + for header in ["{1}{1}25.000", "{0}{0}25.000"] { + let fixture = format!("{header}\n{{50}}{{100}}First cue\n{{100}}{{150}}23.976\n"); + let parsed = parse(fixture.as_bytes(), Format::MicroDvd).expect("parse rate header fixture"); + assert_eq!(parsed.cues.len(), 2, "{header}"); + assert_eq!((parsed.cues[0].start, parsed.cues[0].end), (Tick(2 * T), Tick(4 * T)), "{header}"); + assert_eq!((parsed.cues[1].start, parsed.cues[1].end), (Tick(4 * T), Tick(6 * T)), "{header}"); + assert_eq!(parsed.cues[1].text, "23.976", "{header}"); + } } #[test] From b2756f6f731a1b03be240b907ed90bba85a2bae7 Mon Sep 17 00:00:00 2001 From: el-j Date: Thu, 26 Nov 2026 01:14:57 +0100 Subject: [PATCH 121/130] craft-video: reject out-of-frame Theora EncoderConfig picture bounds --- crates/video/src/theora/encoder.rs | 9 +++++++- crates/video/tests/theora.rs | 33 ++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/crates/video/src/theora/encoder.rs b/crates/video/src/theora/encoder.rs index 407225e6e5..7e1eb82d05 100644 --- a/crates/video/src/theora/encoder.rs +++ b/crates/video/src/theora/encoder.rs @@ -104,9 +104,16 @@ fn alloc_vec_exact(val: T, n: usize) -> Result> { impl Encoder { /// Create a new encoder with the given configuration. pub fn new(config: EncoderConfig) -> Result { - if config.width == 0 || config.height == 0 { + if config.width == 0 || config.height == 0 || config.pic_width == 0 || config.pic_height == 0 { return Err(Error::DimensionMismatch("dimensions cannot be zero")); } + if config.pic_x > 255 + || config.pic_y > 255 + || config.pic_x.checked_add(config.pic_width).is_none_or(|end| end > config.width) + || config.pic_y.checked_add(config.pic_height).is_none_or(|end| end > config.height) + { + return Err(Error::DimensionMismatch("picture region exceeds frame bounds")); + } let frame_width = config.width.checked_add(15).map(|w| w & !15).ok_or(Error::DimensionMismatch("width overflows"))?; let frame_height = config.height.checked_add(15).map(|h| h & !15).ok_or(Error::DimensionMismatch("height overflows"))?; let fmbw_u64 = (frame_width / 16) as u64; diff --git a/crates/video/tests/theora.rs b/crates/video/tests/theora.rs index 2c57b510e6..eadc09d29d 100644 --- a/crates/video/tests/theora.rs +++ b/crates/video/tests/theora.rs @@ -608,6 +608,39 @@ fn test_theora_encoder_invalid_input_rejected() { let mut pic = test_picture(32, 32); pic.y_stride = 16; assert!(matches!(enc.encode_frame(&pic, true), Err(Error::DimensionMismatch(_)))); + + // Out-of-frame configuration picture bounds cannot bypass active picture validation + let cfg_out_of_frame = EncoderConfig { + width: 32, + height: 32, + pic_width: 16, + pic_height: 32, + pic_x: 32, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 40, + keyframe_distance: 64, + }; + assert!(matches!(Encoder::new(cfg_out_of_frame), Err(Error::DimensionMismatch(_)))); + + let cfg_zero_pic = EncoderConfig { + width: 32, + height: 32, + pic_width: 0, + pic_height: 32, + pic_x: 0, + pic_y: 0, + fps_num: 25, + fps_den: 1, + pixel_format: PixelFormat::Yuv420, + color_space: ColorSpace::Undefined, + quality: 40, + keyframe_distance: 64, + }; + assert!(matches!(Encoder::new(cfg_zero_pic), Err(Error::DimensionMismatch(_)))); } #[test] From 9e55fb34bae1296d20e895859f3fe54782cc5676 Mon Sep 17 00:00:00 2001 From: acebear17 <121527825+acebear17@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:56:46 +0000 Subject: [PATCH 122/130] pdf: build the image default-space trials into the test binary crates/pdf/tests/image_default_spaces.rs came in with d53c84d01 without a mod line in tests/main.rs (autotests = false), so its trials never compiled and the unreached-rs lint fails on main and on every PR. --- crates/pdf/tests/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/pdf/tests/main.rs b/crates/pdf/tests/main.rs index bbecb5d6dd..b56550c30b 100644 --- a/crates/pdf/tests/main.rs +++ b/crates/pdf/tests/main.rs @@ -9,6 +9,7 @@ mod crypt; #[path = "filters/main.rs"] mod filters; mod font_tables; +mod image_default_spaces; mod interpretation; mod knockout; mod knockout_backdrop; From d0c8ac9e4a14d9d048bafccdf3f6229c6f3c8ab1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:04:36 +0700 Subject: [PATCH 123/130] craft facade: forward the new feature (features table check) crates/craft/Cargo.toml [features] is checked against the member manifests (crates/craft/tests/features.rs); this adds the line the new member feature needs, as UPDATE_FACADE=1 would write it. --- crates/craft/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index cb06fa708a..362a44aad6 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -353,6 +353,7 @@ audio-qoa = ["audio", "craft-audio/qoa"] audio-qoa-decode = ["audio", "craft-audio/qoa-decode"] audio-qoa-encode = ["audio", "craft-audio/qoa-encode"] audio-rayon = ["audio", "craft-audio/rayon"] +audio-s302m = ["audio", "craft-audio/s302m"] audio-sbc = ["audio", "craft-audio/sbc"] audio-serde = ["audio", "craft-audio/serde"] audio-symphonia = ["audio", "craft-audio/symphonia"] From 2be5ff3495ba562b967202e2ca6c6c6f2f816a6f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:04:40 +0700 Subject: [PATCH 124/130] craft facade: forward the new feature (features table check) crates/craft/Cargo.toml [features] is checked against the member manifests (crates/craft/tests/features.rs); this adds the line the new member feature needs, as UPDATE_FACADE=1 would write it. --- crates/craft/Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index cb06fa708a..167088b9db 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -990,6 +990,7 @@ video-mpeg2-encode = ["video", "craft-video/mpeg2-encode"] video-mpeg4 = ["video", "craft-video/mpeg4"] video-mpeg4-encode = ["video", "craft-video/mpeg4-encode"] video-prores = ["video", "craft-video/prores"] +video-rawvideo = ["video", "craft-video/rawvideo"] video-screen-video = ["video", "craft-video/screen-video"] video-threads = ["video", "craft-video/threads"] video-vmd = ["video", "craft-video/vmd"] From 2225d6575a408dccfc2dafb053a6efb9a5b6eb55 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:05:56 +0700 Subject: [PATCH 125/130] audio tests: reach the ffmpeg helper at its path on main Main builds the codec tests into the lib test under crate::integration, so the oracle test added here calls crate::integration::codecs::testkit::ffmpeg_or_skip like its neighbours. --- crates/audio/tests/codecs/alac.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/audio/tests/codecs/alac.rs b/crates/audio/tests/codecs/alac.rs index c8548ab8ed..8038c3ceb9 100644 --- a/crates/audio/tests/codecs/alac.rs +++ b/crates/audio/tests/codecs/alac.rs @@ -160,7 +160,7 @@ fn ffmpeg_decodes_our_alac_exactly() { /// one stream changes its shift from packet to packet. #[test] fn ffmpeg_decodes_our_quiet_alac_exactly() { - let Some(ff) = crate::testkit::ffmpeg_or_skip("alac oracle") else { return }; + let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("alac oracle") else { return }; for (channels, bits) in [(1, 24), (2, 24), (6, 24), (1, 32), (2, 32)] { let full = input(channels, bits, 4 * 4096); let wav: Vec> = full From 37d5d11b847a89dd6512b996cd26e2e19976554c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:09:31 +0700 Subject: [PATCH 126/130] craft-xfl: give the module doc's parse_edges link its full path cargo doc -D warnings reported the module doc's [`parse_edges`] as unresolved; naming crate::edges::parse_edges resolves it. --- crates/xfl/src/edges.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/xfl/src/edges.rs b/crates/xfl/src/edges.rs index a819fb1534..f624f35e7e 100644 --- a/crates/xfl/src/edges.rs +++ b/crates/xfl/src/edges.rs @@ -7,8 +7,8 @@ //! This module returns neutral points and segments so consumers can map them to their own //! geometry model. Each `!` starts a run that depends on nothing before it, so an unknown or //! malformed command ends only its own run: the run's valid prefix is kept and parsing resumes -//! at the next `!`. [`parse_edges`] reports how many runs were cut short. The segment cap bounds -//! output allocation. +//! at the next `!`. [`parse_edges`](crate::edges::parse_edges) reports how many runs were cut +//! short. The segment cap bounds output allocation. /// Most segments parsed from one edge attribute. pub const MAX_EDGE_SEGMENTS: usize = 2_000_000; From b338465081ffedac8660b266b72c578334b61544 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:16:19 +0700 Subject: [PATCH 127/130] craft-video: bink-decode turns on craft-media Main made craft-media an optional dependency of craft-video, enabled by the features that use it; the Bink decoder reads craft_media::CodecParams, so bink-decode enables it like vp8-decode and av1-decode do. --- crates/video/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/video/Cargo.toml b/crates/video/Cargo.toml index 1777acbf94..b301cfd4da 100644 --- a/crates/video/Cargo.toml +++ b/crates/video/Cargo.toml @@ -57,7 +57,7 @@ mjpeg = ["dep:craft-jpeg"] prores = ["craft-media/bitstream"] # Bink video (Bink 1): decoder (`bink-decode`). bink = ["bink-decode"] -bink-decode = [] +bink-decode = ["dep:craft-media"] # H.264 / AVC: decoder and encoder; `h264-decode` or `h264-encode` for one of them. h264 = ["h264-decode", "h264-encode"] h264-decode = ["craft-media/bitstream"] From 20a38fb5b0c887b167e3a7e6eef3a20490c76995 Mon Sep 17 00:00:00 2001 From: citrunade Date: Fri, 27 Nov 2026 00:09:56 +0900 Subject: [PATCH 128/130] Lasso and Polygonal Lasso show the crosshair under the precise cursor (Caps Lock) (#3650) Under the canvas's precise cursor (Other Cursors > Precise, swapped by Caps Lock) the Lasso and the Polygonal Lasso show the crosshair, its centre the point the outline takes, with the operation's badge. Before, Caps Lock left the arrow and the lasso icon in place. The Magnetic Lasso already showed its width circle there. A trial toggles Caps Lock off, on and off over the Lasso and the Polygonal Lasso and checks the crosshair comes and goes; the Magnetic Lasso's width-circle trial stays alongside it. Split out of #3398 at review. Co-authored-by: citrunade <301939363+citrunade@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/imaging/src/ui/select/lasso.rs | 10 +++++++-- crates/imaging/tests/it/select.rs | 31 +++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/imaging/src/ui/select/lasso.rs b/crates/imaging/src/ui/select/lasso.rs index ec6037b6b0..a198630116 100644 --- a/crates/imaging/src/ui/select/lasso.rs +++ b/crates/imaging/src/ui/select/lasso.rs @@ -1,7 +1,7 @@ //! [`LassoTool`]: the freehand Lasso with Alt-latched straight segments, and the pieces the Polygonal Lasso shares. use craft_behavior::geometry::{ConstrainStyle, DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft, SelectionOperation}; -use craft_behavior::{CancelReason, Cursor, PaintedCursor, PointerButton, PointerGlyph}; +use craft_behavior::{CancelReason, Cursor, CursorIcon, PaintedCursor, PointerButton, PointerGlyph}; use craft_keymap::{Key, Mods}; use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer}; use craft_ui::primitives::{Draw, PaintShape, StrokeWidth, ToolIcon}; @@ -53,7 +53,8 @@ pub(super) struct LassoCursor<'a> { /// The arrow with its tip on the point the outline starts from, the lasso icon below and right of it and the /// operation's badge beside the icon: the latched one while an outline is open, else the live modifiers'; -/// Cmd is the Move tool's, so it shows none. Over the selection, the cursors of [`cursor_over`]. +/// Cmd is the Move tool's, so it shows none. Under the canvas's precise cursor, the crosshair with the badge. Over the +/// selection, the cursors of [`cursor_over`]. pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &ToolContext<'_>) -> Cursor { let LassoCursor { icon, draft, operation, bar, inside, rule } = shown; if !draft.is_open() @@ -69,6 +70,11 @@ pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &T } else { SelectionOperation::resolve(*bar, cx.mods, probe.has_selection()).badge() }; + // Under the canvas's precise cursor (Other Cursors > Precise, swapped by Caps Lock) the pointer is the crosshair, + // its centre the point the outline takes, with the operation's badge. + if cx.precise() { + return badge.map_or(CursorIcon::Crosshair.into(), |badge| PaintedCursor::badged(CursorIcon::Crosshair, badge).into()); + } PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, icon.icon(), badge).into() } diff --git a/crates/imaging/tests/it/select.rs b/crates/imaging/tests/it/select.rs index c9ef917fac..1a8c4d0961 100644 --- a/crates/imaging/tests/it/select.rs +++ b/crates/imaging/tests/it/select.rs @@ -951,6 +951,37 @@ fn the_magnetic_lasso_shows_the_width_circle_under_the_precise_cursor() { } } +// The Lasso and the Polygonal Lasso follow the canvas's precise cursor too (Other Cursors > Precise, swapped by Caps +// Lock): the crosshair, its centre the point the outline takes, while it is on; the arrow with the lasso icon otherwise. +// Before, Caps Lock left the arrow and icon in place. +#[trial] +fn the_lassos_show_the_crosshair_under_the_precise_cursor() { + use craft_behavior::{Cursor, CursorIcon, PaintedCursor, PointerGlyph}; + fn check(mut rig: Rig, what: &str) + where + for<'a> SelectToolPass<'a, T>: CanvasTool, + { + let over = rig.canvas().center(); + let ctx = rig.fixture().ctx().clone(); + rig.fixture().frame(vec![pointer::moved(over)]); + for caps_lock in [false, true, false] { + craft_ui::runtime::windows::WindowHost::of(&ctx).set_caps_lock(Some(caps_lock)); + rig.fixture().frame(Vec::new()); + rig.fixture().frame(Vec::new()); + let cursor = craft_ui::runtime::cursor::current(&ctx); + let crosshair = matches!( + cursor, + Some(Cursor::System(CursorIcon::Crosshair) | Cursor::Painted(PaintedCursor::Badged { base: CursorIcon::Crosshair, .. })) + ); + let arrow = matches!(cursor, Some(Cursor::Painted(PaintedCursor::PointerTool { pointer: PointerGlyph::Arrow, .. }))); + assert_eq!(crosshair, caps_lock, "{what}, Caps Lock {caps_lock}: {cursor:?}"); + assert_eq!(arrow, !caps_lock, "{what}, Caps Lock {caps_lock}: {cursor:?}"); + } + } + check(rig("Lasso", LassoTool::new(), Fake::empty()), "Lasso"); + check(rig("Polygonal Lasso", PolygonLassoTool::new(), Fake::empty()), "Polygonal Lasso"); +} + /// The cursor `rig` shows over the middle of its canvas with `mods` held. fn lasso_cursor(rig: &mut Rig, mods: Modifiers) -> Option where From cf5b00d077832beabc9d22ffc7c4391725a05886 Mon Sep 17 00:00:00 2001 From: acebear17 <121527825+acebear17@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:34:12 +0000 Subject: [PATCH 129/130] ui-contract: a declared edit keeps the app's title and icon (#3569) (#3585) Fixes #3569. The focused part still answers for the edit's flags and hint; only the label and icon come from the app's state. --- .../ui-contract/src/runtime/commands/board.rs | 11 ++++- .../src/testing/host_key_trials.rs | 42 +++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 8d3474f5cd..12d4c0985f 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -806,6 +806,13 @@ impl Board { }; let state = this.or(last); let flags = resolve_flags(this.map(CommandState::flags), last.map(CommandState::flags)); + // The focused part answers for a declared edit's flags, but its title and icon stay the app's, so the edit's + // label does not change language with the focus (#3569). The hint stays the part's: the app's hint describes + // the app's own enable state, which the part's flags override. + let app_number = matches!(declaring, Some(Declaration::Focused { .. })).then(|| self.numbers.get(command.id.as_str()).copied()).flatten(); + let shown = state.or_else(|| app_number.and_then(|number| self.app_state(number, command))); + // The resolution reads the app's held state, so a change to it invalidates the kept resolution. + let key = key.or(app_number.map(|number| (number, None))); let reached = declaring.is_some() || instance.is_some_and(|id| match reach { Reach::Focus => { @@ -828,9 +835,9 @@ impl Board { let chord = self.keymap.as_ref().and_then(|cache| cache.keymap.shown_chord(command)); let chord_text = chord.and_then(|chord| self.keymap.as_ref()?.shown_text.get(&chord).cloned()); let resolved = ResolvedCommand { - label: state.and_then(|s| s.title_ref().cloned()).unwrap_or_else(|| Arc::from(def.map_or(command.id.as_str(), |def| def.label.as_str()))), + label: shown.and_then(|s| s.title_ref().cloned()).unwrap_or_else(|| Arc::from(def.map_or(command.id.as_str(), |def| def.label.as_str()))), catalog_label: def.map(|def| Arc::from(def.label.as_str())), - icon: state.and_then(|s| s.icon_ref().cloned()).or_else(|| def.and_then(|def| def.icon.clone())), + icon: shown.and_then(|s| s.icon_ref().cloned()).or_else(|| def.and_then(|def| def.icon.clone())), chord, chord_text, enabled: flags.enabled && !refused, diff --git a/crates/ui-contract/src/testing/host_key_trials.rs b/crates/ui-contract/src/testing/host_key_trials.rs index bba78143bf..f5a9d92c88 100644 --- a/crates/ui-contract/src/testing/host_key_trials.rs +++ b/crates/ui-contract/src/testing/host_key_trials.rs @@ -1387,6 +1387,48 @@ fn clipboard_with_canvas(keys: KeyUse, event: Event) -> (bool, Vec) { (events.borrow().contains(&event), fired) } +/// What `edit.cut` resolves to while a host canvas declares `keys` and the app holds Cut disabled with a translated +/// title and a hint saying why: its label, whether it is enabled, its hint, and its label once the app retitles it. +fn cut_with_canvas(keys: KeyUse) -> (String, bool, Option, String) { + let canvas = named_id("host canvas"); + let (_, mut base) = host_window(); + let mut show = move |ui: &mut Ui| { + base(ui); + widget(ui, canvas); + host_canvas(ui.ctx(), canvas, keys); + }; + let held = |title: &str| { + let mut states = crate::runtime::commands::CommandStates::new(); + states.set(EditCommands::Cut, crate::runtime::commands::CommandState::new().title(title).hint("Nothing is selected").enabled(false)); + CommandInput::new().states(&crate::contract::Tracked::new(states)) + }; + let mut frames = Frames::new(); + frames.commands(held("Ausschneiden")); + frames.frame(Vec::new(), &mut show); + fixture::host_focus(&frames.ctx, canvas); + frames.idle(2, &mut show); + let cut = crate::runtime::commands::resolve(&frames.ctx, EditCommands::Cut); + frames.commands(held("Couper")); + frames.idle(2, &mut show); + let retitled = crate::runtime::commands::resolve(&frames.ctx, EditCommands::Cut); + (cut.label.to_string(), cut.enabled, cut.hint.as_deref().map(str::to_owned), retitled.label.to_string()) +} + +/// An edit the focused part declares answers for its own flags, but its label is still the app's title for it, and +/// follows a new one, so the label of a library edit does not change language with the focus (#3569). The app's hint +/// explains the app's own disabled state, so it does not describe an edit the part enables. +#[trial] +fn a_declared_edit_keeps_the_app_s_title() { + let (declared, enabled, declared_hint, declared_retitled) = cut_with_canvas(KeyUse::CANVAS.with_edits(EditSet::NONE.with(EditCommand::Cut))); + let (undeclared, app_enabled, app_hint, undeclared_retitled) = cut_with_canvas(KeyUse::CANVAS); + assert!(enabled && !app_enabled, "the canvas answers for Cut's flags, the app does without the canvas's Cut"); + assert!(app_hint.is_some(), "the app answers for Cut: its hint says why Cut is unavailable"); + assert_eq!(declared_hint, None, "the canvas enables Cut: the app's reason does not describe it"); + assert_ne!(undeclared, undeclared_retitled, "the app answers for Cut: its title, then its new one"); + assert_eq!(declared, undeclared, "the canvas answers for Cut: still the app's title"); + assert_eq!(declared_retitled, undeclared_retitled, "and the app's new title"); +} + #[trial] fn a_host_canvas_reads_the_clipboard_of_its_edit_set_with_nothing_focused() { let edits = EditSet::NONE.with(EditCommand::Cut).with(EditCommand::Copy).with(EditCommand::Paste); From 0ebc5915b0aeef571ccc68531056e49a67d13bb5 Mon Sep 17 00:00:00 2001 From: Whatever Industries <273006022+whatever-industries@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:14:49 -0800 Subject: [PATCH 130/130] fcproj-format: split and reassemble project bins and items (#3517) Co-authored-by: whatever-industries <77seventy77@users.noreply.github.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- crates/fcproj-format/src/lib.rs | 2 + crates/fcproj-format/src/records.rs | 138 ++++++++++++++++++++++++++ crates/fcproj-format/tests/it/main.rs | 78 +++++++++++++++ 3 files changed, 218 insertions(+) create mode 100644 crates/fcproj-format/src/records.rs create mode 100644 crates/fcproj-format/tests/it/main.rs diff --git a/crates/fcproj-format/src/lib.rs b/crates/fcproj-format/src/lib.rs index 4ac1b72439..11f7e5013f 100644 --- a/crates/fcproj-format/src/lib.rs +++ b/crates/fcproj-format/src/lib.rs @@ -1,6 +1,8 @@ //! FilmCraft `.fcproj` JSON envelope, version detection and historical migrations. //! Project and editor-view types are supplied by the caller. #![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] +pub mod records; + use serde::{Deserialize, Serialize}; use serde_json::Value; /// The `format` tag written in every envelope. diff --git a/crates/fcproj-format/src/records.rs b/crates/fcproj-format/src/records.rs new file mode 100644 index 0000000000..971635cfa6 --- /dev/null +++ b/crates/fcproj-format/src/records.rs @@ -0,0 +1,138 @@ +//! Reversible record boundaries for a FilmCraft project. A bin owns an ordered list of +//! references; each project item (including a sequence) has one payload. Fields outside +//! those boundaries stay in their original JSON objects, including editor and extension data. +//! +//! These types describe logical records, independent of directory names, hashing, and commits. + +use crate::{FormatError, MIGRATIONS, check_supported, detect_bytes, migrate_with}; +use serde::Deserialize; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; + +type Result = std::result::Result; +type Payloads = BTreeMap; + +// Reassembly follows links between separately supplied records, outside the JSON parser's +// recursion limit. A repeated or cyclic bin is also rejected on its second visit. +const MAX_BIN_DEPTH: usize = 64; + +/// The envelope carries the root bin ID and a complete inventory of item IDs, including +/// items outside any bin. The map keys are persisted project IDs, never display names. +#[derive(Debug)] +pub struct ProjectRecords { + pub envelope: Value, + pub bins: BTreeMap, + pub items: BTreeMap, +} + +fn corrupt(message: impl Into) -> FormatError { + FormatError::Corrupt(message.into()) +} + +fn object_id(value: &Value) -> Result { + value.get("id").and_then(Value::as_u64).ok_or_else(|| corrupt("record lacks an unsigned id")) +} + +fn children(bin: &mut Value, depth: usize) -> Result<&mut Vec> { + if depth > MAX_BIN_DEPTH { + return Err(corrupt("bin nesting exceeds the supported depth")); + } + bin.get_mut("children").and_then(Value::as_array_mut).ok_or_else(|| corrupt("bin lacks children")) +} + +// Only nested bins change representation. Item references retain their original position. +fn nested_or_item<'a>(child: &'a mut Value, items: &Payloads) -> Result> { + let entry = child.as_object_mut().filter(|o| o.len() == 1).ok_or_else(|| corrupt("invalid bin entry"))?; + if let Some(item) = entry.get("Item") { + let id = item.as_u64().ok_or_else(|| corrupt("invalid item reference"))?; + if !items.contains_key(&id) { + return Err(corrupt(format!("bin references missing item {id}"))); + } + Ok(None) + } else { + entry.get_mut("Bin").map(Some).ok_or_else(|| corrupt("unknown bin entry")) + } +} + +fn split_bin(mut bin: Value, bins: &mut Payloads, items: &Payloads, depth: usize) -> Result { + let id = object_id(&bin)?; + for child in children(&mut bin, depth)? { + if let Some(nested) = nested_or_item(child, items)? { + *nested = Value::from(split_bin(nested.take(), bins, items, depth + 1)?); + } + } + if bins.insert(id, bin).is_some() { + return Err(corrupt(format!("duplicate bin id {id}"))); + } + Ok(id) +} + +fn join_bin(reference: &Value, bins: &mut Payloads, items: &Payloads, depth: usize) -> Result { + let id = reference.as_u64().ok_or_else(|| corrupt("invalid bin reference"))?; + let mut bin = bins.remove(&id).ok_or_else(|| corrupt(format!("missing or repeated bin {id}")))?; + if object_id(&bin)? != id { + return Err(corrupt(format!("bin payload does not match id {id}"))); + } + for child in children(&mut bin, depth)? { + if let Some(nested) = nested_or_item(child, items)? { + *nested = join_bin(nested, bins, items, depth + 1)?; + } + } + Ok(bin) +} + +impl ProjectRecords { + /// Split supported project bytes, applying the same historical migrations as the + /// ordinary reader. Callers reading from storage must bound input size before parsing. + pub fn split(bytes: &[u8]) -> Result { + let version = detect_bytes(bytes)?; + let doc = serde_json::from_slice(bytes).map_err(|e| corrupt(e.to_string()))?; + let mut envelope = migrate_with(MIGRATIONS, doc, version)?; + let project = envelope.get_mut("project").and_then(Value::as_object_mut).ok_or_else(|| corrupt("missing project"))?; + let Some(Value::Object(payloads)) = project.remove("items") else { return Err(corrupt("missing project items")) }; + let mut items = Payloads::new(); + let mut inventory = Vec::with_capacity(payloads.len()); + for (key, value) in payloads { + let id = object_id(&value)?; + if id.to_string() != key { + return Err(corrupt(format!("item key does not match id {id}"))); + } + items.insert(id, value); + inventory.push(Value::from(id)); + } + project.insert("items".into(), Value::Array(inventory)); + let root = project.get_mut("root").ok_or_else(|| corrupt("missing root bin"))?; + let mut bins = Payloads::new(); + *root = Value::from(split_bin(root.take(), &mut bins, &items, 0)?); + Ok(Self { envelope, bins, items }) + } + + /// Reassemble a complete set, refusing missing, extra or misidentified payloads. + /// A successful result preserves the migrated document as JSON, including unknown + /// fields; the application still validates timeline and media semantics on load. + pub fn into_document(mut self) -> Result { + let probe = crate::Probe::deserialize(&self.envelope).map_err(|e| corrupt(e.to_string()))?; + check_supported(crate::probe_version(&probe)?)?; + let project = self.envelope.get_mut("project").and_then(Value::as_object_mut).ok_or_else(|| corrupt("missing project"))?; + let root = project.get_mut("root").ok_or_else(|| corrupt("missing root bin"))?; + *root = join_bin(root, &mut self.bins, &self.items, 0)?; + if !self.bins.is_empty() { + return Err(corrupt("unreferenced bin payload")); + } + let Some(Value::Array(ids)) = project.remove("items") else { return Err(corrupt("missing item inventory")) }; + let mut items = Map::new(); + for key in ids { + let id = key.as_u64().ok_or_else(|| corrupt("invalid item inventory entry"))?; + let item = self.items.remove(&id).ok_or_else(|| corrupt(format!("missing or repeated item {id}")))?; + if object_id(&item)? != id { + return Err(corrupt(format!("item payload does not match id {id}"))); + } + items.insert(id.to_string(), item); + } + if !self.items.is_empty() { + return Err(corrupt("unreferenced item payload")); + } + project.insert("items".into(), Value::Object(items)); + Ok(self.envelope) + } +} diff --git a/crates/fcproj-format/tests/it/main.rs b/crates/fcproj-format/tests/it/main.rs new file mode 100644 index 0000000000..cdccb7abf6 --- /dev/null +++ b/crates/fcproj-format/tests/it/main.rs @@ -0,0 +1,78 @@ +//! Original, generated project fragments exercise record ownership and preservation. +use craft_fcproj_format::{FormatError, MIGRATIONS, SCHEMA_VERSION, migrate_with, records::ProjectRecords}; +use serde_json::{Value, json}; + +fn project() -> Value { + json!({ + "format": "filmcraft.project", "schema_version": SCHEMA_VERSION, "view": {"tabs":[12]}, + "generator": "test", "extra": [null, {}], + "project": { + "root": {"id":0,"name":"Cut","children":[ + {"Item":12},{"Bin":{"id":19,"name":"Cut","children":[{"Item":4}]}} + ]}, + "items": { + "4":{"id":4,"media":{"path":"../offline/shot.mov"},"label":"A"}, + "12":{"id":12,"sequence":{"nested":[4],"duration":123}}, + "9":{"id":9,"name":"Unfiled","extra":{}} + }, + "next_id":20, "transcripts":{}, "new_project_field":{"value":null} + } + }) +} + +fn split(doc: &Value) -> ProjectRecords { + ProjectRecords::split(&serde_json::to_vec(doc).unwrap()).unwrap() +} + +#[test] +fn changing_one_sequence_preserves_all_other_records_and_the_view() { + let original = project(); + let mut changed = original.clone(); + changed["project"]["items"]["12"]["sequence"]["duration"] = json!(124); + let before = split(&original); + let after = split(&changed); + assert_eq!(before.envelope, after.envelope); + assert_eq!(before.bins, after.bins); + assert_eq!(before.items.keys().filter(|id| before.items[id] != after.items[id]).copied().collect::>(), [12]); + assert_eq!(before.into_document().unwrap(), original); + assert_eq!(after.into_document().unwrap(), changed); +} + +#[test] +fn legacy_uses_the_same_migrations_and_future_versions_are_refused() { + let mut bare = project()["project"].take(); + bare["version"] = json!(1); + assert_eq!(split(&bare).into_document().unwrap(), migrate_with(MIGRATIONS, bare, 1).unwrap()); + let mut doc = project(); + doc["schema_version"] = json!(SCHEMA_VERSION + 1); + assert!(matches!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()), Err(FormatError::TooNew { .. }))); +} + +#[test] +fn incomplete_or_conflicting_records_cannot_be_reassembled() { + let make = || split(&project()); + let mut missing = make(); + missing.items.remove(&9); // Unfiled; a bin traversal alone cannot detect the lost item. + assert!(missing.into_document().is_err()); + let mut extra = make(); + extra.items.insert(11, json!({"id":11})); + assert!(extra.into_document().is_err()); + let mut cycle = make(); + cycle.bins.get_mut(&19).unwrap()["children"] = json!([{"Bin":0}]); + assert!(cycle.into_document().is_err()); + let mut mismatch = make(); + mismatch.items.get_mut(&4).unwrap()["id"] = json!(19); + assert!(mismatch.into_document().is_err()); + let mut detached = make(); + detached.bins.get_mut(&0).unwrap()["children"] = json!([]); + assert!(detached.into_document().is_err()); +} + +#[test] +fn conversion_refuses_ambiguous_bins_and_dangling_membership() { + let mut doc = project(); + doc["project"]["root"]["children"][1]["Bin"]["id"] = json!(0); + assert!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()).is_err()); + doc["project"]["root"]["children"] = json!([{"Item":100}]); + assert!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()).is_err()); +}