From 4b740e0075e413a7acc91edb52fbf2c5b368aa0b Mon Sep 17 00:00:00 2001 From: alehel Date: Sat, 14 Nov 2026 21:18:45 +0100 Subject: [PATCH 001/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] 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/269] =?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/269] 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/269] 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/269] 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/269] 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 460b5438c0a6262135ab5759eafa81dffe8b3a27 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:18:30 -0800 Subject: [PATCH 028/269] Dialogs: a Save As goes ahead when the portal answers with a file type of another shape answer() in crates/dialogs/src/portal.rs read the portal's current_filter with zvariant's tuple conversion, which panics on a structure with fewer fields than the tuple (zvariant 5.15.1, structure.rs:382). The Save dialog's thread then ended after a file was picked, and nothing was saved. filter_label reads the label only from a structure of a string and an array of (us), the (sa(us)) type the FileChooser portal documents. A current_filter of any other shape names no file type, and the answer keeps the path. A structure with more fields than (sa(us)) used to name its file type and now names none. This carries the fix from storytold/photocraft#13490 to the code that moved here from apps/photocraft/src/portal_save.rs. --- crates/dialogs/src/portal.rs | 17 +++++++++--- crates/dialogs/src/portal/tests.rs | 42 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/dialogs/src/portal.rs b/crates/dialogs/src/portal.rs index 1c6e75b04f..f75f2223bd 100644 --- a/crates/dialogs/src/portal.rs +++ b/crates/dialogs/src/portal.rs @@ -158,13 +158,22 @@ fn answer(code: u32, results: &HashMap) -> Result) = v.try_clone().ok()?.try_into().ok()?; - Some(label) - }); + let filter = results.get("current_filter").and_then(|v| filter_label(v)); Ok(Some(Saved { path, filter })) } +/// The label of a file type as the portal sends it, a `(sa(us))` structure; `None` for a value of +/// another shape. +fn filter_label(value: &Value<'_>) -> Option { + match value { + Value::Structure(s) => match s.fields() { + [Value::Str(label), Value::Array(globs)] if globs.element_signature() == "(us)" => Some(label.to_string()), + _ => None, + }, + _ => None, + } +} + /// `file:///home/me/A%20b.psd` → `/home/me/A b.psd`; `None` for other schemes. // pc: apps/photocraft/src/portal_save.rs:134 file_uri_path fn file_uri_path(uri: &str) -> Option { diff --git a/crates/dialogs/src/portal/tests.rs b/crates/dialogs/src/portal/tests.rs index 18cbc07e8b..26cf0b788d 100644 --- a/crates/dialogs/src/portal/tests.rs +++ b/crates/dialogs/src/portal/tests.rs @@ -10,6 +10,48 @@ fn file_uris_become_local_paths() { assert_eq!(file_uri_path("file://host/x.png"), None); } +/// A `current_filter` of another shape than `(sa(us))` (a structure with fewer, other or more fields, a string) +/// gives the path alone; `uris` of another shape is an error. +#[trial] +fn an_answer_of_another_shape_is_not_read() { + let answer_with = |uris: Value<'_>, filter: Option>| { + let mut r = HashMap::new(); + r.insert("uris".to_string(), OwnedValue::try_from(uris).unwrap()); + if let Some(filter) = filter { + r.insert("current_filter".to_string(), OwnedValue::try_from(filter).unwrap()); + } + answer(0, &r) + }; + let card = || Value::from(vec!["file:///tmp/card".to_string()]); + let malformed = [ + Value::from(("PNG".to_string(),)), + Value::from(("PNG".to_string(), vec![(0u32,)])), + Value::from(("PNG".to_string(), vec![("*.png".to_string(), 0u32)])), + Value::from((1u32, vec![(0u32, "*.png".to_string())])), + Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())], 1u32)), + Value::from("PNG"), + ]; + for filter in malformed { + let shape = filter.value_signature().to_string(); + assert_eq!(answer_with(card(), Some(filter)), Ok(Some(Saved { path: "/tmp/card".into(), filter: None })), "{shape}"); + } + // The shape the portal defines is still read, and so is the one `options` sends. + let png = Value::from(("PNG".to_string(), vec![(0u32, "*.png".to_string())])); + assert_eq!(answer_with(card(), Some(png)), Ok(Some(Saved { path: "/tmp/card".into(), filter: Some("PNG".into()) }))); + let sent = Value::from(wire(&Filter::new("Photoshop", &["psd", "psb"]))); + assert_eq!(filter_label(&sent), Some("Photoshop".into())); + let malformed = [ + Value::from(vec![1u32]), + Value::from(vec![("file:///tmp/card".to_string(),)]), + Value::from(Vec::::new()), + Value::from("file:///tmp/card"), + ]; + for uris in malformed { + let shape = uris.value_signature().to_string(); + assert!(answer_with(uris, None).is_err(), "{shape}"); + } +} + /// The name the Save dialog's answer ends up with: the picked type (`picked`, an index into `filters`) decides the /// extension a bare name takes, and an extension the user typed wins unless it is the one the dialog opened with. #[trial] From 5926d7ead3f1e6079b029fbc5fe388947b7f0ae4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:32:21 -0800 Subject: [PATCH 029/269] Screen: the color picker portal's answer of another shape fails the pick without a panic On Wayland the screen color picker reads the Screenshot portal's PickColor answer, whose color is a (ddd) structure. It read it with zvariant's tuple conversion, which panics inside zvariant 5.15.1 (structure.rs:382) on a structure with fewer fields than the tuple. portal_color now reads the channels only from a structure of three doubles; any other shape fails the pick with "the desktop color picker returned no color". --- crates/platform/src/screen.rs | 43 ++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/platform/src/screen.rs b/crates/platform/src/screen.rs index 0fc52b6787..8a247ab446 100644 --- a/crates/platform/src/screen.rs +++ b/crates/platform/src/screen.rs @@ -155,6 +155,19 @@ fn picked_color(rgb: [f64; 3]) -> Result { Ok(Capture::Color(rgb.map(|v| v as f32))) } +/// The colour in the portal's `PickColor` answer, a `(ddd)` structure; `None` for a value of another shape. +#[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] +fn portal_color(value: &zbus::zvariant::Value<'_>) -> Option<[f64; 3]> { + use zbus::zvariant::Value; + match value { + Value::Structure(s) => match s.fields() { + [Value::F64(r), Value::F64(g), Value::F64(b)] => Some([*r, *g, *b]), + _ => None, + }, + _ => None, + } +} + /// The most pixels one monitor image may hold (64 M); larger captures fail with `Failed`. pub const MAX_PIXELS: usize = 64 * 1024 * 1024; @@ -231,7 +244,10 @@ fn unpack_rgba( #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] mod backend { - use super::{Arc, AtomicBool, Capture, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, picked_color, pixel_count, usable_scale}; + use super::{ + Arc, AtomicBool, Capture, MAX_MONITORS, Ordering, ScreenError, ScreenImage, add_to_budget, picked_color, pixel_count, portal_color, + usable_scale, + }; const MAX_ICC_PROFILE_BYTES: usize = 1024 * 1024; /// Length limit of the property reads, in 32-bit units. @@ -437,8 +453,7 @@ mod backend { _ => return Err(failed("the desktop color picker could not sample this screen")), } let value = values.get("color").ok_or_else(|| failed("the desktop color picker returned no color"))?; - let (r, g, b): (f64, f64, f64) = value.try_clone().map_err(failed)?.try_into().map_err(|e: zbus::zvariant::Error| failed(e))?; - picked_color([r, g, b]) + picked_color(portal_color(value).ok_or_else(|| failed("the desktop color picker returned no color"))?) } } @@ -724,4 +739,26 @@ mod tests { assert!(unpack_rgba(&[0; 3], 1, 1, 4, [0, 1, 2, 3], false, true).is_err()); assert!(checked_stride(1, 1, usize::MAX).is_err()); } + + /// A `color` of another shape than `(ddd)` (a structure with fewer, other or more fields, a string, an array) + /// gives no colour; a `(ddd)` value gives its channels. + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + #[test] + fn a_color_of_another_shape_is_not_read() { + use zbus::zvariant::Value; + let malformed = [ + Value::from((0.5f64,)), + Value::from((0.5f64, 0.25f64)), + Value::from((0.5f64, 0.25f64, 1u32)), + Value::from(("red".to_string(), 0.25f64, 0.75f64)), + Value::from((0.5f64, 0.25f64, 0.75f64, 1.0f64)), + Value::from("red"), + Value::from(vec![0.5f64, 0.25, 0.75]), + ]; + for color in malformed { + let shape = color.value_signature().to_string(); + assert_eq!(portal_color(&color), None, "{shape}"); + } + assert_eq!(portal_color(&Value::from((0.5f64, 0.25f64, 0.75f64))), Some([0.5, 0.25, 0.75])); + } } 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 030/269] 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 031/269] 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 032/269] 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 033/269] 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 034/269] 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 035/269] 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 036/269] 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 037/269] 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 038/269] 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 039/269] 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 040/269] 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 041/269] 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 042/269] 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 043/269] 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 e5c911b900b1229f1f79fa1ecf3ff5bb675f9dda Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Thu, 19 Nov 2026 23:52:37 -0500 Subject: [PATCH 044/269] ppt-binary: read PowerPoint 95 pictures and notes (#2317, step 4) PowerPoint 95 keeps a document's pictures as Windows metafiles in a slot list inside the Environment record. A picture on a slide is a rectangle whose link record names its slot and holds its crop. Each one now reads as a picture shape in its box, with its crop and the line and fill PowerPoint 95 draws it with. The metafile becomes image/x-wmf media as stored, as the PowerPoint 97 path keeps its metafiles. A slot is read once however many shapes show it, all of them within the PowerPoint 97 path's 2 GiB budget. A picture whose slot is missing, empty or not a metafile is left out. Each slide's notes page sits inside the slide. The text of its notes placeholder becomes the slide's notes. The notes master is not read. --- crates/ppt-binary/README.md | 8 +- crates/ppt-binary/src/blip.rs | 2 +- crates/ppt-binary/src/lib.rs | 4 +- crates/ppt-binary/src/ppt95.rs | 103 ++++++-- crates/ppt-binary/src/ppt95/picture.rs | 118 +++++++++ crates/ppt-binary/src/ppt95/tests.rs | 347 +++++++++++++++++++++++-- crates/ppt-binary/src/ppt95/text.rs | 2 +- 7 files changed, 541 insertions(+), 43 deletions(-) create mode 100644 crates/ppt-binary/src/ppt95/picture.rs diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md index 5736b17785..ebcdabd935 100644 --- a/crates/ppt-binary/README.md +++ b/crates/ppt-binary/README.md @@ -62,7 +62,13 @@ the rectangle, rounded rectangle and ellipse take the angle the user set. A shap nothing but text is a text box. Freeforms read as custom paths through their points, in their box, with their format's fill, line and shadow, and open ones with their arrowheads. Groups read as groups of their members, which keep their places on the slide (PowerPoint 95 can't turn or flip -a group), nested up to 32 deep. Pictures, notes and the master's text styles come later. +a group), nested up to 32 deep. Pictures read as picture shapes in their box, with their crop and +the line and fill PowerPoint 95 draws them with. PowerPoint 95 keeps every picture as a Windows +metafile, whatever was inserted; each becomes `image/x-wmf` media as stored, as the PowerPoint 97 +path keeps its metafiles, read once however many shapes show it, and all of them within the +PowerPoint 97 path's 2 GiB budget. A picture whose picture can't be read is left out. Each slide's +notes page gives the slide its notes: the text of the page's notes placeholder. The master's text +styles come later. The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from: its layouts and placeholders. The file's masters then place and style the placeholders that diff --git a/crates/ppt-binary/src/blip.rs b/crates/ppt-binary/src/blip.rs index 56b6abaeca..32aa261290 100644 --- a/crates/ppt-binary/src/blip.rs +++ b/crates/ppt-binary/src/blip.rs @@ -11,7 +11,7 @@ const MAX_INFLATED: usize = 64 << 20; /// may inflate to (`craft_pptx::MAX_TOTAL`). Pictures are the only part of a `.ppt` /// that inflates, so a small hostile file can't make the import hold more than a `.pptx` could. /// It also fits a 32-bit `usize` (wasm32), where a 4 GiB constant wraps to 0. -const MAX_TOTAL: usize = 2 << 30; +pub(crate) const MAX_TOTAL: usize = 2 << 30; // A zero or tiny budget would drop every picture without a word, and the shift above can wrap on // a 32-bit target (wasm32) without any error, so the build checks it on every target. const _: () = assert!(MAX_TOTAL >= MAX_INFLATED); diff --git a/crates/ppt-binary/src/lib.rs b/crates/ppt-binary/src/lib.rs index 8637b778af..22a52bc33d 100644 --- a/crates/ppt-binary/src/lib.rs +++ b/crates/ppt-binary/src/lib.rs @@ -10,8 +10,8 @@ //! PowerPoint 95 files (a different record framing, learned from files PowerPoint 95 wrote) read //! as far as their slide size, masters with their colour schemes, backgrounds and placeholder //! boxes, and slides with their order, master, layout type, background, placeholders and text -//! boxes with formatted text, and shapes and lines with their fill, line and shadow; their -//! pictures and notes are not read yet. +//! boxes with formatted text, shapes and lines with their fill, line and shadow, freeforms, groups +//! and pictures, and their notes. //! PowerPoint 4.0 and earlier are refused as too old. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 797c68e3ae..1b8afe7252 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -7,8 +7,8 @@ //! //! Read so far: the slide size, the masters with their colour schemes and backgrounds, and the //! slides in order with their master, layout type and background, holding their placeholders, text -//! boxes, shapes, lines, freeforms and groups, with the text and its character and paragraph -//! formatting ([`text`]). +//! boxes, shapes, lines, freeforms, groups and pictures, with the text and its character and +//! paragraph formatting ([`text`]), and their notes. //! //! A page's object list (3000) holds shapes (3008), placeholders (3010, which add a 3011 atom: the //! type, the size, then the index), lines (3014), freeforms (3016) and groups (3001). A shape or @@ -41,12 +41,18 @@ //! caller's default master's, and the footer row places every layout's, as the PowerPoint 97 path //! does. //! -//! Not read yet: pictures; notes; and the master's text styles, so the levels of the default -//! master's styles stay as they are (the slide text carries its own formatting in full). +//! A picture is a shape naming one of the document's pictures, which are Windows metafiles; its +//! box is the cropped picture's ([`picture`]). A slide's notes page is a Notes record (1008) inside +//! the slide, whose notes placeholder (type 0x0E) holds the notes text ([`notes`]). +//! +//! Not read yet: the master's text styles, so the levels of the default master's styles stay as +//! they are (the slide text carries its own formatting in full). use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use craft_pptx::style::PictureFill; +use craft_pptx::text::BodyProps; use craft_pptx::{ Background, ColorRef, Defaults, Effects, Fill, Geom, LayoutType, Line, Master, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId, ShapeKind, Size, Slide, SlideId, TextBody, Xfrm, @@ -54,9 +60,11 @@ use craft_pptx::{ use crate::convert::{Scheme, layout_kind, layout_table, page_side, place_placeholder, same_family, scheme_theme}; use crate::record::u32_at; +use picture::{PictureRef, Pictures}; use shape::Look; use text::Env; +mod picture; mod shape; mod text; @@ -68,6 +76,7 @@ mod rt { pub const SLIDE_BOX: u32 = 1005; pub const SLIDE: u32 = 1006; pub const SLIDE_ATOM: u32 = 1007; + pub const NOTES: u32 = 1008; pub const SCHEME: u32 = 1012; pub const LAYOUT: u32 = 1015; pub const MAIN_MASTER: u32 = 1016; @@ -87,8 +96,15 @@ mod rt { pub const FREEFORM_ATOM: u32 = 3017; pub const POINTS: u32 = 3035; pub const TEXT: u32 = 4001; + pub const TEXT_BODY: u32 = 4002; + pub const TEXT_ATOM: u32 = 4003; } +/// A notes page's notes placeholder, in PowerPoint 95's numbering (3011 +0). +const NOTES_PLACEHOLDER: u8 = 0x0E; +/// The notes text type ([MS-PPT] `TextTypeEnum`), in a text atom's (4003) +0. +const NOTES_TEXT: u32 = 2; + /// "No instance". const NO_INSTANCE: u32 = 0xFFFF; /// Slides, and masters, read at most: beyond any real presentation, so a file of empty slide @@ -273,6 +289,8 @@ enum Kind { Line, /// A freeform (3016). Freeform, + /// A picture: a shape (3008) naming one of the document's pictures. + Picture(PictureRef), /// A group (3001) and its members. Group(Vec), } @@ -417,15 +435,22 @@ fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option { look = shape::look(&f, scheme); } } - Some(Object { placeholder, ph, xfrm, text, geom, look, kind: Kind::Shape }) + let kind = match picture::picture_ref(r).filter(|_| !placeholder) { + Some(pic) => Kind::Picture(pic), + None => Kind::Shape, + }; + Some(Object { placeholder, ph, xfrm, text, geom, look, kind }) } -/// An object as a shape: a placeholder of a known type; a text box when it draws nothing but its -/// text; else a shape or line that draws something. One that draws nothing is left out. A -/// placeholder of an unknown type keeps its text as a text box. -fn shape(p: &mut Presentation, o: Object) -> Option { - if let Kind::Group(members) = o.kind { - return group(p, members); +/// An object as a shape: a placeholder of a known type; a picture; a text box when it draws +/// nothing but its text; else a shape or line that draws something. One that draws nothing is left +/// out, and so is a picture whose picture can't be read. A placeholder of an unknown type keeps its +/// text as a text box. +fn shape(p: &mut Presentation, pictures: &mut Pictures, o: Object) -> Option { + match o.kind { + Kind::Group(members) => return group(p, pictures, members), + Kind::Picture(pic) => return picture(p, pictures, o.xfrm, o.geom, o.look, pic), + _ => {} } let Some(ph) = o.ph else { let text = o.text.filter(|t| !t.is_empty()); @@ -475,19 +500,39 @@ fn shape(p: &mut Presentation, o: Object) -> Option { Some(Shape { id: ShapeId(p.alloc_id()?), name: name.into(), xfrm: Some(o.xfrm), ph: Some(ph), text, ..Default::default() }) } +/// A picture in its box, drawn with its format as PowerPoint 95 draws it (a picture made by +/// inserting a file has a line, and a fill behind it, as any new shape does), showing the cropped +/// picture. +fn picture(p: &mut Presentation, pictures: &mut Pictures, xfrm: Xfrm, geom: Option, look: Look, pic: PictureRef) -> Option { + let media = pictures.media(p, pic.slot)?; + let id = p.alloc_id()?; + let Look { fill, line, shadow } = look; + Some(Shape { + id: ShapeId(id), + name: format!("Picture {id}"), + xfrm: Some(xfrm), + geom: geom.unwrap_or_else(|| Geom::Preset { name: "rect".into(), adj: vec![] }), + fill: Some(fill), + line: Some(line), + effects: shadow.map(|s| Effects { outer_shadow: Some(s), ..Default::default() }), + kind: ShapeKind::Picture { fill: PictureFill { media, crop: pic.crop, ..Default::default() } }, + ..Default::default() + }) +} + /// A group of the shapes its members are, in the box they span, which is also its child space, so /// the members keep their places on the slide. A group none of whose members draws anything is /// left out. /// /// A nested group recurses here directly, not through [`shape`], whose frame is far larger: the /// recursion is bounded by [`MAX_DEPTH`], and each level should cost the stack little. -fn group(p: &mut Presentation, members: Vec) -> Option { +fn group(p: &mut Presentation, pictures: &mut Pictures, members: Vec) -> Option { let id = p.alloc_id()?; let mut children = Vec::with_capacity(members.len()); for m in members { let s = match m.kind { - Kind::Group(inner) => group(p, inner), - _ => shape(p, m), + Kind::Group(inner) => group(p, pictures, inner), + _ => shape(p, pictures, m), }; children.extend(s); } @@ -509,6 +554,11 @@ fn group(p: &mut Presentation, members: Vec) -> Option { /// Build the presentation from a PowerPoint 95 Document container. pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { + convert_within(document, app, crate::blip::MAX_TOTAL) +} + +/// [`convert`], with all of the document's pictures together within `budget` bytes. +fn convert_within(document: &Rec, app: &dyn Defaults, budget: usize) -> Presentation { let atom = document.child(rt::DOCUMENT_ATOM); let field = |at: usize| atom.and_then(|a| a.i32(at)); let size = Size::new(page_side(field(0), 720.0), page_side(field(4), 540.0)); @@ -516,6 +566,7 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { p.notes_size = Size::new(page_side(field(8), 540.0), page_side(field(12), 720.0)); let env = Env::new(document); + let mut pictures = Pictures::new(document, budget); // The lists are told apart by what they hold, in whatever order they come. let (mut slides, mut masters) = (vec![], vec![]); @@ -549,7 +600,7 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { } continue; } - if let Some(s) = shape(&mut p, o) { + if let Some(s) = shape(&mut p, &mut pictures, o) { master.shapes.push(s); } } @@ -574,13 +625,31 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation { let Some(id) = p.alloc_id() else { break }; let mut shapes = vec![]; for o in Reader::page(&env, &scheme, size, &s.rec) { - shapes.extend(shape(&mut p, o)); + shapes.extend(shape(&mut p, &mut pictures, o)); } - p.slides.push(Arc::new(Slide { id: SlideId(id), layout, background, shapes, show_master_shapes: true, ..Default::default() })); + let notes = s.rec.child(rt::NOTES).and_then(|n| notes(&n, &env, &scheme)).unwrap_or_default(); + p.slides.push(Arc::new(Slide { id: SlideId(id), layout, background, shapes, show_master_shapes: true, notes, ..Default::default() })); } p } +/// The text of a slide's notes page (1008, inside the slide): its notes placeholder's, or else the +/// first text of the notes text type, in the page's own colours. The notes master, a 1008 in the +/// Document itself, isn't read: the PowerPoint 97 path doesn't import notes masters either. +fn notes(page: &Rec, env: &Env, slide_scheme: &Scheme) -> Option { + let scheme = page.child(rt::SCHEME).and_then(|s| s.child(rt::COLOR_SCHEME)).map_or(*slide_scheme, |s| scheme_of(&s)); + let is_notes = |r: &Rec| { + let kind = r.child(rt::PLACEHOLDER_ATOM).filter(|_| r.kind == rt::PLACEHOLDER).and_then(|a| a.u8(0)); + let text_type = r.child(rt::TEXT).and_then(|t| t.child(rt::TEXT_BODY)).and_then(|b| b.child(rt::TEXT_ATOM)).and_then(|a| a.u32(0)); + kind == Some(NOTES_PLACEHOLDER) || (kind.is_none() && text_type == Some(NOTES_TEXT)) + }; + let objects = page.child(rt::OBJECTS)?; + let found = objects.children().take(MAX_OBJECTS).filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER)).find(|r| is_notes(r))?; + let mut body = text::text_body(&found.child(rt::TEXT)?, env, &scheme, None, false)?; + body.body = BodyProps::default(); + Some(body) +} + /// The caller's default master, with ids above those handed out so far, wearing `scheme`. fn default_master(p: &mut Presentation, app: &dyn Defaults, size: Size, scheme: Option) -> Master { let (mut master, last) = app.master(size, p.next_id); diff --git a/crates/ppt-binary/src/ppt95/picture.rs b/crates/ppt-binary/src/ppt95/picture.rs new file mode 100644 index 0000000000..016a91ffeb --- /dev/null +++ b/crates/ppt-binary/src/ppt95/picture.rs @@ -0,0 +1,118 @@ +//! PowerPoint 95 pictures, learned from files PowerPoint 95 wrote. +//! +//! The Environment (1010) holds the document's pictures in a slot list (2006), as it holds its +//! fonts and rulers: each slot is what comes before a 2017 record. A slot's picture is a 4028 +//! container holding a 4037, which holds a header (4038) and the picture itself (4033): always a +//! Windows metafile without a placeable header, whatever was inserted (a BMP, a JPEG and a PNG all +//! became metafiles drawing the bitmap). Inserting the same file again reuses its slot. +//! +//! A picture on a page is a shape (3008, a rectangle drawn with its format as any shape is) holding +//! a 4014 container: 4015, the crop (left, top, right and bottom as i32s, in ten-thousandths of the +//! picture), and 4053 → 4036, the picture's slot number. The shape's box is the cropped picture's. +//! (On a notes page, 4014 → 4054 → 4032 names the slide its slide image shows instead.) Only the +//! left and top crops were seen set; the right and bottom are taken to follow in that order. +//! +//! The metafile is kept as it is, as `image/x-wmf` media, as the PowerPoint 97 path keeps the +//! metafiles of its blip store. Each slot is read once, the first time a shape names it, and all of +//! them together within [`crate::blip::MAX_TOTAL`] bytes, the PowerPoint 97 path's budget. + +use std::collections::HashMap; + +use craft_pptx::{MediaId, Presentation}; + +use super::Rec; +use super::text::slots; +use crate::record::u16_at; + +/// Record types. +pub(super) mod rt { + pub const ENVIRONMENT: u32 = 1010; + pub const PICTURES: u32 = 2006; + pub const PICTURE: u32 = 4028; + pub const PICTURE_BODY: u32 = 4037; + pub const METAFILE: u32 = 4033; + pub const LINK: u32 = 4014; + pub const CROP: u32 = 4015; + pub const PICTURE_LINK: u32 = 4053; + pub const PICTURE_INDEX: u32 = 4036; +} + +/// A WMF's standard header: 9 words. +const WMF_HEADER: usize = 18; +/// Crop values are ten-thousandths of the picture. +const CROP_UNIT: f64 = 10_000.0; + +/// What a shape says about its picture: the slot it names and its crop (left, top, right, bottom, +/// as fractions of the picture). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct PictureRef { + pub slot: u32, + pub crop: [f64; 4], +} + +/// A shape's picture link (4014 → 4053 → 4036), with its crop. `None` for a shape that shows no +/// picture, a notes page's slide image included. +pub(super) fn picture_ref(shape: &Rec) -> Option { + let link = shape.child(rt::LINK)?; + let slot = link.child(rt::PICTURE_LINK)?.child(rt::PICTURE_INDEX)?.u32(0)?; + let mut crop = [0.0; 4]; + if let Some(c) = link.child(rt::CROP) { + for (i, v) in crop.iter_mut().enumerate() { + *v = c.i32(i * 4).map_or(0.0, |n| (f64::from(n) / CROP_UNIT).clamp(-1.0, 1.0)); + } + } + Some(PictureRef { slot, crop }) +} + +/// The document's pictures: each slot's metafile record, made media only when a shape first names +/// it, every slot at most once, and all of them within a byte budget. +pub(super) struct Pictures<'a> { + slots: Vec>>, + media: HashMap>, + budget: usize, +} + +impl<'a> Pictures<'a> { + pub(super) fn new(document: &Rec<'a>, budget: usize) -> Pictures<'a> { + let slots = document + .child(rt::ENVIRONMENT) + .and_then(|e| e.child(rt::PICTURES)) + .map(|list| slots(&list, rt::PICTURE, |p| p.child(rt::PICTURE_BODY)?.child(rt::METAFILE))) + .unwrap_or_default(); + Pictures { slots, media: HashMap::new(), budget } + } + + /// The media of the picture in `slot`. `None` for a slot that is missing or empty, whose + /// metafile can't be read, or that would pass the budget. + pub(super) fn media(&mut self, p: &mut Presentation, slot: u32) -> Option { + if let Some(m) = self.media.get(&slot) { + return *m; + } + let id = self.read(p, slot); + self.media.insert(slot, id); + id + } + + fn read(&mut self, p: &mut Presentation, slot: u32) -> Option { + let record = self.slots.get(usize::try_from(slot).ok()?).copied().flatten()?; + let bytes = metafile(record.data)?; + if bytes.len() > self.budget { + log::warn!("ppt: PowerPoint 95 pictures pass {} bytes; the rest are left out", crate::blip::MAX_TOTAL); + return None; + } + self.budget -= bytes.len(); + p.add_media(&format!("image{}.wmf", u64::from(slot) + 1), "image/x-wmf", bytes.to_vec()) + } +} + +/// A metafile record's bytes as a WMF file: a standard header (a type of 1 or 2 and a header of 9 +/// words), cut to the size the header gives when the record holds more. `None` for anything else. +fn metafile(data: &[u8]) -> Option<&[u8]> { + let (kind, words) = (u16_at(data, 0)?, u16_at(data, 2)?); + if !matches!(kind, 1 | 2) || words != 9 || data.len() < WMF_HEADER { + return None; + } + // The file's size in words. + let size = crate::record::u32_at(data, 6).and_then(|w| usize::try_from(w).ok()).and_then(|w| w.checked_mul(2)).unwrap_or(0); + Some(data.get(..size).filter(|_| size >= WMF_HEADER).unwrap_or(data)) +} diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 9d41014c1a..4b6e27a1dc 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -3,7 +3,7 @@ #![allow(clippy::unwrap_used)] use craft_pptx::text::{Align, Bullet}; -use craft_pptx::{Background, ColorRef, Fill, Geom, LayoutType, Paragraph, PhType, Presentation, Rgba, SchemeSlot, Shape, TextBody}; +use craft_pptx::{Background, ColorRef, Fill, Geom, LayoutType, Paragraph, PhType, Presentation, Rgba, SchemeSlot, Shape, ShapeKind, TextBody}; use super::rt; use crate::tests::{AppDefaults, build}; @@ -66,27 +66,37 @@ struct SlideSpec { scheme: [u32; 8], /// The slide's object list. objects: Vec>, + /// Its notes page (1008). + notes: Option>, } impl SlideSpec { fn new(id: u32, layout: u32) -> SlideSpec { - SlideSpec { id, master: MASTER, layout, follow_background: true, fill: [0, 0, 0, 0], filled: true, scheme: DEFAULT, objects: vec![] } + SlideSpec { + id, + master: MASTER, + layout, + follow_background: true, + fill: [0, 0, 0, 0], + filled: true, + scheme: DEFAULT, + objects: vec![], + notes: None, + } } } fn slide(s: &SlideSpec) -> Vec { - container( - rt::SLIDE, - 0x10, - &[ - rec(rt::SLIDE_ATOM, 0, 0, &le32(&[s.id, s.master])), - slide_box(s.follow_background), - rec(rt::LAYOUT, 1, 0, &le32(&[s.layout, 0, 0])), - container(rt::SCHEME, 0x78, &[scheme_atom(0, s.scheme)]), - background_shape(s.fill, s.filled), - container(rt::OBJECTS, 0x14, &s.objects), - ], - ) + let mut kids = vec![rec(rt::SLIDE_ATOM, 0, 0, &le32(&[s.id, s.master])), slide_box(s.follow_background)]; + // A notes page comes after the slide box, as PowerPoint 95 writes it. + kids.extend(s.notes.clone()); + kids.extend([ + rec(rt::LAYOUT, 1, 0, &le32(&[s.layout, 0, 0])), + container(rt::SCHEME, 0x78, &[scheme_atom(0, s.scheme)]), + background_shape(s.fill, s.filled), + container(rt::OBJECTS, 0x14, &s.objects), + ]); + container(rt::SLIDE, 0x10, &kids) } fn master(id: u32, scheme: [u32; 8], fill: [u8; 4]) -> Vec { @@ -136,7 +146,7 @@ const WIDE_RULER: [(i32, i32); 5] = [(576, 288), (828, 648), (1044, 900), (1260, /// The Environment: fonts Times New Roman, Arial, Courier New and "Café" by slot, and the rulers: /// the body's, a plain one, an empty slot and a wide one. -fn environment() -> Vec { +fn environment(pictures: &[Vec]) -> Vec { let fonts = container( 2005, 0x19, @@ -148,7 +158,9 @@ fn environment() -> Vec { 0x18, &[ruler(BODY_RULER), slot_end(0), ruler(plain), slot_end(1), rec(2018, 0, 0, &[]), slot_end(2), ruler(WIDE_RULER), slot_end(3)], ); - container(1010, 0x15, &[rulers, fonts, container(2005, 0x1A, &[])]) + let mut kids = pictures.to_vec(); + kids.extend([rulers, fonts, container(2005, 0x1A, &[])]); + container(1010, 0x15, &kids) } /// A character run: length, font slot, size in points, style bits (1 bold, 2 italic, @@ -262,16 +274,21 @@ fn document_atom(w: u32, h: u32, slides: u32) -> Vec { /// A `PowerPoint Document` stream: root 3 holding the Document and a type-10 atom. fn stream_of(atom: Vec, slides: &[Vec], masters: &[Vec]) -> Vec { + stream_with(atom, slides, masters, &[], &[]) +} + +/// A stream whose Environment starts with `pictures` (the 2006 list) and whose Document ends with +/// `extra` records (a notes master, say). +fn stream_with(atom: Vec, slides: &[Vec], masters: &[Vec], pictures: &[Vec], extra: &[Vec]) -> Vec { let list = |tag: u32, items: &[Vec]| { let mut kids = vec![rec(2001, 0, 0, &le32(&[items.len() as u32]))]; kids.extend_from_slice(items); container(rt::LIST, tag, &kids) }; - let document = container( - rt::DOCUMENT, - 0, - &[atom, environment(), list(0xA, slides), list(0xB, masters), list(0xC, &[]), container(1026, 0x64, &[]), rec(1002, 0, 0, &[])], - ); + let mut kids = vec![atom, environment(pictures), list(0xA, slides), list(0xB, masters)]; + kids.extend_from_slice(extra); + kids.extend([list(0xC, &[]), container(1026, 0x64, &[]), rec(1002, 0, 0, &[])]); + let document = container(rt::DOCUMENT, 0, &kids); container(rt::ROOT, 0, &[document, rec(10, 0, 0, &le32(&[1, 0x100]))]) } @@ -1491,6 +1508,241 @@ fn hostile_freeforms_and_groups_never_panic() { } } +/// A Windows metafile without a placeable header: the standard header (type 1, 9 words, version +/// 0x300, its size in words), `records`, then the end record. +fn wmf(records: &[u8]) -> Vec { + let words = (18 + records.len() + 6) / 2; + let mut b = vec![1, 0, 9, 0, 0, 3]; + b.extend_from_slice(&(words as u32).to_le_bytes()); + b.extend_from_slice(&[0; 8]); + b.extend_from_slice(records); + b.extend_from_slice(&[3, 0, 0, 0, 0, 0]); + b +} + +/// A metafile that is told apart from others by `n`: a SETWINDOWEXT of n × n. +fn wmf_n(n: u8) -> Vec { + wmf(&[5, 0, 0, 0, 0x0C, 0x02, n, 0, n, 0]) +} + +/// The document's picture list (2006): each slot's metafile record body, or an empty slot. +fn picture_list(slots: &[Option>]) -> Vec { + let mut kids = vec![]; + for (i, s) in slots.iter().enumerate() { + match s { + Some(body) => { + let header = rec(4038, 0, 0, &le32(&[0xF00, 0, 0, 12, 12])); + kids.push(container(4028, 9, &[container(4037, 0, &[header, rec(4033, 0, 0, body)])])); + kids.push(rec(4043, 0, 0, &[])); + } + None => kids.push(rec(2018, 0, 0, &[])), + } + kids.push(slot_end(i as u32)); + } + container(2006, 0x17, &kids) +} + +/// A picture on a slide: a rectangle at `bx` drawn with `f`, naming `slot`, cropped by `crop` +/// (left, top, right, bottom in ten-thousandths). +fn picture_95(bx: [i32; 4], slot: u32, crop: [i32; 4], f: Format) -> Vec { + let link = container(4014, 0x1F, &[rec(4015, 0, 0, &le32(&crop.map(|v| v as u32))), container(4053, 0, &[rec(4036, 0, 0, &le32(&[slot]))])]); + container(rt::SHAPE, 0x13, &[coded_geometry((-3i32) as u32, 0, bx, 0), format(f), link]) +} + +/// 1 in square at 1 in, 1 in: AddPicture(file, 1440, 1440, 1440, 1440). +const PICTURE_BOX: [i32; 4] = [-2304, -1584, -1728, -1008]; + +/// A deck of `slides` slide object lists over the picture list `slots`, its pictures within +/// `budget` bytes. +fn picture_deck(slides: Vec>>, slots: &[Option>], budget: usize) -> Presentation { + let s: Vec> = + slides.into_iter().enumerate().map(|(i, objects)| slide(&SlideSpec { objects, ..SlideSpec::new(0x100 + i as u32, 16) })).collect(); + let stream = stream_with(document_atom(5760, 4320, s.len() as u32), &s, &[master(MASTER, DEFAULT, [0; 4])], &[picture_list(slots)], &[]); + let document = super::document(&stream).unwrap(); + super::convert_within(&document, &AppDefaults, budget) +} + +/// A picture shape as its box, media, crop and the media's bytes. +type Pictured = ((f64, f64, f64, f64), craft_pptx::MediaId, [f64; 4], Vec); + +/// Each picture on slide `i`: its box, media, crop and the media's bytes. +fn pictures_on(p: &Presentation, i: usize) -> Vec { + p.slides[i] + .shapes + .iter() + .filter_map(|s| match &s.kind { + ShapeKind::Picture { fill } => { + let media = p.media.iter().find(|m| m.id == fill.media).unwrap(); + assert_eq!(media.content_type, "image/x-wmf"); + Some((boxed(s), fill.media, fill.crop, media.data.to_vec())) + } + _ => None, + }) + .collect() +} + +/// A picture is a picture shape in its box, showing its slot's metafile as it is, cropped as it +/// says, drawn with its format's line and fill. +#[test] +fn pictures_show_their_metafile() { + let p = picture_deck( + vec![vec![picture_95(PICTURE_BOX, 0, [0; 4], PLAIN), picture_95([-2160, -1512, -1728, -1008], 0, [2500, 1250, 0, -500], PLAIN)]], + &[Some(wmf_n(12))], + usize::MAX, + ); + let pics = pictures_on(&p, 0); + assert_eq!(pics.len(), 2); + assert_eq!((pics[0].0, pics[0].2, &pics[0].3), ((72.0, 72.0, 72.0, 72.0), [0.0; 4], &wmf_n(12))); + assert_eq!((pics[1].0, pics[1].2), ((90.0, 81.0, 54.0, 63.0), [0.25, 0.125, 0.0, -0.05])); + let s = &p.slides[0].shapes[0]; + assert_eq!((s.fill.clone(), s.line.clone()), (Some(Fill::solid(rgb(0, 0xCC, 0x99))), Some(craft_pptx::Line::solid(rgb(0, 0, 0), 1.0)))); + assert_eq!(preset_of(s).0, "rect"); + // Through the whole import too, with the full budget. + let stream = stream_with( + document_atom(5760, 4320, 1), + &[slide(&SlideSpec { objects: vec![picture_95(PICTURE_BOX, 0, [0; 4], PLAIN)], ..SlideSpec::new(0x100, 16) })], + &[master(MASTER, DEFAULT, [0; 4])], + &[picture_list(&[Some(wmf_n(2))])], + &[], + ); + let p = import(&stream).unwrap(); + assert_eq!(pictures_on(&p, 0).iter().map(|x| x.3.clone()).collect::>(), [wmf_n(2)]); +} + +/// Pictures naming one slot share one media item, on one slide or many; each slot is its own. +#[test] +fn pictures_sharing_a_slot_share_media() { + let pic = |slot| picture_95(PICTURE_BOX, slot, [0; 4], PLAIN); + let p = picture_deck(vec![vec![pic(0), pic(1), pic(0)], vec![pic(0)]], &[Some(wmf_n(2)), Some(wmf_n(3))], usize::MAX); + let (first, second) = (pictures_on(&p, 0), pictures_on(&p, 1)); + assert_eq!((first.len(), second.len(), p.media.len()), (3, 1, 2)); + assert_eq!((first[0].1, second[0].1), (first[2].1, first[2].1)); + assert_ne!(first[0].1, first[1].1); + assert_eq!((first[0].3.clone(), first[1].3.clone()), (wmf_n(2), wmf_n(3))); +} + +/// A picture naming a slot that is missing, empty or holds no metafile is left out; the shapes +/// beside it are kept. +#[test] +fn a_dangling_picture_is_left_out() { + let pic = |slot| picture_95(PICTURE_BOX, slot, [0; 4], PLAIN); + let slots = [Some(wmf_n(2)), None, Some(b"GIF89a, not a metafile".to_vec()), Some(vec![1, 0, 9, 0, 0, 3])]; + let p = picture_deck( + vec![vec![pic(1), pic(2), pic(3), pic(7), pic(u32::MAX), autoshape(-1, 0, [0, 0, 576, 576], 0, PLAIN), pic(0)]], + &slots, + usize::MAX, + ); + let shapes = &p.slides[0].shapes; + assert_eq!(shapes.iter().map(|s| preset_of(s).0).collect::>(), ["ellipse", "rect"]); + assert_eq!(pictures_on(&p, 0).len(), 1); +} + +/// A metafile record holding more than its header's size is cut to it; one holding less is kept +/// as it is. +#[test] +fn a_metafile_is_cut_to_its_size() { + let mut long = wmf_n(2); + long.extend_from_slice(b"trailing bytes"); + let mut short = wmf_n(3); + short.truncate(short.len() - 6); + let pic = |slot| picture_95(PICTURE_BOX, slot, [0; 4], PLAIN); + let p = picture_deck(vec![vec![pic(0), pic(1)]], &[Some(long), Some(short.clone())], usize::MAX); + assert_eq!(pictures_on(&p, 0).into_iter().map(|x| x.3).collect::>(), [wmf_n(2), short]); +} + +/// All the pictures together keep to the budget: a picture that would pass it is left out, and a +/// slot read already costs nothing more when it is shown again. +#[test] +fn pictures_keep_to_the_budget() { + let pic = |slot| picture_95(PICTURE_BOX, slot, [0; 4], PLAIN); + let (a, b) = (wmf_n(2), wmf_n(3)); + let p = picture_deck(vec![vec![pic(0), pic(1), pic(0)]], &[Some(a.clone()), Some(b)], a.len() + 4); + assert_eq!(pictures_on(&p, 0).into_iter().map(|x| x.3).collect::>(), [a.clone(), a.clone()]); + // The full import's budget is the PowerPoint 97 path's. + assert_eq!(crate::blip::MAX_TOTAL, 2 << 30); + let p = picture_deck(vec![vec![pic(0)]], &[Some(a.clone())], a.len() - 1); + assert!(p.slides[0].shapes.is_empty() && p.media.is_empty()); +} + +/// A notes page (1008) inside a slide, its slide id in its 1009 atom, holding a slide image +/// placeholder (type 0x13, linked to the slide) and the notes placeholder (0x0E) with `text`. +fn notes_page(slide_id: u32, text: &[u8]) -> Vec { + let bx = [-1440, -2448, 1440, -288]; + let image = container(4014, 0x1F, &[rec(4015, 0, 0, &[0; 16]), container(4054, 0, &[rec(4032, 0, 0, &le32(&[slide_id]))])]); + let image = container(3010, 0x13, &[rec(3011, 0, 0, &[0x13, 0, 0, 0, 0, 0, 0, 0]), geometry(bx, 0), format(PLAIN), image]); + let body_box = [-1584, -144, 1584, 2448]; + let body = placeholder_95(0x0E, 0, 1, body_box, Some(simple_text(text, body_box, BODY))); + notes_with(slide_id, vec![image, body]) +} + +/// A notes page holding `objects`. +fn notes_with(slide_id: u32, objects: Vec>) -> Vec { + container(rt::NOTES, 0x25, &[rec(1009, 0, 0, &le32(&[slide_id])), slide_box(true), container(rt::OBJECTS, 0x14, &objects)]) +} + +/// A text container's text type (its 4003 atom's +0) set to `kind`. +fn text_typed(mut text: Vec, kind: u32) -> Vec { + let at = text.windows(4).position(|w| w == 4003u32.to_le_bytes()).unwrap(); + text[at + 16..at + 20].copy_from_slice(&kind.to_le_bytes()); + text +} + +/// Each slide's notes are its own notes page's notes placeholder's text (or, without one, the text +/// of the notes text type); the notes master's text and the slide image aren't notes, and nothing +/// on a notes page becomes a slide shape. +#[test] +fn notes_land_on_their_slide() { + let mut slides = [SlideSpec::new(0x100, 16), SlideSpec::new(0x101, 16), SlideSpec::new(0x102, 16), SlideSpec::new(0x103, 16)]; + slides[0].notes = Some(notes_page(0x100, b"First note\rsecond line")); + slides[2].notes = Some(notes_page(0x102, b"Third")); + // A notes page whose text is a plain shape of the notes text type. + let bx = [-1584, -144, 1584, 2448]; + slides[3].notes = Some(notes_with( + 0x103, + vec![shape_95(bx, Some(text_typed(simple_text(b"Typed", bx, BODY), 4))), shape_95(bx, Some(text_typed(simple_text(b"Fourth", bx, BODY), 2)))], + )); + slides[0].objects = vec![shape_95([0, 0, 576, 576], Some(simple_text(b"On the slide", [0, 0, 576, 576], BODY)))]; + let s: Vec> = slides.iter().map(slide).collect(); + let notes_master = notes_with(MASTER, vec![placeholder_95(0x05, 0, 1, bx, Some(simple_text(b"Master notes", bx, MASTER_BODY)))]); + let p = import(&stream_with(document_atom(5760, 4320, 4), &s, &[master(MASTER, DEFAULT, [0; 4])], &[], &[notes_master])).unwrap(); + assert_eq!(p.slides.iter().map(|s| s.notes.text()).collect::>(), ["First note\nsecond line", "", "Third", "Fourth"]); + assert_eq!(p.slides[0].notes.paragraphs[0].runs[0].props.size, Some(24.0)); + assert_eq!(texts(&p), ["On the slide"]); + assert!(p.slides[1..].iter().all(|s| s.shapes.is_empty())); +} + +/// Damaged pictures and notes never panic: every word of a deck of them set to hostile values (huge +/// sizes, bad slot numbers, odd types), or the deck cut anywhere. +#[test] +fn hostile_pictures_and_notes_never_panic() { + let mut s = SlideSpec::new(0x100, 16); + s.objects = vec![picture_95(PICTURE_BOX, 0, [2500, 0, -20000, i32::MAX], PLAIN), group_95(&[picture_95(PICTURE_BOX, 1, [0; 4], PLAIN)])]; + s.notes = Some(notes_page(0x100, b"Note")); + let stream = stream_with( + document_atom(5760, 4320, 1), + &[slide(&s)], + &[master(MASTER, DEFAULT, [0; 4])], + &[picture_list(&[Some(wmf_n(2)), None, Some(wmf_n(3))])], + &[], + ); + for at in (0..stream.len() - 4).step_by(2) { + for v in [0u32, 1, 2, 9, 0xFAB, 0xFB5, 0xFC4, 0x3F0, 0x7FFF_FFFF, 0xFFFF_FFFF] { + let mut d = stream.clone(); + d[at..at + 4].copy_from_slice(&v.to_le_bytes()); + if let Ok(p) = import(&d) { + for s in &p.slides { + for x in s.shapes.iter().filter_map(|x| x.xfrm) { + assert!(x.w.is_finite() && x.h.is_finite()); + } + } + } + } + } + for cut in 0..stream.len() { + let _ = import(&stream[..cut]); + } +} + /// The presets of the object model's shape types 1 to 12, as PowerPoint 95 rendered them ("custom" for /// the trapezoid, which has its own outline). const SHAPE_PRESETS: [&str; 12] = @@ -1557,10 +1809,63 @@ fn check_sample(name: &str, p: &Presentation) { // The automation reported 1295, 1367.5, 4610 × 720 twips. assert_eq!(boxed(s), (64.75, 68.375, 230.5, 36.0)); } + "picture" | "jpeg" | "png" | "picwmf" | "piccrop" | "twopics" | "picshare" | "notes" | "notes2" => check_media_sample(name, p), _ => check_shape_sample(name, p), } } +/// What one PowerPoint 95 picture or notes sample shows, by its case name. +fn check_media_sample(name: &str, p: &Presentation) { + let notes: Vec = p.slides.iter().map(|s| s.notes.text()).collect(); + // Each picture on a slide: its box, media, crop, and whether it has the default black line. + let pictures = |i: usize| -> Vec<_> { + p.slides[i] + .shapes + .iter() + .map(|s| { + let ShapeKind::Picture { fill } = &s.kind else { panic!("{name}: {:?} is not a picture", s.name) }; + let media = p.media.iter().find(|m| m.id == fill.media).unwrap(); + assert_eq!((media.content_type.as_str(), &media.data[..4]), ("image/x-wmf", &[1, 0, 9, 0][..]), "{name}"); + assert_eq!(s.line, Some(craft_pptx::Line::solid(rgb(0, 0, 0), 1.0)), "{name}"); + (boxed(s), fill.media, fill.crop, media.data.len()) + }) + .collect() + }; + // AddPicture(file, 1440, 1440, 1440, 1440) in twips: 1 in square at 1 in, 1 in. + let inch = (72.0, 72.0, 72.0, 72.0); + match name { + "picture" | "picwmf" | "jpeg" | "png" => { + let pics = pictures(0); + // The BMP's metafile is 128 bytes, the JPEG's and PNG's 220. + let len = if name == "jpeg" || name == "png" { 220 } else { 128 }; + assert_eq!((pics.len(), pics[0].0, pics[0].2, pics[0].3, p.media.len()), (1, inch, [0.0; 4], len, 1), "{name}"); + } + "piccrop" => { + // CropLeft 0.25 and CropTop 0.125 of the inch square: what is left of it, where it was. + let pics = pictures(0); + assert_eq!((pics.len(), pics[0].0, pics[0].2), (1, (90.0, 81.0, 54.0, 63.0), [0.25, 0.125, 0.0, 0.0])); + } + "twopics" => { + let pics = pictures(0); + assert_eq!(pics.iter().map(|x| (x.0, x.3)).collect::>(), [(inch, 128), ((216.0, 72.0, 144.0, 72.0), 220)]); + assert_ne!(pics[0].1, pics[1].1); + } + "picshare" => { + // One file inserted three times, on two slides: one picture. + let (first, second) = (pictures(0), pictures(1)); + assert_eq!((first.len(), second.len(), p.media.len()), (2, 1, 1)); + assert_eq!((first[0].0, first[1].0, second[0].0), (inch, (216.0, 72.0, 36.0, 36.0), inch)); + assert!(first[1].1 == first[0].1 && second[0].1 == first[0].1); + } + "notes" => assert_eq!(notes, ["Speaker note"]), + "notes2" => assert_eq!(notes, ["Note one", "Note two", ""]), + _ => {} + } + if name.starts_with("notes") { + assert!(p.slides.iter().all(|s| s.shapes.is_empty()), "{name}: the notes page's placeholders aren't slide shapes"); + } +} + /// What one PowerPoint 95 shape sample shows, by its case name. fn check_shape_sample(name: &str, p: &Presentation) { let Some(shapes) = p.slides.first().map(|s| &s.shapes) else { return }; diff --git a/crates/ppt-binary/src/ppt95/text.rs b/crates/ppt-binary/src/ppt95/text.rs index d3d97dba7e..4b1d9952e9 100644 --- a/crates/ppt-binary/src/ppt95/text.rs +++ b/crates/ppt-binary/src/ppt95/text.rs @@ -83,7 +83,7 @@ impl Env { /// A slot list's entries of `kind`, read by `read`: an entry is the slot of the 2017 records /// before it. -fn slots(list: &Rec, kind: u32, read: impl Fn(&Rec) -> Option) -> Vec> { +pub(super) fn slots<'a, T>(list: &Rec<'a>, kind: u32, read: impl Fn(&Rec<'a>) -> Option) -> Vec> { let mut out = vec![]; let mut current = None; for r in list.children() { From 2958d98e8a5d6145f69aaa950e2cd1e8b83c2088 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Thu, 19 Nov 2026 23:53:57 -0500 Subject: [PATCH 045/269] ppt-binary: check the PowerPoint 95 crop's right and bottom values A sample cropped on the right and at the bottom shows the crop record's last two values in that order, as the reader takes them; the samples check now covers it. --- crates/ppt-binary/src/ppt95/picture.rs | 4 ++-- crates/ppt-binary/src/ppt95/tests.rs | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/ppt-binary/src/ppt95/picture.rs b/crates/ppt-binary/src/ppt95/picture.rs index 016a91ffeb..e81a4466d0 100644 --- a/crates/ppt-binary/src/ppt95/picture.rs +++ b/crates/ppt-binary/src/ppt95/picture.rs @@ -9,8 +9,8 @@ //! A picture on a page is a shape (3008, a rectangle drawn with its format as any shape is) holding //! a 4014 container: 4015, the crop (left, top, right and bottom as i32s, in ten-thousandths of the //! picture), and 4053 → 4036, the picture's slot number. The shape's box is the cropped picture's. -//! (On a notes page, 4014 → 4054 → 4032 names the slide its slide image shows instead.) Only the -//! left and top crops were seen set; the right and bottom are taken to follow in that order. +//! (On a notes page, 4014 → 4054 → 4032 names the slide its slide image shows instead.) Each of the +//! four crops was seen set: left and top in one file, right and bottom in another. //! //! The metafile is kept as it is, as `image/x-wmf` media, as the PowerPoint 97 path keeps the //! metafiles of its blip store. Each slot is read once, the first time a shape names it, and all of diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 4b6e27a1dc..53d31298cf 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -1809,7 +1809,7 @@ fn check_sample(name: &str, p: &Presentation) { // The automation reported 1295, 1367.5, 4610 × 720 twips. assert_eq!(boxed(s), (64.75, 68.375, 230.5, 36.0)); } - "picture" | "jpeg" | "png" | "picwmf" | "piccrop" | "twopics" | "picshare" | "notes" | "notes2" => check_media_sample(name, p), + "picture" | "jpeg" | "png" | "picwmf" | "piccrop" | "piccrop2" | "twopics" | "picshare" | "notes" | "notes2" => check_media_sample(name, p), _ => check_shape_sample(name, p), } } @@ -1845,6 +1845,11 @@ fn check_media_sample(name: &str, p: &Presentation) { let pics = pictures(0); assert_eq!((pics.len(), pics[0].0, pics[0].2), (1, (90.0, 81.0, 54.0, 63.0), [0.25, 0.125, 0.0, 0.0])); } + "piccrop2" => { + // CropRight 0.3 and CropBottom 0.05: the crop's last two values, in that order. + let pics = pictures(0); + assert_eq!((pics.len(), pics[0].0, pics[0].2), (1, (72.0, 72.0, 50.375, 68.375), [0.0, 0.0, 0.3, 0.05])); + } "twopics" => { let pics = pictures(0); assert_eq!(pics.iter().map(|x| (x.0, x.3)).collect::>(), [(inch, 128), ((216.0, 72.0, 144.0, 72.0), 220)]); From 4be518decabaaf240fd6905174ee75874441c07d Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 00:54:53 -0500 Subject: [PATCH 046/269] ppt95: the centred-title test takes this branch's environment and stream helpers --- crates/ppt-binary/src/ppt95/tests.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index c1a2428412..54dce20317 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -814,8 +814,13 @@ fn a_masters_centred_title_gives_the_title_style_its_ruler() { Some(text(b"T", &[plain(2)], &[para_run(2, false, 0, 1, 0)], 3, [0; 4], MASTER_BODY)), ); let atoms = [style_atom([LEVEL; 5], 0x13)]; - let stream = - stream_with(document_atom(5760, 4320, 0), &[], &[master_with(MASTER, DEFAULT, [0; 4], &[title])], environment_with(&[styles(&atoms)])); + let stream = stream_with( + document_atom(5760, 4320, 0), + &[], + &[master_with(MASTER, DEFAULT, [0; 4], &[title])], + environment_with(&[], &[styles(&atoms)]), + &[], + ); let t = import(&stream).unwrap().masters[0].title_style.level(0).cloned().unwrap(); // The wide ruler (slot 3): level 1 at 576 units, its first line at 288. assert_eq!((t.para.margin_left, t.para.indent), (Some(72.0), Some(-36.0))); From 8f195d860b04fca074fa9725a7eeecc8babfa614 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:15:56 -0500 Subject: [PATCH 047/269] ppt95: a notes page's notes placeholder wins over other notes text The notes came from the first object that was either the notes placeholder or text of the notes type, so a notes-type shape before the placeholder gave its text instead. The placeholder is now looked for first, and other notes text only without one. --- crates/ppt-binary/src/ppt95.rs | 10 ++++++---- crates/ppt-binary/src/ppt95/tests.rs | 12 ++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 71140e044a..88ecd68f3c 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -741,13 +741,15 @@ fn convert_within(document: &Rec, app: &dyn Defaults, budget: usize) -> Presenta /// Document itself, isn't read: the PowerPoint 97 path doesn't import notes masters either. fn notes(page: &Rec, env: &Env, slide_scheme: &Scheme) -> Option { let scheme = page.child(rt::SCHEME).and_then(|s| s.child(rt::COLOR_SCHEME)).map_or(*slide_scheme, |s| scheme_of(&s)); - let is_notes = |r: &Rec| { - let kind = r.child(rt::PLACEHOLDER_ATOM).filter(|_| r.kind == rt::PLACEHOLDER).and_then(|a| a.u8(0)); + let kind = |r: &Rec| r.child(rt::PLACEHOLDER_ATOM).filter(|_| r.kind == rt::PLACEHOLDER).and_then(|a| a.u8(0)); + let notes_text = |r: &Rec| { let text_type = r.child(rt::TEXT).and_then(|t| t.child(rt::TEXT_BODY)).and_then(|b| b.child(rt::TEXT_ATOM)).and_then(|a| a.u32(0)); - kind == Some(NOTES_PLACEHOLDER) || (kind.is_none() && text_type == Some(NOTES_TEXT)) + kind(r).is_none() && text_type == Some(NOTES_TEXT) }; let objects = page.child(rt::OBJECTS)?; - let found = objects.children().take(MAX_OBJECTS).filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER)).find(|r| is_notes(r))?; + let candidates = || objects.children().take(MAX_OBJECTS).filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER)); + // The notes placeholder wherever it is, before any other text of the notes type. + let found = candidates().find(|r| kind(r) == Some(NOTES_PLACEHOLDER)).or_else(|| candidates().find(|r| notes_text(r)))?; let mut body = text::text_body(&found.child(rt::TEXT)?, env, &scheme, None, false)?; body.body = BodyProps::default(); Some(body) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 5e0fc61191..c5e5789e23 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2137,6 +2137,18 @@ fn notes_land_on_their_slide() { assert_eq!(p.slides[0].notes.paragraphs[0].runs[0].props.size, Some(24.0)); assert_eq!(texts(&p), ["On the slide"]); assert!(p.slides[1..].iter().all(|s| s.shapes.is_empty())); + + // Text of the notes type before the notes placeholder: the placeholder's text is the notes. + let mut spec = SlideSpec::new(0x100, 16); + spec.notes = Some(notes_with( + 0x100, + vec![ + shape_95(bx, Some(text_typed(simple_text(b"Typed first", bx, BODY), 2))), + placeholder_95(0x0E, 0, 1, bx, Some(simple_text(b"From the placeholder", bx, BODY))), + ], + )); + let p = import(&stream_of(document_atom(5760, 4320, 1), &[slide(&spec)], &[master(MASTER, DEFAULT, [0; 4])])).unwrap(); + assert_eq!(p.slides[0].notes.text(), "From the placeholder"); } /// Notes paragraphs keep their spacing and justified alignment, as a slide's do. From 70b6613f0dcb3784494b42097e3ca756728e1525 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 02:19:02 -0500 Subject: [PATCH 048/269] ppt95: a metafile whose header gives a size smaller than itself is not one metafile() fell back to the whole record when the header's size was smaller than the 18-byte header, so a broken header passed as a metafile. It is now refused, and its picture left out. The budget warning now gives the picture's size and the bytes left, which can be less than the 2 GiB total it named. --- crates/ppt-binary/src/ppt95/picture.rs | 16 ++++++++++++---- crates/ppt-binary/src/ppt95/tests.rs | 7 +++++-- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/ppt-binary/src/ppt95/picture.rs b/crates/ppt-binary/src/ppt95/picture.rs index e81a4466d0..46f34cf784 100644 --- a/crates/ppt-binary/src/ppt95/picture.rs +++ b/crates/ppt-binary/src/ppt95/picture.rs @@ -97,7 +97,11 @@ impl<'a> Pictures<'a> { let record = self.slots.get(usize::try_from(slot).ok()?).copied().flatten()?; let bytes = metafile(record.data)?; if bytes.len() > self.budget { - log::warn!("ppt: PowerPoint 95 pictures pass {} bytes; the rest are left out", crate::blip::MAX_TOTAL); + log::warn!( + "ppt: a {}-byte PowerPoint 95 picture passes the {} bytes left of the pictures' budget; it is left out", + bytes.len(), + self.budget + ); return None; } self.budget -= bytes.len(); @@ -106,13 +110,17 @@ impl<'a> Pictures<'a> { } /// A metafile record's bytes as a WMF file: a standard header (a type of 1 or 2 and a header of 9 -/// words), cut to the size the header gives when the record holds more. `None` for anything else. +/// words), cut to the size the header gives when the record holds more. `None` for anything else, +/// a header giving a size smaller than itself included. fn metafile(data: &[u8]) -> Option<&[u8]> { let (kind, words) = (u16_at(data, 0)?, u16_at(data, 2)?); if !matches!(kind, 1 | 2) || words != 9 || data.len() < WMF_HEADER { return None; } // The file's size in words. - let size = crate::record::u32_at(data, 6).and_then(|w| usize::try_from(w).ok()).and_then(|w| w.checked_mul(2)).unwrap_or(0); - Some(data.get(..size).filter(|_| size >= WMF_HEADER).unwrap_or(data)) + let size = crate::record::u32_at(data, 6).and_then(|w| usize::try_from(w).ok()).and_then(|w| w.checked_mul(2))?; + if size < WMF_HEADER { + return None; + } + Some(data.get(..size).unwrap_or(data)) } diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index c5e5789e23..43f352d49b 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2066,7 +2066,7 @@ fn a_dangling_picture_is_left_out() { } /// A metafile record holding more than its header's size is cut to it; one holding less is kept -/// as it is. +/// as it is; one whose header gives a size smaller than the header isn't a metafile. #[test] fn a_metafile_is_cut_to_its_size() { let mut long = wmf_n(2); @@ -2074,7 +2074,10 @@ fn a_metafile_is_cut_to_its_size() { let mut short = wmf_n(3); short.truncate(short.len() - 6); let pic = |slot| picture_95(PICTURE_BOX, slot, [0; 4], PLAIN); - let p = picture_deck(vec![vec![pic(0), pic(1)]], &[Some(long), Some(short.clone())], usize::MAX); + // A header giving a size smaller than itself: not a metafile, so its picture is left out. + let mut tiny = wmf_n(4); + tiny[6..10].copy_from_slice(&4u32.to_le_bytes()); + let p = picture_deck(vec![vec![pic(0), pic(1), pic(2)]], &[Some(long), Some(short.clone()), Some(tiny)], usize::MAX); assert_eq!(pictures_on(&p, 0).into_iter().map(|x| x.3).collect::>(), [wmf_n(2), short]); } From 95a778b30ce038f57fdb378de4606a9fc99e7c3d Mon Sep 17 00:00:00 2001 From: el-j Date: Fri, 20 Nov 2026 09:34:14 +0100 Subject: [PATCH 049/269] 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 050/269] 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 051/269] 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 052/269] 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 053/269] 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 054/269] 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 055/269] 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 056/269] 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 057/269] 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 058/269] 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 059/269] 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 060/269] 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 061/269] 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 92e4cab2d3265f97a436a1982d77cdbf7035ae6c Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 17:07:40 -0500 Subject: [PATCH 062/269] craft-ppt-binary: say unknown master placeholders are left out; match each outline to its own polygon The module doc said a placeholder of an unknown type keeps its text as a text box, which is true on slides only: the master leaves it out. check_outlines let two shapes match the same rendered polygon, so two shapes moved onto one place still passed. Each shape now takes a polygon of its own. --- crates/ppt-binary/src/ppt95.rs | 7 ++++--- crates/ppt-binary/src/ppt95/tests.rs | 8 ++++++-- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/crates/ppt-binary/src/ppt95.rs b/crates/ppt-binary/src/ppt95.rs index 38e4c7333d..a1584bbfa4 100644 --- a/crates/ppt-binary/src/ppt95.rs +++ b/crates/ppt-binary/src/ppt95.rs @@ -37,9 +37,10 @@ //! cap. //! //! PowerPoint 95 numbers placeholders its own way: on the master 1 title, 2 body, 6 date, 7 slide -//! number and 8 footer; on slides 0x0C title, 0x0D body, 0x0F centred title and 0x10 subtitle. A -//! placeholder of any other type keeps its text as a text box. The master's placeholders place the -//! caller's default master's, and the footer row places every layout's, as the PowerPoint 97 path +//! number and 8 footer; on slides 0x0C title, 0x0D body, 0x0F centred title and 0x10 subtitle. On a +//! slide, a placeholder of any other type keeps its text as a text box; on the master it is left +//! out. The master's placeholders place the caller's default master's, and the footer row places +//! every layout's, as the PowerPoint 97 path //! does. //! //! A picture is a shape naming one of the document's pictures, which are Windows metafiles; its diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 1bd81dd20a..61f91721ee 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2808,11 +2808,13 @@ fn the_wmf_reader_stays_in_each_record() { } /// For a sample with a rendering beside it (`.wmf`), each shape on its first slide with a -/// straight outline matches a polygon PowerPoint 95 drew. The number of shapes checked. +/// straight outline matches a polygon PowerPoint 95 drew, each a polygon of its own: two shapes +/// moved onto one place don't both match it. The number of shapes checked. fn check_outlines(name: &str, p: &Presentation, wmf: &[u8]) -> usize { let polygons = wmf_polygons(wmf, p.slide_size); let Some(slide) = p.slides.first() else { return 0 }; let mut checked = 0; + let mut used = vec![false; polygons.len()]; for s in &slide.shapes { let Some(corners) = outline_corners(s) else { continue }; // A dashed line is drawn dash by dash. @@ -2821,7 +2823,9 @@ fn check_outlines(name: &str, p: &Presentation, wmf: &[u8]) -> usize { } let width = s.line.as_ref().and_then(|l| l.width).unwrap_or(1.0); let near = polygons.iter().min_by_key(|poly| poly.len().abs_diff(corners.len())); - assert!(polygons.iter().any(|poly| outline_matches(&corners, poly, width)), "{name}: {corners:?} is not drawn; nearest {near:?}"); + let hit = (0..polygons.len()).find(|&i| !used[i] && outline_matches(&corners, &polygons[i], width)); + let Some(i) = hit else { panic!("{name}: {corners:?} is not drawn, or only where another shape is; nearest {near:?}") }; + used[i] = true; checked += 1; } checked From bbd4b02c899bc3592343bdc3e09e31ca4c8486e9 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 17:14:39 -0500 Subject: [PATCH 063/269] craft-ppt-binary: match outlines to polygons by trying every assignment First-fit could reject shapes that do all fit: a shape that fits two polygons could take the one another shape needs. check_outlines now uses bipartite matching (match_outlines), with a test of that case and of two shapes moved onto one place. --- crates/ppt-binary/src/ppt95/tests.rs | 57 +++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 61f91721ee..6b9f56780f 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -2808,13 +2808,13 @@ fn the_wmf_reader_stays_in_each_record() { } /// For a sample with a rendering beside it (`.wmf`), each shape on its first slide with a -/// straight outline matches a polygon PowerPoint 95 drew, each a polygon of its own: two shapes -/// moved onto one place don't both match it. The number of shapes checked. +/// straight outline matches a polygon PowerPoint 95 drew, each a polygon of its own +/// ([`match_outlines`]): two shapes moved onto one place don't both match it. The number of shapes +/// checked. fn check_outlines(name: &str, p: &Presentation, wmf: &[u8]) -> usize { let polygons = wmf_polygons(wmf, p.slide_size); let Some(slide) = p.slides.first() else { return 0 }; - let mut checked = 0; - let mut used = vec![false; polygons.len()]; + let mut outlines = vec![]; for s in &slide.shapes { let Some(corners) = outline_corners(s) else { continue }; // A dashed line is drawn dash by dash. @@ -2823,12 +2823,51 @@ fn check_outlines(name: &str, p: &Presentation, wmf: &[u8]) -> usize { } let width = s.line.as_ref().and_then(|l| l.width).unwrap_or(1.0); let near = polygons.iter().min_by_key(|poly| poly.len().abs_diff(corners.len())); - let hit = (0..polygons.len()).find(|&i| !used[i] && outline_matches(&corners, &polygons[i], width)); - let Some(i) = hit else { panic!("{name}: {corners:?} is not drawn, or only where another shape is; nearest {near:?}") }; - used[i] = true; - checked += 1; + assert!(polygons.iter().any(|poly| outline_matches(&corners, poly, width)), "{name}: {corners:?} is not drawn; nearest {near:?}"); + outlines.push((corners, width)); } - checked + if let Err(i) = match_outlines(&outlines, &polygons) { + panic!("{name}: {:?} is drawn only where another shape is", outlines[i].0); + } + outlines.len() +} + +/// Gives each outline (its corners and line width) a polygon of its own that it matches, trying +/// every assignment rather than the first that fits, or else the first outline left without one. +fn match_outlines(outlines: &[(Vec<(f64, f64)>, f64)], polygons: &[Vec<(f64, f64)>]) -> Result<(), usize> { + let fits: Vec> = + outlines.iter().map(|(corners, width)| (0..polygons.len()).filter(|&q| outline_matches(corners, &polygons[q], *width)).collect()).collect(); + // Kuhn's algorithm: a polygon already taken is freed when its owner can move to another. + fn assign(fits: &[Vec], s: usize, seen: &mut [bool], owner: &mut [Option]) -> bool { + for &q in &fits[s] { + if std::mem::replace(&mut seen[q], true) { + continue; + } + if owner[q].is_none_or(|t| assign(fits, t, seen, owner)) { + owner[q] = Some(s); + return true; + } + } + false + } + let mut owner = vec![None; polygons.len()]; + for s in 0..outlines.len() { + if !assign(&fits, s, &mut vec![false; polygons.len()], &mut owner) { + return Err(s); + } + } + Ok(()) +} + +/// Two shapes can't both match one drawn polygon, and a polygon that fits two shapes goes to the +/// one that needs it, whatever order the polygons were drawn in. +#[test] +fn each_outline_matches_a_polygon_of_its_own() { + let rect = |x: f64| vec![(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0), (x, 10.0)]; + // Shapes at 100 and 102 drawn at 101 and 99: the first fits both, the second only 101. + assert_eq!(match_outlines(&[(rect(100.0), 1.0), (rect(102.0), 1.0)], &[rect(101.0), rect(99.0)]), Ok(())); + // Two shapes moved onto one place, drawn at two. + assert_eq!(match_outlines(&[(rect(0.0), 1.0), (rect(0.0), 1.0)], &[rect(0.0), rect(50.0)]), Err(1)); } /// A file holding fewer slides than its DocumentAtom counts names the missing ones by position, From d54f840b8f9d3dc24ad19d77da9cd452ad0f4846 Mon Sep 17 00:00:00 2001 From: kiwi4boy Date: Fri, 20 Nov 2026 17:17:18 -0500 Subject: [PATCH 064/269] craft-ppt-binary: check the hostile-text fixture reads before mutating it If the fixture stopped reaching the text reader, every mutated copy could fail early and the sweep would still pass. Import it whole first and check its slide text and the master's title style. --- crates/ppt-binary/src/ppt95/tests.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ppt-binary/src/ppt95/tests.rs b/crates/ppt-binary/src/ppt95/tests.rs index 6b9f56780f..4615c9ea70 100644 --- a/crates/ppt-binary/src/ppt95/tests.rs +++ b/crates/ppt-binary/src/ppt95/tests.rs @@ -1039,6 +1039,11 @@ fn hostile_text_never_panics() { let level = Level { spacing: [150, -36, 20], align: 3, ..LEVEL }; let env = environment_with(&[], &[styles(&[style_atom([level; 5], 0x13), style_atom([level; 5], 0x21)])]); let stream = stream_with(document_atom(5760, 4320, 1), &[slide(&s)], &[master_with(MASTER, DEFAULT, [0; 4], &objects)], env, &[]); + // Whole, it reaches the text reader: else every hostile copy below could fail early and pass. + let p = import(&stream).unwrap(); + assert_eq!(texts(&p), ["One\nTwo", "T"]); + let t = p.masters[0].title_style.level(0).unwrap(); + assert_eq!((t.para.line_spacing, t.para.space_before), (Some(Spacing::Pct(1.5)), Some(Spacing::Pts(36.0)))); for at in (0..stream.len() - 4).step_by(4) { for v in [0u32, 1, 0x7FFF_FFFF, 0xFFFF_FFFF] { let mut d = stream.clone(); From ed647a5d49c88c3ade7486267a329ab5d5ffb485 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:18:35 -0800 Subject: [PATCH 065/269] Canvas: the body's tool pass carries the text the editor part pastes The framework takes a paste event out of egui's input and keeps its text for the focused component, so a canvas body that applies its editor's Edit(Paste) could only read the installed clipboard, which fails where the system clipboard can't be opened (a Wayland session where arboard finds no data-control protocol). ToolPass::pasted now holds the text the platform's paste event carried in the pass of that paste: Ctrl+V's, or the one a Paste command asks the platform for. --- crates/ui-canvas/src/canvas/mod.rs | 13 ++++++++ crates/ui-canvas/tests/it/canvas/editor.rs | 36 +++++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index f8c7da9cab..ad3724c1bd 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -240,6 +240,8 @@ pub struct Canvas<'a> { settled: Option, /// The Menu key or Shift+F10 reached the focused canvas this pass. context_key: bool, + /// The text of the paste the editor part takes this pass, taken in `update` with its inputs. + pasted: Option>, /// The ease the app asked for from the view it drew ([`ease_from`](Self::ease_from)). ease: Option, /// The app's tool moves the view with the pointer this pass (an image-moving crop slides the view by fractional @@ -316,6 +318,7 @@ impl<'a> Canvas<'a> { snap: None, settled: None, context_key: false, + pasted: None, ease: None, follows_pointer: false, tool_regions: Vec::new(), @@ -689,6 +692,7 @@ impl<'a> Canvas<'a> { navigation: self.navigation, editor_input: self.editor_input.clone(), editor: cx.editor_handle(), + pasted: self.pasted.clone(), } } @@ -758,6 +762,11 @@ pub struct ToolPass { pub editor_input: Arc<[EditorInput]>, /// The editor part of this pass, through which the body reports its editor state; `None` without an editor. pub editor: Option, + /// The text of the paste the editor part takes this pass (its [`EditorInput::Edit`] of + /// [`EditCommand::Paste`](craft_behavior::EditCommand::Paste)), as the platform's paste event carried it: Ctrl+V's, + /// or the one a Paste command asks the platform for. The framework takes that event out of egui's input, and the + /// platform's read can succeed where the installed clipboard can't be opened. `None` in a pass without one. + pub pasted: Option>, } impl ToolPass { @@ -863,6 +872,10 @@ impl Component for Canvas<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { // Taken once: `Cx::editor_input` empties the pass's inputs, and the body reads them from the `ToolPass`. self.editor_input = cx.editor_input().collect::>().into(); + self.pasted = match cx.clipboard().paste() { + crate::runtime::pending::Pending::Ready(content) => content.text.clone(), + _ => None, + }; // Left untaken: the canvas's generic context request is recorded as for a secondary click. self.context_key = cx.intents().untaken(&Intent::ContextMenu); // The canvas is no value component: it reads and writes its view's binding itself, as a container does. diff --git a/crates/ui-canvas/tests/it/canvas/editor.rs b/crates/ui-canvas/tests/it/canvas/editor.rs index 48153ff5f3..4cf2f9cd83 100644 --- a/crates/ui-canvas/tests/it/canvas/editor.rs +++ b/crates/ui-canvas/tests/it/canvas/editor.rs @@ -2,7 +2,7 @@ //! body through its `ToolPass`. use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{CanvasView, EditorInput, Proposal, TextPos}; +use craft_behavior::{CanvasView, EditCommand, EditorInput, Proposal, TextPos}; use craft_ui::canvas::{Canvas, tool_pass}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::{EditorPurpose, EditorState}; @@ -88,6 +88,40 @@ fn a_canvas_editor_takes_focus_on_a_background_press_and_hands_its_inputs_to_the ); } +/// One pass's editor inputs and pasted text, as the body read them from its `ToolPass`. +type PassPaste = (Vec, Option); + +/// A paste event's text reaches the body with the editor part's paste in that pass's `ToolPass`, and in no later pass: +/// the framework takes the event out of egui's input, and the body can't read the installed clipboard where it can't +/// be opened. +#[trial] +fn a_paste_events_text_reaches_the_body_with_the_editors_paste() { + let seen: Rc>> = Rc::default(); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0); + let _ = canvas(view).show_at(ui, room, |_, body| { + let Some(pass) = tool_pass(&body.env) else { return }; + shown.borrow_mut().push((pass.editor_input.to_vec(), pass.pasted.as_deref().map(str::to_owned))); + }); + }); + fixture.room(ROOM); + fixture.settle(); + fixture.click_at((ROOM / 2.0).to_pos2()); + seen.borrow_mut().clear(); + fixture.frame(vec![Event::Paste("from the platform".into())]); + fixture.frame(vec![]); + let passes = seen.take(); + let pasted: Vec<&PassPaste> = passes.iter().filter(|(_, text)| text.is_some()).collect(); + assert!(!pasted.is_empty(), "a pass carries the paste's text: {passes:?}"); + for (inputs, text) in &pasted { + assert_eq!(text.as_deref(), Some("from the platform")); + assert!(inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))), "with the editor's paste: {inputs:?}"); + } + assert!(passes.last().is_some_and(|(_, text)| text.is_none()), "a later pass carries none: {passes:?}"); +} + /// Guards `EditorHandle::report` for an editor whose view describes its text (a page editor): its report has no lines, /// so its caret reaches the input method and no empty text is announced on the canvas's node. #[trial] From 6fc1ccd24058b2e8818fab4a9f7db6cf7aa6b8e7 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Fri, 20 Nov 2026 17:58:21 -0800 Subject: [PATCH 066/269] 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 067/269] 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 068/269] 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 9e1c5f75e43c84d973815bcfcaca8632d10cd03d Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Sat, 21 Nov 2026 12:20:36 +0000 Subject: [PATCH 069/269] #7171: scroll bodies offer fill-width children the view, not the bar lane Co-Authored-By: Claude Opus 5.5 --- crates/ui-contract/src/contract/body/hooks.rs | 9 +++++++- .../tests/it/layout/stack_widths.rs | 23 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 70f69657c6..6c96686a88 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -1524,7 +1524,14 @@ impl BodyHooks<'_> { if lays_out { crate::runtime::lazy::begin(ctx, view, self.anchor.map(|anchor| anchor.child), self.glide.map(|glide| glide.child)); } - let env = run.env.derive_local(|scoped| scoped.lazy = Some(view)); + // The children fill what the view shows: the width the body was offered counts the bar's lane, so a child that + // fills the offered width would lie under the bar. + let env = run.env.derive_local(|scoped| { + scoped.lazy = Some(view); + if let Some(offered) = scoped.offered.as_mut() { + *offered = (*offered - inset.x).max(0.0); + } + }); let installed = Env::install_for(®ion_ui, env.clone()); ScrollRegion { ui: region_ui, env, installed, seen, max, shown, bar, lays_out, laid_for: (inset, shows) } } diff --git a/crates/ui-widgets/tests/it/layout/stack_widths.rs b/crates/ui-widgets/tests/it/layout/stack_widths.rs index 2d6ba4bcfb..f3dd67968f 100644 --- a/crates/ui-widgets/tests/it/layout/stack_widths.rs +++ b/crates/ui-widgets/tests/it/layout/stack_widths.rs @@ -190,3 +190,26 @@ fn labelled_radios_in_a_wrapping_row_break_onto_a_new_line() { let starts = KINDS.iter().filter(|kind| (rect(kind).left() - first.left()).abs() < 0.5).count(); assert!(starts >= 2, "a radio that wraps starts its line at the row's start edge: {starts} radios do"); } + +/// A body that scrolls keeps the bar's lane clear: a child that fills the width stops where the bar starts, not under it +/// (a Print page's buttons ran under the settings column's bar). +#[trial] +fn a_fill_width_child_of_a_scrolling_stack_leaves_the_bars_lane() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let child = Cell::new(Rect::NOTHING); + let shown = Stack::new().sizing(Sizing::FillHeight).least_width(LeastWidth::Dialog).scroll(Scroll::vertical()).show(ui, |ui, _| { + for _ in 0..30 { + child.set(Button::new("Save these pages as PDF…").sizing(Sizing::FillWidth).show(ui).rect); + } + }); + if !ui.is_sizing_pass() { + out.set((shown.output.rect, child.get())); + } + }); + fixture.room(Vec2::new(1440.0, 300.0)).settle(); + let (stack, button) = seen.get(); + assert!(stack != Rect::NOTHING && button != Rect::NOTHING, "the stack showed"); + assert!(button.max.x <= stack.max.x - 4.0, "the button leaves the bar's lane: {button:?} in {stack:?}"); +} From 89ba00e62818c124411a6f5c72761d1147cdf758 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sat, 21 Nov 2026 09:10:21 -0800 Subject: [PATCH 070/269] 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 071/269] 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 2cde919852d239ac996621d8037a5e8645c6fdde Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:44:12 -0800 Subject: [PATCH 072/269] craft-docx: read and write the hide spelling and grammar errors settings Settings gains hide_spelling_errors and hide_grammar_errors, the per-document Hide spelling errors and Hide grammar errors options. craft-docx reads w:hideSpellingErrors and w:hideGrammaticalErrors from settings.xml, writes them after w:mirrorMargins and before w:proofState, and lists them as owned in the settings merge, so a saved file carries each one once and drops it when it is turned off. --- crates/docx/src/read/meta.rs | 2 ++ crates/docx/src/write/settings.rs | 7 ++++ crates/docx/src/write/settings_merge.rs | 2 ++ crates/docx/tests/it/settings_merge.rs | 47 +++++++++++++++++++++++++ crates/wordmodel/src/settings.rs | 9 +++++ 5 files changed, 67 insertions(+) diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index b9debe1fa0..a6e3c51bcb 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -24,6 +24,8 @@ impl Reader<'_> { "w:linkStyles" => s.link_styles = on_off(k), "w:removePersonalInformation" => s.remove_personal_info = on_off(k), "w:removeDateAndTime" => s.remove_date_time = on_off(k), + "w:hideSpellingErrors" => s.hide_spelling_errors = on_off(k), + "w:hideGrammaticalErrors" => s.hide_grammar_errors = on_off(k), "w:compat" => { s.allow_space_of_same_style_in_table = k.child("w:allowSpaceOfSameStyleInTable").is_some_and(on_off); // Only Word's own setting: another `w:uri` names a different application's. diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index a098174056..afd7d6a389 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -54,6 +54,13 @@ pub(super) fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, temp if s.gutter_at_top { w.empty("w:gutterAtTop", &[]); } + // After `w:gutterAtTop` and before `w:proofState` in CT_Settings. + if s.hide_spelling_errors { + w.empty("w:hideSpellingErrors", &[]); + } + if s.hide_grammar_errors { + w.empty("w:hideGrammaticalErrors", &[]); + } if let Some(id) = template_rel { w.empty("w:attachedTemplate", &[("r:id", id)]); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index a72046e831..2e064f05ac 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -19,6 +19,8 @@ const OWNED: &[&str] = &[ "w:displayBackgroundShape", "w:mirrorMargins", "w:gutterAtTop", + "w:hideSpellingErrors", + "w:hideGrammaticalErrors", "w:attachedTemplate", "w:linkStyles", "w:trackRevisions", diff --git a/crates/docx/tests/it/settings_merge.rs b/crates/docx/tests/it/settings_merge.rs index c07986795e..312564626c 100644 --- a/crates/docx/tests/it/settings_merge.rs +++ b/crates/docx/tests/it/settings_merge.rs @@ -163,3 +163,50 @@ fn do_not_track_moves_round_trips() { assert!(s.contains(""), "{s}"); assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves); } + +/// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`, +/// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged +/// part), written in a generated part, and left out when they are turned off. +#[test] +fn hidden_proofing_errors_round_trip() { + let original = SETTINGS.replace("") < pos(&s, "")); + assert!(pos(&s, "") < pos(&s, ""), "{s}"); + assert!(pos(&s, "") < pos(&s, "") && !s.contains("hideSpellingErrors"), "{s}"); + let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors); +} diff --git a/crates/wordmodel/src/settings.rs b/crates/wordmodel/src/settings.rs index 46faf16c36..d7689fa66d 100644 --- a/crates/wordmodel/src/settings.rs +++ b/crates/wordmodel/src/settings.rs @@ -170,6 +170,13 @@ pub struct Settings { /// comments and tracked changes are saved without `w:date`. #[serde(skip_serializing_if = "std::ops::Not::not")] pub remove_date_time: bool, + /// Hide spelling errors in this document only (`w:hideSpellingErrors`): no squiggles under + /// misspelled words. Spelling & Grammar (F7) still finds them. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub hide_spelling_errors: bool, + /// Hide grammar errors in this document only (`w:hideGrammaticalErrors`). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub hide_grammar_errors: bool, /// The document was opened from ODF: the standard's rules that differ from Word's apply as /// it is laid out. #[serde(skip_serializing_if = "Option::is_none")] @@ -333,6 +340,8 @@ impl Default for Settings { zoom: None, remove_personal_info: false, remove_date_time: false, + hide_spelling_errors: false, + hide_grammar_errors: false, odf: None, } } From 97b202c281875d53a4dee080a394c125cbaa3aaf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:22:43 -0800 Subject: [PATCH 073/269] Fit: items rank their short forms, and late ones shorten after the free items leave fit_items took every short form, last item first, before any free item left the strip. A host could not choose which items shorten first, or keep a label until the other items had gone to the overflow menu. FitItem gains two builder options: - short_order(order: u16) ranks the item's short form. Lower ranks shorten first; items of one rank shorten last item first. Every item ranks 0 by default. - short_late() keeps the item's full form until no more free items can leave. Late items then shorten in the same rank order. Items that left do not come back. Items that set neither option fit exactly as before. --- crates/behavior/src/fit.rs | 58 ++++++++++++++++++++++++++---------- crates/behavior/tests/fit.rs | 31 +++++++++++++++++++ 2 files changed, 74 insertions(+), 15 deletions(-) diff --git a/crates/behavior/src/fit.rs b/crates/behavior/src/fit.rs index 4814a0078d..ee52c7e4a7 100644 --- a/crates/behavior/src/fit.rs +++ b/crates/behavior/src/fit.rs @@ -1,6 +1,6 @@ //! The fit rules: which tabs, bar items or titles stay in a strip and which go to an overflow menu. [`fit`] and //! [`fit_whole`] assign tab widths (tabs shrink before they overflow, or keep their width); [`fit_items`] shortens -//! items that have a short form, then drops command items and titles from the end. All of them read no egui types. +//! items that have a short form, in the order their host ranks, and drops command items and titles from the end. All of them read no egui types. /// Tabs visible on a strip and tabs that need an overflow menu, all in original order. #[derive(Clone, Debug, Default, PartialEq)] @@ -230,12 +230,16 @@ pub struct FitItem { pub keep: FitKeep, /// The extent of the item's shorter form, if it has one. pub short: Option, + /// The rank of the item's short form: lower ranks shorten first, and equal ranks shorten the last item first. + pub short_order: u16, + /// Whether the item keeps its full form until no more free items can leave. + pub short_late: bool, } impl FitItem { /// An item `extent` long in `section`. pub const fn new(extent: f32, section: u16, keep: FitKeep) -> Self { - FitItem { extent, section, keep, short: None } + FitItem { extent, section, keep, short: None, short_order: 0, short_late: false } } /// The item with a shorter form `extent` long, which it takes before any free item leaves. @@ -243,6 +247,20 @@ impl FitItem { self.short = Some(extent); self } + + /// The item with its short form ranked `order`: short forms of a lower rank are taken first, and items of + /// one rank take theirs last item first. Every item ranks 0 by default. + pub const fn short_order(mut self, order: u16) -> Self { + self.short_order = order; + self + } + + /// The item takes its short form only after every free item that can leave has left, so the other items go to + /// the overflow menu before this one shortens. A free item with a late short form leaves in its turn instead. + pub const fn short_late(mut self) -> Self { + self.short_late = true; + self + } } /// Which items the strip shows and which go to the overflow menu, as indexes into the input, in input order. @@ -277,11 +295,13 @@ pub fn run_extent(items: &[FitItem], shown: &[bool], gap: f64, section_gap: f64) } /// Decides which items stay in a strip `available` long. Everything fits and no item is `Menu`: all items show. -/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, the last -/// one first, until the run fits (listed in [`Fit::short`]); a `Pinned` item shortens as a `Free` one does. Only then -/// does the last `Free` item leave, one at a time, until the rest and an overflow control `overflow_extent` long, -/// set off by `gap`, fit; `Pinned` items stay even when they alone are longer than `available`. Items that leave are -/// never listed as short. Negative and non-finite lengths count as zero. +/// Otherwise the `Menu` items are in the menu, and the items with a [`FitItem::short`] form take it first, lowest +/// [`FitItem::short_order`] first and the last item of a rank first, until the run fits (listed in [`Fit::short`]); a +/// `Pinned` item shortens as a `Free` one does. Only then does the last `Free` item leave, one at a time, until the +/// rest and an overflow control `overflow_extent` long, set off by `gap`, fit. When no `Free` item is left to go, the +/// items marked [`FitItem::short_late`] take their short forms in the same order; items that left do not come back. +/// `Pinned` items stay even when they alone are longer than `available`. Items that leave are never listed as short. +/// Negative and non-finite lengths count as zero. pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, overflow_extent: f32) -> Fit { let (available, gap, section_gap, overflow_extent) = (item_extent(available), item_extent(gap), item_extent(section_gap), item_extent(overflow_extent)); @@ -302,19 +322,27 @@ pub fn fit_items(items: &[FitItem], available: f32, gap: f32, section_gap: f32, // The shadow run holds each item at the extent it takes: shortened items at their `short` extent. let mut run: Vec = items.to_vec(); let mut short = vec![false; items.len()]; - while !fits(&run, &shown) { - let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && !short[at] && items[at].short.is_some()) else { - break; - }; - short[last] = true; - if let (Some(item), Some(extent)) = (run.get_mut(last), items[last].short) { - item.extent = extent; + // Takes the short forms of the shown items with this `late` mark, lowest rank first and the last item of a rank + // first (`min_by_key` keeps the first minimum, which is the last index in a reversed scan), until the run fits. + let shorten = |late: bool, run: &mut [FitItem], short: &mut [bool], shown: &[bool]| { + while !fits(run, shown) { + let next = (0..items.len()) + .rev() + .filter(|&at| shown[at] && !short[at] && items[at].short.is_some() && items[at].short_late == late) + .min_by_key(|&at| items[at].short_order); + let Some(next) = next else { break }; + short[next] = true; + if let (Some(item), Some(extent)) = (run.get_mut(next), items[next].short) { + item.extent = extent; + } } - } + }; + shorten(false, &mut run, &mut short, &shown); while !fits(&run, &shown) { let Some(last) = (0..items.len()).rev().find(|&at| shown[at] && items[at].keep == FitKeep::Free) else { break }; shown[last] = false; } + shorten(true, &mut run, &mut short, &shown); let (kept, left): (Vec, Vec) = (0..items.len()).partition(|&at| shown[at]); let short = kept.iter().copied().filter(|&at| short[at]).collect(); Fit { shown: kept, overflow: left, short } diff --git a/crates/behavior/tests/fit.rs b/crates/behavior/tests/fit.rs index 08cd377125..d1110a4a8a 100644 --- a/crates/behavior/tests/fit.rs +++ b/crates/behavior/tests/fit.rs @@ -64,6 +64,37 @@ fn short_items_shorten_from_the_end_before_any_item_leaves() { assert_eq!(squeezed.short.len(), 2, "pinned items shorten as free ones do: {squeezed:?}"); } +/// Guards the host's order of short forms: a lower `short_order` shortens first wherever its item sits, and a +/// `short_late` item keeps its full form until every free item has gone to the menu, then shortens in rank order. +#[test] +fn short_forms_follow_their_rank_and_late_ones_wait_for_the_free_items() { + let item = |extent| FitItem::new(extent, 0, FitKeep::Free); + let ranked = [item(50.0).short(20.0), item(50.0), item(50.0).short(20.0).short_order(1)]; + let fit = fit_items(&ranked, 120.0, 0.0, 0.0, 10.0); + assert_eq!(fit.short, [0], "the lower rank shortens before the later item: {fit:?}"); + assert!(fit.overflow.is_empty(), "{fit:?}"); + + // Two free items in one section, then two pinned ones that shorten only late, the first ranked before the second. + let pinned = |extent| FitItem::new(extent, 1, FitKeep::Pinned).short(20.0).short_late(); + let bar = [item(40.0), item(40.0), pinned(60.0), pinned(60.0).short_order(1)]; + let at = |available| fit_items(&bar, available, 0.0, 0.0, 10.0); + + let roomy = at(180.0); + assert_eq!(roomy.overflow, [1], "a free item leaves before any late item shortens: {roomy:?}"); + assert!(roomy.short.is_empty(), "{roomy:?}"); + + let tight = at(130.0); + assert_eq!(tight.overflow, [0, 1], "every free item leaves first: {tight:?}"); + assert!(tight.short.is_empty(), "{tight:?}"); + + let narrow = at(100.0); + assert_eq!(narrow.short, [2], "then the lower-ranked late item shortens: {narrow:?}"); + assert_eq!(narrow.overflow, [0, 1], "items that left stay in the menu: {narrow:?}"); + + let narrowest = at(50.0); + assert_eq!(narrowest.short, [2, 3], "then the next rank: {narrowest:?}"); +} + #[test] fn kept_selection_keeps_its_width_and_overflow_starts_at_the_end() { let natural = [80.0, 90.0, 85.0, 95.0, 70.0]; From 45515d18b536184b357ffdd1cce3eb84bf97525d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:29:19 -0800 Subject: [PATCH 074/269] craft-automation: ui.drag presses, moves in even steps and releases as one request A host app that serves the control channel can now run a whole drag from one request instead of composing ui.click with hold, ui.move steps and ui.release itself. - synthetic::Drag reads {from, to, button?, steps?, modifiers}. from and to are point objects {x?, y?, coordinates?, page?}, each in its own space; errors inside one name it (from.x ...). steps runs from 1 to MAX_DRAG_STEPS (200), default DRAG_STEPS (12). - Drag::inject resolves both points before it queues anything, then queues the press at from, the moves to to in even steps (the last one lands on to) and the release at to. The modifiers stay held through the release and are let go afterwards unless other input stays held, as after ui.click. - input_method dispatches ui.drag, so its reply waits for the release. - The crate README, docs/craft-framework.md and docs/porting.md list it. Tests: a drag with a document-point end presses at from, makes one move per step towards to, releases at to and leaves nothing held; a drag keeps its modifiers while a held key stays down; a drag whose end cannot be placed queues no press; bad drag params join the refused-input table. --- crates/automation/README.md | 2 +- crates/automation/src/synthetic.rs | 79 ++++++++++++++++++++++++- crates/automation/tests/it/synthetic.rs | 70 +++++++++++++++++++++- docs/craft-framework.md | 2 +- docs/porting.md | 2 +- 5 files changed, 147 insertions(+), 8 deletions(-) diff --git a/crates/automation/README.md b/crates/automation/README.md index d82a01e5b5..be6496ceb0 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -14,7 +14,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | -| `synthetic` | `Click`, `KeyPress` and `move_from_params`: the validated parameters of `ui.click`, `ui.move` and `ui.key`, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `synthetic` | `Click`, `KeyPress`, `move_from_params` and `Drag`: the validated parameters of `ui.click`, `ui.move`, `ui.key` and `ui.drag` (a press, moves in even steps and the release, from one request), and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | | `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | | `screenshot` | `Captures`: the bounded, cancellable screenshot queue over `WindowHost::screenshot`, with settling, geometry epochs, retries and the PNG reply. | diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index 96024d958c..8a2bdb184b 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -1,5 +1,5 @@ -//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`, -//! `ui.type`, `ui.ime` and `ui.capsLock`. +//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.drag`, `ui.wheel`, `ui.key`, +//! `ui.release`, `ui.type`, `ui.ime` and `ui.capsLock`. //! //! This module reads and validates the protocol's parameters; the window host queues the input //! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`], @@ -11,7 +11,8 @@ //! withdraws a step queued for a document or focus that changed before the pass consumed it. //! //! Held input: `hold: true` on `ui.click` leaves its last press down and on `ui.key` its key, until `ui.release`; a -//! `ui.move` while a button is held drags. Each request names the modifiers held during it; a move or wheel leaves +//! `ui.move` while a button is held drags. `ui.drag` is the whole gesture in one request: a press, moves in even steps +//! and the release, queued together, so its reply waits for the release. Each request names the modifiers held during it; a move or wheel leaves //! them held (a hover with modifiers across a screenshot), a click or key that holds nothing lets them go. //! //! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application @@ -33,6 +34,12 @@ pub const MAX_CLICKS: u64 = 256; /// display, yet small enough that egui's pointer delta between two such points stays finite. pub const MAX_SCREEN_POINT: f64 = 1e6; +/// Most moves one `ui.drag` may ask for (`steps`). +pub const MAX_DRAG_STEPS: u64 = 200; + +/// The moves a `ui.drag` makes when its request names no `steps`. +pub const DRAG_STEPS: u64 = 12; + /// The longest hover rest one `ui.move` may ask for (`rest`, seconds). pub const MAX_REST: f64 = 10.0; @@ -192,6 +199,71 @@ impl Move { } } +/// A validated `ui.drag`: a press at one point, moves in even steps to another with the button down, and the release +/// there. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Drag { + /// Where the button goes down. + pub from: At, + /// Where the button comes up. + pub to: At, + /// The button pressed. + pub button: PointerButton, + /// Moves from `from` to `to`; the last one lands on `to`. + pub steps: u64, + /// Modifiers held from the press to the release. + pub mods: Mods, +} + +impl Drag { + /// `{from, to, button?, steps?, modifiers…}`, no other fields. `from` and `to` are each a point object + /// `{x?, y?, coordinates?, page?}` in its own space, as `ui.click` reads its point; a missing one is + /// ``"missing `from`"``, and the errors inside one name it (``"from.x must be a finite number"``). `button` + /// defaults to `left`. `steps` is an unsigned integer from 1 to [`MAX_DRAG_STEPS`], default [`DRAG_STEPS`]; + /// outside that range is ``"`steps` must be between 1 and 200 (got {steps})"``. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["from", "to", "button", "steps", "modifiers", "shift", "alt", "command", "ctrl"])?; + let p = Params(&p); + let point = |name: &str| -> Result { + let Some(point) = p.0.get(name) else { return Err(format!("missing `{name}`")) }; + let point = Params(point).only(Some(name), &POINT)?; + At::from_params(&Params(&point)).map_err(|error| format!("{name}.{error}")) + }; + let steps = p.uint_field("steps")?.unwrap_or(DRAG_STEPS); + if !(1..=MAX_DRAG_STEPS).contains(&steps) { + return Err(format!("`steps` must be between 1 and {MAX_DRAG_STEPS} (got {steps})")); + } + Ok(Self { + from: point("from")?, + to: point("to")?, + button: button(&p)?.unwrap_or(PointerButton::Primary), + steps, + mods: p.modifiers(&KEY_MODIFIERS)?, + }) + } + + /// Queues a move to `from` and a press there, `steps` moves in even steps to `to` with the button held, and the + /// release at `to`, in `viewport`; the modifiers are then let go unless other input stays held, as after a click. + /// Both points are resolved before anything is queued, so a point that cannot be placed leaves no press down. + /// When the host withdraws the rest of the gesture after its press ran, the button stays down until `ui.release`, + /// as any held input does. + pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { + let (from, to) = (self.from.resolve(map)?, self.to.resolve(map)?); + let steps = u16::try_from(self.steps).unwrap_or(u16::MAX); + host.inject_click(viewport, from, self.button, 1, self.mods, true); + for step in 1..=steps { + let at = if step == steps { to } else { from.lerp(to, f32::from(step) / f32::from(steps)) }; + host.inject_move(viewport, at, self.mods, 0.0); + } + host.inject_release(viewport, Some(to), Released::Button(self.button)); + // A click of no presses at the pointer's place queues no event: it only lets the modifiers go when nothing + // stays held. + host.inject_click(viewport, to, self.button, 0, self.mods, false); + Ok(()) + } +} + /// A validated `ui.wheel`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -304,6 +376,7 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V Some(match method { "ui.click" => Click::from_params(params).and_then(|click| click.inject(host, viewport, map)), "ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)), + "ui.drag" => Drag::from_params(params).and_then(|drag| drag.inject(host, viewport, map)), "ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)), "ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)), "ui.release" => Release::from_params(params).and_then(|release| release.inject(host, viewport, map)), diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 494cc848dd..aa70cb1439 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -1,11 +1,11 @@ -//! Synthetic input through the window host: held presses and keys, modifiers, the wheel, Caps Lock, hover rest, +//! Synthetic input through the window host: held presses and keys, drags, modifiers, the wheel, Caps Lock, hover rest, //! document coordinates and input-method compositions, as the passes see them, and the params refused before //! anything is queued. use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::synthetic::{At, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; +use craft_automation::synthetic::{At, MAX_CLICKS, MAX_DRAG_STEPS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -122,6 +122,52 @@ fn a_held_press_stays_down_until_its_release() { assert!(!rig.now().primary_down, "a click without hold releases"); } +/// `ui.drag` presses at `from`, moves to `to` in `steps` even steps with the button down, releases at `to` with its +/// modifiers held throughout, then lets them go. Each point is in its own space: `to` here is a document point. +#[trial] +fn a_drag_presses_moves_in_steps_and_releases_at_its_end() { + let mut rig = Rig::new(); + rig.fx.settle(); + rig.take(); + let to = map(0, pos2(220.0, 40.0)).expect("the test map places every point"); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 20}, "to": {"x": 220, "y": 40, "coordinates": "document"}, "steps": 4, "shift": true})); + let after = rig.now(); + let events: Vec = rig.take().into_iter().flat_map(|pass| pass.events).collect(); + let buttons: Vec<(Pos2, bool, bool)> = events + .iter() + .filter_map(|event| match event { + Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers } => Some((*pos, *pressed, modifiers.shift)), + _ => None, + }) + .collect(); + assert_eq!(buttons, vec![(pos2(10.0, 20.0), true, true), (to, false, true)], "one press at `from`, one release at `to`, both with Shift"); + let held = events.iter().skip_while(|event| !matches!(event, Event::PointerButton { pressed: true, .. })); + let moves: Vec = held + .take_while(|event| !matches!(event, Event::PointerButton { pressed: false, .. })) + .filter_map(|event| match event { + Event::PointerMoved(at) => Some(*at), + _ => None, + }) + .collect(); + assert_eq!(moves.len(), 4, "one move per step while the button is down: {moves:?}"); + assert!(moves.windows(2).all(|pair| pair[1].x > pair[0].x), "each step goes further towards `to`: {moves:?}"); + assert_eq!(moves.last(), Some(&to), "the last step lands on `to`"); + assert!(!after.primary_down && !after.shift, "the drag leaves no button or modifier held"); +} + +/// A drag keeps its modifiers held after its release while other input stays down, as a click does. +#[trial] +fn a_drag_keeps_its_modifiers_while_a_held_key_stays_down() { + let mut rig = Rig::new(); + rig.send("ui.key", json!({"key": "Space", "hold": true})); + rig.send("ui.drag", json!({"from": {"x": 10, "y": 10}, "to": {"x": 60, "y": 10}, "steps": 2, "shift": true})); + let after = rig.now(); + assert!(after.space_down && !after.primary_down, "the key stays down and the drag's button is up"); + assert!(after.shift, "the modifiers stay with the held key"); + rig.send("ui.release", json!({})); + assert!(!rig.now().space_down && !rig.now().shift, "the release lets everything go"); +} + /// A move's modifiers stay held after it (a hover with modifiers); a click that holds nothing lets its own go. #[trial] fn a_move_keeps_its_modifiers_and_a_click_lets_them_go() { @@ -291,6 +337,19 @@ fn document_points_need_a_canvas() { assert_eq!(screen, Some(Ok(()))); } +/// A drag whose end cannot be placed is refused whole: its press at a screen point is not queued either. +#[trial] +fn a_drag_with_an_end_it_cannot_place_queues_no_press() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + let none = |_: usize, _: Pos2| None; + let params = json!({"from": {"x": 1, "y": 1}, "to": {"x": 5, "y": 5, "coordinates": "document"}}); + assert_eq!(input_method("ui.drag", ¶ms, &host, ViewportId::ROOT, &none), Some(Err(NO_DOCUMENT.to_owned()))); + assert!(host.injected_idle()); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "the refused drag queued nothing"); +} + /// A step handed to the input whose pass has not run is withdrawn when the focus moved, and when the application /// withdraws the input because its document changed: the integration's preserved copy leaves the input, no key /// stays down, and the waiters fail with `TARGET_CHANGED`. @@ -356,6 +415,13 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.move", json!({"x": 10, "rest": "long"})), ("ui.move", json!({"x": 10, "coordinates": "page"})), ("ui.move", json!({"y": -far})), + ("ui.drag", json!({"from": {"x": 10}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20, "nudge": 1}})), + ("ui.drag", json!({"from": {"x": 10}, "to": [20, 20]})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": far}})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": 0})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "steps": MAX_DRAG_STEPS + 1})), + ("ui.drag", json!({"from": {"x": 10}, "to": {"x": 20}, "x": 5})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 5e24eaacdc..0c87b65c8a 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -1124,7 +1124,7 @@ Control channel, screenshot queue, profiler and recorded actions for tests and s | `server` | Loopback JSON-lines TCP transport (native): `listen`, `serve`, stopped by dropping its `Listening` | exists | | `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and the CLI's live client (re-exported from `craft-control`), the link host and the Agents page of Preferences | exists | | `client` | JSON-lines client for tests and command-line tools (native) | exists | -| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.key`, `ui.type` | exists | +| `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.drag`, `ui.key`, `ui.type` | exists | | `dialogs` | `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` over a `DialogHost` | exists | | `profiler` | Frame profiler | exists | | `screenshot` | Screenshot request queue | exists | diff --git a/docs/porting.md b/docs/porting.md index f7a03e41bd..fdd9301051 100644 --- a/docs/porting.md +++ b/docs/porting.md @@ -130,7 +130,7 @@ The old app is the visual reference, but not automatically right: judge each dif | Command-line values | `args::ControlOptions`, `EnvNames` | Parses its own flags and calls `ControlOptions::resolve` | | Transport | `server::listen`, `server::serve`, `ControlClient` | Calls `listen` (or `serve` on a listener it bound earlier), keeps the `Listening` and owns the `ControlChannel` | | Request queue, replies | `ControlChannel`, `Reply`, `result_reply` | Runs each request and returns a `Reply` | -| Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`: the checked parameters of `ui.click`, `ui.key`, `ui.move` | Dispatches the method names to them | +| Input methods | `synthetic::Click`, `KeyPress`, `move_from_params`, `Drag`: the checked parameters of `ui.click`, `ui.key`, `ui.move`, `ui.drag` | Dispatches the method names to them | | Dialog methods | `dialogs`: `ui.dialog.set`, `ui.dialog.confirm`, `ui.dialog.cancel` and the dialog list | Dispatches them; may add `ui.dialog.open` for its own dialog kinds | | Screenshots | `Captures` (the bounded queue), `screenshot_reply`, PNG encoding | Allocates a token for `ui.screenshot`, drives the queue each frame, supplies the file writer | | View and window state | nothing | Methods such as `ui.set` (tool, panels, theme), `ui.resize`, `engine.execute` | From 6c33621a06715619e8a82d1bc6e01ccfdbaa32fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:30:38 -0800 Subject: [PATCH 075/269] Menu bar: the output reports the width every title takes side by side craft_ui::menu::MenuBarOutput and craft_menu::MenuBarOutput gain a `natural: f32` field: the width of every title side by side with none in the "..." menu, whatever room the bar had. `titles` stays the rect of the titles drawn. A host that puts controls after the titles on the same row compares `natural` with the room it leaves the bar, and can narrow its own controls before titles fold. The field is zero while the bar shows nothing (ScreenTop), and a memoized replay keeps it. Trials: a bar in a wide and a narrow rect (craft-ui-widgets) and MenuBarUi in a wide and a narrow Stack (craft-menu) report the same natural width, equal to the titles' width when all fit and larger than the drawn titles when some fold. --- crates/menu/README.md | 4 ++- crates/menu/src/bar.rs | 12 ++++++--- crates/menu/tests/it/title_bar.rs | 30 ++++++++++++++++++++- crates/ui-widgets/src/menu/bar.rs | 14 +++++++--- crates/ui-widgets/tests/it/menu/bar.rs | 36 +++++++++++++++++++++++++- 5 files changed, 86 insertions(+), 10 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index cb82dc8f9e..307cd092ad 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -132,7 +132,9 @@ app translates. The dialog never opens a file dialog or touches the file system. ## Windows, Linux and web: the in-window bar -`MenuBarUi` draws a laid-out bar and returns the titles' rect (`MenuBarOutput`). Show it inside a +`MenuBarUi` draws a laid-out bar and returns the titles' rect and the width every title takes side by +side (`MenuBarOutput`). A host that puts controls after the titles on the same row compares that +width with the room it leaves the bar. Show it inside a `Stack` (a top panel's body) or the title bar's row: there the titles that don't fit its room fold into "…". Each item is a command row: its enabled state, check mark and chord follow the command in the diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 4b2c81e742..9ea75cec33 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -48,11 +48,11 @@ pub(crate) fn keymap_platform(target: Target, os: Platform) -> Platform { /// A replay at another place moves the titles' rect with the bar. impl craft_ui::runtime::Shift for MenuBarOutput { fn shifted(&self, by: &egui::RecordShift) -> Self { - MenuBarOutput { titles: by.rect(self.titles) } + MenuBarOutput { titles: by.rect(self.titles), natural: self.natural } } fn snapped(&self, to: &Self, within: f32) -> Self { - MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within) } + MenuBarOutput { titles: craft_ui::runtime::Shift::snapped(&self.titles, &to.titles, within), natural: self.natural } } } @@ -63,6 +63,9 @@ pub struct MenuBarOutput { /// The menu titles alone, without the room the bar leaves after them /// ([`craft_ui::menu::MenuBarOutput::titles`]). pub titles: Rect, + /// The width every title takes side by side with none in "…", whatever room the bar had + /// ([`craft_ui::menu::MenuBarOutput::natural`]). Zero when the bar shows nothing. + pub natural: f32, } /// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, inside a `Stack` (a top @@ -145,7 +148,7 @@ impl<'a> MenuBarUi<'a> { help, label: env.words::().label.clone(), }; - MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING }) + MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING, natural: 0.0 }) } } @@ -182,7 +185,8 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { if let Some(menu) = props.help { bar = bar.help(MenuHelp::new(menu, &entries)); } - MenuBarOutput { titles: bar.show(ui).titles } + let shown = bar.show(ui); + MenuBarOutput { titles: shown.titles, natural: shown.natural } } /// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics, diff --git a/crates/menu/tests/it/title_bar.rs b/crates/menu/tests/it/title_bar.rs index 1e79bf5c18..15543e8d97 100644 --- a/crates/menu/tests/it/title_bar.rs +++ b/crates/menu/tests/it/title_bar.rs @@ -1,6 +1,7 @@ //! The in-window menu bar in an app's title bar: every title shows while the bar has room for them, the document title //! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". In a `Stack` -//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. +//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. In any room the bar +//! reports the width its titles take side by side. use std::cell::Cell; use std::rc::Rc; @@ -131,3 +132,30 @@ fn a_bar_in_a_stack_narrower_than_its_titles_folds_them_and_draws_nothing_past_i fixture.click(&more).settle(); assert!(fixture.by_label("Help").is_some(), "Help is a row of the \"…\" menu"); } + +/// The bar reports the width every title takes side by side: in a stack that holds them all it is the titles' width, +/// and in a stack too narrow for them it is the same width while the drawn titles are narrower. +#[trial] +fn the_bar_reports_the_width_every_title_takes_in_a_wide_and_a_narrow_stack() { + let mut reports = Vec::new(); + for width in [1520.0, 240.0] { + let bar = Rc::new(model()); + let seen = Rc::new(Cell::new((0.0, 0.0))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let bar = Rc::clone(&bar); + let out = Rc::clone(&out); + Stack::new().show(ui, move |ui, _| { + let shown = MenuBarUi::new(&bar).target(Target::Windows).show(ui); + out.set((shown.natural, shown.titles.width())); + }); + }); + fixture.os(Os::Windows).room(vec2(width, 600.0)).settle(); + reports.push(seen.get()); + } + let [(wide, wide_titles), (narrow, narrow_titles)] = [reports[0], reports[1]]; + assert!(wide > 0.0, "the bar reports a width"); + assert!((wide - wide_titles).abs() < 0.5, "with room for every title the natural width {wide} is the titles' width {wide_titles}"); + assert!((narrow - wide).abs() < 0.5, "a narrow bar reports the same natural width {narrow} as a wide one {wide}"); + assert!(narrow_titles < narrow, "a narrow bar draws titles {narrow_titles} narrower than its natural width {narrow}"); +} diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index c74ef97b5c..dced87415a 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -209,6 +209,10 @@ pub struct MenuBarOutput { pub open: bool, /// The titles alone (with "…" when it shows), from the first title's reading start to the last title's end. pub titles: Rect, + /// The width every title takes side by side with none in "…", whatever room the bar had: a host that places + /// controls after the titles on the same row compares it with the room it leaves the bar. Zero when the bar + /// shows nothing (`MenuPlacement::ScreenTop`). + pub natural: f32, } impl Outcome for MenuBarOutput { @@ -304,12 +308,14 @@ pub struct MenuBar<'a> { #[prop] keyboard: bool, open: bool, + /// The width of every title side by side, from this pass's measure or parts step. + natural: f32, } impl<'a> MenuBar<'a> { /// A bar named `label` with one title per menu, in reading order. pub fn new(label: impl Into

    {}\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 115/269] 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 116/269] 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 117/269] 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 118/269] 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 119/269] 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 120/269] 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 121/269] 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 122/269] 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 123/269] 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 124/269] 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 125/269] 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 126/269] 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 127/269] 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 128/269] 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 129/269] 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 130/269] 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 131/269] 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 c9c6010394e83d208b57d25c7e60893834bdfb97 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 10:04:42 -0800 Subject: [PATCH 132/269] automation: the control token file is private from the moment it is created On Windows, create_token_file created the token file with its folder's access list and only then restricted it to the user and SYSTEM. Another local account that the folder lets read new files could open a handle in between, and that handle keeps its read access after the list changes, so it could read the token once it was written. craft_platform::owner_only::create_private_file creates the file with an owner-only security descriptor in the call that creates it, writes the contents through that handle, and checks the result. The control token file now uses it on Windows. Unix keeps mode 0600 at create, and losing the create race to another process still reads the winner's file. --- crates/automation/src/security.rs | 36 ++++++----- crates/automation/src/security_tests.rs | 6 ++ crates/platform/README.md | 2 +- crates/platform/src/owner_only.rs | 83 +++++++++++++++++++++++++ 4 files changed, 110 insertions(+), 17 deletions(-) diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 259d2f3cb2..0932374526 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -8,8 +8,11 @@ //! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept //! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it. +#[cfg(not(windows))] use std::fs::OpenOptions; -use std::io::{BufRead, Write}; +use std::io::BufRead; +#[cfg(not(windows))] +use std::io::Write; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; @@ -323,26 +326,27 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?; } - let mut options = OpenOptions::new(); - options.write(true).create_new(true); - #[cfg(unix)] - { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; - // On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token - // is written, and a file that cannot be restricted is removed rather than left for the token to go into later. + // On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's + // access list, and the token is written through the handle that created it. #[cfg(windows)] { use craft_platform::owner_only; - if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) { - drop(file); - let _ = std::fs::remove_file(path); - return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display()))); + owner_only::current_user_sid() + .and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes())) + .map_err(|e| AutomationError::Io(format!("{}: cannot create the control token file for its owner only: {e}", path.display()))) + } + #[cfg(not(windows))] + { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); } + let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; + writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) } - writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) } /// The server's token, lower-cased. Both given is diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index b5ba980c95..bba93f3c94 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -141,6 +141,12 @@ fn server_token_sources_and_validation() { use std::os::unix::fs::PermissionsExt; assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600); } + #[cfg(windows)] + { + use craft_platform::owner_only; + let sddl = owner_only::sddl_of(&file).unwrap(); + assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}"); + } assert_eq!(server_token(None, Some(&file)).unwrap(), created); // An existing file's content is trimmed and lower-cased. diff --git a/crates/platform/README.md b/crates/platform/README.md index d557f93108..b6d8e949a8 100644 --- a/crates/platform/README.md +++ b/crates/platform/README.md @@ -23,7 +23,7 @@ pull in heavier dependencies. | always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. | | always (native) | `default_app::make_default`: the Preferences button that makes the app the system default for its file types. Windows opens Settings › Default apps (`SettingsOpened`), Linux and BSD run `xdg-mime default` (`MadeDefault`, refused inside Flatpak or without an installed desktop entry), macOS answers `Unsupported`. `path_from_arg` and `rejoin_split_paths` read the paths a launcher hands the app. Only a button may call it. | | always (native) | `temp::TempDir` and `TempFiles`: private temporary folders created exclusively with owner-only permissions (`0700`, files `0600`, `create_new`), named with the process id and a counter, removed on drop. | -| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. | +| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `create_private_file` creates a file with that access list from the start, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. | | always | `PlatformText`: a user-visible message of a platform service (id, English text with `{name}` placeholders) that the app looks up in its own catalog. The open, clipboard, watch, default-app and temp services and craft-dialogs' save flow use it. No words table lists them yet, so the missing-translation list does not show them. | | `screen` | Screen capture for the screen colour picker (`craft_platform::screen`). | | `apple-events` | Apple Events requests on macOS (`open::apple_events`), through `fmv-macos-events`. | diff --git a/crates/platform/src/owner_only.rs b/crates/platform/src/owner_only.rs index e664dcffe4..b60709b4af 100644 --- a/crates/platform/src/owner_only.rs +++ b/crates/platform/src/owner_only.rs @@ -205,6 +205,60 @@ pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<() restricted } +/// Create the file `path`, which must not exist yet, with user `me` (as for [`restrict_to_owner`]) +/// as its owner and an access list of that user and SYSTEM only, given to Windows in the call that +/// creates the file, so the file never has its folder's access list, and write `contents` through +/// that handle, opened unshared. Then check the file's descriptor as [`restrict_to_owner`] does. +/// An existing `path` is an error of kind [`std::io::ErrorKind::AlreadyExists`] and is left as it +/// is. A file that was created but could not be written or checked is removed again. `contents` +/// reach PowerShell through its standard input, never as script text or an environment variable. +#[cfg(windows)] +pub fn create_private_file(path: &std::path::Path, me: &str, contents: &[u8]) -> std::io::Result<()> { + use std::io::Write as _; + /// The exit code the script ends with when the file already exists. + const EXISTS: i32 = 3; + // No double quotes: the command line would strip them. -2147024816 and -2147024713 are the + // HRESULTs of ERROR_FILE_EXISTS and ERROR_ALREADY_EXISTS. + const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \ + $s = New-Object Security.AccessControl.FileSecurity; \ + $s.SetSecurityDescriptorSddlForm('O:' + $env:CRAFT_ACL_USER + 'D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)'); \ + try { $fs = New-Object IO.FileStream -ArgumentList @($env:CRAFT_ACL_PATH, [IO.FileMode]::CreateNew, \ + [Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None, 4096, [IO.FileOptions]::None, $s) } \ + catch { $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; \ + if ($e.HResult -eq -2147024816 -or $e.HResult -eq -2147024713) { exit 3 }; throw }; \ + try { [Console]::OpenStandardInput().CopyTo($fs); $fs.Flush($true); $fs.Dispose() } \ + catch { $fs.Dispose(); [IO.File]::Delete($env:CRAFT_ACL_PATH); throw }"; + let mut child = system_tool(POWERSHELL) + .args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]) + .env("CRAFT_ACL_PATH", path) + .env("CRAFT_ACL_USER", me) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn()?; + // A script that stops before reading (the file exists) closes the pipe; its exit code says why. + let sent = child.stdin.take().map(|mut stdin| stdin.write_all(contents)); + let out = child.wait_with_output()?; + if out.status.code() == Some(EXISTS) { + return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists")); + } + if !out.status.success() { + return Err(std::io::Error::other(format!( + "PowerShell could not create the file for its owner only: {}", + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + let checked = match sent { + Some(Ok(())) => sddl_of(path).and_then(|sddl| still_foreign(&sddl, me)), + Some(Err(e)) => Err(e), + None => Err(std::io::Error::other("PowerShell's standard input could not be opened")), + }; + if checked.is_err() { + let _ = std::fs::remove_file(path); + } + checked +} + /// `Err` naming the problem when the descriptor read back after restricting still isn't `me`'s /// alone, so a file that only looks restricted is never used as one. #[cfg(any(test, windows))] @@ -495,6 +549,35 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256) let _ = std::fs::remove_dir_all(&dir); } + /// A file created by `create_private_file` in a folder that lets Users read what's in it is the + /// user's alone as soon as it exists, with nothing written to it yet; one created with contents + /// holds them, and an existing file is refused and left as it is. + #[cfg(windows)] + #[test] + fn a_private_file_is_private_from_the_start() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-private-file-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); + let me = current_user_sid().unwrap(); + let empty = dir.join("empty.token"); + create_private_file(&empty, &user(), b"").unwrap(); + let sddl = sddl_of(&empty).unwrap(); + assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}"); + assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}"); + assert_eq!(std::fs::read(&empty).unwrap(), b""); + let file = dir.join("ctl.token"); + create_private_file(&file, &user(), b"secret\n").unwrap(); + let sddl = sddl_of(&file).unwrap(); + assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}"); + assert_eq!(std::fs::read(&file).unwrap(), b"secret\n"); + let again = create_private_file(&file, &user(), b"other\n").unwrap_err(); + assert_eq!(again.kind(), std::io::ErrorKind::AlreadyExists, "{again}"); + assert_eq!(std::fs::read(&file).unwrap(), b"secret\n"); + let _ = std::fs::remove_dir_all(&dir); + } + /// A folder may give its user Modify but not Full control, so a file created there doesn't let /// its owner change the owner (no `WRITE_OWNER`). An owner can always replace the access list, /// though, and the user's Full control on it then allows setting the owner. From 7e63794b2d7fa41de4f3d79df71a1e7378096a0f Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Wed, 25 Nov 2026 00:33:29 +0530 Subject: [PATCH 133/269] 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 1798f485a28b1c5b17d3ca0551903366e9d7040a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 10:45:42 -0800 Subject: [PATCH 134/269] control: the token file is private from the moment it is created On Windows, write_token_file_with created the control token file with create_new, so the file started with its folder's access list, and only then ran icacls to restrict it to the user. Another local account that the folder lets read new files could open a handle in between, and that handle keeps its read access after the list changes, so it could read the token once it was written. On Windows the file is now created with craft_platform::owner_only::create_private_file under a name of its own beside the token file: the user and SYSTEM are the only entries from the call that creates it, and the token is written through that handle. The finished file then takes the token file's name through a hard link, so a token file another launch wrote meanwhile is kept and this write fails, as create_new did. The discovery file (current.port) is renamed into place instead, so the latest launch replaces it. The create runs on its own thread and is waited for at most 10 seconds, as icacls was waited for 5. When it does not finish in time, a folder named by the app's CONTROL_DIR gets no token, the default folder gets the file with its own access list, as before, and the late file is removed when the create finishes. While such a create is still running, later writes start no create of their own and take the timed-out path at once. Unix keeps mode 0600 at create. --- Cargo.lock | 1 + crates/control/Cargo.toml | 4 + crates/control/src/auth.rs | 367 +++++++++++++++++++++++++------------ 3 files changed, 253 insertions(+), 119 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 27b9e695a6..be23438e23 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2263,6 +2263,7 @@ dependencies = [ "craft-ai-agents", "craft-atomic", "craft-flags", + "craft-platform", "dirs", "getrandom 0.3.4", "log", diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 3e756aff75..1f3851ffd0 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -32,6 +32,10 @@ craft-flags = { workspace = true, optional = true } dirs = { version = "7", optional = true } log = { workspace = true, optional = true } +[target.'cfg(windows)'.dependencies] +# The token file, created with an access list of its user and SYSTEM only (MIT OR Apache-2.0, ours). +craft-platform = { workspace = true } + [dev-dependencies] proptest = { workspace = true } tempfile = "3" diff --git a/crates/control/src/auth.rs b/crates/control/src/auth.rs index bb2cef86b3..d3cc93a358 100644 --- a/crates/control/src/auth.rs +++ b/crates/control/src/auth.rs @@ -101,7 +101,7 @@ impl App { /// Record `port` as the running app's, readable only by the user like the token files. pub fn write_current_port(&self, port: u16) -> Result { let path = self.current_port_path().ok_or_else(|| Error::new(ErrorKind::NotFound, "no data folder"))?; - self.write_token_file(&path, &port.to_string())?; + self.write_private(&path, &port.to_string(), true)?; Ok(path) } @@ -141,16 +141,27 @@ impl App { } /// Write `token` to `path`, readable and writable only by the user: the folder is made `0700` - /// and the file `0600` on Unix; on Windows the file's inherited permissions are replaced by one - /// entry for the user (`icacls`) before the token goes in; when that fails, the still empty file - /// is removed and no token is written. A file left by an earlier launch is replaced. The process - /// file beside it ([`pid_path`]) records this process, best effort. + /// and the file `0600` on Unix; on Windows the file is created with an access list of the user + /// and SYSTEM only and the token is written through the handle that created it + /// ([`create_for_user`]), so the file never has its folder's access list. A file left by an + /// earlier launch is replaced. The process file beside it ([`pid_path`]) records this process, + /// best effort. pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> { + self.write_private(path, token, false) + } + + /// [`App::write_token_file`]. `replace`: on Windows, a file another launch put at `path` while + /// this one was being created is replaced (the discovery file, which names the latest launch); + /// otherwise this write fails and that launch's token stays. + fn write_private(&self, path: &Path, token: &str, replace: bool) -> Result<()> { #[cfg(windows)] - let restrict = |p: &Path| restrict_to_user(p, self.custom_control_dir().is_some()); + let create = |p: &Path, contents: &[u8]| create_for_user(p, contents, self.custom_control_dir().is_some(), replace); #[cfg(not(windows))] - let restrict = |_: &Path| Ok(()); - write_token_file_with(path, token, restrict) + let create = { + let _ = replace; + create_new_file + }; + write_token_file_with(path, token, create) } } @@ -314,31 +325,18 @@ pub fn tokens_match(a: &str, b: &str) -> bool { a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 } -/// [`App::write_token_file`], with `restrict` limiting the new file to the user (Windows). -fn write_token_file_with(path: &Path, token: &str, restrict: impl FnOnce(&Path) -> Result<()>) -> Result<()> { +/// [`App::write_token_file`], with `create` making the new file with its contents, readable only +/// by the user. +fn write_token_file_with(path: &Path, token: &str, create: impl FnOnce(&Path, &[u8]) -> Result<()>) -> Result<()> { let dir = path.parent().ok_or_else(|| Error::new(ErrorKind::InvalidInput, "no folder"))?; std::fs::create_dir_all(dir)?; let _ = std::fs::remove_file(path); - let mut opts = std::fs::OpenOptions::new(); - opts.write(true).create_new(true); #[cfg(unix)] { - use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))?; - opts.mode(0o600); } - let opened = opts.open(path)?; - // On a refusal the file goes with the closure, so it is closed before it is removed. - let mut f = match restrict(path).map(|()| opened) { - Ok(f) => f, - Err(e) => { - let _ = std::fs::remove_file(path); - return Err(e); - } - }; - f.write_all(token.as_bytes())?; - f.write_all(b"\n")?; - f.sync_all()?; + create(path, format!("{token}\n").as_bytes())?; let pid = std::process::id(); let line = process_start(pid).map_or_else(|| format!("{pid}\n"), |start| format!("{pid} {start}\n")); let _ = std::fs::write(pid_path(path), line); @@ -369,74 +367,143 @@ fn held_by_another(path: &Path, token: &str) -> bool { read_token(path).is_some_and(|held| !tokens_match(&held, token.trim())) } -/// How long `icacls` may take (#6145). It finishes at once; on some computers the new process -/// is left suspended (security software holding it), and waiting on it without a limit froze -/// the app. -#[cfg(windows)] -const ICACLS_LIMIT: std::time::Duration = std::time::Duration::from_secs(5); - -/// How a run of `icacls` ended. -#[cfg(any(windows, test))] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum IcaclsEnd { - Succeeded, - Failed, - /// It didn't finish within [`ICACLS_LIMIT`] and was ended. - TimedOut, +/// Create `path`, which must not exist yet, holding `contents`: mode `0600` on Unix. On Windows a +/// file created this way has its folder's access list; the token file there is made by +/// [`create_for_user`]. +fn create_new_file(path: &Path, contents: &[u8]) -> Result<()> { + let mut opts = std::fs::OpenOptions::new(); + opts.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + let mut f = opts.open(path)?; + f.write_all(contents)?; + f.sync_all() } -/// Whether a token may go into a file after `icacls` ended this way. `custom_folder`: the file is -/// in the folder the app's `CONTROL_DIR` names. A timeout is accepted only in the default folder, -/// the user's own local app data, which other users can't read by default; nothing is known about -/// the permissions of any other folder. +/// How long creating the token file may take on Windows (#6145). It runs `whoami` and PowerShell; +/// on some computers a new process is left suspended (security software holding it), and waiting +/// on it without a limit froze the app. +#[cfg(windows)] +const CREATE_LIMIT: std::time::Duration = std::time::Duration::from_secs(10); + +/// Windows: create `path` with the current user as owner and an access list of that user and +/// SYSTEM only, given to Windows in the call that creates the file, with `contents` written +/// through that handle (`craft_platform::owner_only::create_private_file`), then named `path`. +/// Another account never gets a moment in which the file has its folder's access list and could be +/// opened. `custom_folder`: the file is in the folder the app's `CONTROL_DIR` names; +/// [`create_within`] says what it changes when the create takes longer than [`CREATE_LIMIT`], and +/// what `replace` changes. +#[cfg(windows)] +fn create_for_user(path: &Path, contents: &[u8], custom_folder: bool, replace: bool) -> Result<()> { + use craft_platform::owner_only; + /// How many creates that were not waited for are still running. + static STUCK: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let private = |p: &Path, c: &[u8]| owner_only::current_user_sid().and_then(|me| owner_only::create_private_file(p, &me, c)); + create_within(path, contents, custom_folder, replace, CREATE_LIMIT, &STUCK, private).0 +} + +/// What a create that wasn't waited for gives: in a folder the app's `CONTROL_DIR` names +/// (`custom_folder`) an error of kind [`ErrorKind::TimedOut`], since nothing is known about that +/// folder's permissions; in the default folder, the user's own local app data, which other users +/// can't read by default, `path` created with that folder's access list ([`create_new_file`]). #[cfg(any(windows, test))] -fn restriction_result(end: IcaclsEnd, custom_folder: bool, path: &Path) -> Result<()> { - match end { - IcaclsEnd::Succeeded => Ok(()), - IcaclsEnd::TimedOut if !custom_folder => Ok(()), - IcaclsEnd::TimedOut => Err(Error::new(ErrorKind::TimedOut, format!("icacls did not finish in time to restrict {}", path.display()))), - IcaclsEnd::Failed => Err(Error::other(format!("icacls failed to restrict {}", path.display()))), +fn not_waited_for(path: &Path, contents: &[u8], custom_folder: bool) -> Result<()> { + if custom_folder { + Err(Error::new(ErrorKind::TimedOut, format!("creating {} for its user only did not finish in time", path.display()))) + } else { + create_new_file(path, contents) } } -/// Windows: drop inherited entries and grant only the current user full access. An `icacls` -/// that doesn't finish in time is ended, and [`restriction_result`] decides what that means. -#[cfg(windows)] -fn restrict_to_user(path: &Path, custom_folder: bool) -> Result<()> { - use std::os::windows::process::CommandExt; - let user = std::env::var("USERNAME").map_err(|_| Error::other("USERNAME is not set"))?; - let domain = std::env::var("USERDOMAIN").ok().filter(|d| !d.is_empty()); - let who = domain.map_or(user.clone(), |d| format!("{d}\\{user}")); - let child = std::process::Command::new("icacls") - .arg(path) - .args(["/inheritance:r", "/grant:r", &format!("{who}:F")]) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .creation_flags(0x0800_0000) - .spawn()?; - let end = match wait_within(child, ICACLS_LIMIT)? { - Some(status) if status.success() => IcaclsEnd::Succeeded, - Some(_) => IcaclsEnd::Failed, - None => IcaclsEnd::TimedOut, +/// Run `private`, which creates a file holding `contents` for the user alone, on a thread of its +/// own, and wait for it at most `limit`. The thread creates a file of its own beside `path` +/// (`....tmp`), and the file takes the name `path` only once `private` +/// has finished, so `path` never holds a file that is still being written: with `replace` by a +/// rename that replaces a file another launch put there meanwhile, otherwise by [`place_new`], +/// which leaves that file and fails. When +/// the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its +/// file whenever it does finish, and `stuck` counts it until then. While `stuck` counts any +/// thread, no other thread is started and [`not_waited_for`] answers at once, so a computer that +/// leaves new processes suspended holds at most the threads that were started together. The +/// thread's handle is returned for tests. +#[cfg(any(windows, test))] +fn create_within( + path: &Path, + contents: &[u8], + custom_folder: bool, + replace: bool, + limit: std::time::Duration, + stuck: &'static std::sync::atomic::AtomicUsize, + private: impl FnOnce(&Path, &[u8]) -> Result<()> + Send + 'static, +) -> (Result<()>, Option>) { + use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::mpsc::{RecvTimeoutError, channel}; + use std::sync::{Arc, Mutex, PoisonError}; + /// Numbers the thread's files within this process. + static COUNT: AtomicU64 = AtomicU64::new(0); + if stuck.load(Ordering::Acquire) > 0 { + return (not_waited_for(path, contents, custom_folder), None); + } + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let staged = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))); + let (sender, receiver) = channel(); + // Set under the lock when the caller stops waiting; the thread reads it under the same lock + // before it reports, so its result is either received or its file is removed. + let abandoned = Arc::new(Mutex::new(false)); + let (own_file, owned_contents, flag) = (staged.clone(), contents.to_vec(), Arc::clone(&abandoned)); + let spawned = std::thread::Builder::new().name("craft-control-token-file".into()).spawn(move || { + let made = private(&own_file, &owned_contents); + let abandoned = flag.lock().unwrap_or_else(PoisonError::into_inner); + if *abandoned { + let _ = std::fs::remove_file(&own_file); + stuck.fetch_sub(1, Ordering::AcqRel); + } else { + let _ = sender.send(made); + } + }); + let handle = match spawned { + Ok(handle) => handle, + Err(e) => return (Err(e), None), }; - restriction_result(end, custom_folder, path) + let made = match receiver.recv_timeout(limit) { + Ok(made) => made, + Err(RecvTimeoutError::Disconnected) => Err(Error::other(format!("the thread creating {} stopped", path.display()))), + Err(RecvTimeoutError::Timeout) => { + let mut abandoned = abandoned.lock().unwrap_or_else(PoisonError::into_inner); + match receiver.try_recv() { + Ok(made) => made, + Err(_) => { + *abandoned = true; + stuck.fetch_add(1, Ordering::AcqRel); + drop(abandoned); + return (not_waited_for(path, contents, custom_folder), Some(handle)); + } + } + } + }; + let placed = made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }); + let _ = std::fs::remove_file(&staged); + (placed, Some(handle)) } -/// Wait for `child` at most `limit`: its exit status, or `None` (and the child ended) when it -/// hasn't finished by then. +/// Give the finished file `staged` the name `path`, which must not exist yet: a second launch +/// writing the same token file at the same time gets [`ErrorKind::AlreadyExists`], as a +/// `create_new` there would, instead of replacing the first one's token. The new name is a hard +/// link. On a volume without hard links the file is renamed once `path` is found free; there a +/// launch that puts its file at `path` between that check and the rename has it replaced, as std +/// offers no rename that refuses an existing file without `unsafe`. `staged` is left for the +/// caller to remove. #[cfg(any(windows, test))] -fn wait_within(mut child: std::process::Child, limit: std::time::Duration) -> Result> { - let start = std::time::Instant::now(); - loop { - if let Some(status) = child.try_wait()? { - return Ok(Some(status)); +fn place_new(staged: &Path, path: &Path) -> Result<()> { + match std::fs::hard_link(staged, path) { + Ok(()) => Ok(()), + Err(e) if e.kind() == ErrorKind::AlreadyExists || std::fs::symlink_metadata(path).is_ok() => { + Err(Error::new(ErrorKind::AlreadyExists, format!("{}: {e}", path.display()))) } - if start.elapsed() >= limit { - // Not waited for afterwards: a suspended process may not end at once. - let _ = child.kill(); - return Ok(None); - } - std::thread::sleep(std::time::Duration::from_millis(20)); + Err(_) => std::fs::rename(staged, path), } } @@ -456,50 +523,112 @@ mod tests { /// An app with no data folder and no environment, whose times read `t`. const TEST: App = App { name: "TestCraft", data_dir: || None, env: |_| None, utc: |secs| format!("t{secs}"), default_port: 27878 }; - /// #6145: a child that doesn't finish in time is given up on, not waited for forever. - #[cfg(unix)] + /// #6145: a private create that doesn't finish in time doesn't hold the caller up. In a folder + /// the app's `CONTROL_DIR` names, the call fails; in the default folder, the file is created + /// anyway and holds the token. Either way the file the late create makes is removed when it + /// finishes and never takes the token file's name, even when a later write has put a file + /// there. While it runs, the next create starts no thread of its own. A create that finishes in + /// time puts its file in place unless a file already has the name, and one that fails leaves + /// nothing. #[test] - fn a_slow_child_is_waited_for_only_so_long() { - use std::time::{Duration, Instant}; - let start = Instant::now(); - let slow = std::process::Command::new("sleep").arg("30").spawn().unwrap(); - assert!(wait_within(slow, Duration::from_millis(200)).unwrap().is_none()); - assert!(start.elapsed() < Duration::from_secs(5), "{:?}", start.elapsed()); - let quick = std::process::Command::new("true").spawn().unwrap(); - assert!(wait_within(quick, Duration::from_secs(5)).unwrap().is_some_and(|s| s.success())); - let failing = std::process::Command::new("false").spawn().unwrap(); - assert!(wait_within(failing, Duration::from_secs(5)).unwrap().is_some_and(|s| !s.success())); - } - - /// #6145's freeze fix stays in the default folder, the user's own; a folder picked with - /// the app's `CONTROL_DIR` gets no token unless the file was really restricted. - #[test] - fn only_the_default_folder_accepts_an_icacls_that_timed_out() { - let path = Path::new("control/7878.token"); - for custom in [false, true] { - assert!(restriction_result(IcaclsEnd::Succeeded, custom, path).is_ok()); - assert!(restriction_result(IcaclsEnd::Failed, custom, path).is_err()); + fn a_private_create_that_does_not_finish_in_time_is_not_waited_for() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::mpsc::channel; + use std::time::Duration; + static STUCK: AtomicUsize = AtomicUsize::new(0); + let dir = std::env::temp_dir().join(format!("craft-control-create-limit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let names = || { + let mut names: Vec = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + names + }; + for custom in [true, false] { + let path = dir.join("7878.port"); + let (go, wait) = channel::<()>(); + let (made, handle) = create_within(&path, b"7878\n", custom, false, Duration::ZERO, &STUCK, move |p, c| { + wait.recv().map_err(Error::other)?; + create_new_file(p, c) + }); + assert_eq!(STUCK.load(Ordering::Acquire), 1); + if custom { + assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut); + assert!(!path.exists()); + let unused = |_: &Path, _: &[u8]| -> Result<()> { panic!("a second thread was started") }; + let (again, none) = create_within(&path, b"7878\n", custom, false, Duration::from_secs(600), &STUCK, unused); + assert_eq!(again.unwrap_err().kind(), ErrorKind::TimedOut); + assert!(none.is_none()); + // A later write of the same contents, as a retry of the same port would make. + create_new_file(&path, b"7878\n").unwrap(); + } else { + made.unwrap(); + } + go.send(()).unwrap(); + handle.unwrap().join().unwrap(); + assert_eq!(STUCK.load(Ordering::Acquire), 0); + assert_eq!(names(), ["7878.port"]); + assert_eq!(read_token(&path).as_deref(), Some("7878")); + std::fs::remove_file(&path).unwrap(); } - assert!(restriction_result(IcaclsEnd::TimedOut, false, path).is_ok()); - let e = restriction_result(IcaclsEnd::TimedOut, true, path).unwrap_err(); - assert_eq!(e.kind(), ErrorKind::TimedOut); - assert!(e.to_string().contains("7878.token"), "{e}"); + let path = dir.join("quick.token"); + let (made, handle) = create_within(&path, b"quick\n", true, false, Duration::from_secs(600), &STUCK, create_new_file); + made.unwrap(); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["quick.token"]); + assert_eq!(read_token(&path).as_deref(), Some("quick")); + // Another launch's file at the name is kept, as `create_new` keeps it. + let (made, handle) = create_within(&path, b"later\n", true, false, Duration::from_secs(600), &STUCK, create_new_file); + assert_eq!(made.unwrap_err().kind(), ErrorKind::AlreadyExists); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["quick.token"]); + assert_eq!(read_token(&path).as_deref(), Some("quick")); + // With `replace` (the discovery file) the later launch's file takes the name. + let (made, handle) = create_within(&path, b"later\n", true, true, Duration::from_secs(600), &STUCK, create_new_file); + made.unwrap(); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["quick.token"]); + assert_eq!(read_token(&path).as_deref(), Some("later")); + let refused = |_: &Path, _: &[u8]| -> Result<()> { Err(Error::other("refused")) }; + let (made, handle) = create_within(&dir.join("refused.token"), b"other\n", true, false, Duration::from_secs(600), &STUCK, refused); + assert!(made.is_err()); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["quick.token"]); + let _ = std::fs::remove_dir_all(&dir); } - /// A file that couldn't be restricted is removed, empty and with no process file beside it, and - /// the error goes to the caller. A restricted one gets its token. + /// A file that couldn't be created leaves no process file beside it, and the error goes to the + /// caller. A created one gets the token and a newline. #[test] - fn a_token_file_that_could_not_be_restricted_is_removed() { - let dir = std::env::temp_dir().join(format!("craft-control-restrict-{}", std::process::id())); + fn a_token_file_that_could_not_be_created_leaves_nothing() { + let dir = std::env::temp_dir().join(format!("craft-control-create-{}", std::process::id())); let path = dir.join("7879.token"); - let e = write_token_file_with(&path, "secret-token", |p| { - assert_eq!(std::fs::read(p).unwrap(), b"", "restricted before the token goes in"); - restriction_result(IcaclsEnd::TimedOut, true, p) - }) - .unwrap_err(); + let e = write_token_file_with(&path, "secret-token", |_, _| Err(Error::new(ErrorKind::TimedOut, "refused"))).unwrap_err(); assert_eq!(e.kind(), ErrorKind::TimedOut); assert!(!path.exists() && !pid_path(&path).exists()); - write_token_file_with(&path, "secret-token", |p| restriction_result(IcaclsEnd::TimedOut, false, p)).unwrap(); + write_token_file_with(&path, "secret-token", create_new_file).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"secret-token\n"); + assert!(pid_path(&path).exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// On Windows the token file is its user's alone from the moment it exists: in a folder that + /// lets Users read what is created in it, the file has no entry for Users and no other + /// account's access. + #[cfg(windows)] + #[test] + fn the_token_file_is_private_from_the_start_on_windows() { + use craft_platform::owner_only; + let dir = std::env::temp_dir().join(format!("craft-control-private-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); + let path = dir.join("7880.token"); + TEST.write_token_file(&path, "secret-token").unwrap(); + let sddl = owner_only::sddl_of(&path).unwrap(); + assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}"); + assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}"); assert_eq!(read_token(&path).as_deref(), Some("secret-token")); let _ = std::fs::remove_dir_all(&dir); } From cce0c76a979ec2e5dc4ac44995fe65a463e73a8b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 11:55:59 -0800 Subject: [PATCH 135/269] platform: owner_only ends a Windows tool that runs longer than 10 seconds Every whoami, PowerShell and icacls run in owner_only now goes through run_until, which waits for the tool with try_wait and a deadline (TOOL_LIMIT, 10 s) and ends it with Child::kill when the deadline passes. The call then fails with ErrorKind::TimedOut. Before, each run used output() or wait_with_output() with no limit, so a process left suspended held create_token_file and every other caller indefinitely. create_private_file writes the file under its own name beside the path (....tmp) and moves it to the path only once the contents are written, so the path never holds a partly written file. When PowerShell is ended, that file is removed once PowerShell has exited. server_token no longer reads a file left at the path by a create that ran out of time as another process's token; it returns the timeout error. --- crates/automation/src/security.rs | 34 ++- crates/automation/src/security_tests.rs | 22 ++ crates/platform/README.md | 2 +- crates/platform/src/owner_only.rs | 307 +++++++++++++++++++++--- 4 files changed, 317 insertions(+), 48 deletions(-) diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 0932374526..8e75f07ecd 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -322,9 +322,12 @@ fn read_token_file(path: &Path) -> Result { Ok(token) } -fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { +/// Create the token file `path` holding `token` and a newline. An error keeps the kind of the one +/// that caused it, with the path in its message. +fn create_token_file(path: &Path, token: &str) -> std::io::Result<()> { + let at = |p: &Path, e: std::io::Error| std::io::Error::new(e.kind(), format!("{}: {e}", p.display())); if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { - std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?; + std::fs::create_dir_all(parent).map_err(|e| at(parent, e))?; } // On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's // access list, and the token is written through the handle that created it. @@ -333,7 +336,7 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { use craft_platform::owner_only; owner_only::current_user_sid() .and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes())) - .map_err(|e| AutomationError::Io(format!("{}: cannot create the control token file for its owner only: {e}", path.display()))) + .map_err(|e| std::io::Error::new(e.kind(), format!("{}: cannot create the control token file for its owner only: {e}", path.display()))) } #[cfg(not(windows))] { @@ -344,8 +347,8 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } - let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; - writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) + let mut file = options.open(path).map_err(|e| at(path, e))?; + writeln!(file, "{token}").map_err(|e| at(path, e)) } } @@ -359,8 +362,19 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { /// file can be reached by others: ; restrict it to its owner`), and its trimmed content is /// validated. A missing one is created with a generated token (parent directories created, /// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a -/// newline); losing that create race to another process reads the winner's file instead. +/// newline); losing that create race to another process reads the winner's file instead. On +/// Windows a create that does not finish in time fails (`I/O: : cannot create the control +/// token file for its owner only: `), and a file it left at the path is not read as a winner's. pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result { + server_token_with(supplied, token_file, create_token_file) +} + +/// [`server_token`], with `create` making a missing token file. +fn server_token_with( + supplied: Option<&str>, + token_file: Option<&Path>, + create: impl FnOnce(&Path, &str) -> std::io::Result<()>, +) -> Result { if supplied.is_some() && token_file.is_some() { return Err(token_conflict()); } @@ -374,11 +388,11 @@ pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result }; match read_token_file(path) { Ok(existing) => Ok(existing.to_ascii_lowercase()), - Err(AutomationError::Io(_)) if !path.exists() => match create_token_file(path, &token) { + Err(AutomationError::Io(_)) if !path.exists() => match create(path, &token) { Ok(()) => Ok(token), - // Another process won the create-new race. - Err(AutomationError::Io(_)) if path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()), - Err(e) => Err(e), + // Another process won the create-new race. A file left by a create that ran out of time is this one's. + Err(e) if e.kind() != std::io::ErrorKind::TimedOut && path.exists() => read_token_file(path).map(|v| v.to_ascii_lowercase()), + Err(e) => Err(AutomationError::Io(e.to_string())), }, Err(e) => Err(e), } diff --git a/crates/automation/src/security_tests.rs b/crates/automation/src/security_tests.rs index bba93f3c94..2716fc24c2 100644 --- a/crates/automation/src/security_tests.rs +++ b/crates/automation/src/security_tests.rs @@ -169,3 +169,25 @@ fn server_token_sources_and_validation() { "bridge mode needs --control-token, --control-token-file, PHOTOCRAFT_CONTROL_TOKEN, or PHOTOCRAFT_CONTROL_TOKEN_FILE" ); } + +// A token file create that runs out of time fails with its own error, even when it left a file at +// the path: that file is not read as another process's. A create that another process beat to the +// path reads that process's token. +#[trial] +fn a_token_file_create_that_runs_out_of_time_is_an_error() { + let dir = scratch_dir("token-limit"); + let file = dir.join("token"); + let late = |p: &Path, _: &str| { + std::fs::write(p, "partial").unwrap(); + Err(std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{}: powershell.exe did not finish within 10 s and was ended", p.display()))) + }; + let err = server_token_with(None, Some(&file), late).unwrap_err().to_string(); + assert!(err.starts_with("I/O: ") && err.ends_with("did not finish within 10 s and was ended"), "{err}"); + std::fs::remove_file(&file).unwrap(); + let beaten = |p: &Path, _: &str| { + create_token_file(p, TOKEN).unwrap(); + Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists")) + }; + assert_eq!(server_token_with(None, Some(&file), beaten).unwrap(), TOKEN); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/platform/README.md b/crates/platform/README.md index b6d8e949a8..a8377d927d 100644 --- a/crates/platform/README.md +++ b/crates/platform/README.md @@ -23,7 +23,7 @@ pull in heavier dependencies. | always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. | | always (native) | `default_app::make_default`: the Preferences button that makes the app the system default for its file types. Windows opens Settings › Default apps (`SettingsOpened`), Linux and BSD run `xdg-mime default` (`MadeDefault`, refused inside Flatpak or without an installed desktop entry), macOS answers `Unsupported`. `path_from_arg` and `rejoin_split_paths` read the paths a launcher hands the app. Only a button may call it. | | always (native) | `temp::TempDir` and `TempFiles`: private temporary folders created exclusively with owner-only permissions (`0700`, files `0600`, `create_new`), named with the process id and a counter, removed on drop. | -| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `create_private_file` creates a file with that access list from the start, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. | +| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `create_private_file` creates a file with that access list from the start, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. A run of a tool that takes longer than `TOOL_LIMIT` (10 s) is ended, and the call fails with `ErrorKind::TimedOut`. | | always | `PlatformText`: a user-visible message of a platform service (id, English text with `{name}` placeholders) that the app looks up in its own catalog. The open, clipboard, watch, default-app and temp services and craft-dialogs' save flow use it. No words table lists them yet, so the missing-translation list does not show them. | | `screen` | Screen capture for the screen colour picker (`craft_platform::screen`). | | `apple-events` | Apple Events requests on macOS (`open::apple_events`), through `fmv-macos-events`. | diff --git a/crates/platform/src/owner_only.rs b/crates/platform/src/owner_only.rs index b60709b4af..6f18c9a798 100644 --- a/crates/platform/src/owner_only.rs +++ b/crates/platform/src/owner_only.rs @@ -9,7 +9,9 @@ //! through one handle. [`foreign_access`] reads the descriptor in SDDL form, which names accounts //! by SID and so reads the same in every Windows language, and says why another user could have //! written or could read the file. They run the tools Windows ships rather than calling the -//! security API directly, which would need `unsafe`. +//! security API directly, which would need `unsafe`. A run of a tool that takes longer than +//! `TOOL_LIMIT` (10 s) is ended, and the function fails with an error of kind +//! [`std::io::ErrorKind::TimedOut`]. /// Why the file whose security descriptor is `sddl` (`O:` owner and `D:` access list, in SDDL or /// as `read_with_sddl` writes it) can't be trusted as user `me`'s own: it is owned by someone else, it has no @@ -146,11 +148,129 @@ fn system_tool(relative: &str) -> std::process::Command { command } +/// How long one run of a tool may take before it is ended. Each tool finishes in a second or two. +/// On some computers a new process is left suspended (security software holding it), and without +/// a limit the caller would wait on it for as long as it stays that way. +#[cfg(windows)] +pub const TOOL_LIMIT: std::time::Duration = std::time::Duration::from_secs(10); + +/// How often [`run_until`] checks whether the tool has exited. +#[cfg(any(test, windows))] +const POLL: std::time::Duration = std::time::Duration::from_millis(20); + +/// How many more checks [`run_until`] makes for a tool it has ended to exit before it stops +/// waiting on it. +#[cfg(any(test, windows))] +const EXIT_POLLS: u32 = 50; + +/// How a run of [`run_until`] ended. +#[cfg(any(test, windows))] +enum Ran { + /// The tool exited by itself: its status and output, and how writing its standard input went. + Exited(std::process::Output, std::io::Result<()>), + /// The time was up first and the tool was ended. `exited` is whether it was then seen to exit. + Ended { exited: bool }, +} + +/// Start `command` with its standard input, output and error piped, hand its standard input to +/// `feed` on a thread of its own, and wait for it to exit. Between checks, `expired` gets what +/// the tool has written to its standard output so far; when it answers `true` first, the tool is +/// ended ([`std::process::Child::kill`]). Standard output and error are read on threads of their +/// own, so a tool that writes more than a pipe holds is not stopped by it. +#[cfg(any(test, windows))] +fn run_until( + mut command: std::process::Command, + feed: impl FnOnce(std::process::ChildStdin) -> std::io::Result<()> + Send + 'static, + mut expired: impl FnMut(&[u8]) -> bool, +) -> std::io::Result { + use std::io::Read as _; + use std::process::Stdio; + let mut child = command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?; + let fed = child.stdin.take().map(|stdin| std::thread::spawn(move || feed(stdin))); + let (chunks, received) = std::sync::mpsc::channel::>(); + if let Some(mut out) = child.stdout.take() { + std::thread::spawn(move || { + let mut buf = [0u8; 4096]; + while let Ok(n @ 1..) = out.read(&mut buf) { + if chunks.send(buf.get(..n).unwrap_or_default().to_vec()).is_err() { + break; + } + } + }); + } + let errors = child.stderr.take().map(|mut err| { + std::thread::spawn(move || { + let mut text = Vec::new(); + let _ = err.read_to_end(&mut text); + text + }) + }); + let mut stdout = Vec::new(); + loop { + stdout.extend(received.try_iter().flatten()); + if let Some(status) = child.try_wait()? { + // The pipes close when the tool exits, which ends both readers. + stdout.extend(received.iter().flatten()); + let stderr = errors.and_then(|e| e.join().ok()).unwrap_or_default(); + let sent = match fed.map(std::thread::JoinHandle::join) { + Some(Ok(sent)) => sent, + Some(Err(_)) => Err(std::io::Error::other("the thread writing the standard input stopped")), + None => Err(std::io::Error::other("the standard input could not be opened")), + }; + return Ok(Ran::Exited(std::process::Output { status, stdout, stderr }, sent)); + } + if expired(&stdout) { + let _ = child.kill(); + let mut exited = false; + for _ in 0..EXIT_POLLS { + if child.try_wait().ok().flatten().is_some() { + exited = true; + break; + } + std::thread::sleep(POLL); + } + return Ok(Ran::Ended { exited }); + } + std::thread::sleep(POLL); + } +} + +/// Run `command`, with nothing on its standard input, for at most [`TOOL_LIMIT`]: its status and +/// output, or an error of kind [`std::io::ErrorKind::TimedOut`] when it was ended. +#[cfg(windows)] +fn run(command: std::process::Command) -> std::io::Result { + let deadline = std::time::Instant::now() + TOOL_LIMIT; + let program = tool_name(&command); + let close = |stdin: std::process::ChildStdin| { + drop(stdin); + Ok(()) + }; + match run_until(command, close, |_| std::time::Instant::now() >= deadline)? { + Ran::Exited(out, _) => Ok(out), + Ran::Ended { .. } => Err(timed_out(&program)), + } +} + +/// The file name of the program `command` starts, for messages. +#[cfg(windows)] +fn tool_name(command: &std::process::Command) -> String { + let program = std::path::Path::new(command.get_program()); + program.file_name().unwrap_or(program.as_os_str()).to_string_lossy().into_owned() +} + +/// The error for a run of `program` that [`run_until`] ended. +#[cfg(windows)] +fn timed_out(program: &str) -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::TimedOut, format!("{program} did not finish within {} s and was ended", TOOL_LIMIT.as_secs())) +} + /// The current user's SID (`whoami /user`). It starts a process, so a caller that needs it for /// several steps reads it once and passes it to each. #[cfg(windows)] pub fn current_user_sid() -> std::io::Result { - let out = system_tool(WHOAMI).args(["/user", "/fo", "csv", "/nh"]).output()?; + let mut whoami = system_tool(WHOAMI); + whoami.args(["/user", "/fo", "csv", "/nh"]); + let out = run(whoami)?; if !out.status.success() { return Err(std::io::Error::other("whoami /user failed")); } @@ -208,51 +328,86 @@ pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<() /// Create the file `path`, which must not exist yet, with user `me` (as for [`restrict_to_owner`]) /// as its owner and an access list of that user and SYSTEM only, given to Windows in the call that /// creates the file, so the file never has its folder's access list, and write `contents` through -/// that handle, opened unshared. Then check the file's descriptor as [`restrict_to_owner`] does. -/// An existing `path` is an error of kind [`std::io::ErrorKind::AlreadyExists`] and is left as it -/// is. A file that was created but could not be written or checked is removed again. `contents` -/// reach PowerShell through its standard input, never as script text or an environment variable. +/// that handle, opened unshared. The file is created beside `path` under a name of its own +/// (`....tmp`) and takes the name `path` only once `contents` are +/// written, so `path` never holds a partly written file. Then check the file's descriptor as +/// [`restrict_to_owner`] does. An existing `path` is an error of kind +/// [`std::io::ErrorKind::AlreadyExists`] and is left as it is. A file that was created but could +/// not be written or checked is removed again. `contents` reach PowerShell through its standard +/// input, never as script text or an environment variable. +/// +/// PowerShell is ended when it takes longer than [`TOOL_LIMIT`], and the call fails with an error +/// of kind [`std::io::ErrorKind::TimedOut`]. The file under its own name is then removed. If +/// PowerShell is not seen to exit after being ended, that file may stay; it still has the access +/// list given when it was created. #[cfg(windows)] pub fn create_private_file(path: &std::path::Path, me: &str, contents: &[u8]) -> std::io::Result<()> { use std::io::Write as _; + let deadline = std::time::Instant::now() + TOOL_LIMIT; + let contents = contents.to_vec(); + create_private_file_until(path, me, move |mut stdin| stdin.write_all(&contents), |_| std::time::Instant::now() >= deadline) +} + +/// [`create_private_file`], with `feed` writing the contents to PowerShell's standard input and +/// `expired` saying when to end it, as [`run_until`] takes them. +#[cfg(windows)] +fn create_private_file_until( + path: &std::path::Path, + me: &str, + feed: impl FnOnce(std::process::ChildStdin) -> std::io::Result<()> + Send + 'static, + expired: impl FnMut(&[u8]) -> bool, +) -> std::io::Result<()> { + use std::sync::atomic::{AtomicU64, Ordering}; /// The exit code the script ends with when the file already exists. const EXISTS: i32 = 3; + /// Numbers the staged files of this process. + static COUNT: AtomicU64 = AtomicU64::new(0); // No double quotes: the command line would strip them. -2147024816 and -2147024713 are the - // HRESULTs of ERROR_FILE_EXISTS and ERROR_ALREADY_EXISTS. + // HRESULTs of ERROR_FILE_EXISTS and ERROR_ALREADY_EXISTS. `File.Move` fails when the + // destination exists. const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \ + if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; \ $s = New-Object Security.AccessControl.FileSecurity; \ $s.SetSecurityDescriptorSddlForm('O:' + $env:CRAFT_ACL_USER + 'D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)'); \ - try { $fs = New-Object IO.FileStream -ArgumentList @($env:CRAFT_ACL_PATH, [IO.FileMode]::CreateNew, \ - [Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None, 4096, [IO.FileOptions]::None, $s) } \ - catch { $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; \ - if ($e.HResult -eq -2147024816 -or $e.HResult -eq -2147024713) { exit 3 }; throw }; \ + $fs = New-Object IO.FileStream -ArgumentList @($env:CRAFT_ACL_STAGED, [IO.FileMode]::CreateNew, \ + [Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None, 4096, [IO.FileOptions]::None, $s); \ try { [Console]::OpenStandardInput().CopyTo($fs); $fs.Flush($true); $fs.Dispose() } \ - catch { $fs.Dispose(); [IO.File]::Delete($env:CRAFT_ACL_PATH); throw }"; - let mut child = system_tool(POWERSHELL) + catch { $fs.Dispose(); [IO.File]::Delete($env:CRAFT_ACL_STAGED); throw }; \ + try { [IO.File]::Move($env:CRAFT_ACL_STAGED, $env:CRAFT_ACL_PATH) } \ + catch { [IO.File]::Delete($env:CRAFT_ACL_STAGED); $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; \ + if ($e.HResult -eq -2147024816 -or $e.HResult -eq -2147024713) { exit 3 }; throw }"; + let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let staged = path.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))); + let mut powershell = system_tool(POWERSHELL); + powershell .args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]) .env("CRAFT_ACL_PATH", path) - .env("CRAFT_ACL_USER", me) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::piped()) - .spawn()?; + .env("CRAFT_ACL_STAGED", &staged) + .env("CRAFT_ACL_USER", me); // A script that stops before reading (the file exists) closes the pipe; its exit code says why. - let sent = child.stdin.take().map(|mut stdin| stdin.write_all(contents)); - let out = child.wait_with_output()?; + let ran = run_until(powershell, feed, expired); + // The staged name is this call's own, so removing it never removes another process's file. + // PowerShell holds the staged file open unshared until it exits. + let (out, sent) = match ran? { + Ran::Exited(out, sent) => (out, sent), + Ran::Ended { exited } => { + if exited { + let _ = std::fs::remove_file(&staged); + } + return Err(timed_out("powershell.exe")); + } + }; if out.status.code() == Some(EXISTS) { return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists")); } if !out.status.success() { + let _ = std::fs::remove_file(&staged); return Err(std::io::Error::other(format!( "PowerShell could not create the file for its owner only: {}", String::from_utf8_lossy(&out.stderr).trim() ))); } - let checked = match sent { - Some(Ok(())) => sddl_of(path).and_then(|sddl| still_foreign(&sddl, me)), - Some(Err(e)) => Err(e), - None => Err(std::io::Error::other("PowerShell's standard input could not be opened")), - }; + let checked = sent.and_then(|()| sddl_of(path)).and_then(|sddl| still_foreign(&sddl, me)); if checked.is_err() { let _ = std::fs::remove_file(path); } @@ -295,11 +450,9 @@ fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Res Kind::File => FILE, Kind::Folder => FOLDER, }; - let out = system_tool(POWERSHELL) - .args(["-NoProfile", "-NonInteractive", "-Command", script]) - .env("CRAFT_ACL_PATH", path) - .env("CRAFT_ACL_USER", me) - .output()?; + let mut powershell = system_tool(POWERSHELL); + powershell.args(["-NoProfile", "-NonInteractive", "-Command", script]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_USER", me); + let out = run(powershell)?; if out.status.success() { Ok(()) } else { @@ -309,7 +462,9 @@ fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Res #[cfg(windows)] fn icacls(path: &std::path::Path, args: &[String]) -> std::io::Result<()> { - let out = system_tool(ICACLS).arg(path).args(args).output()?; + let mut icacls = system_tool(ICACLS); + icacls.arg(path).args(args); + let out = run(icacls)?; if out.status.success() { Ok(()) } else { @@ -348,11 +503,9 @@ pub fn read_with_sddl(path: &std::path::Path, max: u64) -> std::io::Result<(Stri ); // Bounded so the script's `[int]` and buffer stay small; a token file is far below this. let max = max.min(1 << 20); - let out = system_tool(POWERSHELL) - .args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]) - .env("CRAFT_ACL_PATH", path) - .env("CRAFT_ACL_MAX", max.to_string()) - .output()?; + let mut powershell = system_tool(POWERSHELL); + powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_MAX", max.to_string()); + let out = run(powershell)?; let read = if out.status.success() { sddl_and_bytes(&String::from_utf8_lossy(&out.stdout)) } else { None }; read.ok_or_else(|| std::io::Error::other("PowerShell could not read the file with its owner and access list")) } @@ -368,7 +521,9 @@ pub fn sddl_of(path: &std::path::Path) -> std::io::Result { describe_raw!(), "[Console]::Out.Write($sddl + [char]10)" ); - let out = system_tool(POWERSHELL).args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).output()?; + let mut powershell = system_tool(POWERSHELL); + powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path); + let out = run(powershell)?; let read = if out.status.success() { sddl_and_bytes(&String::from_utf8_lossy(&out.stdout)) } else { None }; read.map(|(sddl, _)| sddl).ok_or_else(|| std::io::Error::other("PowerShell could not read the file's owner and access list")) } @@ -578,6 +733,84 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256) let _ = std::fs::remove_dir_all(&dir); } + /// A command that writes `ready` to its standard output and then reads its standard input until + /// it closes. + fn waiting_reader() -> std::process::Command { + #[cfg(windows)] + let command = { + let mut powershell = system_tool(POWERSHELL); + powershell.args([ + "-NoProfile", + "-NonInteractive", + "-Command", + "[Console]::Out.Write('ready'); [Console]::Out.Flush(); $null = [Console]::In.ReadToEnd()", + ]); + powershell + }; + #[cfg(not(windows))] + let command = { + let mut sh = std::process::Command::new("sh"); + sh.args(["-c", "printf ready; cat >/dev/null"]); + sh + }; + command + } + + /// A tool still running when the time is up is ended and exits. The time is up once the tool + /// has said it is waiting (a handshake, not a clock). + /// The same tool, given its input, exits by itself and nothing ends it. + #[test] + fn a_tool_that_does_not_finish_in_time_is_ended() { + let (keep, kept) = std::sync::mpsc::channel(); + // The standard input stays open, so the tool waits until it is ended. + let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other); + match run_until(waiting_reader(), hold, |out| out == b"ready").unwrap() { + Ran::Ended { exited } => assert!(exited, "the tool was ended but is still running"), + Ran::Exited(out, _) => panic!("the tool exited by itself: {out:?}"), + } + drop(kept); + let close = |stdin: std::process::ChildStdin| { + drop(stdin); + Ok(()) + }; + match run_until(waiting_reader(), close, |_| false).unwrap() { + Ran::Exited(out, sent) => { + assert!(out.status.success(), "{out:?}"); + assert_eq!(out.stdout, b"ready"); + sent.unwrap(); + } + Ran::Ended { .. } => panic!("the tool was ended"), + } + } + + /// PowerShell that has created the file but not written it when the time is up is ended, the + /// call fails as timed out, and the file it created is removed; nothing took the name. A file + /// that was at the name before is another's, and it is left as it is whenever the time runs out. + #[cfg(windows)] + #[test] + fn a_private_file_whose_create_does_not_finish_in_time_is_removed() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-limit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("ctl.token"); + let entries = || std::fs::read_dir(&dir).unwrap().count(); + let (keep, kept) = std::sync::mpsc::channel(); + let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other); + // The time is up once the script has created its file and waits for the contents. + let late = create_private_file_until(&file, &user(), hold, |_| entries() > 0).unwrap_err(); + drop(kept); + assert_eq!(late.kind(), std::io::ErrorKind::TimedOut, "{late}"); + assert_eq!(entries(), 0, "the file PowerShell created is removed"); + std::fs::write(&file, b"other\n").unwrap(); + let (keep, kept) = std::sync::mpsc::channel(); + let hold = move |stdin: std::process::ChildStdin| keep.send(stdin).map_err(std::io::Error::other); + let refused = create_private_file_until(&file, &user(), hold, |_| true).unwrap_err(); + drop(kept); + assert!(matches!(refused.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::AlreadyExists), "{refused}"); + assert_eq!(std::fs::read(&file).unwrap(), b"other\n"); + let _ = std::fs::remove_dir_all(&dir); + } + /// A folder may give its user Modify but not Full control, so a file created there doesn't let /// its owner change the owner (no `WRITE_OWNER`). An owner can always replace the access list, /// though, and the user's Full control on it then allows setting the owner. From 1f3b0578cc2ee4354187baa18062b0983522fd53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 11:57:46 -0800 Subject: [PATCH 136/269] suite-account: the account list is private from the moment it is created on Windows On Windows, accounts::write created each new copy of the list with plain create_new and then called restrict, which did nothing, so the copy kept its folder's access list. A portable install or ARTCRAFT_SUITE_DIR in a folder such as a new folder at the root of C:\ left the list (subjects, display names, emails, deployment URLs) readable by every local account. Every copy is now created with owner_only::create_private_file, which gives it a protected access list of the user and SYSTEM only in the call that creates it. The rename keeps that list, and a later change to the folder's list does not reach the file. The PowerShell run this needs happens before the accounts lock is taken: with_lock prepares an empty copy for its thread, opens it without delete sharing, checks its access list and holds it open until the write, so no other account can remove, rename or replace it in between. A copy that no write takes is closed and removed when the locked change ends, and empty copies that ended processes left beside the list are removed by the next preparation. --- Cargo.lock | 1 + crates/suite-account/Cargo.toml | 5 + crates/suite-account/src/accounts.rs | 176 ++++++++++++++++++++++++--- crates/suite-account/src/lock.rs | 2 + crates/suite-account/src/tests.rs | 153 +++++++++++++++++++++++ 5 files changed, 317 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 27b9e695a6..c6fa436bf8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4103,6 +4103,7 @@ dependencies = [ name = "craft-suite-account" version = "0.1.0" dependencies = [ + "craft-platform", "dirs", "keyring", "keyring-core", diff --git a/crates/suite-account/Cargo.toml b/crates/suite-account/Cargo.toml index e1527bfd8c..75edc2a751 100644 --- a/crates/suite-account/Cargo.toml +++ b/crates/suite-account/Cargo.toml @@ -31,5 +31,10 @@ keyring = "4.2" # machine-local persistence. `keyring` installs the platform store; this reads it. keyring-core = "1" +# The account list is created with an access list of its user and SYSTEM only +# (`owner_only::create_private_file`). +[target.'cfg(windows)'.dependencies] +craft-platform = { workspace = true } + [dev-dependencies] tempfile = "3" diff --git a/crates/suite-account/src/accounts.rs b/crates/suite-account/src/accounts.rs index fb8ce5d7de..b11cb27156 100644 --- a/crates/suite-account/src/accounts.rs +++ b/crates/suite-account/src/accounts.rs @@ -263,7 +263,10 @@ pub fn read(path: &Path) -> Result { /// [`Error::Malformed`] forever. Every mutation here reads the file first. There would be /// nothing left to repair it with. /// -/// Readable by this user alone where the platform has file modes. The file holds no token. It does +/// Readable by this user alone: mode `0600` on Unix, and on Windows an access list of this user and +/// SYSTEM only from the moment the file exists, whatever folder a portable install or +/// [`crate::paths::ENV_VAR`] chose. On Windows the access list is protected, so a change to the +/// folder's list does not reach the file. The file holds no token. It does /// say who is signed in. That is nobody else's business. /// /// Refuses a list that would serialize past `MAX_BYTES`, before any file is touched. [`read`] @@ -282,14 +285,17 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> { ))); } std::fs::create_dir_all(dir).map_err(|e| Error::Io(format!("couldn't create {} ({e})", dir.display())))?; - use std::io::Write; let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); let pid = std::process::id(); - let tmp = dir.join(format!(".{}.{}.{}.tmp", path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts"), stamp, pid)); + let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts"); + let tmp_name = format!(".{file_name}.{stamp}.{pid}.tmp"); + #[cfg(not(windows))] + let tmp = dir.join(&tmp_name); #[cfg(unix)] { use std::fs::OpenOptions; + use std::io::Write; use std::os::unix::fs::OpenOptionsExt; let mut file = OpenOptions::new() .write(true) @@ -300,14 +306,16 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> { file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?; file.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", tmp.display())))?; } - #[cfg(not(unix))] + #[cfg(windows)] + let tmp = private_copy(path, dir, &tmp_name, &json)?; + #[cfg(not(any(unix, windows)))] { use std::fs::OpenOptions; + use std::io::Write; let mut file = OpenOptions::new().write(true).create_new(true).open(&tmp).map_err(|e| Error::Io(format!("couldn't create {} ({e})", tmp.display())))?; file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?; file.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", tmp.display())))?; - restrict(&tmp)?; } std::fs::rename(&tmp, path).map_err(|e| Error::Io(format!("couldn't replace {} ({e})", path.display())))?; // The flush above persisted the file's bytes. The rename changed a directory entry, and that @@ -324,19 +332,147 @@ pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> { Ok(()) } -#[cfg(not(unix))] -fn restrict(_path: &Path) -> Result<(), Error> { - // A no-op today. That is a real gap this comment used to paper over. A new file in the - // platform configuration folder (the default `paths::Rule::Platform` home) inherits that - // folder's own, profile-scoped access rules. The account list is this user's alone there. - // `paths::Rule::Portable` and `paths::Rule::EnvVar` point `write` at whatever folder the - // caller named. A new file there inherits that folder's own Windows access control list, - // whatever it is. A shared or loosely permissioned folder in either of those two cases - // leaves the account list (subjects, display names, emails, never a token) readable by - // anyone else with access to it. Narrowing that needs a per-user Windows DACL on the file, - // set through the Win32 authorization API. Every binding for that API is an `unsafe fn`. - // This workspace forbids `unsafe_code` outright. Closing this for real needs either a - // maintainer-approved exception for one call site or a vetted dependency that wraps that API - // safely. Both are decisions for a dedicated PR. See `paths::Rule`. - Ok(()) +/// Write `json` to a new file beside the list at `path`, in its folder `dir`, that only this user +/// and SYSTEM can open, and return its path for [`write`] to rename into place. +/// +/// A new file on Windows takes its folder's access list, and a portable install or +/// [`crate::paths::ENV_VAR`] can name a folder that lets every local user read what is created in +/// it. Every copy is created by `owner_only::create_private_file`, which gives the file a protected +/// access list of this user and SYSTEM only in the call that creates it. The rename keeps that +/// list, and a later change to the folder's list does not reach it. That call runs PowerShell, so +/// [`prepare`] creates an empty copy before the accounts lock is taken, and this function writes +/// the list into it. Without a copy this thread prepared (a direct call, or a failed preparation), +/// the copy is created here, named `tmp_name`. +#[cfg(windows)] +fn private_copy(path: &Path, dir: &Path, tmp_name: &str, json: &[u8]) -> Result { + use std::io::Write; + if let Some((copy, mut file)) = take_prepared(path) { + match file.write_all(json).and_then(|()| file.sync_all()) { + Ok(()) => return Ok(copy), + Err(e) => { + drop(file); + let _ = std::fs::remove_file(©); + log::warn!("couldn't write a prepared copy of the account list ({e}); a new one is created"); + } + } + } + let tmp = dir.join(tmp_name); + user_sid() + .and_then(|me| craft_platform::owner_only::create_private_file(&tmp, &me, json)) + .map_err(|e| Error::Io(format!("couldn't create {} for its owner only ({e})", tmp.display())))?; + Ok(tmp) +} + +/// Copies made by [`prepare`] that wait for [`private_copy`]: the thread that made the copy, the +/// list it is for, the copy, and the copy held open without delete sharing. +#[cfg(windows)] +type Prepared = Vec<(std::thread::ThreadId, std::path::PathBuf, std::path::PathBuf, std::fs::File)>; + +/// The copy one [`prepare`] call made. Dropping it closes and removes the copy if no write took it. +#[cfg(windows)] +pub(crate) struct PreparedCopy(Option); + +#[cfg(windows)] +impl Drop for PreparedCopy { + fn drop(&mut self) { + let Some(copy) = self.0.take() else { return }; + let mut waiting = prepared(); + let Some(at) = waiting.iter().position(|(_, _, waiting, _)| *waiting == copy) else { return }; + let (_, _, copy, file) = waiting.swap_remove(at); + drop(waiting); + drop(file); + let _ = std::fs::remove_file(©); + } +} + +/// The copies waiting for [`private_copy`]. +#[cfg(windows)] +fn prepared() -> std::sync::MutexGuard<'static, Prepared> { + static PREPARED: std::sync::Mutex = std::sync::Mutex::new(Vec::new()); + PREPARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// The copy of the list at `path` that this thread prepared, with its open handle, removed from the +/// waiting list. A copy another thread prepared is left for that thread's write. +#[cfg(windows)] +fn take_prepared(path: &Path) -> Option<(std::path::PathBuf, std::fs::File)> { + let me = std::thread::current().id(); + let mut prepared = prepared(); + let at = prepared.iter().position(|(thread, list, ..)| *thread == me && list == path)?; + let (_, _, copy, file) = prepared.swap_remove(at); + Some((copy, file)) +} + +/// This user's SID, read once per process (`whoami` is a process start). +#[cfg(windows)] +fn user_sid() -> std::io::Result { + static SID: std::sync::OnceLock = std::sync::OnceLock::new(); + if let Some(sid) = SID.get() { + return Ok(sid.clone()); + } + let sid = craft_platform::owner_only::current_user_sid()?; + Ok(SID.get_or_init(|| sid).clone()) +} + +/// Before the accounts lock is taken, create an empty copy of the list at `path` for its owner only +/// and keep it open for [`private_copy`], so that the PowerShell run it needs doesn't hold the lock +/// other processes wait on. The caller keeps the returned [`PreparedCopy`] until its change under +/// the lock is done; a change that writes nothing then has its copy removed. A failure here is left +/// for [`write`] to handle. +/// +/// The copy is opened without delete sharing and then checked, so no other account can remove, +/// rename or replace it between the check and the write. A copy that fails the check is removed. +/// Empty copies beside the list that are at least a minute old, which ended processes left, are +/// removed first; a copy that a running process holds open can't be, since removing it needs +/// delete sharing. +#[cfg(windows)] +pub(crate) fn prepare(path: &Path) -> PreparedCopy { + use std::os::windows::fs::OpenOptionsExt as _; + use std::sync::atomic::{AtomicU64, Ordering}; + + use craft_platform::owner_only; + /// `FILE_SHARE_READ | FILE_SHARE_WRITE`: no `FILE_SHARE_DELETE`. + const SHARE_NO_DELETE: u32 = 0x1 | 0x2; + /// How old an empty copy that no process holds must be before it is removed. Another process + /// that is preparing its copy has it closed for a moment, between its creation and the open. + const LEFT_AFTER: std::time::Duration = std::time::Duration::from_secs(60); + static COUNT: AtomicU64 = AtomicU64::new(0); + + let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else { return PreparedCopy(None) }; + let Ok(me) = user_sid() else { return PreparedCopy(None) }; + let _ = std::fs::create_dir_all(dir); + for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() { + let left = entry.file_name(); + let left = left.to_string_lossy(); + if left.starts_with(&format!(".{name}.")) + && left.ends_with(".prepared.tmp") + && entry.metadata().is_ok_and(|meta| { + meta.is_file() && meta.len() == 0 && meta.modified().ok().and_then(|at| at.elapsed().ok()).is_some_and(|age| age >= LEFT_AFTER) + }) + { + let _ = std::fs::remove_file(entry.path()); + } + } + let copy = dir.join(format!(".{name}.{}.{}.prepared.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))); + if let Err(e) = owner_only::create_private_file(©, &me, b"") { + log::warn!("couldn't prepare a copy of the account list for its owner only ({e})"); + return PreparedCopy(None); + } + let checked = std::fs::OpenOptions::new().write(true).share_mode(SHARE_NO_DELETE).open(©).and_then(|file| { + match owner_only::foreign_access(&owner_only::sddl_of(©)?, &me) { + None => Ok(file), + Some(problem) => Err(std::io::Error::other(problem)), + } + }); + match checked { + Ok(file) => { + prepared().push((std::thread::current().id(), path.to_path_buf(), copy.clone(), file)); + PreparedCopy(Some(copy)) + } + Err(e) => { + let _ = std::fs::remove_file(©); + log::warn!("a prepared copy of the account list is not this user's alone ({e}); it was removed"); + PreparedCopy(None) + } + } } diff --git a/crates/suite-account/src/lock.rs b/crates/suite-account/src/lock.rs index 160ff3e3c8..6a95e6bd2a 100644 --- a/crates/suite-account/src/lock.rs +++ b/crates/suite-account/src/lock.rs @@ -49,6 +49,8 @@ fn open_lock_file(path: &Path) -> io::Result { /// [`Error::Io`]; `f` may return any [`Error`]. pub(crate) fn with_lock(path: &Path, f: impl FnOnce() -> Result) -> Result { let lock = open_lock_file(path).map_err(|e| Error::Io(format!("couldn't open the lock beside {} ({e})", path.display())))?; + #[cfg(windows)] + let _prepared = crate::accounts::prepare(path); let start = Instant::now(); loop { match lock.try_lock() { diff --git a/crates/suite-account/src/tests.rs b/crates/suite-account/src/tests.rs index c1a614aab4..045a2065ee 100644 --- a/crates/suite-account/src/tests.rs +++ b/crates/suite-account/src/tests.rs @@ -521,6 +521,159 @@ fn write_leaves_a_previously_good_file_untouched_when_the_new_one_is_too_large() assert_eq!(accounts::read(&path).unwrap(), good, "the earlier, readable file must still be exactly what was there before"); } +/// A portable install or `ARTCRAFT_SUITE_DIR` can put the list in a folder that lets every local +/// user read the files created in it, as a new folder at a drive root does. The list written there +/// has an access list of its user and SYSTEM only. +#[cfg(windows)] +#[test] +fn the_list_in_a_folder_users_can_read_is_still_this_users_alone() { + use craft_platform::owner_only; + let dir = tempfile::tempdir().unwrap(); + let granted = std::process::Command::new("icacls").arg(dir.path()).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stderr)); + let path = dir.path().join(paths::FILE); + let list = + accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() }; + + accounts::write(&path, &list).unwrap(); + + let me = owner_only::current_user_sid().unwrap(); + let sddl = owner_only::sddl_of(&path).unwrap(); + assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}"); + assert_eq!(owner_only::foreign_access(&sddl, &me), None, "{sddl}"); + assert_eq!(accounts::read(&path).unwrap(), list); + // A second write, through a copy prepared before the lock as a `Store` does, leaves no copy behind. + let _copy = accounts::prepare(&path); + accounts::write(&path, &list).unwrap(); + assert_eq!(owner_only::foreign_access(&owner_only::sddl_of(&path).unwrap(), &me), None); + let names: Vec<_> = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(names, [std::ffi::OsString::from(paths::FILE)], "no temporary file is left behind"); +} + +/// The list's access list is protected: a change to its folder's access list, which Windows hands +/// down to the files in the folder that inherit from it, does not reach the list, whether the list +/// was written directly or through a `Store`. +#[cfg(windows)] +#[test] +fn a_change_to_the_folders_access_list_does_not_reach_the_list() { + use craft_platform::owner_only; + let me = owner_only::current_user_sid().unwrap(); + for through_store in [false, true] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(paths::FILE); + if through_store { + let store = Store::at(Some(dir.path().to_path_buf()), Memory::new()); + store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap(); + } else { + let list = accounts::Accounts { + format: accounts::FORMAT, + accounts: vec![account_at("a", 0)], + active: Some("a".to_owned()), + tombstones: Vec::new(), + }; + accounts::write(&path, &list).unwrap(); + } + + let granted = std::process::Command::new("icacls").arg(dir.path()).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stdout)); + + let sddl = owner_only::sddl_of(&path).unwrap(); + assert_eq!(owner_only::foreign_access(&sddl, &me), None, "through a Store: {through_store}; {sddl}"); + } +} + +/// A prepared copy that no write took is closed and removed when its change under the lock is +/// done, as for a discard of an account that is not in the list. +#[cfg(windows)] +#[test] +fn a_prepared_copy_no_write_took_is_removed() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(paths::FILE); + let copy = accounts::prepare(&path); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "the copy is made"); + drop(copy); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0, "the copy is removed"); + + let store = Store::at(Some(dir.path().to_path_buf()), Memory::new()); + store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap(); + let names = || std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect::>(); + let before = names(); + let _ = store.discard("no such account"); + assert_eq!(names(), before, "a change that writes nothing leaves no copy behind"); +} + +/// A write uses the copy its own thread prepared and leaves another thread's copy for that +/// thread, which would otherwise have to create one while it holds the accounts lock. +#[cfg(windows)] +#[test] +fn a_write_takes_only_the_copy_its_thread_prepared() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(paths::FILE); + let list = + accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() }; + let copies = || std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().path()).filter(|p| p != &path).collect::>(); + let prepared = std::sync::Barrier::new(2); + // The other thread keeps its copy until `done` is dropped, which a failed assertion does too. + let (done, wait) = std::sync::mpsc::channel::<()>(); + std::thread::scope(|scope| { + let (list_path, prepared) = (&path, &prepared); + scope.spawn(move || { + let _other = accounts::prepare(list_path); + prepared.wait(); + let _ = wait.recv(); + }); + prepared.wait(); + let other = copies(); + assert_eq!(other.len(), 1, "{other:?}"); + let _mine = accounts::prepare(&path); + accounts::write(&path, &list).unwrap(); + assert_eq!(copies(), other, "the other thread's copy is still waiting"); + drop(done); + }); + assert_eq!(copies(), Vec::::new()); +} + +/// A prepared copy is created with an access list of its user and SYSTEM only, and can't be +/// removed, renamed or replaced, nor its folder renamed, between its check and the write. An empty +/// copy that an ended process left a minute or more ago is removed by the next preparation; a +/// newer one, which another process may be about to open, is kept. +#[cfg(windows)] +#[test] +fn a_prepared_copy_is_private_and_cannot_be_swapped_before_the_write() { + use craft_platform::owner_only; + let me = owner_only::current_user_sid().unwrap(); + let root = tempfile::tempdir().unwrap(); + let dir = root.path().join("suite"); + std::fs::create_dir(&dir).unwrap(); + let granted = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(granted.status.success(), "{}", String::from_utf8_lossy(&granted.stdout)); + let path = dir.join(paths::FILE); + let left = dir.join(format!(".{}.1.0.prepared.tmp", paths::FILE)); + std::fs::File::create(&left).unwrap().set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(120)).unwrap(); + let fresh = dir.join(format!(".{}.2.0.prepared.tmp", paths::FILE)); + std::fs::write(&fresh, b"").unwrap(); + + let _copy = accounts::prepare(&path); + + assert!(!left.exists(), "an old empty copy that no process holds is removed"); + assert!(fresh.exists(), "a new empty copy, which another process may be about to open, is kept"); + let copies: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().path()).filter(|p| *p != fresh).collect(); + assert_eq!(copies.len(), 1, "{copies:?}"); + let copy = &copies[0]; + let sddl = owner_only::sddl_of(copy).unwrap(); + assert_eq!(owner_only::foreign_access(&sddl, &me), None, "{sddl}"); + assert!(std::fs::remove_file(copy).is_err(), "the checked copy must stay in place"); + assert!(std::fs::rename(copy, dir.join("moved")).is_err(), "the checked copy must not be renamed away"); + assert!(std::fs::rename(&dir, root.path().join("moved")).is_err(), "its folder must not be renamed away"); + + let list = + accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() }; + accounts::write(&path, &list).unwrap(); + assert!(!copy.exists(), "the write used the prepared copy"); + assert_eq!(accounts::read(&path).unwrap(), list); + assert_eq!(owner_only::foreign_access(&owner_only::sddl_of(&path).unwrap(), &me), None); +} + #[test] fn a_sign_in_with_an_oversized_display_name_fails_without_bricking_the_list() { let dir = tempfile::tempdir().unwrap(); From c89a2a844f98823582e771c553b77d56143abb5f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 14:07:30 -0800 Subject: [PATCH 137/269] platform: owner_only creates a private folder with its access list and checks inherit-only entries create_private_dir created the folder with create_dir and set its access list afterwards, so for a moment the folder carried its parent's list. It now creates the folder under a name of its own with the user as owner and the user and SYSTEM as its only entries (Directory.CreateDirectory with a DirectorySecurity), then moves it to the path with Directory.Move, which fails when the path exists. A missing parent is NotFound; a relative path is made absolute first. When PowerShell is ended, the folder under its own name is removed once PowerShell has exited. sddl_of read a folder through File.GetAccessControl, which leaves out inherit-only entries, so a folder check could miss an entry that every new file inherits. It now reads a folder through Directory.GetAccessControl, and the check after create_private_dir counts inherit-only entries. foreign_access still skips them for files. --- crates/platform/README.md | 2 +- crates/platform/src/owner_only.rs | 203 +++++++++++++++++++++++------- 2 files changed, 157 insertions(+), 48 deletions(-) diff --git a/crates/platform/README.md b/crates/platform/README.md index a8377d927d..e7d1e8afae 100644 --- a/crates/platform/README.md +++ b/crates/platform/README.md @@ -23,7 +23,7 @@ pull in heavier dependencies. | always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. | | always (native) | `default_app::make_default`: the Preferences button that makes the app the system default for its file types. Windows opens Settings › Default apps (`SettingsOpened`), Linux and BSD run `xdg-mime default` (`MadeDefault`, refused inside Flatpak or without an installed desktop entry), macOS answers `Unsupported`. `path_from_arg` and `rejoin_split_paths` read the paths a launcher hands the app. Only a button may call it. | | always (native) | `temp::TempDir` and `TempFiles`: private temporary folders created exclusively with owner-only permissions (`0700`, files `0600`, `create_new`), named with the process id and a counter, removed on drop. | -| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `create_private_file` creates a file with that access list from the start, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. A run of a tool that takes longer than `TOOL_LIMIT` (10 s) is ended, and the call fails with `ErrorKind::TimedOut`. | +| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` gives a file an access list of the user and SYSTEM only, `create_private_dir` and `create_private_file` create a folder or file with that access list from the start, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. A run of a tool that takes longer than `TOOL_LIMIT` (10 s) is ended, and the call fails with `ErrorKind::TimedOut`. | | always | `PlatformText`: a user-visible message of a platform service (id, English text with `{name}` placeholders) that the app looks up in its own catalog. The open, clipboard, watch, default-app and temp services and craft-dialogs' save flow use it. No words table lists them yet, so the missing-translation list does not show them. | | `screen` | Screen capture for the screen colour picker (`craft_platform::screen`). | | `apple-events` | Apple Events requests on macOS (`open::apple_events`), through `fmv-macos-events`. | diff --git a/crates/platform/src/owner_only.rs b/crates/platform/src/owner_only.rs index 6f18c9a798..fcfdad684e 100644 --- a/crates/platform/src/owner_only.rs +++ b/crates/platform/src/owner_only.rs @@ -4,8 +4,8 @@ //! a new folder at a drive root, `C:\Users\Public` or `C:\ProgramData` let every signed-in user //! read what is created in them. `restrict_to_owner` replaces the whole list with the current //! user and SYSTEM only, makes that user the owner, and checks the result. `create_private_dir` -//! does the same for a new folder whose list the files created in it inherit, so a file can be -//! private from the moment it exists. `read_with_sddl` reads a file and its security descriptor +//! creates a folder with that owner and list from the start, which the files created in it +//! inherit, so a file can be private from the moment it exists. `read_with_sddl` reads a file and its security descriptor //! through one handle. [`foreign_access`] reads the descriptor in SDDL form, which names accounts //! by SID and so reads the same in every Windows language, and says why another user could have //! written or could read the file. They run the tools Windows ships rather than calling the @@ -23,6 +23,18 @@ /// file over. `restrict_to_owner` never grants it, so the app's own file always passes; a file /// that inherited it from a user's folder is refused. pub fn foreign_access(sddl: &str, me: &str) -> Option { + foreign(sddl, me, false) +} + +/// [`foreign_access`] for a folder's descriptor: an inherit-only entry (`IO`) counts too, since +/// every file and folder created in the folder gets it. +#[cfg(any(test, windows))] +fn foreign_folder_access(sddl: &str, me: &str) -> Option { + foreign(sddl, me, true) +} + +/// [`foreign_access`], counting inherit-only entries when `inherit_only` is set. +fn foreign(sddl: &str, me: &str, inherit_only: bool) -> Option { let me = me.trim(); let owner = section(sddl, "O:"); match owner { @@ -43,7 +55,7 @@ pub fn foreign_access(sddl: &str, me: &str) -> Option { let (Some(kind), Some(flags)) = (parts.first(), parts.get(1)) else { continue }; // Deny entries take access away, and inherit-only entries apply to children, not the file. let allows = matches!(*kind, "A" | "OA" | "XA" | "ZA"); - if !allows || flags.contains("IO") { + if !allows || (flags.contains("IO") && !inherit_only) { continue; } // An entry that grants access but names no account can't be shown to be the user's. @@ -297,32 +309,87 @@ fn sid_from_whoami(text: &str) -> Option { /// replace it, while setting the owner needs the Full control it grants (a folder may give Modify). #[cfg(windows)] pub fn restrict_to_owner(path: &std::path::Path, me: &str) -> std::io::Result<()> { - set_access_list(path, me, Kind::File)?; + set_access_list(path, me)?; icacls(path, &["/setowner".into(), format!("*{me}")])?; still_foreign(&sddl_of(path)?, me) } -/// Create the folder `dir`, which must not exist yet, and give it an access list of user `me` (as -/// for [`restrict_to_owner`]) and SYSTEM only, which every file created in it inherits; then make -/// that user its owner and check the result as [`restrict_to_owner`] does. A file created in it is -/// private from the moment it exists. Restricting a file after creating it leaves a window in which another user -/// whom the parent folder lets read it can open a handle, and Windows checks access only when a -/// handle is opened, so a later change of the list doesn't revoke it. A handle on the folder -/// itself, opened during the folder's own window, gives no access to the files created in it -/// later. The folder is removed again when it can't be restricted. +/// Create the folder `dir`, which must not exist yet and whose parent must, with user `me` (as for +/// [`restrict_to_owner`]) as its owner and an access list of that user and SYSTEM only, which every +/// file created in it inherits, given to Windows in the call that creates the folder. The folder +/// never has its parent's access list, and a file created in it is private from the moment it +/// exists. The folder is created beside `dir` under a name of its own +/// (`....tmp`) and then moved to `dir`, which fails when `dir` exists. +/// Then check its descriptor, inherit-only entries included. An existing `dir` is an error of kind +/// [`std::io::ErrorKind::AlreadyExists`] and a missing parent one of kind +/// [`std::io::ErrorKind::NotFound`]; the folder is removed again when the check fails. +/// +/// PowerShell is ended when it takes longer than [`TOOL_LIMIT`], and the call fails with an error +/// of kind [`std::io::ErrorKind::TimedOut`]; the folder under its own name is then removed once +/// PowerShell has exited. A folder PowerShell had already moved to `dir` stays there, with the +/// access list it was created with: this call can't tell it from a folder another process put at +/// `dir` since, so it doesn't remove what is there. #[cfg(windows)] pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<()> { - std::fs::create_dir(dir)?; - fn restrict(dir: &std::path::Path, me: &str) -> std::io::Result<()> { - set_access_list(dir, me, Kind::Folder)?; - icacls(dir, &["/setowner".into(), format!("*{me}")])?; - still_foreign(&sddl_of(dir)?, me) + use std::sync::atomic::{AtomicU64, Ordering}; + /// Numbers the staged folders of this process. + static COUNT: AtomicU64 = AtomicU64::new(0); + // No double quotes: the command line would strip them. `Directory.CreateDirectory` also creates + // a missing parent and returns an existing folder as it is, hence the checks before it. + // `Directory.Move` doesn't replace an existing folder (`std::fs::rename` does, when it is + // empty). + const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \ + if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; \ + if (-not [IO.Directory]::Exists([IO.Path]::GetDirectoryName($env:CRAFT_ACL_PATH))) { exit 4 }; \ + if (Test-Path -LiteralPath $env:CRAFT_ACL_STAGED) { exit 5 }; \ + $s = New-Object Security.AccessControl.DirectorySecurity; \ + $s.SetSecurityDescriptorSddlForm('O:' + $env:CRAFT_ACL_USER + 'D:P(A;OICI;FA;;;' + $env:CRAFT_ACL_USER + ')(A;OICI;FA;;;SY)'); \ + [void][IO.Directory]::CreateDirectory($env:CRAFT_ACL_STAGED, $s); \ + try { [IO.Directory]::Move($env:CRAFT_ACL_STAGED, $env:CRAFT_ACL_PATH) } \ + catch { [IO.Directory]::Delete($env:CRAFT_ACL_STAGED); if (Test-Path -LiteralPath $env:CRAFT_ACL_PATH) { exit 3 }; throw }"; + // A relative `dir` such as `private` has no parent in its text; the script needs one. + let dir = &std::path::absolute(dir)?; + let name = dir.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let staged = dir.with_file_name(format!(".{name}.{}.{}.tmp", std::process::id(), COUNT.fetch_add(1, Ordering::Relaxed))); + let mut powershell = system_tool(POWERSHELL); + powershell + .args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]) + .env("CRAFT_ACL_PATH", dir) + .env("CRAFT_ACL_STAGED", &staged) + .env("CRAFT_ACL_USER", me); + let deadline = std::time::Instant::now() + TOOL_LIMIT; + let close = |stdin: std::process::ChildStdin| { + drop(stdin); + Ok(()) + }; + let out = match run_until(powershell, close, |_| std::time::Instant::now() >= deadline)? { + Ran::Exited(out, _) => out, + Ran::Ended { exited } => { + if exited { + let _ = std::fs::remove_dir(&staged); + } + return Err(timed_out("powershell.exe")); + } + }; + match out.status.code() { + Some(3) => return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the folder already exists")), + Some(4) => return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "the folder's parent does not exist")), + _ if !out.status.success() => { + return Err(std::io::Error::other(format!( + "PowerShell could not create the folder for its owner only: {}", + String::from_utf8_lossy(&out.stderr).trim() + ))); + } + _ => {} } - let restricted = restrict(dir, me); - if restricted.is_err() { + let checked = sddl_of(dir).and_then(|sddl| match foreign_folder_access(&sddl, me) { + None => Ok(()), + Some(problem) => Err(std::io::Error::other(format!("the folder could not be restricted to its owner: {problem}"))), + }); + if checked.is_err() { let _ = std::fs::remove_dir(dir); } - restricted + checked } /// Create the file `path`, which must not exist yet, with user `me` (as for [`restrict_to_owner`]) @@ -338,8 +405,9 @@ pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<() /// /// PowerShell is ended when it takes longer than [`TOOL_LIMIT`], and the call fails with an error /// of kind [`std::io::ErrorKind::TimedOut`]. The file under its own name is then removed. If -/// PowerShell is not seen to exit after being ended, that file may stay; it still has the access -/// list given when it was created. +/// PowerShell is not seen to exit after being ended, that file may stay, and a file PowerShell had +/// already moved to `path` stays there: this call can't tell it from a file another process put at +/// `path` since. Either still has the access list given when it was created. #[cfg(windows)] pub fn create_private_file(path: &std::path::Path, me: &str, contents: &[u8]) -> std::io::Result<()> { use std::io::Write as _; @@ -424,34 +492,17 @@ fn still_foreign(sddl: &str, me: &str) -> std::io::Result<()> { } } -/// What [`set_access_list`] restricts: a file, or a folder whose entries the files and folders -/// created in it inherit. +/// Set file `path`'s access list to Full control for `me` and SYSTEM and nothing else, protected +/// from inheritance. Only the list is written, not the owner. `me` and the path reach PowerShell +/// through environment variables, never as script text. #[cfg(windows)] -#[derive(Clone, Copy)] -enum Kind { - File, - Folder, -} - -/// Set `path`'s access list to Full control for `me` and SYSTEM and nothing else, protected from -/// inheritance; on a folder, what is created in it inherits the two entries. Only the list is -/// written, not the owner. `me` and the path reach PowerShell through environment variables, never -/// as script text. -#[cfg(windows)] -fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Result<()> { +fn set_access_list(path: &std::path::Path, me: &str) -> std::io::Result<()> { // No double quotes: the command line would strip them. - const FILE: &str = "$s = New-Object Security.AccessControl.FileSecurity; \ + const SCRIPT: &str = "$s = New-Object Security.AccessControl.FileSecurity; \ $s.SetSecurityDescriptorSddlForm('D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)', 'Access'); \ [IO.File]::SetAccessControl($env:CRAFT_ACL_PATH, $s)"; - const FOLDER: &str = "$s = New-Object Security.AccessControl.DirectorySecurity; \ - $s.SetSecurityDescriptorSddlForm('D:P(A;OICI;FA;;;' + $env:CRAFT_ACL_USER + ')(A;OICI;FA;;;SY)', 'Access'); \ - [IO.Directory]::SetAccessControl($env:CRAFT_ACL_PATH, $s)"; - let script = match kind { - Kind::File => FILE, - Kind::Folder => FOLDER, - }; let mut powershell = system_tool(POWERSHELL); - powershell.args(["-NoProfile", "-NonInteractive", "-Command", script]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_USER", me); + powershell.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).env("CRAFT_ACL_USER", me); let out = run(powershell)?; if out.status.success() { Ok(()) @@ -512,12 +563,15 @@ pub fn read_with_sddl(path: &std::path::Path, max: u64) -> std::io::Result<(Stri /// The security descriptor of `path` as [`read_with_sddl`] writes it, read by name without opening /// the file's contents, so it works on a file that is open for writing (an app restricts its -/// token file before writing the token through the handle it created). +/// token file before writing the token through the handle it created). A folder is read as a +/// folder, so its inherit-only entries are included (`IO`); a file's reading leaves them out. #[cfg(windows)] pub fn sddl_of(path: &std::path::Path) -> std::io::Result { const SCRIPT: &str = concat!( // Stop: a failed read (a missing file) must end the script with an error, not print `O:`. - "$ErrorActionPreference = 'Stop'; $raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @([IO.File]::GetAccessControl($env:CRAFT_ACL_PATH).GetSecurityDescriptorBinaryForm(), 0); ", + "$ErrorActionPreference = 'Stop'; $p = $env:CRAFT_ACL_PATH; \ + if ([IO.Directory]::Exists($p)) { $sec = [IO.Directory]::GetAccessControl($p) } else { $sec = [IO.File]::GetAccessControl($p) }; \ + $raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @($sec.GetSecurityDescriptorBinaryForm(), 0); ", describe_raw!(), "[Console]::Out.Write($sddl + [char]10)" ); @@ -619,6 +673,15 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256) assert!(foreign_access("D:(A;;FA;;;SY)", ME).unwrap().contains("owner")); } + /// An inherit-only entry doesn't apply to a file, but does to what's created in a folder. + #[test] + fn an_inherit_only_entry_counts_for_a_folder_only() { + let sddl = format!("O:{ME}D:(A;;FA;;;{ME})(A;IO;FR;;;BU)"); + assert_eq!(foreign_access(&sddl, ME), None, "{sddl}"); + assert!(foreign_folder_access(&sddl, ME).is_some_and(|p| p.contains("BU")), "{sddl}"); + assert_eq!(foreign_folder_access(&format!("O:{ME}D:(A;;FA;;;{ME})(A;IO;FA;;;SY)"), ME), None); + } + /// A conditional entry can hold a `:` in a string; the access list doesn't end there, so the /// entry after it is still checked. #[test] @@ -704,6 +767,52 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256) let _ = std::fs::remove_dir_all(&dir); } + /// A folder's inherit-only entries are read, and the folder check counts them: every file + /// created in the folder would get them. + #[cfg(windows)] + #[test] + fn a_folders_inherit_only_entries_are_read_and_refused() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-inherit-only-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)(IO)R").output().unwrap(); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); + let sddl = sddl_of(&dir).unwrap(); + assert!(sddl.contains(";IO;") && sddl.contains(";S-1-5-32-545)"), "the inherit-only entry for Users is read: {sddl}"); + let me = current_user_sid().unwrap(); + assert!(foreign_folder_access(&sddl, &me).is_some_and(|p| p.contains("S-1-5-32-545")), "{sddl}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// `create_private_dir` gives the folder its owner and list in the call that creates it, so in + /// a folder that lets Users read what's created in it, no step leaves the new folder with that + /// entry: the folder is moved to its name only after it was created with its own list. An + /// existing name and a missing parent are refused. + #[cfg(windows)] + #[test] + fn a_private_folder_has_its_list_from_the_start() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-private-dir-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); + let me = current_user_sid().unwrap(); + let private = dir.join("staging"); + let made = create_private_dir(&private, &user()); + assert!(made.is_ok(), "{made:?}"); + let folder = sddl_of(&private).unwrap(); + assert_eq!((section(&folder, "O:"), foreign_folder_access(&folder, &me)), (Some(me.as_str()), None), "{folder}"); + assert!(!folder.contains(";S-1-5-32-545)") && !folder.contains(";BU)"), "Users must not inherit read access: {folder}"); + let names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(names, ["staging"], "no folder is left under its own name"); + let again = create_private_dir(&private, &user()).unwrap_err(); + assert_eq!(again.kind(), std::io::ErrorKind::AlreadyExists, "{again}"); + let orphan = create_private_dir(&dir.join("missing").join("staging"), &user()).unwrap_err(); + assert_eq!(orphan.kind(), std::io::ErrorKind::NotFound, "{orphan}"); + assert!(!dir.join("missing").exists()); + let _ = std::fs::remove_dir_all(&dir); + } + /// A file created by `create_private_file` in a folder that lets Users read what's in it is the /// user's alone as soon as it exists, with nothing written to it yet; one created with contents /// holds them, and an existing file is refused and left as it is. From 1418db7abe97298700d3baed74d4e2466b093c0a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 12:03:01 -0800 Subject: [PATCH 138/269] control: a token file create that owner_only timed out takes the timed-out path owner_only now ends a whoami or PowerShell run after 10 seconds and returns ErrorKind::TimedOut. create_within treats that error, when it arrives before its own 10-second wait ends, the same as a create it stopped waiting for: a CONTROL_DIR folder gets no token and the default folder gets the file with that folder's access list. Before, the default folder returned the error and got no token file. --- crates/control/src/auth.rs | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/control/src/auth.rs b/crates/control/src/auth.rs index d3cc93a358..1f3438a0fa 100644 --- a/crates/control/src/auth.rs +++ b/crates/control/src/auth.rs @@ -143,7 +143,7 @@ impl App { /// Write `token` to `path`, readable and writable only by the user: the folder is made `0700` /// and the file `0600` on Unix; on Windows the file is created with an access list of the user /// and SYSTEM only and the token is written through the handle that created it - /// ([`create_for_user`]), so the file never has its folder's access list. A file left by an + /// (`create_for_user`), so the file never has its folder's access list. A file left by an /// earlier launch is replaced. The process file beside it ([`pid_path`]) records this process, /// best effort. pub fn write_token_file(&self, path: &Path, token: &str) -> Result<()> { @@ -369,7 +369,7 @@ fn held_by_another(path: &Path, token: &str) -> bool { /// Create `path`, which must not exist yet, holding `contents`: mode `0600` on Unix. On Windows a /// file created this way has its folder's access list; the token file there is made by -/// [`create_for_user`]. +/// `create_for_user`. fn create_new_file(path: &Path, contents: &[u8]) -> Result<()> { let mut opts = std::fs::OpenOptions::new(); opts.write(true).create_new(true); @@ -423,8 +423,9 @@ fn not_waited_for(path: &Path, contents: &[u8], custom_folder: bool) -> Result<( /// (`....tmp`), and the file takes the name `path` only once `private` /// has finished, so `path` never holds a file that is still being written: with `replace` by a /// rename that replaces a file another launch put there meanwhile, otherwise by [`place_new`], -/// which leaves that file and fails. When -/// the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its +/// which leaves that file and fails. When `private` fails with [`ErrorKind::TimedOut`] (a tool +/// `craft_platform::owner_only` ended after its own limit), [`not_waited_for`] gives the result. +/// When the thread hasn't finished in time, [`not_waited_for`] gives the result, the thread removes its /// file whenever it does finish, and `stuck` counts it until then. While `stuck` counts any /// thread, no other thread is started and [`not_waited_for`] answers at once, so a computer that /// leaves new processes suspended holds at most the threads that were started together. The @@ -484,7 +485,11 @@ fn create_within( } } }; - let placed = made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }); + let placed = match made { + // `owner_only` ended a tool that ran out of its own time: the same as not waiting. + Err(e) if e.kind() == ErrorKind::TimedOut => not_waited_for(path, contents, custom_folder), + made => made.and_then(|()| if replace { std::fs::rename(&staged, path) } else { place_new(&staged, path) }), + }; let _ = std::fs::remove_file(&staged); (placed, Some(handle)) } @@ -529,7 +534,7 @@ mod tests { /// finishes and never takes the token file's name, even when a later write has put a file /// there. While it runs, the next create starts no thread of its own. A create that finishes in /// time puts its file in place unless a file already has the name, and one that fails leaves - /// nothing. + /// nothing. A create that fails as timed out by itself is taken as one not waited for. #[test] fn a_private_create_that_does_not_finish_in_time_is_not_waited_for() { use std::sync::atomic::{AtomicUsize, Ordering}; @@ -594,6 +599,21 @@ mod tests { assert!(made.is_err()); handle.unwrap().join().unwrap(); assert_eq!(names(), ["quick.token"]); + // A create whose tool was ended after its own limit, within this one, is taken as one + // that was not waited for. + let ended = + |_: &Path, _: &[u8]| -> Result<()> { Err(Error::new(ErrorKind::TimedOut, "powershell.exe did not finish within 10 s and was ended")) }; + let path = dir.join("ended.token"); + let (made, handle) = create_within(&path, b"ended\n", true, false, Duration::from_secs(600), &STUCK, ended); + assert_eq!(made.unwrap_err().kind(), ErrorKind::TimedOut); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["quick.token"]); + let (made, handle) = create_within(&path, b"ended\n", false, false, Duration::from_secs(600), &STUCK, ended); + made.unwrap(); + handle.unwrap().join().unwrap(); + assert_eq!(names(), ["ended.token", "quick.token"]); + assert_eq!(read_token(&path).as_deref(), Some("ended")); + assert_eq!(STUCK.load(Ordering::Acquire), 0); let _ = std::fs::remove_dir_all(&dir); } From 97ce4a2bea13080a38a49e42ad82f4747db69e18 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 25 Nov 2026 00:36:30 +0100 Subject: [PATCH 139/269] 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 140/269] 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 3a0f4565281cb3edca7949399dfaca2c4895c9e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:31:10 -0800 Subject: [PATCH 141/269] color-ui: HarmonyPanel's variation end labels sit at the two edges of the grid The row under the variations grid holds the two end labels (Shades and Tints, Cool and Warm, Muted and Vivid). It is aligned SpaceBetween but was not made full width, so it was only as wide as its two labels and they sat together at the left. The row now fills the panel's width: the left label starts at the grid's left edge and the right label ends at its right edge. --- crates/color-ui/src/ui/harmony.rs | 2 +- crates/color-ui/tests/it/panels.rs | 21 +++++++++++++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/color-ui/src/ui/harmony.rs b/crates/color-ui/src/ui/harmony.rs index a153276ada..254d30f628 100644 --- a/crates/color-ui/src/ui/harmony.rs +++ b/crates/color-ui/src/ui/harmony.rs @@ -522,7 +522,7 @@ impl<'a> HarmonyPanel<'a> { Variation::WarmCool => (&words.cool, &words.warm), Variation::VividMuted => (&words.muted, &words.vivid), }; - Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| { + Row::new().fill_width().align(RowAlign::SpaceBetween).show(ui, |ui, _| { Text::new(left.clone()).show(ui); Text::new(right.clone()).show(ui); }); diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index 840a36c56a..c915848cd9 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -7,8 +7,9 @@ use std::rc::Rc; use craft_behavior::{EditEvent, Mixed, Selection}; use craft_color_ui::palette::{SwatchColor, SwatchGroup}; use craft_color_ui::ui::{ - ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyWheel, PanelTarget, PickedColor, SwatchEdit, SwatchKey, - SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, SwatchesWords, swatch_rows, + ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelShown, ColorPanelState, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel, + PanelTarget, PickedColor, SwatchEdit, SwatchKey, SwatchLibrary, SwatchPalette, SwatchesCommand, SwatchesMenu, SwatchesPanel, SwatchesState, + SwatchesWords, swatch_rows, }; use craft_host::target::Os; use craft_theme::{ColorModel as _, HsbModel, Srgba}; @@ -768,3 +769,19 @@ fn a_click_on_a_harmony_wheel_marker_reports_it() { fixture.click(&marker).idle(1); assert_eq!(clicked.get(), Some(Some(1)), "the click names the second marker"); } + +/// The Color Guide's variation end labels sit at the two sides of the grid: Shades at its left edge and Tints at its +/// right edge. +#[trial] +fn the_color_guide_end_labels_sit_at_the_two_sides_of_the_grid() { + let mut fixture = Fixture::new(|ui| { + let (mut state, mut picked) = (HarmonyPanelState::default(), HarmonyPicked::default()); + let _ = HarmonyPanel::new(Bind::bound(&mut state), Bind::bound(&mut picked), RED).show(ui); + }); + fixture.room(COLOR_ROOM).settle(); + let grid = fixture.by_label("Variations").expect("the variations grid").rect; + let run = |text: &str| fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text} is painted")); + let (shades, tints) = (run("Shades"), run("Tints")); + assert!(shades.left() <= grid.left() + 1.0 && shades.right() < grid.center().x, "Shades {shades:?} starts at the left edge of {grid:?}"); + assert!(tints.right() >= grid.right() - 1.0 && tints.left() > grid.center().x, "Tints {tints:?} ends at the right edge of {grid:?}"); +} From 6642934ce68542c46ef6f42bd015c5ca184d26a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:33:33 -0800 Subject: [PATCH 142/269] color-ui: the FillStroke Color panel shows its Recent Colors caption while the host's list is empty, as production drew the labeled empty row; a host that gives no recent colors (ColorPanel::recent not called) still shows no row --- crates/color-ui/src/ui/panel.rs | 11 ++++++----- crates/color-ui/src/ui/panel/fill_stroke.rs | 14 +++++++++---- crates/color-ui/tests/it/panels.rs | 22 +++++++++++++++++++++ 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 90c92271b2..d79e86cf93 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -448,7 +448,7 @@ pub struct ColorPanel<'a> { wells: Option<([PairWell; 2], Bind<'a, Well>)>, edited: Option>, shown: Option, - recent: &'a [Srgba], + recent: Option<&'a [Srgba]>, recent_setup: Option, gamut: Option>, } @@ -471,7 +471,7 @@ struct Inputs<'a> { wells: Option<&'a [PairWell; 2]>, edited: Option<&'a Option>, shown: &'a ColorPanelShown, - recent: &'a [Srgba], + recent: Option<&'a [Srgba]>, recent_setup: Option<&'a RecentSetup>, } @@ -488,7 +488,7 @@ impl<'a> ColorPanel<'a> { wells: None, edited: None, shown: None, - recent: &[], + recent: None, recent_setup: None, gamut: None, } @@ -541,9 +541,10 @@ impl<'a> ColorPanel<'a> { self } - /// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. + /// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. The FillStroke layout shows the captioned row + /// for a host that gives them, an empty list included; without them it shows no row. pub fn recent(mut self, colors: &'a [Srgba]) -> Self { - self.recent = colors; + self.recent = Some(colors); self } diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index a3ff66c160..483f690885 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -6,10 +6,11 @@ use craft_behavior::{EditEvent, Mixed}; use craft_theme::Srgba; use craft_ui::choice::{Swatch, SwatchSpacing}; use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; -use craft_ui::display::Text; +use craft_ui::display::{Shade, Text}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::runtime::env::Label; +use craft_ui::style::TypeRole; use craft_ui::text::{HexField, TextField}; use egui::Ui; @@ -154,14 +155,19 @@ impl Body<'_> { } } - /// The Recent Colors as a spaced palette; a pick sets the colour. + /// The Recent Colors caption over a spaced palette; a pick sets the color. The caption shows while the host's list + /// is empty, where the first applied color will go. // PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and // `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip). fn recent(&mut self, ui: &mut Ui) { - if self.inputs.recent.is_empty() { + let Some(recent) = self.inputs.recent else { + return; + }; + Text::new(self.words.recent_colors.clone()).role(TypeRole::Caption).shade(Shade::Faint).show(ui); + if recent.is_empty() { return; } - let swatches: Vec<(Label, Srgba)> = self.inputs.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); + let swatches: Vec<(Label, Srgba)> = recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); let mut current = self.color(); let mut palette = SwatchPalette::new(self.words.recent_colors.clone(), Bind::bound(&mut current), &swatches).spacing(SwatchSpacing::Spaced); if let Some(setup) = self.inputs.recent_setup { diff --git a/crates/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index 840a36c56a..1a2f359245 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -408,6 +408,28 @@ fn the_other_cell_files_a_request_at_the_colour_and_a_recent_pick_sets_it() { assert_eq!(taken.picked.iter().map(|c| c.to_rgba()).collect::>(), [swatch("Violet").to_rgba()], "and still reports the pick"); } +/// The FillStroke layout shows its Recent Colors caption while the host's list is empty, as it does with colors in +/// it; a host that gives no recent colors gets no row. +#[trial] +fn a_fill_stroke_panel_shows_its_recent_colors_row_while_the_list_is_empty() { + let caption = |recent: Option<&'static [Srgba]>| { + let mut fixture = Fixture::new(move |ui| { + let mut state = ColorPanelState::default(); + let panel = ColorPanel::new(Bind::bound(&mut state), [RED, BLUE]).layout(ColorPanelLayout::FillStroke); + let _ = match recent { + Some(colors) => panel.recent(colors), + None => panel, + } + .show(ui); + }); + fixture.room(COLOR_ROOM).settle(); + fixture.texts().iter().any(|run| run.text == "Recent Colors") + }; + assert!(caption(Some(&[])), "an empty list shows the row's caption"); + assert!(caption(Some(&RECENT)), "a list with a color shows it"); + assert!(!caption(None), "a host with no recent colors shows no row"); +} + /// A palette over a colour that may be none, bound to no colour: no swatch is selected and Tab enters on the first; /// a click writes `Same(Some(colour))` and reports one `Set` from `Mixed`. #[trial] From ccf616d1f988a00801b1fc58a7ab18121f689699 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:29:48 -0800 Subject: [PATCH 143/269] color-ui: the FillStroke Color panel's Spectrum ramp is at least as tall as its two square end boxes (ColorRamp::square_boxes, 40 pt in Compact), near production's 46 pt floor, instead of a 10 pt band in a panel sized by its content --- crates/color-ui/src/ui/panel/fill_stroke.rs | 5 ++-- crates/color-ui/src/ui/ramp.rs | 16 ++++++++-- crates/color-ui/tests/it/panels.rs | 33 ++++++++++++++++++++- 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs index a3ff66c160..3b915e793f 100644 --- a/crates/color-ui/src/ui/panel/fill_stroke.rs +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -131,8 +131,8 @@ impl Body<'_> { } } - /// The Spectrum ramp (grey in Grayscale) with a tooltip naming the shown mode. A Cmd or Ctrl click recolours and - /// picks nothing; a Shift click moves to the next mode. + /// The Spectrum ramp (gray in Grayscale) with a tooltip naming the shown mode, at least as tall as its square end + /// boxes. A Cmd or Ctrl click recolors and picks nothing; a Shift click moves to the next mode. fn spectrum(&mut self, ui: &mut Ui) { let mode = self.shown_mode(); let kind = if mode == ColorPanelMode::GrayscaleSlider { RampKind::Grayscale } else { RampKind::Spectrum }; @@ -145,6 +145,7 @@ impl Body<'_> { .gamut(gamut) .gamut_revision(revision) .web_safe(self.now.web_safe_ramp) + .square_boxes(true) .sizing(Sizing::Fill) .show(ui); self.ramp_events(ramp.edit.events); diff --git a/crates/color-ui/src/ui/ramp.rs b/crates/color-ui/src/ui/ramp.rs index 2a01579348..e541695543 100644 --- a/crates/color-ui/src/ui/ramp.rs +++ b/crates/color-ui/src/ui/ramp.rs @@ -6,8 +6,8 @@ use craft_cms::convert::CmykConverter; use craft_theme::{Hsb, Srgba}; use craft_ui::canvas::context_click; use craft_ui::contract::{ - Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, Name, Outcome, PaintUi, PartsCx, - Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, + Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Outcome, PaintUi, + PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, }; use craft_ui::primitives::{Marker, PaintShape, StrokeWidth}; use craft_ui::runtime::commands::FireSource; @@ -240,6 +240,11 @@ pub struct ColorRamp<'a> { /// Whether the white and black boxes follow the bar; on by default. #[prop] boxes: bool, + /// Whether the ramp is at least as tall as its two end boxes stacked, each as tall as it is wide, in place of a + /// color band; off by default. A ramp that takes the room under other rows keeps this height in a host sized by + /// its content and in a short one. + #[prop] + square_boxes: bool, /// The ramp's kind as the host names it ("RGB Spectrum"), the bar's accessible value. #[prop(into)] kind_name: Option

    { /// goes back. #[serde(default)] hidden: Vec<(P, Location

    )>, - /// Floating panels with the docked location each one left, so Dock Panel can return it. Saved with the - /// workspace. + /// Floating panels with the docked location each one left, so Dock Panel can return it; a closed panel that + /// floats records the place it would reopen at. Saved with the workspace. #[serde(default, skip_serializing_if = "Vec::is_empty")] floated: Vec<(P, Location

    )>, /// Counts the replacements of this live workspace. Not saved, and not part of equality. @@ -264,6 +264,16 @@ impl Workspace

    { Action::Open { panel, .. } if proposed.hidden.iter().any(|(p, _)| p == panel) => proposed.reopen(panel, &policy)?, _ => false, }; + // Floating a hidden panel records the docked place it would reopen at, without reopening it there. A panel + // that would reopen in a floating window has no docked place. + let hidden_place = match &action { + Action::Float { panel, .. } if !proposed.layout.contains(panel) && proposed.hidden.iter().any(|(p, _)| p == panel) => proposed + .restored(panel, &policy) + .filter(|restored| !floats(&restored.layout, panel)) + .and_then(|restored| restored.layout.location(panel).ok()) + .map(|location| (panel.clone(), location)), + _ => None, + }; if !reopened { // SetNative records where the window system has a floating window, so a lock // does not refuse it. @@ -278,6 +288,12 @@ impl Workspace

    { proposed.hidden.push((panel, location)); } proposed.track_floated(&before); + if let Some((panel, location)) = hidden_place + && floats(&proposed.layout, &panel) + && !proposed.floated.iter().any(|(p, _)| p == &panel) + { + proposed.floated.push((panel, location)); + } all_closed.extend(closed); } let visible: HashSet

    = proposed.layout.panels().into_iter().cloned().collect(); diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index 1d25354fdc..b6eea87da1 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -241,6 +241,35 @@ fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { assert!(workspace.floated().is_empty(), "closing drops the record"); } +/// A closed panel that floats by itself records the place it would reopen at, as opening it first records, and its old +/// group keeps its front tab; docking it then returns it to that group at its old index. +#[test] +fn a_closed_panel_that_floats_keeps_its_docked_place_and_its_old_group_keeps_its_front_tab() { + let float = Action::float(2, rect(10.0, 10.0, 200.0, 200.0)); + let mut opened = Workspace::new(docked()); + opened.apply(Action::close(2), false, allow).unwrap(); + opened.apply_all([Action::open(2, None), float.clone()], false, allow).unwrap(); + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(2), false, allow).unwrap(); + workspace.apply(float, false, allow).unwrap(); + let layout = workspace.layout(); + assert!(matches!(layout.place(&2), Some(PanelPlace::Floating { .. }))); + assert_eq!(group_members(layout, 3), [3]); + assert_eq!(front(layout, 3), 3, "the old group keeps its front tab"); + assert_eq!(workspace.floated(), opened.floated(), "the record matches the one opening it first gives"); + + let [(_, location)] = workspace.floated() else { panic!("one record: {:?}", workspace.floated()) }; + let back = Action::move_beside(2, location.anchor.unwrap(), location.placement.clone()); + workspace.apply(back, false, allow).unwrap(); + assert_eq!(end_dock(workspace.layout())[0].groups[0].panels, [2, 3], "Dock Panel returns it to its old index"); + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(6), false, allow).unwrap(); + workspace.apply(Action::float(6, rect(10.0, 10.0, 200.0, 200.0)), false, allow).unwrap(); + assert!(workspace.floated().is_empty(), "a panel closed from a floating window has no docked place"); +} + /// Canvas 1; an end dock with an expanded column [2] and a collapsed column [3], [4]; a floating window [6]. fn columns() -> Layout { let dock = Node::dock(DockEdge::End, vec![Column::new(vec![g(&[2], 0)]), Column::new(vec![g(&[3], 0), g(&[4], 0)]).with_iconic(true)]); From 52a090c6428fe235896f2f051c02102833684ddc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 00:48:05 -0800 Subject: [PATCH 160/269] behavior: a Fill column raised to its least takes the difference from the other Fill columns, so a grid whose least widths fit no longer overflows GridCursor::new raised each Fill column's share to the column's least width but left the other Fill columns at their shares, so the row was wider than the grid by the difference even when the least widths fit. The Fill columns now share their room again: a column whose share by weight is below its least takes its least, and the other Fill columns share what is left by weight, down to their own least widths. The row is wider than the grid only when the least widths together do not fit. A grid whose shares already cover every least width is unchanged. --- crates/behavior/src/grid.rs | 86 ++++++++++++++++++++++++++++++++++--- 1 file changed, 80 insertions(+), 6 deletions(-) diff --git a/crates/behavior/src/grid.rs b/crates/behavior/src/grid.rs index bd782a0e9c..103a97fcf0 100644 --- a/crates/behavior/src/grid.rs +++ b/crates/behavior/src/grid.rs @@ -85,15 +85,12 @@ pub struct GridCursor { impl GridCursor { /// A cursor over `columns` in `flow`'s rect, with `gap` between columns (x) and rows (y), placed by `last`. A /// column is never narrower than its least in `last`: a `Content` column starts there, and a `Fill` column's share - /// does not go below it. + /// does not go below it. A `Fill` column raised to its least takes the difference from the other `Fill` columns. pub fn new(flow: Flow, columns: &[ColumnWidth], gap: Vec2, last: &GridMeasure) -> Self { let least = |i: usize| last.least.get(i).copied().unwrap_or(0.0); let content: Vec = (0..columns.len()).map(|i| last.columns.get(i).copied().unwrap_or(0.0).max(least(i))).collect(); - let widths = resolve_columns(columns, &content, flow.rect().width(), gap.x) - .into_iter() - .enumerate() - .map(|(i, width)| if matches!(columns[i], ColumnWidth::Fill { .. }) { width.max(least(i)) } else { width }) - .collect(); + let mut widths = resolve_columns(columns, &content, flow.rect().width(), gap.x); + keep_fill_least(columns, &mut widths, least); let fills = columns.iter().map(|kind| matches!(kind, ColumnWidth::Fill { .. })).collect(); GridCursor { flow, @@ -266,6 +263,44 @@ impl GridCursor { } } +/// Shares the room the `Fill` columns of `widths` hold among them again so that none is narrower than its `least`: a +/// column whose share by weight is below its least takes its least, and the columns left share the rest by weight. +/// The fill columns together take more than their room only when their least widths do not fit in it. +fn keep_fill_least(columns: &[ColumnWidth], widths: &mut [f32], least: impl Fn(usize) -> f32) { + let fills: Vec<(usize, f32)> = columns + .iter() + .enumerate() + .filter_map(|(i, column)| if let ColumnWidth::Fill { weight } = column { Some((i, *weight)) } else { None }) + .collect(); + let room: f32 = fills.iter().map(|(i, _)| widths[*i]).sum(); + if !room.is_finite() { + // Room with no bound leaves every share above its least. + for (i, _) in &fills { + widths[*i] = widths[*i].max(least(*i)); + } + return; + } + let mut raised = vec![false; columns.len()]; + loop { + let left = room - fills.iter().filter(|(i, _)| raised[*i]).map(|(i, _)| least(*i)).sum::(); + let weights: f32 = fills.iter().filter(|(i, _)| !raised[*i]).map(|(_, weight)| weight).sum(); + let share = |weight: f32| if weights > 0.0 { left.max(0.0) * weight / weights } else { 0.0 }; + let mut more = false; + for (i, weight) in &fills { + if !raised[*i] && share(*weight) < least(*i) { + raised[*i] = true; + more = true; + } + } + if !more { + for (i, weight) in &fills { + widths[*i] = if raised[*i] { least(*i) } else { share(*weight).max(least(*i)) }; + } + return; + } + } +} + /// `columns` with each `Fill` column as a `Content` column. fn as_content(columns: &[ColumnWidth]) -> Vec { columns.iter().map(|kind| if matches!(kind, ColumnWidth::Fill { .. }) { ColumnWidth::Content } else { *kind }).collect() @@ -288,4 +323,43 @@ mod tests { cursor.cell(Vec2::new(150.0, 100.0)); assert_eq!(cursor.room(), Vec2::new(200.0, 100.0), "the content cell may take what the fill column holds"); } + + /// The widths of one row of `columns` placed by `last`, read from the cells. + fn row_widths(columns: &[ColumnWidth], last: &GridMeasure) -> Vec { + let mut cursor = GridCursor::new(flow(false), columns, Vec2::ZERO, last); + columns.iter().map(|_| cursor.cell(Vec2::new(10.0, 10.0)).width()).collect() + } + + #[test] + fn a_fill_column_raised_to_its_least_takes_the_difference_from_the_other_fill_columns() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(2.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let fitting = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]); + let shares = row_widths(&columns, &fitting); + let raised = row_widths(&columns, &fitting.clone().with_least(vec![120.0, 0.0, 0.0, 0.0])); + assert!(shares[0] < 120.0, "the first column's share is below its least"); + assert!(raised[0] >= 120.0, "the first column keeps its least"); + assert!(raised[1] < shares[1] && raised[2] < shares[2], "the other fill columns narrow"); + assert_eq!(raised[1], 2.0 * raised[2], "the other fill columns keep their weights"); + assert_eq!(raised[3], shares[3], "the content column keeps its width"); + assert_eq!(raised.iter().sum::(), 300.0, "the row fills the grid and no more"); + } + + #[test] + fn fill_columns_whose_least_widths_do_not_fit_take_their_least_widths() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]).with_least(vec![200.0, 70.0, 0.0, 0.0]); + let widths = row_widths(&columns, &last); + assert!(widths[0] >= 200.0 && widths[1] >= 70.0, "each fill column keeps its least"); + assert_eq!(widths[2], 0.0, "the fill column with no least gives up its room"); + assert_eq!(widths.iter().sum::(), 330.0, "the row is as wide as the least widths and no wider"); + } + + #[test] + fn fill_columns_whose_shares_cover_their_least_widths_keep_their_shares() { + let columns = [ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::fill(1.0), ColumnWidth::Content]; + let last = GridMeasure::new(vec![0.0, 0.0, 0.0, 60.0], vec![10.0]); + let shares = row_widths(&columns, &last); + let kept = row_widths(&columns, &last.clone().with_least(vec![50.0, 50.0, 50.0, 0.0])); + assert_eq!(kept, shares); + } } From 55756099eefff805eb000a3101f1340a23d56776 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 01:34:50 -0800 Subject: [PATCH 161/269] ui-contract: every row of a label group that stacks takes the stacked height When a FieldGroup's shared label column grows too wide for its room, each field puts its control under its label. The rows measured before the widest label read a narrower column in the measuring run, sat beside it and kept that height. The real run stacked them at the final column, so their controls overlapped the next row and their values were clipped to a 1 pt band. The label step now notes, in a measuring run, the widest column at which a row that placed its label beside the group's column (or indented a row after it, or left a hidden label's column empty) keeps that placement. When the group's final column is wider, the group reports its widths as unsettled and its rows run once more at them, as for a sized row that read a narrower column. A group whose rows all keep their placement runs as before. --- .../ui-contract/src/contract/label/place.rs | 22 ++++++-- crates/ui-contract/src/layout/column_group.rs | 31 +++++++++-- crates/ui-contract/src/layout/mod.rs | 2 +- crates/ui-widgets/tests/it/label/mod.rs | 1 + crates/ui-widgets/tests/it/label/stacked.rs | 55 +++++++++++++++++++ 5 files changed, 100 insertions(+), 11 deletions(-) create mode 100644 crates/ui-widgets/tests/it/label/stacked.rs diff --git a/crates/ui-contract/src/contract/label/place.rs b/crates/ui-contract/src/contract/label/place.rs index 47f510ece6..256e480322 100644 --- a/crates/ui-contract/src/contract/label/place.rs +++ b/crates/ui-contract/src/contract/label/place.rs @@ -59,6 +59,7 @@ pub(super) fn hidden_control(ctx: &egui::Context, input: &LabelIn<'_>, flow: Flo } match crate::layout::ambient_width(ctx, &crate::layout::LABELS, 0.0).filter(|column| *column > 0.0) { Some(column) if input.room >= column + gap + input.control_min => { + crate::layout::note_beside(ctx, &crate::layout::LABELS, input.room - gap - input.control_min); let (_, rest) = flow.take_start(column); rest.take_start(gap).1.rect() } @@ -75,7 +76,10 @@ fn after_indent(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, gap: f32) - return 0.0; } match crate::layout::ambient_width(ctx, &crate::layout::LABELS, 0.0).filter(|column| *column > 0.0) { - Some(column) if input.room >= column + gap + input.control_min => column + gap, + Some(column) if input.room >= column + gap + input.control_min => { + crate::layout::note_beside(ctx, &crate::layout::LABELS, input.room - gap - input.control_min); + column + gap + } _ => 0.0, } } @@ -107,15 +111,17 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let label = Flow::new(rest.rect(), rtl).align(Vec2::new(width, natural.y), Align::Min, Align::Min).translate(Vec2::new(0.0, drop)); return Placed { label, control: cell, trailing: Rect::NOTHING, caption: 0.0 }; } + let key = if glyph { crate::layout::GLYPHS } else { crate::layout::LABELS }; + let mut read = false; let (column, stack_below) = match input.side.layout { FieldLayout::Beside => { let own = natural.x; // An inline form shares no label column unless it asks for one ([`CaptionColumn`]): each caption is as wide // as its own text. let shared = env.values.get::() != LabelScheme::Inline || env.values.get::().shared(); - let width = crate::layout::ambient_width(ctx, &if glyph { crate::layout::GLYPHS } else { crate::layout::LABELS }, own) - .filter(|width| shared && *width > 0.0) - .unwrap_or(own); + let width = crate::layout::ambient_width(ctx, &key, own).filter(|width| shared && *width > 0.0); + read = width.is_some(); + let width = width.unwrap_or(own); (width, width + gap + input.control_min) } FieldLayout::Above => (natural.x, f32::INFINITY), @@ -132,8 +138,12 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let caption = if matches!(input.side.layout, FieldLayout::Above | FieldLayout::Caption(_)) { column } else { 0.0 }; // The room decides; a beside label gets the width it needs even where last frame's content was narrower. A label // that never sits beside stacks in an unbounded room as well. - let stacks = (input.room < stack_below || stack_below == f32::INFINITY) - && !((input.content_row || input.egui_cell) && input.side.layout == FieldLayout::Beside); + let pinned = (input.content_row || input.egui_cell) && input.side.layout == FieldLayout::Beside; + let stacks = (input.room < stack_below || stack_below == f32::INFINITY) && !pinned; + // A label that sits beside the group's column measured so far stacks once the column passes this. + if read && !stacks && !pinned { + crate::layout::note_beside(ctx, &key, input.room - gap - input.control_min); + } // A stacked label has the row's width at most, where its name elides; in an egui grid's cell it keeps its own. let column = if stacks && !input.egui_cell { column.min(input.row.width()) } else { column }; // A beside label that does not stack takes its column, the gap and the control's least, past the row's end where diff --git a/crates/ui-contract/src/layout/column_group.rs b/crates/ui-contract/src/layout/column_group.rs index 105f6af610..7f5fefb513 100644 --- a/crates/ui-contract/src/layout/column_group.rs +++ b/crates/ui-contract/src/layout/column_group.rs @@ -114,8 +114,10 @@ enum Frame { /// sits after (in order from the start edge), the widest the row reaches past them (see [`report_beyond`]). /// `early`: per column, the narrowest width a row that shows at its measured width read in a measuring run: a /// label column read by a row of a `sized` Through frame inside, any other column read by any row. + /// `stays`: per label column, the widest the column could be for every row that placed its label beside it in a + /// measuring run to keep it there (`note_beside`). /// `depth`: the measuring runs open when the group opened (`layout_memory::depth`). - Group { id: Id, widest: Columns, beyond: HashMap, f32>, early: Columns, room: Option, depth: usize }, + Group { id: Id, widest: Columns, beyond: HashMap, f32>, early: Columns, stays: Columns, room: Option, depth: usize }, /// A plain container's body in the group around it: its rows read and report that group's widths, as the rows /// directly in the group do. Their reaches past the columns stay here, and the container hands them on to the /// frame around it (`Reached`). `room`: the width the container was offered. `sized`: the container shows at the @@ -198,7 +200,7 @@ fn column_group(grid: Id, column: usize) -> Id { /// Closes `frame`, a group a measuring run opened: records its widest width per column for the rows of the real run, /// and returns what its rows found. Any other frame found nothing. fn close(ctx: &Context, frame: Frame) -> Scoped { - let Frame::Group { id, widest, beyond, early, .. } = frame else { return Scoped::default() }; + let Frame::Group { id, widest, beyond, early, stays, .. } = frame else { return Scoped::default() }; let mut widths = HashMap::new(); for (column, width) in widest { // A row whose record a later sweep reused reports nothing there, so the widest of the pass stands. @@ -210,7 +212,10 @@ fn close(ctx: &Context, frame: Frame) -> Scoped { .iter() .filter_map(|(columns, past)| columns.iter().map(|column| widths.get(column).copied()).sum::>().map(|sum| sum + past)) .reduce(f32::max); - let early = early.iter().any(|(column, read)| widths.get(column).is_some_and(|width| width > read)); + // A row measured beside a label column narrower than the group's final one stacks under the final column, and + // its measure is of the other placement. + let wider = |columns: &Columns| columns.iter().any(|(column, most)| widths.get(column).is_some_and(|width| width > most)); + let early = wider(&early) || wider(&stays); Scoped { extent, unsettled: early.then(|| widths.clone()), widths } } @@ -251,7 +256,7 @@ impl ColumnGroup { let depth = layout_memory::depth(ctx); let widest = seed.unwrap_or_default(); pass_state::with::(ctx, |open| { - open.0.push(Frame::Group { id, widest, beyond: HashMap::new(), early: HashMap::new(), room: None, depth }); + open.0.push(Frame::Group { id, widest, beyond: HashMap::new(), early: HashMap::new(), stays: HashMap::new(), room: None, depth }); }); ColumnGroup { id, ctx: ctx.clone() } } @@ -289,6 +294,7 @@ impl ColumnGroup { widest, beyond: HashMap::new(), early: HashMap::new(), + stays: HashMap::new(), room: None, depth, }); @@ -404,6 +410,23 @@ pub fn ambient_width(ctx: &Context, column: &ColumnKey, content: f32) -> Option< Some(width) } +/// Notes, in a measuring run, that a row of the group the innermost open frame reads placed its label beside column +/// `column`, and would stack its control under the label once the column is wider than `most`. When the group's final +/// width passes it, the row's measure is of the beside placement the real run does not give it, and the group's scope +/// returns its widths as unsettled. Nothing happens outside a measuring run or a group. +pub(crate) fn note_beside(ctx: &Context, column: &ColumnKey, most: f32) { + if !crate::runtime::measure::active(ctx) { + return; + } + let Some((group, _)) = pass_state::with::(ctx, |open| open.innermost(std::slice::from_ref(column))) else { return }; + pass_state::with::(ctx, |open| { + if let Some(Frame::Group { stays, .. }) = open.0.iter_mut().rev().find(|frame| matches!(frame, Frame::Group { id, .. } if *id == group)) { + let stays = stays.entry(column.clone()).or_insert(most); + *stays = stays.min(most); + } + }); +} + /// The width the innermost open frame's container was offered, `None` when no label group is open, a barrier or a /// field's body is, or the container recorded none. pub(crate) fn ambient_room(ctx: &Context) -> Option { diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 2895b9f4da..a11ff15e8f 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -13,7 +13,7 @@ pub use column_group::ColumnGroup; pub use column_group::ambient_width; #[doc(hidden)] pub use column_group::report_beyond; -pub(crate) use column_group::{Columns, GLYPHS, LABELS, Reached, ambient_room}; +pub(crate) use column_group::{Columns, GLYPHS, LABELS, Reached, ambient_room, note_beside}; pub use label::{control_baseline, place_label, record_control_baseline}; pub use slot::measure_slot; diff --git a/crates/ui-widgets/tests/it/label/mod.rs b/crates/ui-widgets/tests/it/label/mod.rs index 37af7d23db..0ab8b3540e 100644 --- a/crates/ui-widgets/tests/it/label/mod.rs +++ b/crates/ui-widgets/tests/it/label/mod.rs @@ -14,6 +14,7 @@ pub(crate) mod reset; pub(crate) mod scheme; pub(crate) mod scrub_drags; pub(crate) mod short; +pub(crate) mod stacked; pub(crate) mod tooltip; use self::kit::{Dial, Field, Seen, Wide}; diff --git a/crates/ui-widgets/tests/it/label/stacked.rs b/crates/ui-widgets/tests/it/label/stacked.rs new file mode 100644 index 0000000000..dbace1561b --- /dev/null +++ b/crates/ui-widgets/tests/it/label/stacked.rs @@ -0,0 +1,55 @@ +//! A group whose label column is too wide for its room puts every row's control under its label: the rows measured +//! before the widest label take the stacked height too. + +use craft_theme::Size; +use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; +use craft_ui::form::{Field, FieldGroup}; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::NumberField; +use egui::{Rect, Vec2}; + +/// How far two edges may differ and still line up, in points. +const SLACK: f32 = 0.5; + +/// The rows of the group, with the widest label last, and the value each field shows. +const ROWS: [(&str, f64); 3] = [("Width", 11.0), ("Corner radius", 22.0), ("Maximum number of layers", 33.0)]; + +fn control(fixture: &Fixture, name: &str) -> Rect { + fixture.by_label(name).unwrap_or_else(|| panic!("{name:?} names its control")).rect +} + +fn caption(fixture: &Fixture, text: &str) -> Rect { + fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text:?} is painted")) +} + +/// In a group 240 pt wide, the last row's label is too wide to sit beside a control, so every row stacks. Each field +/// shows under its label and above the next row, and its value shows whole, not clipped to the row it measured +/// beside a narrower column. +#[trial] +fn every_row_of_a_group_that_stacks_takes_the_stacked_height() { + let mut fixture = Fixture::new(|ui| { + FieldGroup::new("Shape").show(ui, |ui, _| { + for (name, value) in ROWS { + Field::new(name).show(ui, |ui, _| NumberField::new(name, Bind::given(Some(value))).show(ui)); + } + }); + }); + fixture.room(Vec2::new(240.0, 600.0)).density(Size::Comfortable); + fixture.settle(); + let mut above = f32::NEG_INFINITY; + for (name, value) in ROWS { + let (label, field) = (caption(&fixture, name), control(&fixture, name)); + assert!(label.max.y <= field.min.y + SLACK, "{name}'s field shows under its label: {label:?} {field:?}"); + assert!(label.min.y >= above - SLACK, "{name}'s row starts under the field before: {label:?} {above}"); + above = field.max.y; + let digits = format!("{value}"); + let texts = fixture.texts(); + let run = texts.iter().find(|run| run.text.starts_with(&digits)).unwrap_or_else(|| panic!("{digits:?} is painted: {texts:?}")); + assert!( + run.clip.min.y <= run.rect.min.y + SLACK && run.clip.max.y >= run.rect.max.y - SLACK, + "{name}'s value shows whole: {:?} under the clip {:?}", + run.rect, + run.clip + ); + } +} From 7f8fec0e549a3cb4cd07e4600c22754ae4472e4c Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 09:49:06 +0000 Subject: [PATCH 162/269] menu gallery: the current tile is outlined in the accent, with no fill The current tile of a gallery was a state.selected fill inside a line.control_edge edge, which on the Styles gallery read as a grey tile. It is now a thin outline in accent.border, the colour a selected icon button's outline takes, and the tile keeps its own background. The outline is still a shape, so the current tile is not marked by colour alone. Reference: storytold/wordcraft#7678. Co-Authored-By: Claude Sonnet 5.5 --- crates/menu/src/ribbon/gallery.rs | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index 4375f7053b..33515f33b4 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -366,11 +366,7 @@ struct GalleryTileStyle { focus: FocusLook, /// Between the tile's edge and its picture. pad: f32, - /// The selection edge's width. - stroke: f32, - /// The current tile's fill. - fill: StyleColor, - /// The current tile's edge. + /// The current tile's outline: accent, unfilled, so the picture keeps its own background. edge: StyleColor, /// The ink of the item's name under the picture, in a captioned gallery. caption: StyleColor, @@ -443,9 +439,7 @@ impl Component for GalleryTile<'_> { metrics: Metrics::new().padding(Insets::new(pad, pad, pad, pad)), focus: cx.focus_look(), pad, - stroke: cx.tokens.stroke.thin, - fill: cx.color(colors.state.selected), - edge: cx.color(colors.line.control_edge), + edge: cx.color(colors.accent.border), caption: cx.color(colors.text.normal), gap: cx.tokens.space.gap.tight, thumbs: [cx.tokens.size.thumb.sm, cx.tokens.size.thumb.md, cx.tokens.size.thumb.lg], @@ -472,9 +466,7 @@ impl Component for GalleryTile<'_> { } if self.selected { let outer = area.expand(cx.style.pad); - let draw = ui.draw(); - draw.fill(&PaintShape::Rect(outer, CornerRadius::ZERO), cx.style.edge); - draw.fill(&PaintShape::Rect(outer.shrink(cx.style.stroke), CornerRadius::ZERO), cx.style.fill); + ui.draw().stroke(&PaintShape::Rect(outer, CornerRadius::ZERO), craft_ui::primitives::StrokeWidth::Thin, cx.style.edge); } // A captioned tile keeps the picture's height at the top and shows the name in the rest under it. let (area, caption) = match self.caption { From f7ddd9957a5de5b5af7d90bb82711caf6149b367 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 09:50:25 +0000 Subject: [PATCH 163/269] ui-canvas rulers: a centimetre document ruler labels every whole centimetre TickRule::of_unit gave centimetres the generic metric rule, whose least label step is 60 points, so at 100% (1 cm is about 28 points) the page and text rulers labelled every 2 cm. Add TickRule::Centimetres for document rulers: labels every centimetre down to 24 points apart, thinning to 2, 5, 10 and so on when zoomed out, with quarter-centimetre ticks (halves when tighter), as WordCraft v0.18.1 drew. Canvas and image rulers keep TickRule::Metric. Fixes storytold/wordcraft#7686. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-canvas/src/canvas/mod.rs | 3 ++- crates/ui-canvas/src/canvas/rulers/mod.rs | 2 +- crates/ui-canvas/src/canvas/rulers/ticks.rs | 30 +++++++++++++++++++-- crates/ui-canvas/tests/it/canvas/rulers.rs | 22 +++++++++++++-- 4 files changed, 51 insertions(+), 6 deletions(-) diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 88a0dd64db..bf6c136d8a 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -82,7 +82,8 @@ pub use zoom_motion::{HoldZoom, ZoomAnimation, ZoomDrag, easing_view}; pub(crate) mod rulers; pub(crate) mod scrollbars; pub use rulers::{ - INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerCommands, RulerMargins, RulerPart, RulerTick, Rulers, RulersOutput, StepLadder, TickRule, + CENTIMETRE_LABEL_STEP_MIN, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerCommands, RulerMargins, RulerPart, RulerTick, Rulers, + RulersOutput, StepLadder, TickRule, }; pub use scrollbars::{CanvasScrollbars, CanvasScrollbarsOutput}; diff --git a/crates/ui-canvas/src/canvas/rulers/mod.rs b/crates/ui-canvas/src/canvas/rulers/mod.rs index 96acf884f3..811a86d813 100644 --- a/crates/ui-canvas/src/canvas/rulers/mod.rs +++ b/crates/ui-canvas/src/canvas/rulers/mod.rs @@ -6,7 +6,7 @@ pub(crate) mod stories; mod ticks; -pub use ticks::{INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerTick, StepLadder, TickRule}; +pub use ticks::{CENTIMETRE_LABEL_STEP_MIN, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, RulerTick, StepLadder, TickRule}; use super::words::CanvasWords; use super::{CanvasRulers, CanvasSpace, GuideDrag, RulerText, Snap, context_menu, readout}; diff --git a/crates/ui-canvas/src/canvas/rulers/ticks.rs b/crates/ui-canvas/src/canvas/rulers/ticks.rs index 2d0355edb5..1566afd8a4 100644 --- a/crates/ui-canvas/src/canvas/rulers/ticks.rs +++ b/crates/ui-canvas/src/canvas/rulers/ticks.rs @@ -13,6 +13,14 @@ pub const INCH_EIGHTHS: [u32; 3] = [8, 4, 2]; /// The least distance between labelled ticks, in points. pub const LABEL_STEP_MIN: f32 = 60.0; +/// The least distance between labelled ticks of a centimetre document ruler, in points: a whole centimetre at 100% +/// (about 28 points) is labelled, as Word's ruler does. +pub const CENTIMETRE_LABEL_STEP_MIN: f32 = 24.0; +/// The least distance between ticks of a centimetre document ruler, in points. +const CENTIMETRE_TICK_STEP_MIN: f64 = 4.0; +/// Labelled centimetre steps: 1, 2, 5, 10 times the base. +const CENTIMETRE_STEPS: [f64; 9] = [1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0]; + /// The metric rule's subdivisions of a labelled step. const METRIC_SUBDIVISIONS: f32 = 10.0; /// Labelled inch steps in inches: 1, 2, 5, 10 times the base. @@ -71,6 +79,9 @@ impl StepLadder { pub enum TickRule<'a> { /// The units' own table ([`RulerUnits::step`]): decimal steps and ten subdivisions, or the host's custom table. Metric, + /// Centimetres of a document ruler: a label every centimetre (every 2, 5, 10 and so on when smaller), with quarter + /// centimetre ticks while they stay [`CENTIMETRE_TICK_STEP_MIN`] apart, then halves. + Centimetres, /// Inches: a label every inch (every 2, 5, 10 and so on when smaller), subdivided by the first of these counts, /// finest first, that keeps the ticks a tenth of the least label step apart ([`INCH_SIXTEENTHS`], /// [`INCH_EIGHTHS`]). @@ -81,9 +92,14 @@ pub enum TickRule<'a> { } impl TickRule<'static> { - /// The rule for a ruler counting `kind`: Word's sixteenths for inches, `Metric` otherwise. + /// The rule for a document ruler counting `kind`: Word's sixteenths for inches, whole labelled centimetres for + /// centimetres, `Metric` otherwise. pub fn of_unit(kind: UnitKind) -> TickRule<'static> { - if kind == UnitKind::Inches { TickRule::Inches(&INCH_SIXTEENTHS) } else { TickRule::Metric } + match kind { + UnitKind::Inches => TickRule::Inches(&INCH_SIXTEENTHS), + UnitKind::Centimetres => TickRule::Centimetres, + _ => TickRule::Metric, + } } } @@ -112,6 +128,15 @@ fn inch_step(points_per_inch: f64, finest: &[u32]) -> (f64, u32) { (step, subdivisions) } +/// The labelled centimetre step and its subdivisions at `points_per_cm` screen points per centimetre. +fn centimetre_step(points_per_cm: f64) -> (f64, u32) { + let step_min = f64::from(CENTIMETRE_LABEL_STEP_MIN); + let step = CENTIMETRE_STEPS.into_iter().find(|step| step * points_per_cm >= step_min).unwrap_or(1000.0); + let subdivisions = + if step > 1.0 { 2 } else { [4_u32, 2].into_iter().find(|n| points_per_cm / f64::from(*n) >= CENTIMETRE_TICK_STEP_MIN).unwrap_or(1) }; + (step, subdivisions) +} + /// The ticks of one ruler over `values` (ruler units from the zero point): the one tick rule of every ruler, so a /// text ruler or a page view's ruler shows the same ticks as the canvas's. One labelled step beyond each end is /// included, since a label starts right of its tick. `zoom` is screen points per document unit along the axis, as @@ -119,6 +144,7 @@ fn inch_step(points_per_inch: f64, finest: &[u32]) -> (f64, u32) { pub fn ticks(units: &RulerUnits, rule: TickRule<'_>, zoom: f64, values: RangeInclusive) -> Vec { let (step, subdivisions) = match rule { TickRule::Metric => units.step(zoom, LABEL_STEP_MIN), + TickRule::Centimetres => centimetre_step(zoom / units.per_doc), TickRule::Inches(finest) => inch_step(zoom / units.per_doc, finest), TickRule::Steps(ladder) => { let (tick, label) = ladder.steps(zoom / units.per_doc); diff --git a/crates/ui-canvas/tests/it/canvas/rulers.rs b/crates/ui-canvas/tests/it/canvas/rulers.rs index 16aa582880..5fe156210e 100644 --- a/crates/ui-canvas/tests/it/canvas/rulers.rs +++ b/crates/ui-canvas/tests/it/canvas/rulers.rs @@ -4,8 +4,8 @@ use craft_behavior::geometry::{SnapOptions, SnapTargets}; use craft_behavior::kurbo::{Point, Rect as DocRect}; use craft_behavior::{CancelReason, CanvasView, RulerUnits, TickLabels, Ticks}; use craft_ui::canvas::{ - Canvas, CanvasTool, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, PageFrame, Pasteboard, RulerText, Rulers, Snap, StepLadder, TickRule, - ToolAction, ToolContext, ToolPath, ToolPointer, + CENTIMETRE_LABEL_STEP_MIN, Canvas, CanvasTool, INCH_EIGHTHS, INCH_SIXTEENTHS, LABEL_STEP_MIN, PageFrame, Pasteboard, RulerText, Rulers, Snap, + StepLadder, TickRule, ToolAction, ToolContext, ToolPath, ToolPointer, }; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::TickRank; @@ -60,6 +60,24 @@ fn labelled_ticks_never_touch_at_any_zoom() { } } +/// A document ruler labels every whole centimetre at 100% (28.35 points each), and thins the labels out when zoomed +/// out so they never touch. +#[trial] +fn a_centimetre_document_ruler_labels_each_centimetre_and_thins_out_zoomed_out() { + let centimetres = RulerUnits::new(2.54 / 72.0, Ticks::decimal(false)); + let rule = TickRule::of_unit(UnitKind::Centimetres); + let at_full = least_label_gap(¢imetres, rule, 1.0); + assert!(at_full < f64::from(LABEL_STEP_MIN), "labels at 100% are closer than the generic metric step: {at_full}"); + let one_cm = 72.0 / 2.54; + assert!((at_full - one_cm).abs() < 1e-6, "labels at 100% are one centimetre apart: {at_full}"); + let least = f64::from(CENTIMETRE_LABEL_STEP_MIN) - 1e-9; + for zoom in ZOOMS { + let gap = least_label_gap(¢imetres, rule, zoom); + assert!(gap >= least, "centimetre labels at zoom {zoom}: {gap} points apart"); + } + assert!(least_label_gap(¢imetres, rule, 0.25) > at_full, "labels thin out when zoomed out"); +} + /// A vertical label stacks its characters one label-role size apart; the longest label the metric rule gives at the /// least step (five characters) and its gap to the tick stay inside that step, so neighbouring labels never touch. #[trial] From 4c6c3bb6e18f65c6492f2da02a104202d688e2ff Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 09:57:07 +0000 Subject: [PATCH 164/269] menu gallery: scroll and more arrows show the small glyph, not the ribbon's icon side The Styles gallery's up, down and more buttons are icon buttons, and in a ribbon an icon-only button's glyph takes the ribbon's small icon side (17), which made the arrows far larger than the old ribbon's. A new GlyphRole::Compact shows the glyph at size.icon.glyph_sm whatever the control size and skips that ribbon side; the gallery sets it on its three buttons, and on the one it measures. Other icon buttons are unchanged. Reference: storytold/wordcraft#7679. Co-Authored-By: Claude Sonnet 5.5 --- crates/menu/src/ribbon/gallery.rs | 10 +++++----- crates/ui-contract/src/style/cx.rs | 3 +++ crates/ui-widgets/src/buttons/face.rs | 3 ++- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index 4375f7053b..f026ac82a0 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -19,7 +19,7 @@ use craft_ui::primitives::textures::{Revision, ThumbSource, Thumbnails}; use craft_ui::primitives::{ContentPainterCx, HAlign, PaintShape, TextRun}; use craft_ui::runtime::env::Label; use craft_ui::runtime::focus::KeyUse; -use craft_ui::style::{ComponentStyle, Flags, FocusLook, StyleColor, StyleCx, TypeRole}; +use craft_ui::style::{ComponentStyle, Flags, FocusLook, GlyphRole, StyleColor, StyleCx, TypeRole}; use craft_ui::tile_grid::{CaptionPlace, Tile, TileGrid}; use egui::{ColorImage, CornerRadius, Rect, Response, Ui, Vec2}; @@ -189,7 +189,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> { fn sizes(&self, cx: &MeasureCx<'_, Self>) -> Sizes { let words = cx.env.words::(); - let button = cx.face(IconButton::new(IconId::new("more")).label(words.more.clone())); + let button = cx.face(IconButton::new(IconId::new("more")).label(words.more.clone()).glyphs(GlyphRole::Compact)); Sizes { tile: cx.face(GalleryTile::blank(self.aspect, self.thumb_size, self.captioned())), button, gap: cx.gap() } } } @@ -723,9 +723,9 @@ impl Component for Gallery<'_, K> draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y1), egui::pos2(self.column.right(), y1)); draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y2), egui::pos2(self.column.right(), y2)); } - ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0)); - ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last)); - ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone())); + ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0).glyphs(GlyphRole::Compact)); + ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last).glyphs(GlyphRole::Compact)); + ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone()).glyphs(GlyphRole::Compact)); } /// The context request is recorded after `update`, so `finish` reads it: a secondary click on a tile, or the Menu diff --git a/crates/ui-contract/src/style/cx.rs b/crates/ui-contract/src/style/cx.rs index d5ab7c55ea..021e3249d9 100644 --- a/crates/ui-contract/src/style/cx.rs +++ b/crates/ui-contract/src/style/cx.rs @@ -38,6 +38,9 @@ pub enum GlyphRole { ToolRail, /// A list row's trailing icon button: the control glyph, resting in `text.faint` and in the variant's ink under the pointer. PanelRail, + /// A stack of small arrow buttons (a gallery's scroll arrows): `size.icon.glyph_sm` whatever the control size, and + /// a ribbon's small icon side does not widen it. + Compact, } /// What `fn style` gets. Tokens are read here and nowhere else. diff --git a/crates/ui-widgets/src/buttons/face.rs b/crates/ui-widgets/src/buttons/face.rs index d1070aa957..b27b517c08 100644 --- a/crates/ui-widgets/src/buttons/face.rs +++ b/crates/ui-widgets/src/buttons/face.rs @@ -407,9 +407,10 @@ pub(crate) fn icon_face(cx: &StyleCx<'_>) -> IconFace { GlyphRole::Tool => (icon.md, None), GlyphRole::ToolRail => (icon.lg, Some(text.muted)), GlyphRole::PanelRail => (cx.glyph(), Some(text.faint)), + GlyphRole::Compact => (icon.glyph_sm, None), _ => (cx.glyph(), None), }; - let side = super::small_icon(cx, side); + let side = if cx.glyph_role() == GlyphRole::Compact { side } else { super::small_icon(cx, side) }; let mut ink = off.text.clone(); if let Some(rest) = rest { ink.off.rest = cx.color(rest); From f2656d986137ceb0ed89c8bd0d79255cb1861d10 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 09:57:22 +0000 Subject: [PATCH 165/269] ui-widgets: icon button reads in a side menu's ink IconButton ignored ControlPlace::SideMenu: only Button took the menu's on-strong ink and brand-surface bands, so WordCraft's File rail Back arrow drew in the dark ghost ink on the blue rail and was almost invisible. Move the ink and band fills into side_menu_ink and use it from both. The glyph keeps tinted(), so a multi-colour icon keeps its own colours as in Button. Disabled stays the ink at the menu's disabled alpha. Refs storytold/wordcraft#7707 Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-widgets/src/buttons/button.rs | 31 +++++++++++------- crates/ui-widgets/src/buttons/icon_button.rs | 12 +++++-- crates/ui-widgets/tests/it/buttons.rs | 34 ++++++++++++++++++++ 3 files changed, 63 insertions(+), 14 deletions(-) diff --git a/crates/ui-widgets/src/buttons/button.rs b/crates/ui-widgets/src/buttons/button.rs index 10060b7bc1..9609fa8e19 100644 --- a/crates/ui-widgets/src/buttons/button.rs +++ b/crates/ui-widgets/src/buttons/button.rs @@ -289,6 +289,23 @@ impl<'a> Button<'a> { } } +/// A side menu stands on the brand surface: its names and icons read in the ink of strong fills, a disabled page's +/// dimmed, and its bands are that ink laid thinly over the brand colour (hover lighter than the page shown), not the +/// panel's state fills, which painted a light band with dark text over the rail. The row of the page shown (`on`) +/// keeps its band, so the menu marks where the page is. Returns the ink and the band fill, for every control of the +/// place (`Button`, `IconButton`). +pub(super) fn side_menu_ink(cx: &StyleCx<'_>) -> (craft_theme::Stateful, craft_theme::Stateful) { + let ink = cx.tokens.color.text.on_strong; + let (rest, dim) = (cx.color(ink), cx.color(ink.with_alpha(SIDE_MENU_DISABLED_ALPHA))); + let text = craft_theme::Stateful::new(rest).off(craft_theme::States::new(rest, rest, rest, dim)); + let (clear, hover, shown) = + (cx.color(Rgba::TRANSPARENT), cx.color(ink.with_alpha(SIDE_MENU_HOVER_ALPHA)), cx.color(ink.with_alpha(SIDE_MENU_SHOWN_ALPHA))); + let fill = craft_theme::Stateful::new(clear) + .off(craft_theme::States::new(clear, hover, shown, clear)) + .on(craft_theme::States::new(shown, shown, shown, shown)); + (text, fill) +} + impl Component for Button<'_> { const ROLE: Role = Role::BUTTON; const OVERLAYS: bool = false; @@ -330,13 +347,7 @@ impl Component for Button<'_> { let pad = &cx.tokens.space.pad; style.text.role = TypeRole::BodyLarge; style.metrics.padding = Insets::new(pad.roomy, pad.roomy, pad.segment, pad.segment); - // A side menu stands on the brand surface: its names and icons read in the ink of strong fills, a disabled - // page's dimmed, and its bands are that ink laid thinly over the brand colour (hover lighter than the page - // shown), not the panel's state fills, which painted a light band with dark text over the rail. The row of - // the page shown (`selected`) keeps its band, so the menu marks where the page is. - let ink = cx.tokens.color.text.on_strong; - let (rest, dim) = (cx.color(ink), cx.color(ink.with_alpha(SIDE_MENU_DISABLED_ALPHA))); - let text = craft_theme::Stateful::new(rest).off(craft_theme::States::new(rest, rest, rest, dim)); + let (text, fill) = side_menu_ink(cx); style.text.color = text.clone(); // A place's icon is the large icon, not a control's standard one, set off from its name by a section gap: a // list of places reads by its icons (WordCraft's File rail: 18 pt icons, nearest token 20 pt, 12 pt before 14 pt names). @@ -344,11 +355,7 @@ impl Component for Button<'_> { // The face paints by its gap and the measure by the metrics', so the two stay one. style.face.gap = style.face.gap.max(cx.tokens.space.gap.section); style.metrics.gap = style.face.gap; - let (clear, hover, shown) = - (cx.color(Rgba::TRANSPARENT), cx.color(ink.with_alpha(SIDE_MENU_HOVER_ALPHA)), cx.color(ink.with_alpha(SIDE_MENU_SHOWN_ALPHA))); - style.surface.fill = craft_theme::Stateful::new(clear) - .off(craft_theme::States::new(clear, hover, shown, clear)) - .on(craft_theme::States::new(shown, shown, shown, shown)); + style.surface.fill = fill; } style } diff --git a/crates/ui-widgets/src/buttons/icon_button.rs b/crates/ui-widgets/src/buttons/icon_button.rs index 0dec4ab37f..cbf0e0fe5b 100644 --- a/crates/ui-widgets/src/buttons/icon_button.rs +++ b/crates/ui-widgets/src/buttons/icon_button.rs @@ -172,11 +172,19 @@ impl Component for IconButton<'_> { fn style(cx: &StyleCx<'_>, _: IconButtonStyleKey) -> IconButtonStyle { let face = face::icon_face(cx); let marker = MarkerStyle::of(cx); + let (mut surface, mut glyph) = (face.surface, face.glyph); + // On a side menu's brand surface the glyph reads in the menu's ink and its bands lie over the brand colour, as a + // `Button` row's do. + if cx.env::() == super::ControlPlace::SideMenu { + let (ink, fill) = super::button::side_menu_ink(cx); + glyph.color = ink; + surface.fill = fill; + } IconButtonStyle { - surface: face.surface, + surface, metrics: face.metrics, focus: face::focus(cx), - glyph: face.glyph, + glyph, marker: marker.side, marker_color: marker.color, marker_edge: marker.edge, diff --git a/crates/ui-widgets/tests/it/buttons.rs b/crates/ui-widgets/tests/it/buttons.rs index 144252af84..dcba8e7fb8 100644 --- a/crates/ui-widgets/tests/it/buttons.rs +++ b/crates/ui-widgets/tests/it/buttons.rs @@ -647,6 +647,40 @@ fn a_side_menus_row_shows_the_standard_icon() { assert!(menu > plain, "a side menu's icon is the standard one: {menu} against {plain}"); } +/// An icon-only button in a side menu (WordCraft's Back arrow on the File rail) reads in the menu's ink, as a `Button` +/// row's icon does, not in the dark ghost ink that vanished on the brand surface; elsewhere it keeps its own ink. +#[trial] +fn a_side_menus_icon_button_reads_in_the_menus_ink() { + let rest = |side: bool, icon_only: bool| { + let mut fixture = Fixture::new(move |ui| { + let show = |ui: &mut Ui| { + if icon_only { + let _ = IconButton::new(IconId::new("print")).label("Back").show(ui); + } else { + let _ = Button::new("Print").icon(IconId::new("print")).variant(Variant::GHOST).show(ui); + } + }; + if side { + with_env( + ui, + |overrides| { + overrides.values.set(ControlPlace::SideMenu); + }, + show, + ); + } else { + show(ui); + } + }); + fixture.settle(); + let kind = if icon_only { std::any::type_name::>() } else { std::any::type_name::>() }; + let style = fixture.styles_of(kind).into_iter().next().expect("the button resolved its style"); + style.looks.icons.first().expect("the button has an icon look").color.off.rest.egui() + }; + assert_eq!(rest(true, true), rest(true, false), "the icon button takes the ink of the menu's rows"); + assert_ne!(rest(true, true), rest(false, true), "outside a side menu it keeps its own ink"); +} + /// A split button's body that closes itself (a colour palette's swatch pick) closes the split's menu layer: before, /// the close reached only the inline menu inside the layer, which stayed open around an empty body. Opened again, the /// body shows its rows. From 9a2615d2d97874a9844a6def9d366cec3e85921a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:06:27 -0800 Subject: [PATCH 166/269] ui-widgets, ui-panels: a focused disclosure or tool rail button shows the focus ring A Disclosure and a FlyoutButton (a tool rail slot) take keyboard focus, but neither style held a focus look. The paint step draws the focus ring only for a style that has one, so after Tab neither control showed where focus was. Both styles now take the theme's focus look, as Link and the breadcrumb bar do, and the paint step draws the ring around each control's rect. A disclosure painted as part of a list row, tree row, title row or grid header is a face, which draws no ring, so those rows look as before. FlyoutButtonStyle no longer derives Default, since the focus look has no default. --- crates/ui-panels/src/rails/flyout.rs | 17 +++++++++++---- crates/ui-panels/tests/it/rails/mod.rs | 23 ++++++++++++++++++++ crates/ui-widgets/src/controls/disclosure.rs | 6 +++-- crates/ui-widgets/tests/it/focus_ring.rs | 22 +++++++++++++++++++ 4 files changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index b96af1e160..619abb756f 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -14,7 +14,7 @@ use crate::menu::{self, Menu, MenuItem}; use crate::primitives::{PaintShape, StrokeWidth}; use crate::runtime::commands::{CommandRef, FireSource, ResolvedCommand}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, GlyphRole, StyleColor, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, GlyphRole, StyleColor, StyleCx}; use craft_behavior::overlay::{Align, Side}; use craft_behavior::{CursorIcon, HitLevel, HitPriority, IconId, Metrics, PartKey, PointerButton, PressPhase, Sense, Value}; use egui::{Pos2, Rect, Response, Vec2}; @@ -30,12 +30,16 @@ const MARK: PartKey = PartKey::new("mark"); const BAR: PartKey = PartKey::new("bar"); /// The style of a flyout button: it paints through its face, so it holds no look of its own besides its side, the rail -/// button's, and the size of the corner mark's press area, which is the size and the inset of the mark the face paints. -#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +/// button's, its focus ring, and the size of the corner mark's press area, which is the size and the inset of the mark +/// the face paints. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct FlyoutButtonStyle { #[style(metrics)] metrics: Metrics, + /// The ring the button shows while it has keyboard focus: a face paints none. + #[style(focus)] + focus: FocusLook, /// The side of the corner mark, which is also its inset from the face's corner. mark: f32, /// The button's glyph role, which its face shows the icon in. @@ -235,7 +239,12 @@ impl Component for FlyoutButton<'_, T> { fn style(cx: &StyleCx<'_>, _: FlyoutButtonStyleKey) -> FlyoutButtonStyle { let side = cx.env::().button(cx.tokens); - FlyoutButtonStyle { metrics: Metrics::new().min_size(Vec2::splat(side)), mark: cx.tokens.space.gap.tight, glyphs: cx.glyph_role() } + FlyoutButtonStyle { + metrics: Metrics::new().min_size(Vec2::splat(side)), + focus: cx.focus_look(), + mark: cx.tokens.space.gap.tight, + glyphs: cx.glyph_role(), + } } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { diff --git a/crates/ui-panels/tests/it/rails/mod.rs b/crates/ui-panels/tests/it/rails/mod.rs index 24d4dcca32..9494807aeb 100644 --- a/crates/ui-panels/tests/it/rails/mod.rs +++ b/crates/ui-panels/tests/it/rails/mod.rs @@ -149,6 +149,29 @@ fn the_current_tools_button_reports_pressed_and_the_others_not() { assert_eq!(pressed("Cut"), Some(Mixed::Same(false)), "another tool's button reports that it is not"); } +/// A rail button with keyboard focus is ringed as a button is: a focus stroke of two points around its own rect. +#[trial] +fn a_focused_rail_button_shows_the_focus_ring_around_it() { + let all = tools(&[UNDO, REDO]); + let mut fixture = Fixture::new(move |ui| { + FlyoutButton::new(&all, &UNDO).show(ui); + }); + fixture.settle(); + let ring = |fixture: &mut Fixture| { + fixture.frame_shapes().iter().find_map(|shape| match shape { + egui::Shape::Rect(rect) if rect.stroke.width >= 2.0 => Some(rect.rect), + _ => None, + }) + }; + assert!(ring(&mut fixture).is_none(), "an unfocused rail button has no ring"); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.settle(); + assert!(fixture.focused().is_some(), "Tab focused the rail button"); + let target = fixture.by_role(Role::BUTTON).into_iter().next().expect("the rail button shows"); + let ring = ring(&mut fixture).expect("the focused rail button paints a focus ring"); + assert!(ring.expand(1.0).contains_rect(target.rect), "the ring {ring:?} goes around the button {:?}", target.rect); +} + /// With a click command a click, Enter or Space fires it and selects nothing; a hold, a drag away and a right click /// list the tools, and the release that ends a hold fires nothing. #[trial] diff --git a/crates/ui-widgets/src/controls/disclosure.rs b/crates/ui-widgets/src/controls/disclosure.rs index 6785bf03a1..16ff31972c 100644 --- a/crates/ui-widgets/src/controls/disclosure.rs +++ b/crates/ui-widgets/src/controls/disclosure.rs @@ -5,7 +5,7 @@ use crate::contract::{ Animate as _, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, PaintUi, Pointer as _, Role, Styled as _, spec, }; use crate::primitives::{Glyph, PaintShape, StrokeWidth}; -use crate::style::{ComponentStyle, IconLook, StyleCx, UiTokens, ink_color, rgba_color}; +use crate::style::{ComponentStyle, FocusLook, IconLook, StyleCx, UiTokens, ink_color, rgba_color}; use craft_behavior::{Metrics, Sense}; use craft_i18n::Direction; use egui::emath::GuiRounding as _; @@ -190,6 +190,8 @@ impl Glyph for DisclosureGlyph { pub struct DisclosureStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// The triangle. #[style(icon)] glyph: IconLook, @@ -223,7 +225,7 @@ impl Component for Disclosure<'_> { fn style(cx: &StyleCx<'_>, _: DisclosureStyleKey) -> DisclosureStyle { let side = cx.control().icon; - DisclosureStyle { metrics: Metrics::new().min_size(Vec2::splat(side)), glyph: IconLook::new(side, cx.quiet_ink()) } + DisclosureStyle { metrics: Metrics::new().min_size(Vec2::splat(side)), focus: cx.focus_look(), glyph: IconLook::new(side, cx.quiet_ink()) } } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { diff --git a/crates/ui-widgets/tests/it/focus_ring.rs b/crates/ui-widgets/tests/it/focus_ring.rs index 0c45a55142..c09225d910 100644 --- a/crates/ui-widgets/tests/it/focus_ring.rs +++ b/crates/ui-widgets/tests/it/focus_ring.rs @@ -31,3 +31,25 @@ fn the_focus_ring_is_two_points_thick() { let width = widest_stroke(&mut fixture); assert!((width - 2.0).abs() < 0.01, "the ring is the theme's focus stroke of two points: {width}"); } + +/// A disclosure with keyboard focus is ringed as a button is: a focus stroke around its own rect. +#[trial] +fn a_focused_disclosure_shows_the_focus_ring_around_it() { + use craft_ui::contract::{Bind, Props as _, Role}; + use craft_ui::controls::disclosure::Disclosure; + let mut fixture = Fixture::new(|ui| { + let _ = Disclosure::new(Bind::given(false)).label("Details").show(ui); + }); + fixture.settle(); + assert!(widest_stroke(&mut fixture) < 2.0, "an unfocused disclosure has no thick line"); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.settle(); + assert!(fixture.focused().is_some(), "Tab focused the disclosure"); + let target = fixture.by_role(Role::BUTTON).into_iter().next().expect("the disclosure shows"); + let ring = fixture.frame_shapes().iter().find_map(|shape| match shape { + Shape::Rect(rect) if rect.stroke.width >= 2.0 => Some(rect.rect), + _ => None, + }); + let ring = ring.expect("the focused disclosure paints a focus ring"); + assert!(ring.expand(1.0).contains_rect(target.rect), "the ring {ring:?} goes around the disclosure {:?}", target.rect); +} From 9dfaf04f0275a000ae5c0408ed8ce6ae219fb7a2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:16:48 -0800 Subject: [PATCH 167/269] draw: the Bezier overlay counts other paths' selected anchors instead of copying them for each path other_handles runs once per path when the overlay paints. For each path it built a new PathSelection by cloning every other path's anchor list and adding it with PathSelection::also, which searches the list it is building. With n paths in `others` one frame made about n^2 calls of also and n^2 vector clones, and also's search made the frame cubic in n. The rebuilt selection was only used to count the selected anchors for HandlesShown::OneAnchor. other_handles now sums the anchor counts of the other paths and passes the count to shown_handles_of, which shown_handles also calls with the selection's own count. The handles drawn do not change. With 1,500 selected rectangles in VectorCraft (every path but the first is in `others`), 28% of a profile's samples were in also, and about 120 hover frames after select all made 404,730,000 calls of it. Trial one_anchor_draws_other_paths_handles_only_while_one_anchor_is_selected_over_all_paths checks the count with anchors listed in two other paths. --- crates/draw/src/ui/pen/bezier/hit_test.rs | 25 ++++++++++++++--------- crates/draw/tests/it/bezier.rs | 24 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/crates/draw/src/ui/pen/bezier/hit_test.rs b/crates/draw/src/ui/pen/bezier/hit_test.rs index 79bf7d2634..5c947df2d3 100644 --- a/crates/draw/src/ui/pen/bezier/hit_test.rs +++ b/crates/draw/src/ui/pen/bezier/hit_test.rs @@ -55,6 +55,11 @@ impl BezierOverlay<'_> { /// The handles to show, in path order, in then out, leaving out retracted ones and those of subpaths the selection /// does not show. pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec { + shown_handles_of(paths, sel, sel.selected_len(), handles, view) +} + +/// [`shown_handles`] with `selected` as the number of selected anchors that `OneAnchor` counts. +fn shown_handles_of(paths: &[EditPath], sel: &PathSelection, selected: usize, handles: HandlesShown, view: &CanvasView) -> Vec { let mut shown = Vec::new(); for (index, path) in paths.iter().enumerate() { let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| { @@ -71,7 +76,7 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha }; let wanted = match handles { HandlesShown::All => true, - HandlesShown::OneAnchor => sel.selected_len() == 1 && of_selection(), + HandlesShown::OneAnchor => selected == 1 && of_selection(), HandlesShown::Selected => of_selection(), }; if wanted && !knot.retracted(side) { @@ -85,19 +90,19 @@ pub(super) fn shown_handles(paths: &[EditPath], sel: &PathSelection, handles: Ha /// The handles to draw for the anchors `sel` lists for the path at index `at` of `paths`, which the overlay does not /// edit: [`shown_handles`]' rule applied with that path as the selection's, the other selected anchors still counted. -/// Empty for `All`, whose handles the scene already holds. The index of each is `at`. +/// Empty for `All`, whose handles the scene already holds. The index of each is `at`. The overlay calls it once per +/// path, so it reads the other paths' anchor counts from `sel` and copies none of their anchors. pub(super) fn other_handles(paths: &[EditPath], at: usize, sel: &PathSelection, handles: HandlesShown, view: &CanvasView) -> Vec { let Some(path) = paths.get(at) else { return Vec::new() }; let listed = sel.others.iter().find(|(key, _)| *key == path.key).filter(|_| sel.path != Some(path.key)); let (Some((_, anchors)), false) = (listed, handles == HandlesShown::All) else { return Vec::new() }; - let mut own = PathSelection::new(Some(path.key), anchors.clone(), None); - for (key, rest) in sel.others.iter().filter(|(key, _)| *key != path.key) { - own = own.also(*key, rest.clone()); - } - if let Some(edited) = sel.path.filter(|edited| *edited != path.key) { - own = own.also(edited, sel.anchors.clone()); - } - shown_handles(std::slice::from_ref(path), &own, handles, view).into_iter().map(|shown| Shown { path: at, ..shown }).collect() + let rest: usize = sel.others.iter().filter(|(key, _)| *key != path.key).map(|(_, rest)| rest.len()).sum(); + let edited = sel.path.filter(|edited| *edited != path.key).map_or(0, |_| sel.anchors.len()); + let own = PathSelection::new(Some(path.key), anchors.clone(), None); + shown_handles_of(std::slice::from_ref(path), &own, anchors.len() + rest + edited, handles, view) + .into_iter() + .map(|shown| Shown { path: at, ..shown }) + .collect() } /// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index aa17f19146..994fdcbeaf 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -465,6 +465,30 @@ fn one_anchor_shows_handles_only_while_one_anchor_is_selected_over_all_paths() { assert!(!matches!(none, Some(BezierHit::Handle { .. })), "{none:?}"); } +// Under `OneAnchor` the handles of an anchor listed in `others` draw while it is the only selected anchor over all +// paths, as `Selected` draws them; with an anchor of a third path listed too, neither path's handles draw. +#[trial] +fn one_anchor_draws_other_paths_handles_only_while_one_anchor_is_selected_over_all_paths() { + let painted_with = |selection: PathSelection, handles: HandlesShown| { + let mut other = path_b(); + other.subpaths[0].knots[0] = Knot::smooth(p(60.0, 200.0), p(90.0, 170.0)); + let third = + EditPath::new(3, vec![EditSubpath::new(vec![Knot::smooth(p(300.0, 220.0), p(330.0, 190.0)), Knot::corner(p(360.0, 260.0))], false)]); + let mut h = harness(vec![path_a(), other, third]); + h.update(|st| (st.selection, st.handles) = (selection, handles)); + format!("{:?}", h.fixture.frame_shapes()) + }; + let one = || sel(1, &[]).also(2, vec![kr(0)]); + assert_eq!(painted_with(one(), HandlesShown::OneAnchor), painted_with(one(), HandlesShown::Selected)); + let two = || sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]); + assert_ne!(painted_with(two(), HandlesShown::OneAnchor), painted_with(two(), HandlesShown::Selected)); + assert_eq!( + painted_with(two(), HandlesShown::OneAnchor), + painted_with(sel(1, &[]).also(2, vec![kr(0)]).also(3, vec![kr(0)]), HandlesShown::OneAnchor), + "painting is the same from frame to frame" + ); +} + // Hovering a segment under Add reports the segment with its parameter, which the preview anchor stands at. // `AnchorsShown::Hidden` draws outlines only: no anchor, no handle, no part, no AccessKit object. From d4552077e99d89e746846ac329cf0ded928e9012 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 10:31:08 +0000 Subject: [PATCH 168/269] ui-canvas rulers: drop the centimetre rule's unreachable halves fallback A whole labelled centimetre is at least 24 points wide, so its quarter ticks are always 6 points apart; the 4-point fallback to halves never ran and the doc promised it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-canvas/src/canvas/rulers/ticks.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/crates/ui-canvas/src/canvas/rulers/ticks.rs b/crates/ui-canvas/src/canvas/rulers/ticks.rs index 1566afd8a4..8ed6dd2f93 100644 --- a/crates/ui-canvas/src/canvas/rulers/ticks.rs +++ b/crates/ui-canvas/src/canvas/rulers/ticks.rs @@ -16,8 +16,6 @@ pub const LABEL_STEP_MIN: f32 = 60.0; /// The least distance between labelled ticks of a centimetre document ruler, in points: a whole centimetre at 100% /// (about 28 points) is labelled, as Word's ruler does. pub const CENTIMETRE_LABEL_STEP_MIN: f32 = 24.0; -/// The least distance between ticks of a centimetre document ruler, in points. -const CENTIMETRE_TICK_STEP_MIN: f64 = 4.0; /// Labelled centimetre steps: 1, 2, 5, 10 times the base. const CENTIMETRE_STEPS: [f64; 9] = [1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0]; @@ -79,8 +77,8 @@ impl StepLadder { pub enum TickRule<'a> { /// The units' own table ([`RulerUnits::step`]): decimal steps and ten subdivisions, or the host's custom table. Metric, - /// Centimetres of a document ruler: a label every centimetre (every 2, 5, 10 and so on when smaller), with quarter - /// centimetre ticks while they stay [`CENTIMETRE_TICK_STEP_MIN`] apart, then halves. + /// Centimetres of a document ruler: a label every centimetre with quarter centimetre ticks, or every 2, 5, 10 and so + /// on centimetres with halves when a centimetre is narrower than [`CENTIMETRE_LABEL_STEP_MIN`]. Centimetres, /// Inches: a label every inch (every 2, 5, 10 and so on when smaller), subdivided by the first of these counts, /// finest first, that keeps the ticks a tenth of the least label step apart ([`INCH_SIXTEENTHS`], @@ -132,9 +130,8 @@ fn inch_step(points_per_inch: f64, finest: &[u32]) -> (f64, u32) { fn centimetre_step(points_per_cm: f64) -> (f64, u32) { let step_min = f64::from(CENTIMETRE_LABEL_STEP_MIN); let step = CENTIMETRE_STEPS.into_iter().find(|step| step * points_per_cm >= step_min).unwrap_or(1000.0); - let subdivisions = - if step > 1.0 { 2 } else { [4_u32, 2].into_iter().find(|n| points_per_cm / f64::from(*n) >= CENTIMETRE_TICK_STEP_MIN).unwrap_or(1) }; - (step, subdivisions) + // A whole labelled centimetre is at least 24 points wide, so its quarters are 6 points apart. + (step, if step > 1.0 { 2 } else { 4 }) } /// The ticks of one ruler over `values` (ruler units from the zero point): the one tick rule of every ruler, so a From 3b36acc52bb005fd0b60e216ac3849af834a93f2 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 10:32:25 +0000 Subject: [PATCH 169/269] menu gallery: the current tile's outline is accent.solid, not the translucent accent.border Several themes pin accent.border translucent so it reads on a control's own fill (Adwaita, Breeze, Soft, Studio, Solarized Dark). The current tile has no fill now, so that outline sat at 1.6 to 2.6:1 on the ribbon, under the 3:1 a state mark needs. accent.solid is what the other selection outlines take (table cells, graph nodes, timeline clips). Also drops the tile style's stale note about a selection fill. Co-Authored-By: Claude Opus 5.5 --- crates/menu/src/ribbon/gallery.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index 33515f33b4..51a4fde5b9 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -356,7 +356,7 @@ fn grid(ui: &mut Ui, label: &Label, items: &[GalleryItem<'_, K>], current: Op // --------------------------------------------------------------------------------------------------------------- // The tile. -/// The style of a gallery tile: the theme's selection fill and edge while it is the current one. +/// The style of a gallery tile: the accent outline while it is the current one. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] struct GalleryTileStyle { @@ -366,7 +366,9 @@ struct GalleryTileStyle { focus: FocusLook, /// Between the tile's edge and its picture. pad: f32, - /// The current tile's outline: accent, unfilled, so the picture keeps its own background. + /// The current tile's outline: `accent.solid`, unfilled, so the picture keeps its own background. Not + /// `accent.border`, which several themes pin translucent to read on a control's own fill: with no fill under it, + /// it falls under 3:1 on the ribbon. edge: StyleColor, /// The ink of the item's name under the picture, in a captioned gallery. caption: StyleColor, @@ -439,7 +441,7 @@ impl Component for GalleryTile<'_> { metrics: Metrics::new().padding(Insets::new(pad, pad, pad, pad)), focus: cx.focus_look(), pad, - edge: cx.color(colors.accent.border), + edge: cx.color(colors.accent.solid), caption: cx.color(colors.text.normal), gap: cx.tokens.space.gap.tight, thumbs: [cx.tokens.size.thumb.sm, cx.tokens.size.thumb.md, cx.tokens.size.thumb.lg], From 715cccfbb7a09d9d8563752ee98f33b7e494fc64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:32:25 -0800 Subject: [PATCH 170/269] ui-contract: a field puts a row of controls under its label when the row would fall below its least width A field decides whether its label sits beside its control from the control's least width. Its label scope kept the least width of the first control inside it, so a field whose control is a row of several controls, such as a path field and its Browse button, left only the path field's least beside the label. In a 240 pt room the label "Folder agents can open from" stayed beside the row, the path field got 28 pt and the button's text was cut. A row that is the first control under a label now records its own least width for the label: its fixed content, the least widths of its units, the least widths of the leaves that fill it, and the probed least of each body unit. The label then puts the row under itself when the row does not fit beside it at that width. A field whose controls fit beside its label stays as it was. --- crates/ui-contract/src/contract/run.rs | 7 +++ crates/ui-contract/src/layout/body.rs | 33 ++++++++++- crates/ui-contract/src/layout/mod.rs | 5 +- .../ui-contract/src/runtime/access/scope.rs | 33 ++++++++++- .../ui-contract/src/runtime/layout_memory.rs | 1 + crates/ui-contract/src/runtime/pass_state.rs | 1 + crates/ui-widgets/tests/it/label/mod.rs | 1 + crates/ui-widgets/tests/it/label/row_least.rs | 56 +++++++++++++++++++ 8 files changed, 129 insertions(+), 8 deletions(-) create mode 100644 crates/ui-widgets/tests/it/label/row_least.rs diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 942b93fd31..9765902768 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1798,6 +1798,13 @@ fn measure_step( Some(crate::layout::Shrink::Least(row)) if shape == ShapeKind::Body => crate::layout::report_least(ctx, row, id, size.x), _ => {} } + // A leaf that fills a shrinking row is no unit of it, but a row under a label counts its least among the controls'. + let fills_row = t.fills() == Some(craft_behavior::Axis::X) || begun.common.sizing == Some(super::Sizing::Fill); + if let (Some(least), Some(crate::layout::Shrink::Count(row))) = (min_took.filter(|_| fills_row), env.shrink) + && shrink.is_none() + { + crate::layout::report_fill_least(ctx, row, size.x, least.x); + } // A body that fills the rest of a shrinking row needs at least its content: the row counts it at that width, so // the units narrow to leave it, and it takes what they leave. if let Some(crate::layout::Shrink::Count(row)) = env.shrink.filter(|_| fill_body) { diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 5c64e895ed..b9732e0fb3 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -3,6 +3,7 @@ use super::column_group::{ColumnGroup, Columns}; use crate::contract::InBar; +use crate::runtime::access::scope; use crate::runtime::egui::{alloc, child}; use crate::runtime::env::{ColumnSweep, Env, RowLine, Shrink}; use crate::runtime::layout_memory; @@ -546,6 +547,12 @@ pub(crate) struct ShrinkReports(IdMap>); #[derive(Default)] pub(crate) struct LeastReports(IdMap>); +/// How much the leaves that fill each `Row` body under a label need at their least beyond what they took in its first +/// sweep (less where they took more), by row id: the row adds it to its units' least widths as the least its label +/// leaves it. +#[derive(Default)] +pub(crate) struct FillLeasts(IdMap); + /// How far the units of each `Row` body asked for one this pass reach past the row's room at their ideal widths, by /// row id: `None` for a row whose units fit. #[derive(Default)] @@ -727,6 +734,16 @@ fn level_of(ctx: &egui::Context, row: Id, unit: Id) -> (usize, Option) { .map_or((0, None), |(found, _)| (found.took.y.max(0.0) as usize, Some(found.took.x).filter(|width| width.is_finite() && *width > 0.0))) } +/// Reports the least width `least` of the leaf `leaf` that fills the row `row`, which took `took` in the row's first +/// sweep, to a row that sums its controls' least widths for its label (`FillLeasts`). +pub(crate) fn report_fill_least(ctx: &egui::Context, row: Id, took: f32, least: f32) { + pass_state::with::(ctx, |reports| { + if let Some(sum) = reports.0.get_mut(&row) { + *sum += least - took; + } + }); +} + /// Reports the least width of the body unit `body` of the row `row` that asks for it. pub(crate) fn report_least(ctx: &egui::Context, row: Id, body: Id, least: f32) { pass_state::with::(ctx, |reports| { @@ -984,11 +1001,17 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> } again }; - let (inner, rect, mut leaves, fixed, probe, again) = crate::contract::keeping_ids(&ctx, || { + // A row that is the first control under a label holds every control the label's placement must leave room for. + let labelled = scope::label_awaiting_min(&ctx); + let (inner, rect, mut leaves, fixed, fills, probe, again) = crate::contract::keeping_ids(&ctx, || { let mut first = laid_out_child(ui, layout); pass_state::with::(&ctx, |reports| reports.0.insert(id, Vec::new())); + if labelled.is_some() { + pass_state::with::(&ctx, |reports| reports.0.insert(id, 0.0)); + } let inner = sweep(&mut first, Shrink::Count(id), &mut body); let leaves = pass_state::with::(&ctx, |reports| reports.0.remove(&id)).unwrap_or_default(); + let fills = pass_state::with::(&ctx, |reports| reports.0.remove(&id)).unwrap_or_default(); let rect = first.min_rect(); let fixed = rect.width() - leaves.iter().map(|leaf| leaf.took).sum::(); let shortfall = fixed + leaves.iter().map(|leaf| leaf.widths.ideal).sum::() - room; @@ -996,9 +1019,10 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> if short { pass_state::with::(&ctx, |asked| asked.0.get_mut(&id).map(|slot| *slot = Some(shortfall))); } - let probe = room.is_finite() && short && leaves.iter().any(|leaf| leaf.body); + // A row under a label asks its bodies for their least whatever its room: the label's placement needs it. + let probe = (labelled.is_some() || (room.is_finite() && short)) && leaves.iter().any(|leaf| leaf.body); let again = !probe && settle(&leaves, fixed); - ((inner, rect, leaves, fixed, probe, again), probe || again) + ((inner, rect, leaves, fixed, fills, probe, again), probe || again) }); let again = again || probe; if probe { @@ -1020,6 +1044,9 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> } settle(&leaves, fixed); } + if let Some(container) = labelled { + scope::record_row_min(&ctx, container, fixed + fills + leaves.iter().map(|leaf| leaf.widths.least).sum::()); + } if again { child::block(ui, None, layout, |ui| sweep(ui, Shrink::Apply(id), &mut body)).0 } else { diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 2895b9f4da..b33afc7542 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -26,6 +26,7 @@ pub(crate) use body::run_body; pub(crate) use body::{ BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start_in, count_fill_view, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, - members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, - run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill, view_room, + members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_fill_least, report_held, report_least, + report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill, + view_room, }; diff --git a/crates/ui-contract/src/runtime/access/scope.rs b/crates/ui-contract/src/runtime/access/scope.rs index bb2ae60f6a..fe785b0555 100644 --- a/crates/ui-contract/src/runtime/access/scope.rs +++ b/crates/ui-contract/src/runtime/access/scope.rs @@ -366,27 +366,54 @@ pub(crate) fn record_control_min(ctx: &Context, width: f32) { stack.0.iter().rev().find(|scope| matches!(scope.kind, Kind::Label(_))).map(|scope| scope.container) }); if let Some(container) = container { - layout_memory::contribute(ctx, std::sync::Arc::new(ControlMin { container, width })); + layout_memory::contribute(ctx, std::sync::Arc::new(ControlMin { container, width, whole: false })); } } +/// The innermost open label scope, when no control inside it has reported its narrowest width yet. +pub(crate) fn label_awaiting_min(ctx: &Context) -> Option { + pass_state::with::(ctx, |stack| { + stack + .0 + .iter() + .rev() + .find(|scope| matches!(scope.kind, Kind::Label(_))) + .filter(|scope| scope.control_min.is_none()) + .map(|scope| scope.container) + }) +} + +/// Records `width` as the narrowest width of the controls of `container`'s label scope, in place of what the first of +/// them reported: the least of a row that holds them side by side, the first control of the scope +/// (`label_awaiting_min`). Only a measuring run records it. +pub(crate) fn record_row_min(ctx: &Context, container: Id, width: f32) { + layout_memory::contribute(ctx, std::sync::Arc::new(ControlMin { container, width, whole: true })); +} + /// A control's narrowest width reported to the label scope of `container`, as a measuring run hands it forward. struct ControlMin { container: Id, width: f32, + /// The width is the least of a row of controls (`record_row_min`): it replaces the first control's. + whole: bool, } impl layout_memory::Contribution for ControlMin { fn apply(&self, ctx: &Context) { pass_state::with::(ctx, |stack| { if let Some(scope) = stack.0.iter_mut().rev().find(|scope| scope.container == self.container && matches!(scope.kind, Kind::Label(_))) { - scope.control_min.get_or_insert(self.width); + if self.whole { + scope.control_min = Some(self.width); + } else { + scope.control_min.get_or_insert(self.width); + } } }); } fn report(&self) -> Option<(Id, f32)> { - Some((sub(self.container, "control_min"), self.width)) + // A row's shrink step sweeps only in a measuring run, so a real run has no row least to compare. + (!self.whole).then(|| (sub(self.container, "control_min"), self.width)) } fn undo(&self, ctx: &Context) -> layout_memory::TakeBack { diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index dbea6d3e98..2f35b81e50 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1266,6 +1266,7 @@ pub(crate) mod guard { ("layout::body::Cursors", "grid and spread cursors: opened and closed by the body's own run"), ("layout::body::ShrinkReports", "shrink reports: opened and closed by the row's own first sweep; the widths go through emit_record"), ("layout::body::LeastReports", "least reports: opened and closed by the row's own least sweep; the widths go through emit_record"), + ("layout::body::FillLeasts", "fill leasts: opened and closed by the row's own first sweep; the sum goes through contribute"), ("layout::body::RowShortfalls", "shortfalls: asked and taken by the container around the row in the same measuring sweep"), ("runtime::reads::Runs", "measuring runs of the read record: opened and closed by each run; reads go through contribute"), ("contract::steps::id::IdPass", "id registration: a measuring run keeps the ids it uses out of the pass (keeping_ids)"), diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 417b27d852..2ac5ad08b6 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -91,6 +91,7 @@ pass_state! { jumps: crate::contract::body::scroll::Jumps, shrink_reports: crate::layout::body::ShrinkReports, least_reports: crate::layout::body::LeastReports, + fill_leasts: crate::layout::body::FillLeasts, row_shortfalls: crate::layout::body::RowShortfalls, bar_rules: crate::contract::BarRules, surface_frames: crate::primitives::SurfaceFrames, diff --git a/crates/ui-widgets/tests/it/label/mod.rs b/crates/ui-widgets/tests/it/label/mod.rs index 37af7d23db..caa2537022 100644 --- a/crates/ui-widgets/tests/it/label/mod.rs +++ b/crates/ui-widgets/tests/it/label/mod.rs @@ -11,6 +11,7 @@ pub mod kit; pub(crate) mod link; pub(crate) mod reach; pub(crate) mod reset; +pub(crate) mod row_least; pub(crate) mod scheme; pub(crate) mod scrub_drags; pub(crate) mod short; diff --git a/crates/ui-widgets/tests/it/label/row_least.rs b/crates/ui-widgets/tests/it/label/row_least.rs new file mode 100644 index 0000000000..9fd16fcdc3 --- /dev/null +++ b/crates/ui-widgets/tests/it/label/row_least.rs @@ -0,0 +1,56 @@ +//! A field whose control is a row of several controls (a path field and its Browse button) puts the row under its +//! label when the label beside it would leave the row less than its least width. + +use craft_theme::Size; +use craft_ui::buttons::Button; +use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::form::Field; +use craft_ui::layout_components::Row; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::TextField; +use egui::{Rect, Vec2}; + +/// How far two edges may differ and still line up, in points. +const SLACK: f32 = 0.5; +const BROWSE: &str = "Browse…"; + +/// A field labelled `label` over a fill-width path field and a Browse button, in a room `width` wide. +fn path_field(label: &'static str, width: f32) -> Fixture { + let mut fixture = Fixture::new(move |ui| { + Field::new(label).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + TextField::new(label, Bind::given(String::from("/photos/agents"))).limit(None).sizing(Sizing::FillWidth).show(ui); + Button::new(BROWSE).show(ui); + }); + }); + }); + fixture.room(Vec2::new(width, 300.0)).density(Size::Compact); + fixture.settle(); + fixture +} + +fn caption(fixture: &Fixture, text: &str) -> Rect { + fixture.texts().iter().find(|run| run.text == text).map(|run| run.rect).unwrap_or_else(|| panic!("{text:?} is painted")) +} + +/// In a room 240 pt wide, the long label beside the row would leave it less than the path field's and the button's +/// least widths together. The row shows under the label, and the button's text shows whole. +#[trial] +fn a_long_label_puts_a_row_of_controls_under_it_when_the_row_would_fall_below_its_least() { + const LABEL: &str = "Folder agents can open from"; + let fixture = path_field(LABEL, 240.0); + let (label, field) = (caption(&fixture, LABEL), fixture.by_label(LABEL).expect("the label names the path field").rect); + assert!(label.max.y <= field.min.y + SLACK, "the path field shows under its label: {label:?} {field:?}"); + let texts = fixture.texts(); + let browse = texts.iter().find(|run| run.text == BROWSE).unwrap_or_else(|| panic!("{BROWSE:?} shows whole: {texts:?}")); + assert!(browse.clip.min.x <= browse.rect.min.x + SLACK && browse.clip.max.x >= browse.rect.max.x - SLACK, "Browse shows whole: {browse:?}"); +} + +/// A short label leaves the row its least width beside it, so the label stays beside the row. +#[trial] +fn a_short_label_stays_beside_a_row_of_controls_that_fits() { + const LABEL: &str = "Folder"; + let fixture = path_field(LABEL, 240.0); + let (label, field) = (caption(&fixture, LABEL), fixture.by_label(LABEL).expect("the label names the path field").rect); + assert!(label.max.x <= field.min.x + SLACK && label.max.y > field.min.y, "the label stays beside the path field: {label:?} {field:?}"); +} From c9c90a5a72fe572f9b1daeaa09546fe66aef83b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:46:51 -0800 Subject: [PATCH 171/269] host: QueueOptions::default_lanes reads the core count once per process `QueueOptions::default_lanes` called `std::thread::available_parallelism` on every call. On Linux that call opens /proc/self/cgroup and the cpu.max file of every cgroup level, so each call costs several file opens and reads. `ThumbnailOptions::new` calls it, and the glyphs panel's `glyph_painter` builds a `ThumbnailOptions` for every visible cell in every pass, so the panel made about 5,000 such calls per frame. The lane count is now computed once and kept in a `OnceLock`. wasm32 still returns 0. --- crates/host/src/queue.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/host/src/queue.rs b/crates/host/src/queue.rs index 7197297ccb..8133d17e64 100644 --- a/crates/host/src/queue.rs +++ b/crates/host/src/queue.rs @@ -19,6 +19,8 @@ use std::cmp::Reverse; use std::collections::VecDeque; use std::hash::Hash; +#[cfg(not(target_arch = "wasm32"))] +use std::sync::OnceLock; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Condvar, Mutex, MutexGuard}; use std::thread::{self, ThreadId}; @@ -94,14 +96,17 @@ pub enum QueueOrder { impl QueueOptions { /// Lanes for this machine: the number of cores less one, at least 2 and at most 8 (4 when - /// the core count is unknown); 0 on wasm32. + /// the core count is unknown); 0 on wasm32. The core count is read once per process. // lightcraft: crates/preview/src/pool.rs:104 `default_threads` (cores − 1 clamped to 2..=8; // ours is 0 on wasm32 instead of 1, because wasm runs jobs only through `run_inline`). pub fn default_lanes() -> usize { #[cfg(target_arch = "wasm32")] return 0; #[cfg(not(target_arch = "wasm32"))] - thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8)) + { + static LANES: OnceLock = OnceLock::new(); + *LANES.get_or_init(|| thread::available_parallelism().map_or(4, |n| n.get().saturating_sub(1).clamp(2, 8))) + } } } From 84279466d43f3aee85ca9bdc1cd7a8ba3389651a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:50:15 -0800 Subject: [PATCH 172/269] ui-contract: a scroll bar whose track has no room paints nothing A scroll view shorter than its padding has a view whose top lies below its bottom, and its scroll bar track inherits those crossed ends. The bar painted a thumb in that track. A scroll body 6 pt tall with 6 pt of padding above and below painted a thumb of zero height, and a FileListPicker list given 12 pt with 8 pt of padding painted one with a negative height, at [254.8, 296] to [256.8, 292]. ScrollBar::shapes now returns no shapes when the track is not positive, as ScrollBar::fades already paints no fade over a view with no room. Every bar that goes through it, a scroll body's, a collection's, the canvas's and the timeline's, is covered. Bars in views that have room paint as before. --- .../ui-contract/src/primitives/scroll_bar.rs | 6 +++- crates/ui-contract/tests/it/layout/mod.rs | 1 + .../ui-contract/tests/it/layout/short_view.rs | 33 +++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 crates/ui-contract/tests/it/layout/short_view.rs diff --git a/crates/ui-contract/src/primitives/scroll_bar.rs b/crates/ui-contract/src/primitives/scroll_bar.rs index 8027b18d56..3ff0a08bd8 100644 --- a/crates/ui-contract/src/primitives/scroll_bar.rs +++ b/crates/ui-contract/src/primitives/scroll_bar.rs @@ -89,8 +89,12 @@ impl ScrollBar { /// The shapes of the bar in `track` along `axis` for `span`, in `state` (the bar's: hovered while the pointer is /// anywhere on it): the track and the fully round thumb, `look.thumb_width` thick along the track's outer edge (its - /// bottom, or its end side in the reading direction). + /// bottom, or its end side in the reading direction). No shapes when the track has no room: a view shorter or + /// narrower than its padding gives its bar a track of no length, or one whose ends cross. pub fn shapes(look: &ScrollBarLook, track: Rect, axis: Axis, rtl: bool, span: &ScrollSpan, state: &StateSet) -> Vec { + if !track.is_positive() { + return Vec::new(); + } let full = Self::thumb(look.min_thumb, track, axis, rtl, span); let thumb = Self::along_edge(full, state.resolve(&look.thumb_width), axis, rtl); let round = |rect: Rect| CornerRadius::from(rect.width().min(rect.height()) / 2.0); diff --git a/crates/ui-contract/tests/it/layout/mod.rs b/crates/ui-contract/tests/it/layout/mod.rs index 3c8d9f2c6b..7ccab8dc8c 100644 --- a/crates/ui-contract/tests/it/layout/mod.rs +++ b/crates/ui-contract/tests/it/layout/mod.rs @@ -3,3 +3,4 @@ pub(crate) mod fill; pub(crate) mod line_fill; pub(crate) mod memory; pub(crate) mod overlay_bar; +pub(crate) mod short_view; diff --git a/crates/ui-contract/tests/it/layout/short_view.rs b/crates/ui-contract/tests/it/layout/short_view.rs new file mode 100644 index 0000000000..0264444f38 --- /dev/null +++ b/crates/ui-contract/tests/it/layout/short_view.rs @@ -0,0 +1,33 @@ +//! A scroll body whose rect is shorter than its padding: its view has no room, so its scroll bar paints nothing. + +use craft_ui::contract::{ContainerProps, Pad, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; +use craft_ui::testing::{Frames, pointer, trial}; +use craft_ui_test_kit::body::Slab; +use craft_ui_test_kit::contract::{Probe, Seen}; +use egui::{Pos2, Rect, Shape, Ui, Vec2}; +use std::cell::RefCell; + +/// The container's rect: shorter than the padding above and below its view. +const AT: Rect = Rect { min: Pos2::new(20.0, 20.0), max: Pos2::new(180.0, 26.0) }; + +/// The padded container that scrolls along y under `scroll`'s bar, holding a probe that paints nothing and is far +/// taller than the container. +fn short(ui: &mut Ui, seen: &RefCell, scroll: Scroll) { + let props = ContainerProps::new().pad(Pad::Control).sizing(Sizing::Fill).scroll(scroll); + Slab::new(props).id_salt("short").show_at(ui, AT, |ui, _| { + Probe::new(seen).size(Vec2::new(40.0, 400.0)).sizing(Sizing::FillWidth).id_salt("content").show(ui); + }); +} + +#[trial] +fn a_scroll_body_shorter_than_its_padding_paints_no_bar() { + for (name, scroll) in [("bar", Scroll::vertical()), ("overlay bar", Scroll::vertical().overlay())] { + let seen = RefCell::new(Seen::default()); + let mut show = |ui: &mut Ui| short(ui, &seen, scroll); + let mut frames = Frames::new(); + frames.frame(vec![pointer::moved(AT.center())], &mut show); + frames.idle(4, &mut show); + let painted: Vec = frames.frame_shapes(&mut show).iter().map(Shape::visual_bounding_rect).filter(|bounds| bounds.is_finite()).collect(); + assert!(painted.is_empty(), "{name}: the bar paints nothing: {painted:?}"); + } +} From 6169fc3032abf0f90ee1bae513cc640da3ce5794 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 10:54:15 +0000 Subject: [PATCH 173/269] ui-patterns preview zoom: opt-in whole-percent display PreviewZoom::whole_percent() caps the zoom field at whole percents ("94 %"), as a word processor's print preview shows. The default keeps the units zoom codec (up to two decimals), so image apps' 12.5% step is unchanged. Fixes storytold/wordcraft#7708. Co-Authored-By: Claude Sonnet 5.5 --- .../src/patterns/form_dialogs/preview.rs | 12 +++++++-- .../tests/it/form_dialogs/preview.rs | 26 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/preview.rs b/crates/ui-patterns/src/patterns/form_dialogs/preview.rs index 12ffd5a6e3..3bb60e82c3 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/preview.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/preview.rs @@ -675,13 +675,21 @@ impl Outcome for PreviewZoomOutput { #[derive(crate::contract::Pattern)] pub struct PreviewZoom { view: PreviewView, + whole_percent: bool, } impl PreviewZoom { /// A zoom row for `view`, the one the pane takes: the buttons stay inside its zoom range. While the pane fits, /// the caller has adopted the pane's `PreviewOutput::shown`, so the row steps from what is on screen. pub fn new(view: &PreviewView) -> Self { - PreviewZoom { view: view.clone() } + PreviewZoom { view: view.clone(), whole_percent: false } + } + + /// Shows the zoom as a whole percent ("94 %"), as a word processor's print preview does, instead of up to two + /// decimals. The view keeps its fractional zoom, and a typed fraction still applies; only the shown value is whole. + pub fn whole_percent(mut self) -> Self { + self.whole_percent = true; + self } /// Shows the row. @@ -694,7 +702,7 @@ impl PreviewZoom { let row = Row::new().show(ui, |ui, _| { let out = IconButton::new(IconId::new("minus")).label(words.zoom_out.clone()).enabled(self.view.can_zoom_out()).show(ui); let field = NumberField::new(words.zoom.clone(), Bind::given(Some(percent(self.view.transform.scale)))) - .codec(env.units().zoom_codec()) + .codec(if self.whole_percent { env.units().zoom_codec().at_most(0) } else { env.units().zoom_codec() }) .unit_kind(UnitKind::Percent) .range(range.clone()) .enabled(!self.view.fixed) diff --git a/crates/ui-patterns/tests/it/form_dialogs/preview.rs b/crates/ui-patterns/tests/it/form_dialogs/preview.rs index 093b9cc6d0..8672b922ec 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/preview.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/preview.rs @@ -83,3 +83,29 @@ fn a_click_reports_the_picture_point_under_it() { let (kept, moved) = click(8.0, false, vec2(16.0, 8.0)); assert!(near(kept, pos2(PICTURE.x / 2.0 + 2.0, PICTURE.y / 2.0 + 1.0)) && !moved, "{kept:?} {moved}"); } + +/// The zoom text the row shows for `scale`, with the option applied or not. +fn shown_zoom(scale: f32, whole: bool) -> Vec { + let view = PreviewView::new(CanvasTransform::new(scale, Vec2::ZERO)); + let mut fixture = Fixture::new(move |ui| { + let zoom = PreviewZoom::new(&view); + if whole { zoom.whole_percent() } else { zoom }.show(ui); + }); + fixture.settle(); + fixture.texts().iter().map(|run| run.text.clone()).collect() +} + +/// With `whole_percent`, a fractional zoom shows with no decimals. +#[trial] +fn a_whole_percent_preview_zoom_shows_no_decimals() { + let shown = shown_zoom(0.9415, true); + assert!(shown.iter().any(|text| text == "94"), "the zoom shows as 94: {shown:?}"); + assert!(!shown.iter().any(|text| text.contains('.') || text.contains(',')), "no decimals shown: {shown:?}"); +} + +/// Without it, a fractional zoom step keeps its decimals, as image apps need. +#[trial] +fn a_default_preview_zoom_keeps_a_fractional_step() { + let shown = shown_zoom(0.125, false); + assert!(shown.iter().any(|text| text.starts_with("12") && text.len() > 2), "the zoom keeps its decimals: {shown:?}"); +} From a5a72f1fe6faea5cb10cd09a3283ec8c166bbe10 Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 25 Nov 2026 12:01:31 +0100 Subject: [PATCH 174/269] 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 49c27ec4149fbb90d9f4f91e8dc97beecd085097 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:04:47 -0800 Subject: [PATCH 175/269] ui-widgets: ring focused parts that showed no focus ring Tab reached focusable parts whose component style had no focus look, so the paint step drew no ring: a notice's actions and dismiss button, bar items, a list row's trailing items, status action and thumbnail link, a chip, the alt text field's decorative check, a tile's actions, a tile grid's insert gaps, the thumbnail slider's buttons, a tab strip's end items and a table's header cells. A list row and a tile that are their own stop showed no ring either. Each of those styles now carries the theme's focus look. A collection (table, tile grid, tab strip) rings its focused parts but not itself: paint_focus skips the whole-component ring for the items shape, so no collection gains a ring around itself. TableStyle and BarItemsStyle no longer derive Default, since the focus look comes from the theme. --- crates/ui-contract/src/contract/run.rs | 2 +- .../ui-contract/src/contract/steps/paint.rs | 6 +- crates/ui-widgets/src/bars/items.rs | 7 +- crates/ui-widgets/src/list/row/show.rs | 1 + crates/ui-widgets/src/list/row/style.rs | 4 +- crates/ui-widgets/src/notices/notice.rs | 5 +- crates/ui-widgets/src/table/view.rs | 12 +-- crates/ui-widgets/src/tabs/strip.rs | 7 +- crates/ui-widgets/src/text/alt_text.rs | 6 +- crates/ui-widgets/src/text/chips.rs | 11 ++- crates/ui-widgets/src/tile_grid/grid.rs | 5 +- crates/ui-widgets/src/tile_grid/slider.rs | 6 +- crates/ui-widgets/src/tile_grid/tile.rs | 6 +- crates/ui-widgets/tests/it/main.rs | 1 + crates/ui-widgets/tests/it/part_rings.rs | 87 +++++++++++++++++++ 15 files changed, 143 insertions(+), 23 deletions(-) create mode 100644 crates/ui-widgets/tests/it/part_rings.rs diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 942b93fd31..da56d6a847 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1266,7 +1266,7 @@ fn paint_step(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &mut HostStep e.content_env(&mut h.values); steps::unfade(ui, e.core(), fade); ui.set_clip_rect(h.outer_clip); - steps::paint_focus(ui, e.core_ref(), p.style); + steps::paint_focus(ui, e.core_ref(), p.style, e.shape() != ShapeKind::Item); // A rule a bar's view shows waits for the member after it. if let Some((line, from)) = rule_from { hold_rule(ui, line, from); diff --git a/crates/ui-contract/src/contract/steps/paint.rs b/crates/ui-contract/src/contract/steps/paint.rs index 75f95948c8..0360b61534 100644 --- a/crates/ui-contract/src/contract/steps/paint.rs +++ b/crates/ui-contract/src/contract/steps/paint.rs @@ -114,8 +114,8 @@ pub(crate) fn paint_part_layers(ui: &Ui, env: &Env, core: &CxCore<'_>) { /// Step 13, paint, after `C::paint`: the focus ring of the focused component or its active part, when focus is /// keyboard-visible. An active part's ring takes the shape the part declared (`focus_shape`), else its rect; the /// component's own ring takes the shape it declared (`Cx::focus_shape`), else its rect with its surface's corners. Never -/// on `Well` surfaces. -pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView) { +/// on `Well` surfaces, and never around a collection (`whole` false), whose lead item shows the focus. +pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView, whole: bool) { let Some(look) = style.focus() else { return }; let ppp = ui.ctx().pixels_per_point(); let flags = core.state.flags; @@ -125,7 +125,7 @@ pub(crate) fn paint_focus(ui: &Ui, core: &CxCore<'_>, style: &dyn StyleView) { let declared = core.focus_shapes.iter().find(|((key, index), _)| craft_behavior::PartRef { key: *key, index: *index } == part); let outline = declared.map_or(PaintShape::Rect(rect, egui::CornerRadius::ZERO), |(_, shape)| FocusRing::outline(shape, rect)); ui.painter().extend(FocusRing::shapes(look, FocusKind::Ring, &outline, ppp)); - } else if FocusRing::visible(flags) && !well { + } else if whole && FocusRing::visible(flags) && !well { let outline = match &core.focus_shape { Some(shape) => FocusRing::outline(shape, core.rect), None => PaintShape::Rect(core.rect, style.surface().map_or(egui::CornerRadius::ZERO, |surface| surface.radius)), diff --git a/crates/ui-widgets/src/bars/items.rs b/crates/ui-widgets/src/bars/items.rs index fd524c8ebd..fd61817168 100644 --- a/crates/ui-widgets/src/bars/items.rs +++ b/crates/ui-widgets/src/bars/items.rs @@ -11,7 +11,7 @@ use crate::menu::{Menu, MenuItem}; use crate::primitives::IconSpec; use crate::runtime::commands::{CommandRef, ResolvedCommand}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, GlyphRole, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, GlyphRole, StyleCx}; use craft_behavior::fit::{FitItem, FitKeep, fit_items}; use craft_behavior::{Axis, IconId, Metrics, NavShape, PartKey, PartRef, Proposal, Roving, Sense}; use craft_theme::Variant; @@ -89,11 +89,13 @@ impl BarItem { /// The style of a bar item strip: the gap between items, the space around the rule of a section change and the /// space between the groups of a vertical strip. -#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +#[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct BarItemsStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// Between an item and the rule of a section change. joint: f32, /// The clear space of a section change, on both sides of its rule together. @@ -305,6 +307,7 @@ impl Component for BarItems { let gap = cx.tokens.space.gap.inline; BarItemsStyle { metrics: Metrics::new().gap(gap), + focus: cx.focus_look(), joint: gap, section_gap: gap * 2.0, stack_gap: gap + cx.tokens.space.gap.stack, diff --git a/crates/ui-widgets/src/list/row/show.rs b/crates/ui-widgets/src/list/row/show.rs index 35ca35602f..7113222b91 100644 --- a/crates/ui-widgets/src/list/row/show.rs +++ b/crates/ui-widgets/src/list/row/show.rs @@ -90,6 +90,7 @@ impl Component for ListRow<'_> { surface, // A separator is as high as its rule and the room around it. metrics: Metrics::new().min_size(Vec2::new(0.0, if key.separator { 0.0 } else { sizes.row })).gap(sizes.gap), + focus: cx.focus_look(), text: TextLook::new(role, ink(base)), icon: IconLook::new( sizes.icon, diff --git a/crates/ui-widgets/src/list/row/style.rs b/crates/ui-widgets/src/list/row/style.rs index 3942613e78..b6e7381451 100644 --- a/crates/ui-widgets/src/list/row/style.rs +++ b/crates/ui-widgets/src/list/row/style.rs @@ -2,7 +2,7 @@ use super::placement::Sizes; use crate::display::divider::SeparatorRule; -use crate::style::{ComponentStyle, DataColor, Flags, IconLook, StyleColor, StyleCx, SurfaceLook, TextLook}; +use crate::style::{ComponentStyle, DataColor, Flags, FocusLook, IconLook, StyleColor, StyleCx, SurfaceLook, TextLook}; use craft_behavior::Metrics; use craft_theme::{Contrast, Rgba, Stateful, States, contrast_ratio, identifiable_outline, over}; @@ -17,6 +17,8 @@ pub struct ListRowStyle { pub(super) surface: SurfaceLook, #[style(metrics)] pub(super) metrics: Metrics, + #[style(focus)] + pub(super) focus: FocusLook, /// The label. #[style(text)] pub(super) text: TextLook, diff --git a/crates/ui-widgets/src/notices/notice.rs b/crates/ui-widgets/src/notices/notice.rs index bd710c09f1..a0a3ec72d4 100644 --- a/crates/ui-widgets/src/notices/notice.rs +++ b/crates/ui-widgets/src/notices/notice.rs @@ -11,7 +11,7 @@ use crate::contract::{ use crate::primitives::{HAlign, IconSpec, TextRun, Wrap}; use crate::runtime::commands::CommandRef; use crate::runtime::env::{EnvView, Label}; -use crate::style::{ComponentStyle, IconLook, Insets, StyleColor, StyleCx, SurfaceKind, SurfaceLook, TextLook, TypeRole, UiTokens}; +use crate::style::{ComponentStyle, FocusLook, IconLook, Insets, StyleColor, StyleCx, SurfaceKind, SurfaceLook, TextLook, TypeRole, UiTokens}; use craft_behavior::{Flow, IconId, Metrics, NavShape, PartKey, Proposal, Roving, Sense}; use craft_i18n::Format; use craft_theme::{Rgba, Stateful, States, Variant, variant::Tone}; @@ -135,6 +135,8 @@ pub struct NoticeStyle { surface: SurfaceLook, #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// The title's role and colour. #[style(text)] title: TextLook, @@ -581,6 +583,7 @@ impl Component for Notice<'_> { NoticeStyle { surface, metrics: Metrics::new().padding(padding).gap(control.gap), + focus: cx.focus_look(), title, brand, byline, diff --git a/crates/ui-widgets/src/table/view.rs b/crates/ui-widgets/src/table/view.rs index cdfc063625..4aeaecb6ac 100644 --- a/crates/ui-widgets/src/table/view.rs +++ b/crates/ui-widgets/src/table/view.rs @@ -13,7 +13,7 @@ use crate::display::Divider; use crate::list::{DropTest, ListRow, RowEvent, RowTest, RowText}; use crate::menu::{Menu, MenuItem}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, StyleCx}; use craft_behavior::{ColumnKey, ItemSource, Metrics, Selection, SpanLayout}; use egui::{Rect, Ui}; use std::hash::Hash; @@ -21,12 +21,14 @@ use std::hash::Hash; /// The header menu's popup. const HEADER_MENU: &str = "header_menu"; -/// The style of the table: it has no look of its own beyond its container's surface. -#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] +/// The style of the table: the focus ring of its header cells, and no other look beyond its container's surface. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct TableStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, } /// A table: one Tab stop, a header row over the columns, the selection rules of the collection contract, type-ahead on @@ -134,8 +136,8 @@ impl Component for Table<'_, K> { type Style = TableStyle; type Output = CollectionResponse; - fn style(_: &StyleCx<'_>, _: TableStyleKey) -> TableStyle { - TableStyle::default() + fn style(cx: &StyleCx<'_>, _: TableStyleKey) -> TableStyle { + TableStyle { metrics: Metrics::default(), focus: cx.focus_look() } } fn update(&mut self, cx: &mut Cx<'_, Self>) { diff --git a/crates/ui-widgets/src/tabs/strip.rs b/crates/ui-widgets/src/tabs/strip.rs index e8379d2818..97dce4ce93 100644 --- a/crates/ui-widgets/src/tabs/strip.rs +++ b/crates/ui-widgets/src/tabs/strip.rs @@ -29,7 +29,7 @@ use crate::menu::Menu; use crate::primitives::{PaintShape, StrokeWidth}; use crate::runtime::commands::FireSource; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleColor, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, StyleColor, StyleCx}; use craft_behavior::fit::{FitItem, fit_items}; use craft_behavior::{ Flow, HitLevel, HitPriority, IconId, Insets, ItemLayout, ItemSource, Metrics, NavShape, PartKey, PressPhase, ScrollPos, Selection, @@ -122,12 +122,14 @@ fn strip_lead(kind: TabKind, tokens: &crate::style::UiTokens) -> f32 { if kind == TabKind::Ribbon { tokens.space.pad.regular } else { 0.0 } } -/// The look of a strip: it has none of its own; its row is as high as its tabs. +/// The look of a strip: the focus ring of its end items; its row is as high as its tabs. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct TabStripStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// The text line a wheel notch given in lines counts. line: f32, /// The colour of the one underline a ribbon strip slides under its shown tab. @@ -827,6 +829,7 @@ impl Component f let (lead, side) = (strip_lead(key.kind, tokens), if ribbon { super::tab::ribbon_pad(tokens) - tokens.stroke.thick / 2.0 } else { 0.0 }); TabStripStyle { metrics: Metrics::new().padding(Insets::new(lead, 0.0, 0.0, 0.0)), + focus: cx.focus_look(), line: tokens.typography.body.line_height, underline: cx.color(tokens.color.accent.solid), underline_inset: tokens.stroke.thick / 2.0, diff --git a/crates/ui-widgets/src/text/alt_text.rs b/crates/ui-widgets/src/text/alt_text.rs index 644e2ce1cd..5ca927ce14 100644 --- a/crates/ui-widgets/src/text/alt_text.rs +++ b/crates/ui-widgets/src/text/alt_text.rs @@ -10,7 +10,7 @@ use crate::contract::{ }; use crate::primitives::{TextOptions, TextRun}; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, Flags, StyleCx, SurfaceLook}; +use crate::style::{ComponentStyle, Flags, FocusLook, StyleCx, SurfaceLook}; use craft_behavior::{Codec, Metrics, Mixed, NotAValue, PartKey, Proposal, Sense}; use egui::{Rect, Vec2, pos2, vec2}; use std::borrow::Cow; @@ -104,6 +104,8 @@ pub struct AltTextFieldStyle { surface: SurfaceLook, #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, } /// An alt text editor: a multi-line description box and a Mark as decorative check. While the check is on, the box @@ -148,7 +150,7 @@ impl Component for AltTextField<'_> { fn style(cx: &StyleCx<'_>, _: AltTextFieldStyleKey) -> AltTextFieldStyle { let field = FieldStyle::at(cx); - AltTextFieldStyle { surface: field.surface, metrics: field.metrics.gap(cx.control().gap) } + AltTextFieldStyle { surface: field.surface, metrics: field.metrics.gap(cx.control().gap), focus: cx.focus_look() } } fn sense(&self) -> Sense { diff --git a/crates/ui-widgets/src/text/chips.rs b/crates/ui-widgets/src/text/chips.rs index 15cb0beb81..6ba34734af 100644 --- a/crates/ui-widgets/src/text/chips.rs +++ b/crates/ui-widgets/src/text/chips.rs @@ -14,7 +14,7 @@ use crate::display::Badge; use crate::menu::Menu; use crate::primitives::TextOptions; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleCx, SurfaceLook}; +use crate::style::{ComponentStyle, FocusLook, StyleCx, SurfaceLook}; use craft_behavior::{Caret, Codec, Flow, Granularity, IconId, Intent, Metrics, NavShape, NotAValue, PartKey, Proposal, Roving, Sense}; use craft_theme::Variant; use egui::{Rect, Response, Vec2, pos2, vec2}; @@ -105,6 +105,8 @@ pub struct ChipFieldStyle { surface: SurfaceLook, #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// The least width of the draft, so a full line of chips still leaves room to type. draft_min: f32, } @@ -334,7 +336,12 @@ impl Component for ChipField<'_> { fn style(cx: &StyleCx<'_>, _: ChipFieldStyleKey) -> ChipFieldStyle { let field = FieldStyle::at(cx); - ChipFieldStyle { surface: field.surface, metrics: field.metrics.gap(cx.control().gap), draft_min: cx.tokens.size.length.short } + ChipFieldStyle { + surface: field.surface, + metrics: field.metrics.gap(cx.control().gap), + focus: cx.focus_look(), + draft_min: cx.tokens.size.length.short, + } } fn sense(&self) -> Sense { diff --git a/crates/ui-widgets/src/tile_grid/grid.rs b/crates/ui-widgets/src/tile_grid/grid.rs index 07d0c57aab..d512ddbe30 100644 --- a/crates/ui-widgets/src/tile_grid/grid.rs +++ b/crates/ui-widgets/src/tile_grid/grid.rs @@ -24,7 +24,7 @@ use crate::primitives::{IconSpec, PaintShape, RectSide, StrokeWidth}; use crate::runtime::access::Name; use crate::runtime::commands::FireSource; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, RuleKind, StyleColor, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, RuleKind, StyleColor, StyleCx}; use craft_behavior::{ ColumnKey, ColumnWidth, EditEvent, HitLevel, HitPriority, Intent, ItemLayout as _, ItemSource, Metrics, Mixed, NavShape, PartKey, PointerButton, PressPhase, Roving, Selection, Sense, @@ -154,6 +154,8 @@ impl Outcome for TileGridOutput { pub struct TileGridStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// A header pinned over its group's tiles. pinned: StyleColor, /// The look of a group header: a heading row, which places the disclosure the grid declares. @@ -668,6 +670,7 @@ impl Component for TileGrid<'_, K> fn style(cx: &StyleCx<'_>, _: TileGridStyleKey) -> TileGridStyle { TileGridStyle { metrics: Metrics::new(), + focus: cx.focus_look(), pinned: cx.color(cx.tokens.color.surface.panel), header: ListRow::style(cx, ListRow::new(Label::default()).heading().style_key()), insert: cx.color(cx.tokens.color.accent.solid), diff --git a/crates/ui-widgets/src/tile_grid/slider.rs b/crates/ui-widgets/src/tile_grid/slider.rs index 3b9427b8db..6c7ebc8cad 100644 --- a/crates/ui-widgets/src/tile_grid/slider.rs +++ b/crates/ui-widgets/src/tile_grid/slider.rs @@ -6,7 +6,7 @@ use crate::contract::{ Access, Bind, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, Name, PaintUi, PartsCx, Props as _, Role, WordSetCx as _, }; use crate::runtime::env::Label; -use crate::style::{ComponentStyle, StyleCx}; +use crate::style::{ComponentStyle, FocusLook, StyleCx}; use craft_behavior::{IconId, Metrics, Mixed, NavShape, PartKey, Roving, Sense}; use egui::{Rect, Vec2}; use std::ops::RangeInclusive; @@ -106,6 +106,8 @@ const LARGER_ICON: &str = "grid"; pub struct ThumbnailSliderStyle { #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, } /// Where the thumbnail slider's three controls lie. @@ -152,7 +154,7 @@ impl Component for ThumbnailSlider<'_> { type Output = EditResponse; fn style(cx: &StyleCx<'_>, _: ThumbnailSliderStyleKey) -> ThumbnailSliderStyle { - ThumbnailSliderStyle { metrics: Metrics::new().gap(cx.control().gap) } + ThumbnailSliderStyle { metrics: Metrics::new().gap(cx.control().gap), focus: cx.focus_look() } } fn sense(&self) -> Sense { diff --git a/crates/ui-widgets/src/tile_grid/tile.rs b/crates/ui-widgets/src/tile_grid/tile.rs index 202fd4b8a7..734e225c4b 100644 --- a/crates/ui-widgets/src/tile_grid/tile.rs +++ b/crates/ui-widgets/src/tile_grid/tile.rs @@ -21,7 +21,8 @@ use crate::primitives::{ContentPainterCx, HAlign, IconSpec, PaintShape, StrokeWi use crate::runtime::commands::CommandRef; use crate::runtime::env::{Label, Units}; use crate::style::{ - ComponentStyle, Corners, DataColor, Flags, IconLook, StyleColor, StyleCx, SurfaceEdge, SurfaceKind, SurfaceLook, SurfaceStyle, TextLook, UiTokens, + ComponentStyle, Corners, DataColor, Flags, FocusLook, IconLook, StyleColor, StyleCx, SurfaceEdge, SurfaceKind, SurfaceLook, SurfaceStyle, + TextLook, UiTokens, }; use craft_behavior::{AccessAction, AccessData, Flow, IconId, Insets, Metrics, Mixed, NavShape, PartKey, PressPhase, Proposal, Roving, Sense}; use craft_keymap::Mods; @@ -243,6 +244,8 @@ pub struct TileStyle { surface: SurfaceLook, #[style(metrics)] metrics: Metrics, + #[style(focus)] + focus: FocusLook, /// The name. #[style(text)] name: TextLook, @@ -877,6 +880,7 @@ impl Component for Tile<'_> { sizes.inset, )) .gap(sizes.tight), + focus: cx.focus_look(), name: if key.card { TextLook::new(key.card_text.name_role(), ink(c(text.normal))) } else { diff --git a/crates/ui-widgets/tests/it/main.rs b/crates/ui-widgets/tests/it/main.rs index c9fd20c1dc..c54922f773 100644 --- a/crates/ui-widgets/tests/it/main.rs +++ b/crates/ui-widgets/tests/it/main.rs @@ -22,6 +22,7 @@ pub(crate) mod list; pub(crate) mod menu; pub(crate) mod notices; pub(crate) mod overlay; +pub(crate) mod part_rings; pub(crate) mod pickers; pub(crate) mod picture; pub(crate) mod popover; diff --git a/crates/ui-widgets/tests/it/part_rings.rs b/crates/ui-widgets/tests/it/part_rings.rs new file mode 100644 index 0000000000..ae940f0069 --- /dev/null +++ b/crates/ui-widgets/tests/it/part_rings.rs @@ -0,0 +1,87 @@ +//! The focus ring of focusable parts: Tab to each part of a story and the paint step rings it, as it rings a button. +//! A collection rings its focused parts but not itself, since its lead item shows the focus. + +use craft_behavior::PartKey; +use craft_ui::testing::{Fixture, Registry, trial}; +use egui::{Key, Modifiers, Rect, Shape}; + +/// The story named `name`, settled. +fn story(name: &str) -> Fixture { + let registry = Registry::of(&[crate::register, craft_ui::testing::register]); + let _ = registry.install_story_sets(); + let entry = registry.stories().iter().find(|entry| entry.story.name == name).unwrap_or_else(|| panic!("a story named {name}")); + let mut fixture = Fixture::story(&entry.story); + fixture.settle(); + fixture +} + +/// Presses Tab until the stop `part` (`None` for a component's own stop) holds the focus, and returns its rect. +fn tab_to(fixture: &mut Fixture, part: Option<&'static str>) -> Option { + let wanted = part.map(PartKey::new); + for _ in 0..24 { + fixture.key(Key::Tab, Modifiers::NONE).settle(); + let Some((owner, focused)) = fixture.focused_stop() else { continue }; + if focused.map(|focused| focused.key) != wanted { + continue; + } + return match focused { + Some(focused) => fixture.part_rect(owner, focused), + None => fixture.node_of(owner).map(|target| target.rect), + }; + } + None +} + +/// Whether the latest frame paints a focus ring (a rectangle stroke at least two points wide) around `target`. +fn ringed(fixture: &mut Fixture, target: Rect) -> bool { + fixture.frame_shapes().iter().any(|shape| match shape { + Shape::Rect(rect) if rect.stroke.width >= 2.0 => rect.rect.expand(1.0).contains_rect(target), + _ => false, + }) +} + +/// Each focusable part, and each control that is its own stop, is ringed when Tab reaches it. +#[trial] +fn focused_parts_show_the_focus_ring() { + const STOPS: &[(&str, Option<&str>)] = &[ + ("notice", Some("action")), + ("toast_stack", Some("dismiss")), + ("bar_items", Some("item")), + ("list_row", None), + ("list_row_trailing_items", Some("trailing")), + ("list_row_status_cell", Some("status-action")), + ("list_row_thumbnails_only", Some("link")), + ("chip_field", Some("chip")), + ("alt_text_field", Some("decorative")), + ("tile", None), + ("tile_actions", Some("action")), + ("tile_grid_insert_gaps", Some("insert_gap")), + ("thumbnail_slider", Some("out")), + ("tab_strip_ribbon_end_items", Some("end")), + ("table_one", Some("header")), + ("table_editable_grid", Some("header_remove")), + ]; + let mut unringed = Vec::new(); + for &(name, part) in STOPS { + let mut fixture = story(name); + let rect = tab_to(&mut fixture, part).unwrap_or_else(|| panic!("Tab reaches {part:?} in {name}")); + if !ringed(&mut fixture, rect) { + unringed.push(format!("{name} {part:?}")); + } + } + assert!(unringed.is_empty(), "these focused stops show no ring: {unringed:?}"); +} + +/// A focused collection draws no ring around itself: its lead item shows the focus. +#[trial] +fn a_focused_collection_draws_no_ring_around_itself() { + let mut ringed_whole = Vec::new(); + for name in ["tab_strip_ribbon_end_items", "table_one", "tile_grid_insert_gaps"] { + let mut fixture = story(name); + let rect = tab_to(&mut fixture, None).unwrap_or_else(|| panic!("Tab reaches the collection in {name}")); + if ringed(&mut fixture, rect) { + ringed_whole.push(name); + } + } + assert!(ringed_whole.is_empty(), "these collections ring themselves: {ringed_whole:?}"); +} From c0ed8a3e12a9fc20e5c4e94c2ced569da117816e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:06:37 -0800 Subject: [PATCH 176/269] ui-contract: Fixture::frame_clipped_shapes clears the texture changes it does not render frame_clipped_shapes dropped the frame's paint output with its texture changes still in it, so in a debug build a frame that uploaded a texture panicked with "Dropped TexturesDelta with 7 unapplied deltas". It now clears the texture changes before it reads the shapes, as frame_shapes_with already does. The test calls frame_clipped_shapes on the first frame of six menu, rail and tile stories; without the change it panics on the first of them. --- crates/ui-contract/src/testing/fixture.rs | 4 +++- crates/ui-panels/tests/it/main.rs | 1 + crates/ui-panels/tests/it/story_shapes.rs | 17 +++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 crates/ui-panels/tests/it/story_shapes.rs diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index 47c093e029..4b407b1277 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -525,7 +525,9 @@ impl Fixture { self.frames.record_paint(); self.frame(Vec::new()); let mut out = Vec::new(); - let Some(paint) = self.frames.take_paint() else { return out }; + let Some(mut paint) = self.frames.take_paint() else { return out }; + // Only the shapes are asked for: the texture changes since the first recorded frame go unrendered. + paint.textures_delta.clear(); for clipped in paint.shapes { let mut shapes = Vec::new(); fixture::flatten(clipped.shape, &mut shapes); diff --git a/crates/ui-panels/tests/it/main.rs b/crates/ui-panels/tests/it/main.rs index 83aaa72406..1c11662b45 100644 --- a/crates/ui-panels/tests/it/main.rs +++ b/crates/ui-panels/tests/it/main.rs @@ -18,6 +18,7 @@ pub(crate) mod popup_surface; pub(crate) mod rails; pub(crate) mod sections; +pub(crate) mod story_shapes; craft_ui::registry!(); diff --git a/crates/ui-panels/tests/it/story_shapes.rs b/crates/ui-panels/tests/it/story_shapes.rs new file mode 100644 index 0000000000..ef8f94c747 --- /dev/null +++ b/crates/ui-panels/tests/it/story_shapes.rs @@ -0,0 +1,17 @@ +//! A fixture returns the clipped shapes of a frame that uploads textures. + +use craft_ui::testing::{Fixture, Registry, trial}; + +/// Menu, rail and tile stories; the first frame of each uploads textures, the font atlas among them. +const STORIES: [&str; 6] = + ["tool_rail_marked_in_a_closed_group", "edit_menu", "menu", "menu_taller_than_the_window", "menu_with_companion", "tile_actions"]; + +#[trial] +fn the_first_frame_of_a_story_returns_its_clipped_shapes() { + let registry = Registry::of(&[craft_ui::testing::register, craft_ui_widgets::testing::register]); + for name in STORIES { + let entry = registry.stories().iter().find(|entry| entry.story.name == name).unwrap_or_else(|| panic!("story {name}")); + let shapes = Fixture::story(&entry.story).frame_clipped_shapes(); + assert!(!shapes.is_empty(), "{name}: the frame paints the story"); + } +} From 19114f32954a5c821b0c8a7d25289579120647fe Mon Sep 17 00:00:00 2001 From: alehel Date: Wed, 25 Nov 2026 12:07:56 +0100 Subject: [PATCH 177/269] 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 cb1b2301ad615df8b3592b70218ef74b333a53c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:01:02 -0800 Subject: [PATCH 178/269] ui-widgets: InspectOverlay's Tab-order badges show whole inside the drawing Each badge was centered on its stop's leading top corner with nothing keeping it inside the drawing, so a stop at the region's edge got a badge cut in half. In the inspect_overlay story at 400 x 300, badges 1 and 2 sat across the left edge and badge 1 across the top. The badge, ring included, is now moved the least distance that puts it inside the drawing, with keep_inside, the rule a layer's bounds use. On an axis where it already fits it stays on the corner. keep_inside is now public in craft-ui-contract's contract module. --- crates/ui-contract/src/contract/body.rs | 2 +- .../ui-contract/src/contract/body/window.rs | 2 +- crates/ui-contract/src/contract/mod.rs | 1 + .../ui-widgets/src/display/inspect_overlay.rs | 10 ++- crates/ui-widgets/tests/it/runtime/inspect.rs | 65 +++++++++++++++++++ 5 files changed, 76 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index 34dc4a8640..76f1c9c2aa 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -36,7 +36,7 @@ pub use scroll::{STRIP_BACK, STRIP_FORWARD}; pub(crate) use window::MOVE_BAND; use window::WindowMode; pub use window::grip_band; -pub(crate) use window::keep_inside; +pub use window::keep_inside; /// The scroll region's view in the last pass that showed it. #[derive(Clone, Default)] diff --git a/crates/ui-contract/src/contract/body/window.rs b/crates/ui-contract/src/contract/body/window.rs index 79eb032b4d..518f756173 100644 --- a/crates/ui-contract/src/contract/body/window.rs +++ b/crates/ui-contract/src/contract/body/window.rs @@ -215,7 +215,7 @@ fn resized_edge(before: Rect, after: Rect) -> Option { /// `rect` moved, at its size, the least distance that puts it inside `bounds`: the one keep rule for a layer's /// bounds, whether the user moves the layer or the host places it. On an axis where it is longer than the bounds, its /// low edge sits on theirs. -pub(crate) fn keep_inside(rect: Rect, bounds: Rect) -> Rect { +pub fn keep_inside(rect: Rect, bounds: Rect) -> Rect { let keep = |low: f32, high: f32, bounds_low: f32, bounds_high: f32| low.min(bounds_high - (high - low)).max(bounds_low) - low; rect.translate(Vec2::new(keep(rect.min.x, rect.max.x, bounds.min.x, bounds.max.x), keep(rect.min.y, rect.max.y, bounds.min.y, bounds.max.y))) } diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 60c7bfd0c1..c92e4accef 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -54,6 +54,7 @@ pub use crate::runtime::pending::{Job, Pending, Progress}; pub use body::REORDER_BAND; #[doc(hidden)] pub use body::grip_band; +pub use body::keep_inside; pub use body::pad_of; #[doc(hidden)] pub use body::{STRIP_BACK, STRIP_FORWARD}; diff --git a/crates/ui-widgets/src/display/inspect_overlay.rs b/crates/ui-widgets/src/display/inspect_overlay.rs index 73f9e24ab7..fd259d3399 100644 --- a/crates/ui-widgets/src/display/inspect_overlay.rs +++ b/crates/ui-widgets/src/display/inspect_overlay.rs @@ -1,7 +1,7 @@ //! `InspectOverlay`: the debug inspector's drawing over an inspected region ([`inspect::record`]): each element's //! padding, the hit areas and the focus stops numbered in Tab order, as the record of the region says. -use crate::contract::{Common, Component, Cx, MeasureCx, PaintUi, Role}; +use crate::contract::{Common, Component, Cx, MeasureCx, PaintUi, Role, keep_inside}; use crate::primitives::{Draw, PaintShape, StrokeWidth, TextRun}; use crate::runtime::inspect::Recorded; use crate::style::{ComponentStyle, StyleColor, StyleCx, TypeRole}; @@ -46,6 +46,8 @@ pub struct InspectOverlayStyle { marquee_fill: StyleColor, badge: StyleColor, badge_text: StyleColor, + /// The width of the ring round a badge: `stroke.thin`. + badge_ring: f32, /// Hit areas under this size across are flagged. pub min_target: f32, } @@ -120,6 +122,7 @@ impl Component for InspectOverlay { marquee_fill: cx.color(color.overlay.marquee.faded(Opacity::TINT)), badge: cx.color(color.status.info.solid), badge_text: cx.color(color.text.on_status), + badge_ring: cx.tokens.stroke.thin, min_target: cx.tokens.size.control.sm, } } @@ -177,10 +180,13 @@ impl InspectOverlay { stops.sort_unstable(); for (number, index) in stops { let Some(bounds) = recorded.stop_rect(index) else { continue }; - let centre = if rtl { bounds.right_top() } else { bounds.left_top() }; + let corner = if rtl { bounds.right_top() } else { bounds.left_top() }; let run = TextRun::new(number.to_string()).role(TypeRole::Caption).color(style.badge_text); let layout = draw.layout(&run, f32::INFINITY); let radius = (layout.size().max_elem() / 2.0 + 2.0).max(7.0); + // Centred on the stop's leading top corner, moved in where that would put the badge past the drawing's edge. + let reach = Vec2::splat(2.0 * (radius + style.badge_ring)); + let centre = keep_inside(Rect::from_center_size(corner, reach), cx.content_rect).center(); draw.fill(&PaintShape::Circle(centre, radius), style.badge); draw.stroke(&PaintShape::Circle(centre, radius), StrokeWidth::Thin, style.halo); draw.galley(centre - layout.size() / 2.0, &layout); diff --git a/crates/ui-widgets/tests/it/runtime/inspect.rs b/crates/ui-widgets/tests/it/runtime/inspect.rs index b4ef417476..3f24e90960 100644 --- a/crates/ui-widgets/tests/it/runtime/inspect.rs +++ b/crates/ui-widgets/tests/it/runtime/inspect.rs @@ -88,6 +88,71 @@ fn a_region_records_its_own_elements_and_numbers_every_stop() { } } +/// The inspected region's rect and its record, as the latest real pass showed them. +type Drawn = (Rect, Arc); + +/// Each Tab-order badge shows whole inside the drawing, in both directions: a badge on a stop at the region's edge +/// moves in until it fits, and on an axis where it already fits it stays on its stop's leading top corner. +#[trial] +fn every_badge_shows_whole_inside_the_region() { + use craft_ui::runtime::env::Direction; + use egui::{Shape, vec2}; + + for direction in [Direction::Ltr, Direction::Rtl] { + let key = Id::NULL.with("trial.inspect.badges"); + let seen: Rc>> = Rc::new(RefCell::new(None)); + let out = Rc::clone(&seen); + let mut snap = true; + let mut fixture = Fixture::new(move |ui| { + let (shown, recorded) = inspect::record(ui, key, |ui| { + Stack::new().show(ui, |ui, _| { + Button::new("Apply").show(ui); + Checkbox::new(Bind::bound(&mut snap)).label("Snap to grid").show(ui); + }) + }); + if let Some(recorded) = recorded { + InspectOverlay::new(Arc::clone(&recorded)).show_at(ui, shown.output.rect); + *out.borrow_mut() = Some((shown.output.rect, recorded)); + } + }); + fixture.room(vec2(400.0, 300.0)).direction(direction); + fixture.ctx().disable_accesskit(); + fixture.settle(); + let shapes = fixture.frame_shapes(); + let seen = seen.borrow(); + let (region, recorded) = seen.as_ref().expect("the region ran"); + let mut stops: Vec<(usize, usize)> = + recorded.elements.iter().enumerate().filter_map(|(index, element)| Some((element.stop?, index))).collect(); + stops.sort_unstable(); + assert!(stops.len() >= 2, "{direction:?}: the region has stops: {stops:?}"); + for (number, index) in stops { + let text = fixture.texts().iter().find(|text| text.text == number.to_string()).cloned().expect("the badge's number is painted"); + // The badge's disc and ring, centred on its number; a circle's stroke lies outside its radius. + let reach = shapes + .iter() + .filter_map(|shape| match shape { + Shape::Circle(circle) if circle.center.distance(text.rect.center()) < 1.0 => Some(circle.radius + circle.stroke.width), + _ => None, + }) + .fold(0.0_f32, f32::max); + assert!(reach > 0.0, "{direction:?}: badge {number} has a disc round its number"); + let badge = Rect::from_center_size(text.rect.center(), vec2(2.0 * reach, 2.0 * reach)); + assert!(region.expand(0.05).contains_rect(badge), "{direction:?}: badge {number} at {badge:?} shows whole in the region {region:?}"); + assert!(region.expand(0.5).contains_rect(text.rect), "{direction:?}: badge {number}'s number at {:?} shows whole", text.rect); + // Where the stop's corner leaves room for the whole badge, the badge stays on it. + let stop = recorded.stop_rect(index).expect("the stop is recorded"); + let corner = if direction == Direction::Rtl { stop.right_top() } else { stop.left_top() }; + let room = region.shrink(reach); + if (room.min.x..=room.max.x).contains(&corner.x) { + assert!((badge.center().x - corner.x).abs() < 1.0, "{direction:?}: badge {number} stays on its stop across"); + } + if (room.min.y..=room.max.y).contains(&corner.y) { + assert!((badge.center().y - corner.y).abs() < 1.0, "{direction:?}: badge {number} stays on its stop down"); + } + } + } +} + /// The commands the command trial's buttons are bound to. #[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] #[command(prefix = "inspectTrial")] From 52948ceaaf2518c95b2a66ba6274c610fbed4007 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 03:41:50 -0800 Subject: [PATCH 179/269] dock: a docked group's drag band narrows before the shown tab loses its first letters In a header too narrow for the drag band and the shown tab, the band took its whole width first and the tab strip got what was left. In the DockArea story's 40 pt Tools column the shown tab was 2 pt wide at compact density and missing at comfortable density, though TabStrip keeps the shown tab visible. - ui-contract: HeaderParts::end_narrows lets a container's end parts give up width, down to a least, so the header's children keep a given room. The header line applies it; headers that fit are unchanged. - ui-panels: DockGroup keeps room for the shown tab with its first three letters (with its icon, count, mark and close button, and the overflow button beside other tabs), and its band narrows to an icon's width before that room shrinks. Floating groups use the same header. Test: a_narrow_groups_drag_band_narrows_before_the_shown_tab --- .../ui-contract/src/contract/body/regions.rs | 11 +++- crates/ui-contract/src/contract/container.rs | 15 ++++- crates/ui-panels/src/docking/group.rs | 56 +++++++++++++++---- crates/ui-panels/tests/it/dock_group.rs | 49 ++++++++++++++++ docs/contract-api.md | 3 +- 5 files changed, 119 insertions(+), 15 deletions(-) diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index 5b4025a61e..2e39c20830 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -362,7 +362,8 @@ impl<'b> BodyHooks<'b> { } /// The header's line inside its inset, less the slots of the container's own header parts at its two edges: the - /// rect the header's children get, and the slots. + /// rect the header's children get, and the slots. An end edge that narrows (`HeaderParts::end_narrows`) gives up + /// room, down to its least, until the children keep their room. pub(super) fn header_line(&self, header: Rect, inset: f32, parts: HeaderParts, rtl: bool) -> (Rect, HeaderSlots) { let mut flow = craft_behavior::Flow::new(header.shrink2(Vec2::new(inset, 0.0)), rtl); let mut slots = HeaderSlots::default(); @@ -371,8 +372,12 @@ impl<'b> BodyHooks<'b> { slots.start = Some(slot); flow = rest.take_start(self.region_gap).1; } - if parts.end > 0.0 { - let (slot, rest) = flow.take_end(parts.end); + let end = match parts.end_least { + Some(least) => parts.end.min((flow.rect().width() - self.region_gap - parts.keep).max(least)), + None => parts.end, + }; + if end > 0.0 { + let (slot, rest) = flow.take_end(end); slots.end = Some(slot); flow = rest.take_end(self.region_gap).1; } diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 942cdd8240..7866ce3a95 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -280,11 +280,16 @@ pub struct HeaderParts { pub start: f32, /// The width at the end edge. pub end: f32, + /// The least the end edge narrows to, when the line is too narrow for the header's children to keep `keep` + /// beside the end parts' whole width. `None`: the end edge keeps its width. + pub end_least: Option, + /// The room the header's children keep before the end edge narrows below `end` (to `end_least`). + pub keep: f32, } impl HeaderParts { /// No room for parts. - pub const NONE: HeaderParts = HeaderParts { start: 0.0, end: 0.0 }; + pub const NONE: HeaderParts = HeaderParts { start: 0.0, end: 0.0, end_least: None, keep: 0.0 }; /// `width` at the start edge. pub const fn start(mut self, width: f32) -> Self { @@ -297,6 +302,14 @@ impl HeaderParts { self.end = width; self } + + /// The end edge narrows, down to `least`, so the header's children keep `keep` of the line: on a line too narrow + /// for both, the children's least room comes before the end parts' whole width. + pub const fn end_narrows(mut self, least: f32, keep: f32) -> Self { + self.end_least = Some(least); + self.keep = keep; + self + } } /// An edge of a header's line, where a container's own header parts sit. diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 29c277e8ac..a4426dbcdb 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -221,6 +221,15 @@ const GRIP: PartKey = PartKey::new("grip"); fn grip_width(tokens: &Tokens) -> f32 { tokens.size.icon.lg + 2.0 * tokens.space.pad.regular } + +/// The least the drag band narrows to in a header too narrow for it and the shown tab: an icon's room. +fn grip_least(tokens: &Tokens) -> f32 { + tokens.size.icon.lg +} + +/// How many of the shown tab's first letters the header keeps room for before the drag band narrows, as many as a +/// shrunk panel tab shows. +const SHOWN_TAB_LETTERS: usize = 3; /// The panel menu button at the header's end edge. pub(super) const MENU: PartKey = PartKey::new("panel_menu"); /// Where the group menu hangs while a context request on a tab holds it open: the request's point. @@ -492,6 +501,34 @@ impl<'a, P: Clone + Hash + Send + Sync + PartialEq + Debug + 'static> DockGroup< IconButton::new(self.panel_menu_icon.clone()).size(ControlSize::Sm).popup(PopupKind::Menu).label(name) } + /// The room the panel menu button takes past the drag band, with the gap before it; none when it does not show. + fn menu_room(&self, cx: &MeasureCx<'_, Self>) -> f32 { + if self.shows_menu_button() { cx.tokens.space.gap.item + cx.face(self.menu_face(cx.words::().panel_menu.clone())).x } else { 0.0 } + } + + /// The least room the strip takes to show the shown tab's first letters: the tab as the strip builds it (icon, + /// count, mark and close button) with only those letters of its title, and beside other tabs the overflow + /// button, which is as wide as the tab is high. + fn shown_tab_least(&self, cx: &MeasureCx<'_, Self>) -> f32 { + let panels = self.panels.as_slice(); + let tabs = strip_tabs(panels, self.closable); + let shown = shown_tab(panels, self.active); + let Some(tab) = tabs.iter().find(|tab| tab.key == shown) else { return 0.0 }; + let letters: String = tab.title.as_str().chars().take(SHOWN_TAB_LETTERS).collect(); + let marked = tab_marks(cx.ui.ctx(), panels).iter().any(|(key, _)| *key == shown); + let mut face = Tab::new(letters).kind(TabKind::Panel).panel_look(self.tab_look).closable(tab.closes).marked(marked); + if let Some(count) = tab.count { + face = face.detail(cx.env.format().integer(u64::try_from(count).unwrap_or(u64::MAX))); + } + match tab.swatch { + Some(Some(color)) => face = face.icon(IconSpec::swatch(color)), + Some(None) => face = face.icon(IconSpec::empty_swatch()), + None => {} + } + let size = cx.face(face); + if tabs.len() > 1 { size.x + size.y } else { size.x } + } + /// Starts a drag of the whole group: its drop region shows the group's name. fn start_drag(&mut self, cx: &mut Cx<'_, Self>) { start_group_drag(cx, DragUnit::Group(self.anchor.clone()), self.active, Some(self.size), Some(cx.label())); @@ -520,12 +557,14 @@ impl Component for let Some(slot) = cx.header_slot(HeaderEdge::End) else { return }; let words = cx.words::(); let flow = craft_behavior::Flow::new(slot, cx.flow.is_rtl()); - let (band, rest) = flow.take_start(grip_width(cx.tokens)); + // The band takes what the slot leaves past the panel menu button, which a narrowed header takes from the band. + let width = (slot.width() - self.menu_room(cx)).clamp(0.0, grip_width(cx.tokens)); + let (band, rest) = flow.take_start(width); let sense = if self.movable { Sense::CLICK | Sense::DRAG | Sense::FOCUS } else { Sense::CLICK | Sense::FOCUS }; let _ = cx.header_part(HeaderEdge::End, GRIP, band).sense(sense).focusable(); if self.shows_menu_button() { // An icon button is square: its side is the slot's room past the band and the gap. - let side = (slot.width() - grip_width(cx.tokens) - cx.tokens.space.gap.item).max(0.0); + let side = (slot.width() - width - cx.tokens.space.gap.item).max(0.0); let end = rest.take_end(side).0; let height = side.min(slot.height()); let top = if self.tab_look == PanelTabLook::Plain { slot.top() } else { slot.center().y - height / 2.0 }; @@ -680,15 +719,12 @@ impl Container for Some(self.open.reborrow()) } - /// The drag band, then the panel menu button when it shows, at the header's end edge. + /// The drag band, then the panel menu button when it shows, at the header's end edge. In a header too narrow for + /// them and the shown tab's least room, the band narrows to an icon's room, so the shown tab stays visible. fn header_parts(&self, cx: &MeasureCx<'_, Self>) -> HeaderParts { - let band = grip_width(cx.tokens); - let button = if self.shows_menu_button() { - cx.tokens.space.gap.item + cx.face(self.menu_face(cx.words::().panel_menu.clone())).x - } else { - 0.0 - }; - HeaderParts::NONE.end(band + button) + let button = self.menu_room(cx); + let parts = HeaderParts::NONE.end(grip_width(cx.tokens) + button); + if self.titled { parts } else { parts.end_narrows(grip_least(cx.tokens) + button, self.shown_tab_least(cx)) } } fn footer(&mut self, ui: &mut Ui, _: &mut BodyCx<'_>) { diff --git a/crates/ui-panels/tests/it/dock_group.rs b/crates/ui-panels/tests/it/dock_group.rs index b76f4b2753..70e4217822 100644 --- a/crates/ui-panels/tests/it/dock_group.rs +++ b/crates/ui-panels/tests/it/dock_group.rs @@ -296,6 +296,55 @@ fn a_press_on_an_app_drag_widget_in_the_body_is_no_surface_press() { assert!(surface.get(), "a press on the empty body is the group's surface press"); } +// As a group narrows, at both densities, the drag band narrows to its least before the shown tab goes below the width a +// shrunk tab keeps (its first letters), alone and beside a tab that goes to the overflow menu. The shown tab stays +// inside the group, and the band never covers it, down to a 40 pt column. +#[trial] +fn a_narrow_groups_drag_band_narrows_before_the_shown_tab() { + use craft_theme::Size; + let tab = |width: f32, density: Size, names: &'static [&'static str]| { + let panels: Vec = names.iter().enumerate().map(|(at, name)| PanelTitle::new(PanelKey::new(at as u64 + 1), *name)).collect(); + let group_rect = Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(width, 200.0)); + let grip = Rc::new(Cell::new(None::)); + let seen = Rc::clone(&grip); + let mut fixture = Fixture::new(move |ui| { + let out = DockGroup::new(1usize, Titles::from_content(panels.clone()), panels[0].key).show_at(ui, group_rect, |_, _| ()); + seen.set(out.output.grip.map(|(rect, _)| rect)); + }); + fixture.density(density).settle(); + (fixture.by_label("Tools").map(|node| node.rect), grip.get()) + }; + for density in [Size::Compact, Size::Comfortable] { + // The least a tab shows: the narrowest "Tools" gets beside a shown tab as the group narrows by 1 pt steps, before + // it overflows; so within 1 pt of the strip's least. + let least = (0..260) + .filter_map(|step| tab(300.0 - step as f32, density, &["Tools Options", "Tools"]).0) + .map(|rect| rect.width()) + .fold(f32::INFINITY, f32::min); + assert!(least.is_finite(), "the other tab shows shrunk in some group ({density:?})"); + for names in [&["Tools"][..], &["Tools", "Swatches"][..]] { + let (Some(natural), Some(whole)) = tab(300.0, density, names) else { panic!("a wide group shows the tab and the band ({density:?})") }; + let least = least.min(natural.width()); + // The band at its narrowest, in the narrowest group. + let (_, Some(narrowest)) = tab(40.0, density, names) else { panic!("a 40 pt group shows the band ({density:?}, {names:?})") }; + assert!(narrowest.width() < whole.width() - 0.5, "the band narrows in a 40 pt group ({density:?}, {names:?})"); + for width in (0..13).map(|step| 40.0 + 8.0 * step as f32) { + let (shown, grip) = tab(width, density, names); + let Some(shown) = shown else { panic!("the shown tab shows in a {width} pt group ({density:?}, {names:?})") }; + let Some(grip) = grip else { panic!("the band shows in a {width} pt group ({density:?}, {names:?})") }; + let group = Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(width, 200.0)); + assert!(group.contains_rect(shown), "the shown tab {shown:?} lies inside the {width} pt group ({density:?}, {names:?})"); + assert!(!grip.intersects(shown.shrink(0.5)), "the band {grip:?} does not cover the shown tab {shown:?} in {width} pt ({density:?})"); + assert!( + shown.width() >= least - 1.0 || grip.width() <= narrowest.width() + 0.5, + "the band {grip:?} narrows to {} pt before the shown tab {shown:?} goes below {least} pt in {width} pt ({density:?}, {names:?})", + narrowest.width() + ); + } + } + } +} + // Closable panel tabs stay panel tabs: in a group too narrow for their whole names every tab keeps its place in the // strip, the shown one its whole name, and each shows a close button. A middle click closes an inactive tab without // showing it first. diff --git a/docs/contract-api.md b/docs/contract-api.md index b186ce4737..2f49f3115d 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2279,10 +2279,11 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::GroupState`: `pub struct GroupState { pub selected: Option, pub members: Vec<(M, Id, bool)> }`. A group's registrations: the members shown in the last pass and the member the group picked. - `craft_ui::contract::HeaderEdge`: `pub enum HeaderEdge { Start, End }`. An edge of a header's line, where a container's own header parts sit. - `craft_ui::contract::HeaderMenuRequest`: `pub struct HeaderMenuRequest { pub column: Option, pub at: Pos2 }`. A request for the header menu: a secondary click on a header cell or on the empty header after the last one, or the -- `craft_ui::contract::HeaderParts`: `pub struct HeaderParts { pub start: f32, pub end: f32 }`. The room a container's own parts take on its header's line (`Container::header_parts`): a width at the start edge +- `craft_ui::contract::HeaderParts`: `pub struct HeaderParts { pub start: f32, pub end: f32, pub end_least: Option, pub keep: f32 }`. The room a container's own parts take on its header's line (`Container::header_parts`): a width at the start edge - `pub const NONE: HeaderParts`. No room for parts. - `pub const fn start(mut self, width: f32) -> Self`. `width` at the start edge. - `pub const fn end(mut self, width: f32) -> Self`. `width` at the end edge. + - `pub const fn end_narrows(mut self, least: f32, keep: f32) -> Self`. The end edge narrows, down to `least`, so the header's children keep `keep` of the line: on a line too narrow - `craft_ui::contract::HeaderRegion`: `pub struct HeaderRegion { pub band: DragBand, pub rule: bool, pub rule_above: bool, pub inline: bool, pub trailing: bool, pub fill: Option, pub inset: Pad, pub gap: Option }`. A header region, filled by `Container::header`. - `pub const fn new() -> Self`. A header with no drag band, no rule, on its own line, with no trailing region, no fill and no inset. - `pub const fn fill(mut self, kind: SurfaceKind) -> Self`. The surface of a band behind the header. From 3fb6e6794962fca78c86e16eb4e056f5efddc296 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:52:44 -0800 Subject: [PATCH 180/269] ui-widgets: a list row's cell nodes take their own cell's bounds ListRow::access added the label, toggle, text and status Cell nodes without bounds, so each took the row's rect: in a row with a toggle column, every Cell reported the whole row. The row now keeps each cell's placed rect from parts (the label band for the label cell) and gives it to the cell's node, as a link gives its line and piece nodes theirs. --- crates/ui-widgets/src/list/row.rs | 5 ++- crates/ui-widgets/src/list/row/show.rs | 28 ++++++++++++ crates/ui-widgets/tests/it/list.rs | 62 ++++++++++++++++++++++++++ 3 files changed, 94 insertions(+), 1 deletion(-) diff --git a/crates/ui-widgets/src/list/row.rs b/crates/ui-widgets/src/list/row.rs index f3ac7af3eb..48ebe16a79 100644 --- a/crates/ui-widgets/src/list/row.rs +++ b/crates/ui-widgets/src/list/row.rs @@ -14,7 +14,7 @@ use crate::contract::{Common, OpenChange, RowHeight, RowPressed, RowState, Show} use crate::primitives::{ContentPainterCx, HAlign, IconSpec, Span, TextRun}; use crate::runtime::env::Label; use crate::style::DataColor; -use craft_behavior::{ColumnKey, Cursor}; +use craft_behavior::{ColumnKey, Cursor, PartRef}; use craft_i18n::Word; use craft_theme::variant::Tone; use craft_theme::{LabelColor, TypeRole}; @@ -467,6 +467,8 @@ pub struct ListRow<'a> { /// The row's menu button was clicked: its rect, where the menu hangs. pub(super) menu: Option, pub(super) label_rect: Rect, + /// The placed rect of each cell node, by the node's part: the access step reads them as the cells' bounds. + pub(super) cell_bounds: Vec<(PartRef, Rect)>, } impl<'a> ListRow<'a> { @@ -564,6 +566,7 @@ impl<'a> ListRow<'a> { open: None, menu: None, label_rect: Rect::NOTHING, + cell_bounds: Vec::new(), } .label(label) } diff --git a/crates/ui-widgets/src/list/row/show.rs b/crates/ui-widgets/src/list/row/show.rs index 35ca35602f..1d8da0170d 100644 --- a/crates/ui-widgets/src/list/row/show.rs +++ b/crates/ui-widgets/src/list/row/show.rs @@ -211,6 +211,7 @@ impl Component for ListRow<'_> { self.measure_hosted(cx); let widths = self.widths(&cx.style.sizes, &|run| cx.layout_at(run, f32::INFINITY).size().x); let placed = self.place(&cx.style.sizes, &widths, rect, cx.flow.is_rtl()); + self.record_cell_bounds(&placed); self.toggle_parts(&placed, cx); for (at, position, _) in &placed.texts { if self.cell_selects(*at) { @@ -475,12 +476,18 @@ impl Component for ListRow<'_> { let column_of = |key: &ColumnKey| self.cells.iter().position(|(column, _)| column == key); if let Some(column) = self.label_column(&self.cells) { let node = access.node(LABEL_CELL, Role::CELL); + if let Some(rect) = self.cell_rect(LABEL_CELL) { + node.bounds(rect); + } node.name = Name::Text(label.to_owned()); node.grid.column_index = column_of(column); node.flags.set(Flags::SELECTED, selected); } for (at, toggle) in self.toggles.iter().enumerate() { let cell = access.node(TOGGLE_CELL.at(at as u64), Role::CELL); + if let Some(rect) = self.cell_rect(TOGGLE_CELL.at(at as u64)) { + cell.bounds(rect); + } cell.name = Name::Text(label.to_owned()); cell.grid.column_index = column_of(&toggle.column); cell.flags.set(Flags::SELECTED, selected); @@ -492,6 +499,9 @@ impl Component for ListRow<'_> { for text in &self.texts { let Some(position) = self.cells.iter().position(|(column, _)| *column == text.column) else { continue }; let node = access.node(TEXT_CELL.at(position as u64), Role::CELL); + if let Some(rect) = self.cell_rect(TEXT_CELL.at(position as u64)) { + node.bounds(rect); + } node.name = Name::Text(text.text.as_str().to_owned()); node.description = self.tips.iter().find(|(column, _)| *column == text.column).map(|(_, tip)| tip.as_str().to_owned()); node.grid.column_index = Some(position); @@ -500,6 +510,9 @@ impl Component for ListRow<'_> { for (at, cell) in self.statuses.iter().enumerate() { let Some(position) = self.cells.iter().position(|(column, _)| *column == cell.column) else { continue }; let node = access.node(STATUS.at(position as u64), Role::CELL); + if let Some(rect) = self.cell_rect(STATUS.at(position as u64)) { + node.bounds(rect); + } node.name = Name::Text(cell.status.text.as_str().to_owned()); node.description = cell.status.tip.as_ref().map(|tip| tip.as_str().to_owned()); node.grid.column_index = Some(position); @@ -745,6 +758,21 @@ impl ListRow<'_> { if part == TrailingPart::MENU { Label::from(named(&words.more, row)) } else { name.clone() } } + /// Keeps the placed rect of each cell node for the access step: the label cell's is the label band, which spans + /// the label column and the empty toggle columns beside it. + fn record_cell_bounds(&mut self, placed: &Placed) { + let toggles = placed.toggles.iter().map(|(at, cell)| (TOGGLE_CELL.at(*at as u64), *cell)); + let texts = placed.texts.iter().map(|(_, position, cell)| (TEXT_CELL.at(*position as u64), *cell)); + let statuses = placed.statuses.iter().map(|(_, position, cell)| (STATUS.at(*position as u64), *cell)); + self.cell_bounds = std::iter::once((LABEL_CELL.into(), placed.band)).chain(toggles).chain(texts).chain(statuses).collect(); + } + + /// The placed rect of the cell node `part`, which `parts` recorded. + fn cell_rect(&self, part: impl Into) -> Option { + let part = part.into(); + self.cell_bounds.iter().find(|(key, _)| *key == part).map(|(_, rect)| *rect) + } + /// The parts of the row's toggle cells: their flags, held state and tooltip with the toggle's key. fn toggle_parts(&self, placed: &Placed, cx: &mut PartsCx<'_, Self>) { for (at, cell) in &placed.toggles { diff --git a/crates/ui-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index 8d451418de..1ebaa84ce6 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -916,6 +916,68 @@ fn a_toggle_column_holds_one_toggle_with_room_on_each_side() { assert!(cell.width() < 2.0 * cell.height(), "the toggle column holds one toggle: {cell:?}"); } +/// Each cell node of a row lies in its own column: a leading and a trailing toggle cell, the label cell, a text cell +/// and a status cell each take their column's span of the row, not the whole row. +#[trial] +fn each_cell_node_of_a_row_takes_its_columns_bounds() { + use craft_behavior::{ColumnKey, ColumnWidth}; + use craft_theme::variant::Tone; + use craft_ui::contract::{ColumnSpec, Role, ToggleColumn}; + use craft_ui::list::{CellStatus, ToggleCell}; + const EYE: ColumnKey = ColumnKey::new("eye"); + const NAME: ColumnKey = ColumnKey::new("name"); + const SIZE: ColumnKey = ColumnKey::new("size"); + const WARNINGS: ColumnKey = ColumnKey::new("warnings"); + const LOCK: ColumnKey = ColumnKey::new("lock"); + let cells = Rc::new(RefCell::new(Vec::new())); + let held = cells.clone(); + let mut fixture = Fixture::new(move |ui| { + let columns = vec![ + ColumnSpec::toggle(EYE, "", ToggleColumn::sweepable()), + ColumnSpec::new(NAME, "Name", ColumnWidth::fill(1.0)), + ColumnSpec::new(SIZE, "Size", ColumnWidth::fill(1.0)), + ColumnSpec::new(WARNINGS, "Warnings", ColumnWidth::fill(1.0)), + ColumnSpec::toggle(LOCK, "", ToggleColumn::sweepable()), + ]; + let keys = [0_usize]; + let source = keyed(&keys, |key: &usize| *key); + let _ = List::new("Layers").columns(columns).show_items(ui, &source, &mut |_, icx| { + held.replace(icx.cells().to_vec()); + ListRow::new("Layer 1") + .cells(icx.cells()) + .toggle(ToggleCell::eye(EYE, true)) + .cell(SIZE, "12 KB") + .cell_status(WARNINGS, CellStatus::new(Tone::Warn, "2 warnings")) + .toggle(ToggleCell::lock(LOCK, false)) + }); + }); + fixture.room(Vec2::new(600.0, 200.0)); + fixture.settle(); + let cells = cells.borrow(); + let column = |key: &ColumnKey| cells.iter().find(|(column, _)| column == key).map(|(_, rect)| *rect).expect("the row lists the column"); + let nodes = fixture.by_role(Role::CELL); + assert_eq!(nodes.len(), 5, "one cell node per column: {nodes:?}"); + for node in &nodes { + let tree = fixture.tree(); + let key = match tree.name_of(node.node) { + Some("12 KB") => SIZE, + Some("2 warnings") => WARNINGS, + Some("Layer 1") => match tree.children_of(node.node).first().and_then(|child| tree.name_of(*child)) { + Some(name) if name.contains("Lock") => LOCK, + Some(_) => EYE, + None => NAME, + }, + other => panic!("an unexpected cell node {other:?}"), + }; + let span = column(&key); + assert!( + (node.rect.left() - span.left()).abs() < 0.5 && (node.rect.right() - span.right()).abs() < 0.5, + "the {key:?} cell spans its column: {:?}, the column {span:?}", + node.rect + ); + } +} + /// A toggle cell's glyph rests in `text.muted` and reads in `text.normal` under the pointer. #[trial] fn a_toggle_glyph_rests_muted_and_reads_normal_under_the_pointer() { From 01ab6c5d1dc3b746e3d4f6156fdd5c30d1b98ce6 Mon Sep 17 00:00:00 2001 From: Martin Ball Date: Wed, 25 Nov 2026 12:54:51 +0000 Subject: [PATCH 181/269] ui-patterns: CommandPalette quiet look for an in-place search in a bar The in-place palette face drew TextField::search at the field look: field fill and the control edge, so in a title bar it read as a heavy outlined white box. Add TextField::quiet (style key) and StyleCx::quiet_field: surface.chrome fill at rest, surface.sunken under the pointer and while focused, line.border edge at rest (line.divider disabled). Focus and invalid edges stay the field's own. CommandPalette::quiet(bool) passes it to both the closed and open in-place field; default false, so the dialog face and other users are unchanged. For storytold/wordcraft#7682. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-contract/src/style/cx.rs | 18 +++++++++++++++ .../tests/it/style/surface_look.rs | 19 ++++++++++++++++ .../src/patterns/panels/palette.rs | 22 +++++++++++++++---- crates/ui-widgets/src/text/text_field.rs | 8 +++++++ 4 files changed, 63 insertions(+), 4 deletions(-) diff --git a/crates/ui-contract/src/style/cx.rs b/crates/ui-contract/src/style/cx.rs index d5ab7c55ea..d8aaf1fa49 100644 --- a/crates/ui-contract/src/style/cx.rs +++ b/crates/ui-contract/src/style/cx.rs @@ -487,6 +487,24 @@ impl<'a> StyleCx<'a> { look } + /// The look of a field that sits in a bar (a title bar's search box): [`field`](Self::field) filled with the bar's + /// `surface.chrome` at rest and with the field fill under the pointer and while it holds focus, and with the quieter + /// `line.border` edge at rest. The focus and invalid edges are the field's own. A bevelled well keeps its look. + pub fn quiet_field(&self) -> SurfaceLook { + let mut look = self.field(); + let (surface, line) = (&self.tokens.color.surface, &self.tokens.color.line); + let (chrome, sunken) = (self.color(surface.chrome), self.color(surface.sunken)); + let off = self.color(self.tokens.color.state.disabled_fill); + look.fill = Stateful::new(chrome).off(States::new(chrome, sunken, sunken, off)).when(Flags::FOCUSED, sunken); + if let Some(edge) = &mut look.border + && edge.off.rest != self.color(Rgba::TRANSPARENT) + { + let (rest, disabled) = (self.color(line.border), self.color(line.divider)); + edge.off = States::new(rest, rest, rest, disabled); + } + look + } + /// The look of the closed box of a dropdown picker: the field, filled with the hover fill under the pointer and /// while its list is open. pub fn dropdown(&self) -> SurfaceLook { diff --git a/crates/ui-contract/tests/it/style/surface_look.rs b/crates/ui-contract/tests/it/style/surface_look.rs index 9b012d4995..862452720d 100644 --- a/crates/ui-contract/tests/it/style/surface_look.rs +++ b/crates/ui-contract/tests/it/style/surface_look.rs @@ -53,3 +53,22 @@ fn a_dropdown_box_fills_under_the_pointer_and_while_open() { assert_eq!(open, hover, "an open box keeps the hover fill"); }); } + +#[trial] +fn a_quiet_field_takes_the_bar_fill_and_a_lighter_edge_at_rest_and_keeps_the_focus_edge() { + let ctx = egui::Context::default(); + let tokens = tokens(Mode::Light, Contrast::Standard); + with_cx(&ctx, &tokens, Variant::SECONDARY, ControlSize::Md, |cx| { + let (plain, quiet) = (cx.field(), cx.quiet_field()); + let (plain_edge, quiet_edge) = (plain.border.as_ref().expect("a field draws an edge"), quiet.border.as_ref().expect("so does a quiet one")); + let at = |state: State, flags: Flags| StateSet::new(state, flags, StateMix::REST); + let rest = at(State::Rest, Flags::empty()); + let hover = StateSet::new(State::Hover, Flags::empty(), StateMix::new(1.0, 0.0, 0.0)); + assert_ne!(rest.resolve(&quiet.fill), rest.resolve(&plain.fill), "at rest the field takes the bar's fill, not the field fill"); + assert_eq!(hover.resolve(&quiet.fill), rest.resolve(&plain.fill), "under the pointer it takes the field fill"); + assert_eq!(at(State::Rest, Flags::FOCUSED).resolve(&quiet.fill), rest.resolve(&plain.fill), "so does a focused one"); + assert_ne!(rest.resolve(quiet_edge), rest.resolve(plain_edge), "the rest edge is quieter than the control edge"); + let focused = at(State::Rest, Flags::FOCUSED); + assert_eq!(focused.resolve(quiet_edge), focused.resolve(plain_edge), "the focus edge is the field's own"); + }); +} diff --git a/crates/ui-patterns/src/patterns/panels/palette.rs b/crates/ui-patterns/src/patterns/panels/palette.rs index 2ac09e7201..9cd8bc08b9 100644 --- a/crates/ui-patterns/src/patterns/panels/palette.rs +++ b/crates/ui-patterns/src/patterns/panels/palette.rs @@ -153,6 +153,10 @@ pub struct CommandPalette<'a> { /// Where the search shows: a centred box or in place. #[prop] face: PaletteFace, + /// The in-place face in the look of a bar's own field: the bar's fill and a light edge at rest, the field fill + /// under the pointer and while open. The field is still named, and shows its search glyph and hint. + #[prop] + quiet: bool, /// The hint the in-place search box shows while it is closed. #[prop(into)] placeholder: Option