diff --git a/Cargo.lock b/Cargo.lock index 67be1d206e..040b8765de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2286,6 +2286,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "socket2", "tempfile", ] @@ -2653,6 +2654,7 @@ dependencies = [ "exr", "flate2", "half", + "serde", "serde_json", "thiserror 2.0.21", ] @@ -3466,6 +3468,8 @@ dependencies = [ "base64 0.23.1", "chrono", "craft-flow", + "craft-html", + "craft-markdown", "craft-math", "craft-metafile", "craft-wordmodel", diff --git a/README.md b/README.md index 7ac5622eb3..5fe21ea6f2 100644 --- a/README.md +++ b/README.md @@ -302,7 +302,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-markdown`](crates/markdown/README.md): Markdown read and written (a CommonMark subset with GitHub tables and strikethrough), to and from the craft-flow model. - [`craft-math`](crates/math/README.md): equations as one tree (the Office Math object model) with its syntaxes, read and written: OMML, presentation MathML, LaTeX math and the UnicodeMath linear format. - [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV - (`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`) and + (`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`), Bink (`bink`) and MPEG-TS/PS (`mpegts`) demuxers, from FilmCraft, a Sierra VMD (`vmd`) demuxer, and an ISO BMFF box reader. Containers only; codecs are in `craft-audio`, and video codecs will go in a separate crate. - [`craft-lottie`](crates/lottie/README.md): Lottie (Bodymovin) JSON: the document model of diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 7981f3a013..100986d8b1 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -24,7 +24,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", "vorbis-encode"] # Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files. lossless-encode = ["pcm-encode", "flac-encode"] @@ -44,6 +44,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 = [] # ADPCM (`adpcm`): IMA WAV, Microsoft, Yamaha and Flash (SWF) decoders and encoders. adpcm = ["craft-media/bitstream"] # QOA (Quite OK Audio) files: decoder and encoder in the `qoa` module, each on its own. @@ -54,6 +56,7 @@ qoa-encode = [] g722 = [] # ITU-T G.726 ADPCM speech codec (16/24/32/40 kbit/s). g726 = [] +# The Opus encoder (`opus::encoder`), and Opus through `PacketEncoder`. opus-encode = [] # GSM 06.10 full-rate speech: decoder and encoder in the `gsm` module, each on its own. gsm = ["gsm-decode", "gsm-encode"] diff --git a/crates/audio/README.md b/crates/audio/README.md index ffbe06b25c..75f5694f66 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -34,19 +34,20 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `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-decode` | `flac::decode` (whole `.flac` files) and `flac::Decoder` (single frames, for callers that demux FLAC themselves); native, CRC-checked, 4 to 32 bits. `decode` still uses symphonia for FLAC files | 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 | | `vorbis-encode` | `vorbis::encoder::Encoder` (pure Rust); `encode_ogg_vorbis`, `encode_ogg` and `encode` for Ogg Vorbis files (whole buffer; not `FileEncoder`) | craft-media `ogg` | | `vorbis-decode` | `vorbis::decoder::Decoder` (packets), `vorbis::decoder::decode_ogg` (whole Ogg Vorbis files); native Vorbis I: floors 0 and 1, residues 0 to 2, channel coupling, both block sizes. `decode` still reads Vorbis files through symphonia | craft-media `ogg` | | `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` | -| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` | +| `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` | | `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` | | `adpcm` | `adpcm::{ima, ms, yamaha, swf}`: decoders and encoders for IMA WAV, Microsoft, Yamaha and Flash ADPCM | 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 | | `gsm-decode`, `gsm-encode` (`gsm`) | `gsm::Decoder`, `gsm::Encoder`, `gsm::decode`, `gsm::encode`: GSM 06.10 full-rate speech, bit-exact, raw `.gsm` and WAV (GSM 6.10) packings | none | | `vmd-decode` | `vmd::Decoder`: Sierra VMD sound (8-bit PCM and 16-bit DPCM), frame by frame from `craft_media::vmd` | none | | `peaks` | `peaks::Peaks` | none | @@ -313,12 +314,76 @@ 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()`. 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 +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; 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)). ### 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; @@ -575,7 +640,35 @@ Each codec module's rustdoc lists the coding tools it implements. | MP2 encoder (`mpa::encoder`) | ISO/IEC 11172-3 (§2.4, Annex B and C), 13818-3 | Layer II, constant bit rate, mono or stereo (no joint stereo), 32/44.1/48 kHz at the spec's rate/mode pairs and 16/22.05/24 kHz at 8–160 kbit/s; no CRC | our decoder and ffmpeg decode the frames; SNR of 20–37 dB on tone mixes, and the 481-sample filter delay matches | | MP3 decoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, MPEG-1/2/2.5, 8–48 kHz, every bit rate, CBR and VBR; mono, stereo, dual channel, joint stereo (mid/side and intensity); long, short and mixed blocks; bit reservoir; CRC read, not checked; Xing / Info / VBRI and LAME tags; no free format (read through symphonia) | ffmpeg's float decoder: 127–131 dB SNR on LAME streams of every sampling frequency (CBR, VBR, CRC, no reservoir, transients with short blocks) and on this crate's encoder's; intensity stereo and mixed blocks through LAME frames edited to use them (112–131 dB) | | MP3 encoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, constant bit rate: 32–320 kbit/s at 32/44.1/48 kHz, 8–160 kbit/s at 16/22.05/24 kHz; mono, stereo, joint stereo (mid/side); bit reservoir; long blocks only; no Xing/Info tag, VBR, CRC or free format | ffmpeg decodes every Huffman code as intended; full encodes at every sampling frequency checked with ffprobe and by SNR of ffmpeg's decode | -| ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder, same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | +| 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 diff --git a/crates/audio/src/alac/encoder.rs b/crates/audio/src/alac/encoder.rs index 7fc842597b..e4211dc5b1 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); @@ -563,4 +586,84 @@ mod tests { let mut dec = Decoder::new(&enc.cookie()).unwrap(); assert_eq!(dec.decode(&p).unwrap(), vec![noise[..4096].to_vec()]); } + + /// 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 14bbbf6c50..d580fd9c28 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/src/lib.rs b/crates/audio/src/lib.rs index 29054288ec..d57baa6b59 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -23,6 +23,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. @@ -32,7 +35,8 @@ //! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`] //! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder; //! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), [`adpcm`] -//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`dsd`] (`dsd`: DSF and DSDIFF files to PCM), +//! (`adpcm`: IMA WAV, Microsoft, Yamaha and Flash ADPCM), [`s302m`] (`s302m`: SMPTE 302M packets), +//! [`dsd`] (`dsd`: DSF and DSDIFF files to PCM), //! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech), [`vmd`] (`vmd-decode`: //! Sierra VMD sound). //! @@ -64,6 +68,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", @@ -79,6 +92,8 @@ pub mod peaks; pub mod qoa; #[cfg(feature = "decode-native")] mod read; +#[cfg(feature = "s302m")] +pub mod s302m; #[cfg(feature = "sbc")] pub mod sbc; #[cfg(any( @@ -157,6 +172,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..2d1ab7d621 --- /dev/null +++ b/crates/audio/src/packet.rs @@ -0,0 +1,696 @@ +//! [`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}; + +/// Maximum frames handed to a codec per internal call, bounding that call's input and output. +/// `PacketEncoder::encode` collects packets across all chunks, so its returned vector grows with +/// the caller's input block. 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. + /// + /// 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")] + 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). + /// + /// 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)) + } + + /// 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. + /// + /// Internal codec calls process at most 4096 frames at a time, but this method collects their + /// packets in one returned vector whose memory use grows with `frames`. For streaming with + /// bounded memory, pass bounded input blocks and consume each returned batch before encoding + /// the next block, as [`FileEncoder`](crate::FileEncoder) does for coded formats. + /// + /// `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/s302m.rs b/crates/audio/src/s302m.rs new file mode 100644 index 0000000000..205741c529 --- /dev/null +++ b/crates/audio/src/s302m.rs @@ -0,0 +1,257 @@ +//! 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), 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, + _ => return 0, + }; + (self.channels / 2).checked_mul(pair_bytes).unwrap_or(0) + } +} + +/// 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 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; + } + // 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()); + } + + #[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); + } + + #[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); + } +} 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 bbb42601ec..18beab7872 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 = "vorbis-encode")] mod vorbis; #[cfg(feature = "vorbis-encode")] diff --git a/crates/audio/tests/codecs/alac.rs b/crates/audio/tests/codecs/alac.rs index 2d52234e86..8038c3ceb9 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::integration::codecs::testkit::ffmpeg_or_skip("alac oracle") else { return }; + for (channels, bits) in [(1, 24), (2, 24), (6, 24), (1, 32), (2, 32)] { + let full = input(channels, bits, 4 * 4096); + let wav: Vec> = full + .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"); + } + } +} diff --git a/crates/audio/tests/codecs/main.rs b/crates/audio/tests/codecs/main.rs index 41829be5c9..4701426cd8 100644 --- a/crates/audio/tests/codecs/main.rs +++ b/crates/audio/tests/codecs/main.rs @@ -18,6 +18,7 @@ mod mp3_encoder_oracle; mod mpa_oracle; mod opus; mod opusenc; +mod packet_encoder; mod routing_oracle; mod track_decoder; #[cfg(feature = "vorbis-encode")] diff --git a/crates/audio/tests/codecs/opusenc/modes.rs b/crates/audio/tests/codecs/opusenc/modes.rs index a48ad2d444..723510a0f9 100644 --- a/crates/audio/tests/codecs/opusenc/modes.rs +++ b/crates/audio/tests/codecs/opusenc/modes.rs @@ -268,9 +268,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"); } } diff --git a/crates/audio/tests/codecs/packet_encoder.rs b/crates/audio/tests/codecs/packet_encoder.rs new file mode 100644 index 0000000000..584255d152 --- /dev/null +++ b/crates/audio/tests/codecs/packet_encoder.rs @@ -0,0 +1,244 @@ +//! `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: 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.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:?}"); + } +} diff --git a/crates/audio/tests/main.rs b/crates/audio/tests/main.rs index 5470dc5530..6e1461348b 100644 --- a/crates/audio/tests/main.rs +++ b/crates/audio/tests/main.rs @@ -36,6 +36,9 @@ mod mp2_encoder_oracle; #[cfg(feature = "qoa")] #[path = "qoa_oracle.rs"] mod qoa_oracle; +#[cfg(feature = "s302m")] +#[path = "s302m_oracle.rs"] +mod s302m_oracle; #[cfg(feature = "sbc")] #[path = "sbc_oracle.rs"] mod sbc_oracle; diff --git a/crates/audio/tests/s302m_oracle.rs b/crates/audio/tests/s302m_oracle.rs new file mode 100644 index 0000000000..1d1a0c60da --- /dev/null +++ b/crates/audio/tests/s302m_oracle.rs @@ -0,0 +1,240 @@ +//! 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.as_chunks::<188>().0.iter().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, 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 > 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")); + 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()); + 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; + // 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"); + 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| 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 bits == 16 { v } else { v << (32 - bits) })); + 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()); + } +} diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index 4a4e27520f..7259d7212d 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 b2f6a195f0..4568526750 100644 --- a/crates/captions/README.md +++ b/crates/captions/README.md @@ -60,6 +60,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 612aa6f137..e83b868ce2 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, `` @@ -36,17 +36,22 @@ pub mod ass; pub mod cea608; pub mod jacosub; pub mod mcc; +pub mod microdvd; #[cfg(feature = "mov-text")] pub mod mov_text; +pub mod mpl2; pub mod pjs; pub mod realtext; +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}; @@ -77,6 +82,16 @@ 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, /// Phoenix Japanimation Society (PJS) subtitles. Pjs, /// RealText streaming timed text markup. @@ -86,7 +101,7 @@ pub enum Format { } impl Format { - pub const ALL: [Format; 11] = [ + pub const ALL: [Format; 16] = [ Format::Srt, Format::WebVtt, Format::Scc, @@ -95,6 +110,11 @@ impl Format { Format::Ttml, Format::Dfxp, Format::Ass, + Format::MicroDvd, + Format::Mpl2, + Format::SubViewer, + Format::VPlayer, + Format::Sami, Format::Pjs, Format::RealText, Format::JacoSub, @@ -109,6 +129,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", Format::Pjs => "PJS", Format::RealText => "RealText", Format::JacoSub => "JACOsub", @@ -124,6 +149,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", Format::Pjs => "pjs", Format::RealText => "rt", Format::JacoSub => "jss", @@ -139,6 +170,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), "pjs" => Some(Format::Pjs), "rt" | "realtext" => Some(Format::RealText), "jss" | "js" | "jacosub" => Some(Format::JacoSub), @@ -292,28 +328,51 @@ 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) { + return Some(Format::SubViewer); + } 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); + } + if first_lines.first().is_some_and(|l| mpl2::split_cue(l).is_some()) { + return Some(Format::Mpl2); + } + 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()) { + return Some(Format::VPlayer); + } if first_lines.first().is_some_and(|l| pjs::split_cue(l).is_some()) { return Some(Format::Pjs); } 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), - Some("srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "pjs" | "rt" | "jss" | "js") => None, + Some( + "srt" | "vtt" | "scc" | "mcc" | "stl" | "ttml" | "dfxp" | "xml" | "ass" | "ssa" | "sub" | "mpl" | "vpl" | "smi" | "sami" | "pjs" | "rt" + | "jss" | "js", + ) => None, _ if has_arrow_timing => Some(Format::Srt), _ => None, } @@ -348,6 +407,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::Pjs => pjs::parse(&text), Format::RealText => realtext::parse(&text), Format::JacoSub => jacosub::parse(&text), @@ -389,6 +453,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(), Format::Pjs => pjs::write(doc).into_bytes(), Format::RealText => realtext::write(doc).into_bytes(), Format::JacoSub => jacosub::write(doc).into_bytes(), diff --git a/crates/captions/src/microdvd.rs b/crates/captions/src/microdvd.rs new file mode 100644 index 0000000000..5816373712 --- /dev/null +++ b/crates/captions/src/microdvd.rs @@ -0,0 +1,241 @@ +//! 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}` or `{0}{0}` +//! whose text is a number gives the frame rate; without it the rate is 23.976 fps (the rate other +//! readers assume). Control codes `{y:i}` / `{y:b}` / `{y:u}` (italic, bold, underline; `i,b` together) +//! and `{c:$BBGGRR}` (colour) style the line they start; the capital forms `{Y:…}` and `{C:…}` +//! style every later line of the cue too. Other controls (`{f:…}` font, `{s:…}` size, `{h:…}`, …) +//! are dropped. Writing always starts with the `{1}{1}` rate line and styles a line only when +//! ``, `` 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(""); + // 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; + } else { + // No later control can close either: preserve the entire remaining text. + text.push('{'); + text.push_str(after); + rest = ""; + break; + } + } else { + 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((0, 0, t) | (1, 1, t)) if rows.is_empty() && !has_rate_line && header_rate(t).is_some() => { + rate = header_rate(t).unwrap_or(rate); + has_rate_line = true; + } + 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 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(); + assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25)); + let d = parse("{0}{0}25.000\n{25}{50}x\n{50}{75}29.97\n").unwrap(); + assert_eq!(d.cues.len(), 2); + assert_eq!(d.cues[0].start, FrameRate::FPS_25.tick_of(25)); + assert_eq!(d.cues[1].start, FrameRate::FPS_25.tick_of(50)); + assert_eq!(d.cues[1].text, "29.97"); + let d = parse("{25}{50}x\n").unwrap(); + assert_eq!(d.cues[0].start, DEFAULT_RATE.tick_of(25)); + } + + #[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..b7613f073d --- /dev/null +++ b/crates/captions/src/mpl2.rs @@ -0,0 +1,114 @@ +//! 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, 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}; + +/// `[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().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))); + } + } + 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 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 }); + } + } + 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()); + } + + #[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 new file mode 100644 index 0000000000..29f8281dd9 --- /dev/null +++ b/crates/captions/src/sami.rs @@ -0,0 +1,323 @@ +//! 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| { + // 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; + } 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", + ); + 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(); + let mut resolved_cues: Vec<(i64, i64, &Vec<&str>)> = Vec::with_capacity(active_cues.len()); + let mut prev_end = 0i64; + for (c, lines) in &active_cues { + let start_ms = tick_to_ms(c.start).max(prev_end); + let end_ms = tick_to_ms(c.end).max(start_ms + 1); + prev_end = end_ms; + resolved_cues.push((start_ms, end_ms, lines)); + } + for (i, &(start_ms, end_ms, lines)) in resolved_cues.iter().enumerate() { + out.push_str(&format!("

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

 \n")); + } + } + 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 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(); + 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()); + } + + #[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)); + } + + #[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 new file mode 100644 index 0000000000..96b97ef6d2 --- /dev/null +++ b/crates/captions/src/subviewer.rs @@ -0,0 +1,198 @@ +//! 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, writes `[br]` inside text as `[br]`, and writes `,` in lines that match the timing +//! syntax as `,`. + +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()); + match lines.next() { + 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, + } +} + +/// `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 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) +} + +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 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 + .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}") + .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 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()); + } + + #[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\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"); + } +} diff --git a/crates/captions/src/text.rs b/crates/captions/src/text.rs index 4f1d04f696..35cd23c0fc 100644 --- a/crates/captions/src/text.rs +++ b/crates/captions/src/text.rs @@ -85,8 +85,8 @@ pub fn plain_text(s: &str) -> String { out } -use crate::TICKS_PER_MS; 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. @@ -131,6 +131,62 @@ 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..169e4f24a0 --- /dev/null +++ b/crates/captions/src/vplayer.rs @@ -0,0 +1,206 @@ +//! 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}; +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, ':'); + 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 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(); + 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(); + + let mut resolved_cues: Vec<(i64, i64, &Vec)> = Vec::with_capacity(active_cues.len()); + let mut prev_end = 0i64; + for (c, lines) in &active_cues { + let start_cs = cs(c.start).max(prev_end); + let end_cs = cs(c.end).max(start_cs + 1); + prev_end = end_cs; + resolved_cues.push((start_cs, end_cs, lines)); + } + + for (i, &(start_cs, end_cs, lines)) in resolved_cues.iter().enumerate() { + out.push_str(&format!("{}={}\n", clock(start_cs), lines.join("|"))); + let next_start_cs = resolved_cues.get(i + 1).map(|&(next_s, _, _)| next_s); + if next_start_cs != Some(end_cs) { + out.push_str(&format!("{}=\n", clock(end_cs))); + } + } + out +} + +#[cfg(test)] +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 adjacent_short_cues_do_not_collide_after_rounding() { + let doc = Document { + cues: vec![ + Cue { start: ms_to_tick(1000), end: ms_to_tick(1001), text: "First".to_string(), ..Default::default() }, + Cue { start: ms_to_tick(1001), end: ms_to_tick(1020), text: "Second".to_string(), ..Default::default() }, + ], + ..Default::default() + }; + let written = write(&doc); + assert_eq!(written, "00:00:01.00=First\n00:00:01.01=Second\n00:00:01.02=\n"); + let parsed = parse(&written).unwrap(); + assert_eq!(parsed.cues.len(), 2); + assert_eq!(parsed.cues[0].text, "First"); + assert_eq!(parsed.cues[0].start, ms_to_tick(1000)); + assert_eq!(parsed.cues[0].end, ms_to_tick(1010)); + assert_eq!(parsed.cues[1].text, "Second"); + assert_eq!(parsed.cues[1].start, ms_to_tick(1010)); + assert_eq!(parsed.cues[1].end, ms_to_tick(1020)); + } + + #[test] + fn separators_and_ends() { + let d = parse("00:00:01:Hello|world\n00:00:04.50=\n00:00:05 later\n").unwrap(); + 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()); + } + + #[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 new file mode 100644 index 0000000000..1bfe11bfea --- /dev/null +++ b/crates/captions/tests/it/legacy_text.rs @@ -0,0 +1,252 @@ +//! 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))); + + for header in ["{1}{1}25.000", "{0}{0}25.000"] { + let fixture = format!("{header}\n{{50}}{{100}}First cue\n{{100}}{{150}}23.976\n"); + let parsed = parse(fixture.as_bytes(), Format::MicroDvd).expect("parse rate header fixture"); + assert_eq!(parsed.cues.len(), 2, "{header}"); + assert_eq!((parsed.cues[0].start, parsed.cues[0].end), (Tick(2 * T), Tick(4 * T)), "{header}"); + assert_eq!((parsed.cues[1].start, parsed.cues[1].end), (Tick(4 * T), Tick(6 * T)), "{header}"); + assert_eq!(parsed.cues[1].text, "23.976", "{header}"); + } +} + +#[test] +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)); + // 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 + 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); +} + +#[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 7d8070cad6..9cb0535be6 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; diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index cb2c2f3972..1705f64002 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -319,23 +319,33 @@ 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 { + let k = match p.gcr_curve.first() { // The Photocraft profile's curve. - return if g <= p.gcr_start { 0.0 } else { p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) }; - }; - let mut k = first[1]; - for w in p.gcr_curve.windows(2) { - let ([g0, k0], [g1, k1]) = (w[0], w[1]); - if g >= g1 { - k = k1; - } else if g > g0 { - k = k0 + (k1 - k0) * (g - g0) / (g1 - g0); - break; + None => { + if g <= p.gcr_start { + 0.0 + } else { + p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) + } } - } - k.clamp(0.0, 1.0) + Some(first) => { + let mut k = first[1]; + for w in p.gcr_curve.windows(2) { + let ([g0, k0], [g1, k1]) = (w[0], w[1]); + if g >= g1 { + k = k1; + } else if g > g0 { + k = k0 + (k1 - k0) * (g - g0) / (g1 - g0); + break; + } + } + k + } + }; + 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. @@ -712,6 +722,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))); @@ -847,6 +860,33 @@ 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() { + // Black from either the profile curve or the default empty-curve fallback never exceeds the ink limit. + let m = CmykModel::coated(CmykParams::default().tvi); + for gcr_curve in [vec![[0.0, 0.75]], vec![]] { + for tac in [0.5, 0.0] { + let p = CmykParams { tac, gcr_curve: gcr_curve.clone(), ..CmykParams::default() }; + assert!(gcr(&p, 1.0) <= p.tac, "tac {tac} curve {gcr_curve:?}"); + 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 806bff7138..a555f34c54 100644 --- a/crates/cms/tests/fogra39.rs +++ b/crates/cms/tests/fogra39.rs @@ -430,6 +430,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); diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index efe1f1e446..1464a4cece 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -38,6 +38,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 f5af19a004..e20bada163 100644 --- a/crates/control/src/client_tests.rs +++ b/crates/control/src/client_tests.rs @@ -3,6 +3,7 @@ use super::*; 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; @@ -78,9 +79,14 @@ fn addr(port: u16) -> String { format!("127.0.0.1:{port}") } -/// A port nothing listens on. -fn free_port() -> u16 { - TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().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(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(); + assert_ne!(port, 0); + (reserved, port) } #[test] @@ -115,13 +121,22 @@ fn a_wrong_token_or_none_is_refused() { #[test] fn an_app_not_running_says_how_to_start_it() { - let 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_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 diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 79b3c6ce71..c61d9de908 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -353,6 +353,7 @@ audio-qoa = ["audio", "craft-audio/qoa"] audio-qoa-decode = ["audio", "craft-audio/qoa-decode"] audio-qoa-encode = ["audio", "craft-audio/qoa-encode"] audio-rayon = ["audio", "craft-audio/rayon"] +audio-s302m = ["audio", "craft-audio/s302m"] audio-sbc = ["audio", "craft-audio/sbc"] audio-serde = ["audio", "craft-audio/serde"] audio-symphonia = ["audio", "craft-audio/symphonia"] @@ -636,6 +637,7 @@ mcp-server = ["dep:craft-mcp-server"] media = ["dep:craft-media"] media-avi = ["media", "craft-media/avi"] +media-bink = ["media", "craft-media/bink"] media-bitstream = ["media", "craft-media/bitstream"] media-isobmff = ["media", "craft-media/isobmff"] media-matroska = ["media", "craft-media/matroska"] @@ -979,6 +981,8 @@ video-av1 = ["video", "craft-video/av1"] video-av1-decode = ["video", "craft-video/av1-decode"] video-av1-encode = ["video", "craft-video/av1-encode"] video-av1-large-encode = ["video", "craft-video/av1-large-encode"] +video-bink = ["video", "craft-video/bink"] +video-bink-decode = ["video", "craft-video/bink-decode"] video-dnx = ["video", "craft-video/dnx"] video-ffv1 = ["video", "craft-video/ffv1"] video-h264 = ["video", "craft-video/h264"] @@ -995,7 +999,11 @@ video-mpeg2-encode = ["video", "craft-video/mpeg2-encode"] video-mpeg4 = ["video", "craft-video/mpeg4"] video-mpeg4-encode = ["video", "craft-video/mpeg4-encode"] video-prores = ["video", "craft-video/prores"] +video-rawvideo = ["video", "craft-video/rawvideo"] video-screen-video = ["video", "craft-video/screen-video"] +video-theora = ["video", "craft-video/theora"] +video-theora-decode = ["video", "craft-video/theora-decode"] +video-theora-encode = ["video", "craft-video/theora-encode"] video-threads = ["video", "craft-video/threads"] video-vmd = ["video", "craft-video/vmd"] video-vmd-decode = ["video", "craft-video/vmd-decode"] diff --git a/crates/csv/README.md b/crates/csv/README.md index 7df204e104..91390ac744 100644 --- a/crates/csv/README.md +++ b/crates/csv/README.md @@ -11,7 +11,8 @@ mapping a SYLK sheet onto a document are the caller's work. | Function | What it does | |---|---| | `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; 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_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 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 f4a82f393f..fa5aed71f3 100644 --- a/crates/csv/src/lib.rs +++ b/crates/csv/src/lib.rs @@ -4,7 +4,8 @@ //! - [`decode_text`] turns a file's bytes into a string: byte order marks, UTF-8, else //! Windows-1256 when the bytes read as Arabic and Windows-1252 otherwise. //! - [`decode_utf8`] requires valid UTF-8 and strips a leading UTF-8 byte order mark. -//! - [`sniff_delimiter`] picks comma, semicolon or tab. +//! - [`sniff_delimiter`] picks comma, semicolon or tab; [`sniff_csv_delimiter`] applies the same +//! scan while preferring comma when it coherently separates `.csv` records. //! - [`parse_records`] splits text into records of fields (RFC 4180 with the usual leniency), //! handing each record to a callback, with a cap on the fields kept per record. [`records`] //! collects them. @@ -45,14 +46,35 @@ pub use decode::{decode_text, decode_utf8}; /// with one. When one of those candidates ends the sample inside a quoted field, each of them /// counts only up to that field's opening quote. pub fn sniff_delimiter(text: &str, quote: char) -> u8 { + sniff_delimiter_inner(text, quote, false) +} + +/// Picks comma, semicolon or tab for `.csv`-named text, preferring comma when it coherently +/// separates the sampled records. +/// +/// Uses the same bounded character sample, quote-boundary coherence rules and fallback ranking +/// 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) +} + +fn sniff_delimiter_inner(text: &str, quote: char, prefer_comma: bool) -> u8 { const SAMPLE_CHARS: usize = 64 * 1024; let sample_end = text.char_indices().nth(SAMPLE_CHARS).map_or(text.len(), |(at, _)| at); let sample = &text[..sample_end]; let truncated = sample_end < text.len(); let mut scans = b"\t,;".map(|delimiter| scan_delimiter(sample, delimiter, quote)); if truncated { - if scans.iter().any(|scan| scan.coherent && scan.counts.iter().min().is_some_and(|&min| min > 0)) { - return pick_delimiter(scans); + if scans.iter().any(separates_coherently) { + return pick_delimiter(scans, prefer_comma); } // Every quote in the scans is at a char boundary, so the cut is one too. let cut = scans.iter().filter(|scan| scan.counts.is_empty()).filter_map(|scan| scan.open_quote).min().unwrap_or(sample_end); @@ -93,10 +115,60 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { } } } - pick_delimiter(scans) + pick_delimiter(scans, prefer_comma) } -fn pick_delimiter(scans: [DelimiterScan; 3]) -> u8 { +fn separates_coherently(scan: &DelimiterScan) -> bool { + scan.coherent && scan.counts.iter().min().is_some_and(|&min| min > 0) +} + +/// 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; + } + let &header = scan.counts.first()?; + if header == 0 { + return None; + } + 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 && 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. let delimiters_only = @@ -205,7 +277,6 @@ fn scan_delimiter(sample: &str, delimiter: u8, quote: char) -> DelimiterScan { if ch == quote && field_start { scan.open_quote = Some(at); field_start = false; - scan.record_has_content = true; } else if ch == char::from(delimiter) { scan.count += 1; field_start = true; @@ -505,6 +576,91 @@ mod tests { assert_eq!(sniff_delimiter(&format!("{}x;y\n", ",,,\n".repeat(20_000)), '"'), b','); } + #[test] + fn delimiter_sniffing_ignores_empty_quoted_records() { + assert_eq!(sniff_delimiter("\"\"\nName\tCity\nAda\tLondon\n", '"'), b'\t'); + assert_eq!(sniff_delimiter("\"\"\nName;City\nAda;London\n", '"'), b';'); + assert_eq!(sniff_delimiter("\" \"\nName\tCity\nAda\tLondon\n", '"'), b'\t'); + // Quoted empty cells separated by a delimiter still act as delimiter-only rows. + assert_eq!(sniff_delimiter("\"\";\"\"\n\"\";\"\"\n", '"'), b';'); + // A doubled quote inside a quoted field is content, not a blank line. + assert_eq!(sniff_delimiter("\"\"\"\"\nName\tCity\nAda\tLondon\n", '"'), b','); + } + + #[test] + fn csv_delimiter_sniffing_prefers_coherent_comma_and_detects_tab_and_semicolon() { + // Coherent comma separation wins even when semicolons or tabs appear in fields. + for text in [ + "id,notes; comments\n1,a; b; c\n2,d; e; f\n", + "Ort,\"Name;Vorname\"\nBerlin,\"a;b;c\"\n", + "\"Name\",\"Last; First\"\n\"Ada\",\"Lovelace; Countess\"\n", + "Name,Note\tx\nAda,hi\tthere\n", + "\"Name\tLabel\",City\nAda,London\n", + "\"\"\nName;Team;Role,Email\nAda;Core;Eng,ada@example.com\n", + // A short comma row does not fall back to an incoherent semicolon parse. + "\"Name\",\"Note;Tag\"\nAda;Team\nGrace,Hello;2\n", + // Single-column exports with stray separators fall back to comma. + "alpha;beta\r\ngamma\r\n", + "alpha\tbeta\r\ngamma\r\n", + ] { + assert_eq!(sniff_csv_delimiter(text, '"'), b',', "{text:?}"); + } + + // Tab- and semicolon-delimited CSVs (including headers containing commas) sniff cleanly. + for (text, expected) in [ + ("Name\tPosition\tOrt\nAda\tLead\tBerlin\n", b'\t'), + ("Name;City\nAda;London\n", b';'), + ("\"Name, First\"\tOrt\nAda\tBerlin\n", b'\t'), + ("\"Name\";\"Last, First\"\n\"Ada\";\"Lovelace, Countess\"\n", b';'), + ("\"Name\"\t\"Last, First\"\n\"Ada\"\t\"Lovelace, Countess\"\n", b'\t'), + ("Last, First\tEmail\tCity\nAda Lovelace\tada@example.com\tLondon\n", b'\t'), + ("Last, First;Email;City\nAda Lovelace;ada@example.com;London\n", b';'), + ("\"\"\nName\tCity\nAda\tLondon\n", b'\t'), + ("\"\"\nName;City\nAda;London\n", b';'), + ] { + assert_eq!(sniff_csv_delimiter(text, '"'), expected, "{text:?}"); + } + + let blank_tab_rows = format!("{}a;b\nc;d\n", "\t \t\n".repeat(25)); + assert_eq!(sniff_csv_delimiter(&blank_tab_rows, '"'), b';'); + 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); diff --git a/crates/develop-model/docs/xmp-interop.md b/crates/develop-model/docs/xmp-interop.md index 78cb1f467c..5fc3fbb406 100644 --- a/crates/develop-model/docs/xmp-interop.md +++ b/crates/develop-model/docs/xmp-interop.md @@ -186,7 +186,7 @@ application's renderer and is ignored: the photo keeps LightCraft's own process, | `DefringePurple/GreenAmount/HueLo/HueHi` | `optics.defringe_*` | | | `ShadowTint`, `RedHue/Saturation`, `GreenHue/Saturation`, `BlueHue/Saturation` | `calibration.shadows_tint`, `calibration.red_hue/red_sat`, … | Calibration panel, 1:1 | | `PerspectiveVertical/Horizontal/Rotate/Scale/Aspect/X/Y` | `geometry.vertical/horizontal/rotate/scale/aspect/offset_x/offset_y` | | -| `PerspectiveUpright` | `geometry.upright` | 0 off, 1 auto, 2 level, 3 vertical, 4 full, 5 guided; saved `UprightTransform_*` matrices are not imported, so photo import reports that Lightroom geometry was not preserved and the selected mode will be recalculated | +| `PerspectiveUpright` | `geometry.upright` | 0 off, 1 auto, 2 full, 3 level, 4 vertical, 5 guided; saved `UprightTransform_*` matrices are not imported, so photo import reports that Lightroom geometry was not preserved and the selected mode will be recalculated | | `HasCrop`, `CropLeft/Top/Right/Bottom`, `CropAngle` | `crop.geometry` | normalized edges → rect; angle in degrees; `HasCrop="False"` → no crop | Values pass through our control specs, so anything outside our slider ranges gets clamped. diff --git a/crates/develop-model/src/crs.rs b/crates/develop-model/src/crs.rs index 8ca35379d0..bb23e2373d 100644 --- a/crates/develop-model/src/crs.rs +++ b/crates/develop-model/src/crs.rs @@ -414,11 +414,13 @@ pub fn to_partial(props: &Props, target: Target) -> Value { n(o, "PerspectiveX", "geometry.offset_x"); n(o, "PerspectiveY", "geometry.offset_y"); if let Some(u) = num(props, "crs:PerspectiveUpright") { + // 0 Off, 1 Auto, 2 Full, 3 Level, 4 Vertical, 5 Guided: Lightroom saves one Upright matrix per + // value, and each has that mode's shape (lightcraft#205) let mode = match u as i64 { 1 => "auto", - 2 => "level", - 3 => "vertical", - 4 => "full", + 2 => "full", + 3 => "level", + 4 => "vertical", 5 => "guided", _ => "off", }; diff --git a/crates/develop-model/src/crs/tests.rs b/crates/develop-model/src/crs/tests.rs index b978c8aef2..29d4dc0009 100644 --- a/crates/develop-model/src/crs/tests.rs +++ b/crates/develop-model/src/crs/tests.rs @@ -79,7 +79,7 @@ fn assert_common_detail_fields(s: &DevelopSettings) { } fn assert_common_geometry_fields(s: &DevelopSettings) { - assert_eq!(s.geometry.upright, Upright::Level); + assert_eq!(s.geometry.upright, Upright::Full); assert_eq!(s.geometry.vertical, -10.0); assert!(s.optics.remove_ca); assert_eq!(s.treatment, crate::Treatment::Color); @@ -92,6 +92,19 @@ fn assert_common_geometry_fields(s: &DevelopSettings) { assert_eq!((c.rect.x0, c.rect.y0, c.rect.x1, c.rect.y1, c.angle), (0.05, 0.1, 0.8, 0.9, 1.5)); } +/// `crs:PerspectiveUpright` 2, 3 and 4 name Full, Level and Vertical, in that order. +#[test] +fn upright_mode_numbers_name_full_level_and_vertical() { + for (value, mode) in [(2, Upright::Full), (3, Upright::Level), (4, Upright::Vertical)] { + let xmp = format!( + r#""# + ); + let partial = to_partial(&props(&xmp), Target::Any); + let s = apply_partial(&DevelopSettings::default(), &partial, 1.0); + assert_eq!(s.geometry.upright, mode, "crs:PerspectiveUpright={value}"); + } +} + /// A sidecar curve with a `NaN` or `inf` point (Rust's `parse` reads both) is not a curve: /// it is left out, rather than stored with a point the curve editor can't place. #[test] 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")); + } } 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..5c0d8ed9bc 100644 --- a/crates/docx/src/read/parts.rs +++ b/crates/docx/src/read/parts.rs @@ -74,17 +74,22 @@ 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::(); + // 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, 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/read/story/vml.rs b/crates/docx/src/read/story/vml.rs index 2460be72b2..4fd74b2c92 100644 --- a/crates/docx/src/read/story/vml.rs +++ b/crates/docx/src/read/story/vml.rs @@ -144,7 +144,9 @@ impl Reader<'_> { // Brightness and contrast (Word's picture watermark "Washout" sets them, #1711). let frac = |k: &str| img.attr(k).and_then(crate::units::vml_number); let fx = craft_wordmodel::picfx::PicFx::from_vml(frac("gain").unwrap_or(1.0), frac("blacklevel").unwrap_or(0.0)); - return Some(InlineObject::Image { media, w, h, alt, float, crop: [0.0; 4], fx, ole: None }); + let crop = + ["cropleft", "croptop", "cropright", "cropbottom"].map(|key| img.attr(key).and_then(vml_fraction).unwrap_or(0.0).clamp(0.0, 1.0)); + return Some(InlineObject::Image { media, w, h, alt, float, crop, fx, ole: None }); } // The shapetype the shape is drawn from (its `type`, ECMA-376 Part 4 VML), when written in // the same picture: what the shape leaves out, it takes from there. 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..a6d8794fb6 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 @@ -201,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 { @@ -531,7 +538,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/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] diff --git a/crates/docx/tests/it/picture_links.rs b/crates/docx/tests/it/picture_links.rs index dc5f53e19c..34cf625e1b 100644 --- a/crates/docx/tests/it/picture_links.rs +++ b/crates/docx/tests/it/picture_links.rs @@ -125,3 +125,91 @@ fn a_linked_picture_is_saved_with_its_link_on_the_drawing_too() { let edited = out.finish().unwrap().into_inner(); assert_eq!(picture_links(&craft_docx::read(&edited).unwrap())[0], Some("https://example.com/saved".to_string())); } + +// Original synthetic VML package for #2912, reported by denstu473; no reference-app asset. +#[test] +fn a_vml_picture_keeps_its_crop_when_saved() { + fn image_crop(doc: &Document, original_png: &[u8]) -> [f32; 4] { + let paragraph = doc.body[0].as_para().expect("the synthetic picture's paragraph"); + assert_eq!(paragraph.objects.len(), 1, "the VML picture must be decoded before testing crop"); + let InlineObject::Image { media, w, h, alt, crop, fx, .. } = ¶graph.objects[0] else { + panic!("the synthetic object must be an image"); + }; + assert!((*w - 24.0).abs() < 0.001 && (*h - 12.0).abs() < 0.001, "picture size changed: {w} x {h}"); + assert_eq!(alt, "cropped square"); + assert_eq!(doc.media.get(media).expect("the picture's embedded media").as_slice(), original_png); + assert_eq!(*fx, craft_wordmodel::picfx::PicFx::new(40_000, 0, 0)); + *crop + } + fn crops_near(actual: [f32; 4], expected: [f32; 4], tolerance: f32) -> bool { + actual.into_iter().zip(expected).all(|(a, b)| (a - b).abs() <= tolerance) + } + + let original_png = png(); + let mut lost = Vec::new(); + // Crop slots are left, top, right, bottom. These distinct fractions are exactly binary. + let positive = [0.125, 0.0625, 0.25, 0.5]; + for (label, attributes, expected, saved_rect) in [ + ("default", "", [0.0; 4], None), + ( + "report fixed fractions", + r#"cropleft="8192f" croptop="3277f" cropright="16384f" cropbottom="6554f""#, + [8192.0f32 / 65_536.0, 3277.0 / 65_536.0, 16384.0 / 65_536.0, 6554.0 / 65_536.0], + Some(r#""#), + ), + ( + "fixed fractions", + r#"cropleft="8192f" croptop="4096f" cropright="16384f" cropbottom="32768f""#, + positive, + Some(r#""#), + ), + ( + "decimal fractions", + r#"cropleft="0.125" croptop="0.0625" cropright="0.25" cropbottom="0.5""#, + positive, + Some(r#""#), + ), + ( + "percentage fractions", + r#"cropleft="12.5%" croptop="6.25%" cropright="25%" cropbottom="50%""#, + positive, + Some(r#""#), + ), + ( + "bounded fractions", + r#"cropleft="-25%" croptop="125%" cropright="not-a-fraction" cropbottom="NaN""#, + [0.0, 1.0, 0.0, 0.0], + Some(r#""#), + ), + ] { + // The local namespace keeps the existing package helper and every old fixture intact. + let body = format!( + r#""# + ); + let doc = craft_docx::read(&package(&body)).unwrap(); + let read_crop = image_crop(&doc, &original_png); + let saved = craft_docx::write(&doc).unwrap(); + let xml = part(&saved, "word/document.xml"); + let reopened = craft_docx::read(&saved).unwrap(); + let reopened_crop = image_crop(&reopened, &original_png); + + if let Some(saved_rect) = saved_rect { + if !crops_near(read_crop, expected, 0.000_001) { + lost.push(format!("{label}: read crop {read_crop:?}")); + } + if !xml.contains(saved_rect) { + lost.push(format!("{label}: saved srcRect")); + } + // DrawingML uses 100000 units per fraction; allow its rounding on a real re-read. + if !crops_near(reopened_crop, expected, 0.000_01) { + lost.push(format!("{label}: reopened crop {reopened_crop:?}")); + } + } else { + // The zero/default control must work before any positive-crop regression is reported. + assert_eq!(read_crop, [0.0; 4]); + assert!(!xml.contains(" 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..f826bdf57e 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -229,6 +229,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() }, @@ -976,8 +978,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 +1015,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 +1114,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 +1145,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 +1898,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/dxf/src/lib.rs b/crates/dxf/src/lib.rs index 5dd52af53d..b4035fdc30 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -35,6 +35,10 @@ pub enum DxfError { /// The memory for `tags` group codes couldn't be had: an error, not the process ending. #[error("not enough memory to read this drawing's {tags} DXF group codes")] OutOfMemory { tags: usize }, + /// An invalid integer value ([`Value::Invalid`]) cannot be encoded in binary DXF + /// because binary integer fields have no non-finite sentinel. + #[error("cannot encode invalid integer tag (group {code}) as binary DXF: `{text}`")] + InvalidInteger { code: i32, text: String }, } pub type Result = std::result::Result; @@ -48,12 +52,21 @@ 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), +} + +const I64_MIN_F64: f64 = -9_223_372_036_854_775_808.0; +const I64_MAX_EXCLUSIVE_F64: f64 = 9_223_372_036_854_775_808.0; + +fn f64_to_i64_checked(r: f64) -> Option { + if r.is_finite() && (I64_MIN_F64..I64_MAX_EXCLUSIVE_F64).contains(&r) { Some(r as i64) } else { None } } impl Value { pub fn as_str(&self) -> String { match self { - 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 +97,41 @@ impl Value { _ => 0, } } + /// Return the finite float value, or `None` if this value is non-finite or represents an invalid numeric group. + pub fn checked_f64(&self) -> Option { + match self { + Value::Real(r) if r.is_finite() => Some(*r), + Value::Int(i) => Some(*i as f64), + Value::Str(s) => s.trim().parse::().ok().filter(|v| v.is_finite()), + Value::Bool(b) => Some(f64::from(u8::from(*b))), + _ => None, + } + } + /// Return the integer value, or `None` if this value represents an invalid numeric group or cannot be converted to `i64`. + pub fn checked_i64(&self) -> Option { + match self { + Value::Int(i) => Some(*i), + Value::Real(r) => f64_to_i64_checked(*r), + Value::Str(s) => match s.trim().parse::() { + Ok(i) => Some(i), + Err(err) if matches!(err.kind(), std::num::IntErrorKind::PosOverflow | std::num::IntErrorKind::NegOverflow) => None, + Err(_) => s.trim().parse::().ok().and_then(f64_to_i64_checked), + }, + Value::Bool(b) => Some(i64::from(*b)), + _ => None, + } + } + /// 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)] @@ -100,11 +148,14 @@ 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) } } + 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 +172,20 @@ impl Tag { pub fn i64(&self) -> i64 { self.value.as_i64() } + /// Return the finite float value, or `None` if this tag's value is non-finite or invalid. + pub fn checked_f64(&self) -> Option { + self.value.checked_f64() + } + /// Return the integer value, or `None` if this tag's value is invalid or cannot be converted to `i64`. + pub fn checked_i64(&self) -> Option { + self.value.checked_i64() + } + pub fn is_invalid(&self) -> bool { + self.value.is_invalid() + } + 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,18 +216,26 @@ 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 - // 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)), @@ -201,8 +274,9 @@ pub use codepage::decode_code_page; /// /// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair, /// truncated binary data, or more group codes than the limit returned by [`max_tags()`], which is -/// [`MAX_TAGS`] by default. For ASCII input, invalid numeric text becomes `0.0` for real values or -/// `0` for integer values, and an EOF tag is not required. +/// [`MAX_TAGS`] by default. For ASCII input, invalid numeric text is preserved as [`Value::Invalid`], +/// and an EOF tag is not required. Numeric accessors ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or +/// `0` for backward compatibility. pub fn parse(bytes: &[u8]) -> Result> { parse_with_limit(bytes, max_tags()) } @@ -255,7 +329,8 @@ fn count_ascii_pairs(bytes: &[u8]) -> usize { /// /// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair, /// truncated binary data, or more than `max_tags` group codes. For ASCII input, invalid numeric -/// text becomes `0.0` for real values or `0` for integer values, and an EOF tag is not required. +/// text is preserved as [`Value::Invalid`], and an EOF tag is not required. Numeric accessors +/// ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or `0` for backward compatibility. pub fn parse_with_limit(bytes: &[u8], max_tags: usize) -> Result> { if let Some(body) = bytes.strip_prefix(BINARY_SENTINEL) { return parse_binary_with_limit(body, max_tags); @@ -404,7 +479,8 @@ fn byte_lines(mut rest: &[u8]) -> impl Iterator { /// # Errors /// /// Returns an error for empty input, an invalid group code, an incomplete group-code/value pair, -/// or too many tags. Invalid numeric text becomes `0.0` for real values or `0` for integer values. +/// or too many tags. Invalid numeric text is preserved as [`Value::Invalid`]. Numeric accessors +/// ([`Tag::f64()`], [`Tag::i64()`]) return `0.0` or `0` for backward compatibility. /// A complete tag stream does not require an EOF tag. pub fn parse_ascii(text: &str) -> Result> { parse_ascii_counted(text, max_tags(), 0) @@ -418,6 +494,21 @@ fn parse_ascii_counted(text: &str, max_tags: usize, expected: usize) -> Result String { + let unescaped = unescape_owned(s.clone()); + if unescaped == s { + return s; + } + let becomes_valid_numeric = match kind_of(code) { + Kind::Real => unescaped.trim().parse::().ok().filter(|v| v.is_finite()).is_some(), + Kind::Int16 | Kind::Int32 | Kind::Int64 => { + unescaped.trim().parse::().is_ok() || unescaped.trim().parse::().ok().filter(|f| f.is_finite()).is_some() + } + _ => false, + }; + if becomes_valid_numeric { s } else { unescaped } +} + /// The tags of ASCII DXF text. With `recover`, a line that is no group code, or a group code /// with no value after it, ends the reading instead of failing it: the tags before it are /// returned with the 1-based number of that line. @@ -450,6 +541,7 @@ fn ascii_tags(text: &str, max_tags: usize, expected: usize, recover: bool) -> Re let v = match typed(code, val) { // Only text with a backslash can hold an escape; the rest moves in as it is. Value::Str(s) => Value::Str(unescape_owned(s)), + Value::Invalid(s) => Value::Invalid(unescape_invalid(code, s)), o => o, }; let eof = code == 0 && matches!(&v, Value::Str(s) if s.trim_end() == "EOF"); @@ -570,7 +662,10 @@ 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 +861,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"); } @@ -779,17 +875,36 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec { /// several groups of the same code). Strings are UTF-8 when `utf8` (R2007+), otherwise escaped as /// in [`write_ascii`]. A tag's value is converted to its code's kind, so a number written as text /// is stored as a number; a code outside the 16-bit range is skipped. -pub fn write_binary(tags: &[Tag], utf8: bool) -> Vec { - binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }) +/// +/// Invalid real values ([`Value::Invalid`]) are preserved across binary serialization using +/// `f64::NAN`. +/// +/// # Errors +/// +/// Returns [`DxfError::InvalidInteger`] if any integer tag holds an invalid value ([`Value::Invalid`]), +/// because binary DXF integer representations have no IEEE-754 non-finite sentinel. Callers who +/// want invalid integers normalized to `0` can use [`write_binary_lossy`]. +pub fn write_binary(tags: &[Tag], utf8: bool) -> Result> { + binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }, false) } /// Write tags as pre-R2007 binary DXF with text in the code page `code_page` names, as /// [`write_ascii_in`] does. -pub fn write_binary_in(tags: &[Tag], code_page: &str) -> Vec { - binary(tags, Strings::Escaped(codepage::encoder(code_page))) +/// +/// # Errors +/// +/// Returns [`DxfError::InvalidInteger`] if any integer tag holds an invalid value ([`Value::Invalid`]). +pub fn write_binary_in(tags: &[Tag], code_page: &str) -> Result> { + binary(tags, Strings::Escaped(codepage::encoder(code_page)), false) } -fn binary(tags: &[Tag], strings: Strings) -> Vec { +/// Write tags as binary DXF, normalizing invalid integer tags ([`Value::Invalid`]) to `0` +/// instead of returning an error. +pub fn write_binary_lossy(tags: &[Tag], utf8: bool) -> Vec { + binary(tags, if utf8 { Strings::Utf8 } else { Strings::Escaped(None) }, true).unwrap_or_default() +} + +fn binary(tags: &[Tag], strings: Strings, normalize_invalid_integers: bool) -> Result> { let mut out = Vec::with_capacity(BINARY_SENTINEL.len() + tags.len() * 12); out.extend_from_slice(BINARY_SENTINEL); for t in tags { @@ -809,19 +924,44 @@ 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(f64::NAN), + _ => t.value.checked_f64().unwrap_or(0.0), + }; + out.extend_from_slice(&r.to_le_bytes()); } Kind::Int16 => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&wrap_i16(t.value.as_i64())); + let i = match t.value.checked_i64() { + Some(i) => i, + None if normalize_invalid_integers => 0, + None => { + return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() }); + } + }; + out.extend_from_slice(&wrap_i16(i)); } Kind::Int32 => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&wrap_i32(t.value.as_i64())); + let i = match t.value.checked_i64() { + Some(i) => i, + None if normalize_invalid_integers => 0, + None => { + return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() }); + } + }; + out.extend_from_slice(&wrap_i32(i)); } Kind::Int64 => { out.extend_from_slice(&code_bytes); - out.extend_from_slice(&t.value.as_i64().to_le_bytes()); + let i = match t.value.checked_i64() { + Some(i) => i, + None if normalize_invalid_integers => 0, + None => { + return Err(DxfError::InvalidInteger { code: t.code, text: t.value.invalid_str().unwrap_or_default().to_string() }); + } + }; + out.extend_from_slice(&i.to_le_bytes()); } Kind::Bool => { out.extend_from_slice(&code_bytes); @@ -842,7 +982,7 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec { } } } - out + Ok(out) } /// Hex text cleaned up: only the hex digits are kept, and an odd trailing digit is padded with @@ -1219,6 +1359,137 @@ mod tests { assert_eq!(t[0].str(), expect, "{s:?}"); } } + + #[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).unwrap(); + let back_bin = parse(&bin_out).unwrap(); + assert_eq!(back_bin[0], Tag::invalid(10, "NaN")); + assert_eq!(back_bin[1], Tag::invalid(20, "inf")); + // 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()); + } + + #[test] + fn checked_i64_bounds_enforced_including_exclusive_upper_bound() { + // Inclusive lower bound: -2^63 fits + assert_eq!(Value::Real(-9_223_372_036_854_775_808.0).checked_i64(), Some(i64::MIN)); + assert_eq!(Value::Str("-9223372036854775808".into()).checked_i64(), Some(i64::MIN)); + + // Adjacent decimal below lower bound: must not round to i64::MIN via float fallback + assert_eq!(Value::Str("-9223372036854775809".into()).checked_i64(), None); + + // Far below lower bound: does not fit + assert_eq!(Value::Real(-1e30).checked_i64(), None); + assert_eq!(Value::Str("-1e30".into()).checked_i64(), None); + + // Inclusive upper bound: 2^63 - 1 fits + assert_eq!(Value::Str("9223372036854775807".into()).checked_i64(), Some(i64::MAX)); + + // Exclusive upper bound / adjacent decimal above upper bound: does not fit + assert_eq!(Value::Real(9_223_372_036_854_775_808.0).checked_i64(), None); + assert_eq!(Value::Str("9223372036854775808".into()).checked_i64(), None); + + // Just below exclusive upper bound: 2^63 - 2048 (largest representable f64 < 2^63) + assert_eq!(Value::Real(9_223_372_036_854_774_784.0).checked_i64(), Some(9_223_372_036_854_774_784)); + + // Float syntax fallback still converts finite real strings within integer range + assert_eq!(Value::Str("12.0".into()).checked_i64(), Some(12)); + assert_eq!(Value::Str("-12.0".into()).checked_i64(), Some(-12)); + assert_eq!(Value::Str("1e3".into()).checked_i64(), Some(1000)); + + // Normal values + assert_eq!(Value::Real(42.0).checked_i64(), Some(42)); + assert_eq!(Value::Int(42).checked_i64(), Some(42)); + assert_eq!(Value::Invalid("foo".into()).checked_i64(), None); + } + + #[test] + fn invalid_numeric_escape_does_not_decode_into_valid_numeric_spelling() { + let text = "10\n\\U+0030\n0\nEOF\n"; + let tags = parse(text.as_bytes()).unwrap(); + assert_eq!(tags[0], Tag::invalid(10, "\\U+0030")); + assert!(tags[0].is_invalid()); + + // Roundtrip in ASCII preserves raw invalid escape and signal + let ascii_out = write_ascii(&tags); + let back_ascii = parse(ascii_out.as_bytes()).unwrap(); + assert_eq!(back_ascii[0], Tag::invalid(10, "\\U+0030")); + assert!(back_ascii[0].is_invalid()); + + // Roundtrip in binary preserves invalid signal via NaN sentinel + let bin_out = write_binary(&tags, true).unwrap(); + let back_bin = parse(&bin_out).unwrap(); + assert_eq!(back_bin[0], Tag::invalid(10, "NaN")); + assert!(back_bin[0].is_invalid()); + } + + #[test] + fn binary_integer_writer_reports_error_unless_lossy_normalized() { + let tags = vec![Tag::invalid(70, "corrupted"), Tag::s(0, "EOF")]; + // Checked write_binary returns error for invalid integer tag + assert!(matches!(write_binary(&tags, true), Err(DxfError::InvalidInteger { code: 70, .. }))); + + // Explicit write_binary_lossy normalizes invalid integer to 0 + let lossy_bin = write_binary_lossy(&tags, true); + let back = parse(&lossy_bin).unwrap(); + assert_eq!(back[0], Tag::i(70, 0)); + } } #[cfg(test)] diff --git a/crates/dxf/tests/it/audit_followups.rs b/crates/dxf/tests/it/audit_followups.rs index de61bf175a..bd82631019 100644 --- a/crates/dxf/tests/it/audit_followups.rs +++ b/crates/dxf/tests/it/audit_followups.rs @@ -9,7 +9,7 @@ fn group_code_255_is_an_ordinary_code_in_binary_dxf() { // Code 255 used to be read as an R12 escape (`FF 00 `), so a file with that code could // not be read back. let tags = vec![Tag::s(255, "x"), Tag::s(0, "EOF")]; - let back = parse(&write_binary(&tags, true)).unwrap(); + let back = parse(&write_binary(&tags, true).unwrap()).unwrap(); assert_eq!(back.len(), 2); assert_eq!((back[0].code, back[0].str()), (255, "x".to_string())); } @@ -117,7 +117,7 @@ fn escapes_next_to_other_text_and_backslashes() { assert_eq!(parse(&file).unwrap()[0].str(), "éA\\ ü"); // And the writer keeps the literal text literal. let tags = [Tag::s(1, "é\\U+0041\\ ü"), Tag::s(0, "EOF")]; - assert_eq!(parse(&write_binary(&tags, true)).unwrap()[0].str(), "é\\U+0041\\ ü"); + assert_eq!(parse(&write_binary(&tags, true).unwrap()).unwrap()[0].str(), "é\\U+0041\\ ü"); } #[test] diff --git a/crates/dxf/tests/it/binary_write.rs b/crates/dxf/tests/it/binary_write.rs index 6c56c3a336..ab70341d39 100644 --- a/crates/dxf/tests/it/binary_write.rs +++ b/crates/dxf/tests/it/binary_write.rs @@ -27,7 +27,7 @@ fn binary_converts_values_to_their_codes_kind() { // A number held as text at a numeric code, an out-of-range 16-bit value, a long chunk. let long = "AB".repeat(300); let tags = vec![Tag::s(70, "12"), Tag::i(62, 1 << 20), Tag::new(310, Value::Hex(long)), Tag::s(0, "EOF")]; - let back = parse(&write_binary(&tags, true)).unwrap(); + let back = parse(&write_binary(&tags, true).unwrap()).unwrap(); assert_eq!(back[0], Tag::i(70, 12)); assert_eq!(back[1], Tag::i(62, i64::from(i16::MAX))); let sizes: Vec = back.iter().filter(|t| t.code == 310).map(|t| t.str().len()).collect(); @@ -36,7 +36,7 @@ fn binary_converts_values_to_their_codes_kind() { #[test] fn hostile_binary_input_never_panics() { - let good = write_binary(&sample(), true); + let good = write_binary(&sample(), true).unwrap(); // Every truncation, and every single-byte corruption of the body. for n in 0..good.len() { let _ = parse(good.get(..n).unwrap()); diff --git a/crates/dxf/tests/it/code_page_write.rs b/crates/dxf/tests/it/code_page_write.rs index 02e8a75d2b..35ce1ed457 100644 --- a/crates/dxf/tests/it/code_page_write.rs +++ b/crates/dxf/tests/it/code_page_write.rs @@ -43,7 +43,7 @@ fn text_is_written_in_the_code_page() { ]; for (cp, text, raw) in cases { let tags = file(cp, text); - for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] { assert!(contains(&bytes, raw), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); } @@ -60,7 +60,7 @@ fn unknown_ascii_and_utf8_code_pages_are_pure_ascii() { assert!(bytes.is_ascii(), "{cp}"); assert_eq!(bytes, write_ascii(&tags).into_bytes(), "{cp}"); assert!(contains(&bytes, b"A\\U+00E7\\U+00E3o fim"), "{cp}"); - assert!(write_binary_in(&tags, cp).iter().all(u8::is_ascii), "{cp} binary"); + assert!(write_binary_in(&tags, cp).unwrap().iter().all(u8::is_ascii), "{cp} binary"); } } @@ -74,7 +74,7 @@ fn code_page_bytes_that_are_valid_utf8_are_escaped_in_ascii() { assert!(ascii.is_ascii(), "{:?}", String::from_utf8_lossy(&ascii)); assert!(contains(&ascii, b"\\U+0421\\U+0406")); assert_eq!(parse(&ascii).unwrap()[10].str(), "СІ"); - let binary = write_binary_in(&tags, "ANSI_1251"); + let binary = write_binary_in(&tags, "ANSI_1251").unwrap(); assert!(contains(&binary, b"\xD1\xB2")); assert_eq!(parse(&binary).unwrap()[10].str(), "СІ"); // Bytes that are not valid UTF-8 stay as they are. @@ -111,7 +111,7 @@ fn literal_escapes_survive_code_page_text() { [("ANSI_1252", "Ação \\U+00E9 \\M+183A4F"), ("ANSI_1251", "Слой \\U+0041"), ("ANSI_1251", "СІ \\U+0041"), ("ANSI_932", "表 \\M+1")] { let tags = file(cp, text); - for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] { assert!(contains(&bytes, b"\\U+005C"), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); } @@ -132,7 +132,7 @@ fn a_trail_byte_backslash_never_starts_an_escape() { ]; for (cp, text, written, never) in cases { let tags = file(cp, text); - for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp), "binary")] { + for (bytes, what) in [(write_ascii_in(&tags, cp), "ASCII"), (write_binary_in(&tags, cp).unwrap(), "binary")] { assert!(contains(&bytes, written), "{cp} {what}: {:?}", String::from_utf8_lossy(&bytes)); assert!(!contains(&bytes, never), "{cp} {what}: a trail byte starts an escape"); assert_eq!(parse(&bytes).unwrap()[10].str(), text, "{cp} {what}"); diff --git a/crates/dxf/tests/it/conformance.rs b/crates/dxf/tests/it/conformance.rs index 2c09e28e81..8112a30758 100644 --- a/crates/dxf/tests/it/conformance.rs +++ b/crates/dxf/tests/it/conformance.rs @@ -42,7 +42,7 @@ fn writes_independently_specified_ascii_and_binary_bytes() { for utf8 in [false, true] { let tags = std::slice::from_ref(&tag); assert_eq!(write_ascii_as(tags, utf8).as_bytes(), ascii, "ASCII code {}", tag.code); - assert_eq!(write_binary(tags, utf8), [SENTINEL, binary].concat(), "binary code {}", tag.code); + assert_eq!(write_binary(tags, utf8).unwrap(), [SENTINEL, binary].concat(), "binary code {}", tag.code); } } } @@ -66,7 +66,7 @@ fn integer_code_ranges_have_independent_binary_widths() { let expected = [SENTINEL, &code_bytes, &value_bytes[..width]].concat(); let tags = [Tag::i(code, value)]; for utf8 in [false, true] { - assert_eq!(write_binary(&tags, utf8), expected, "code={code} value={value} utf8={utf8}"); + assert_eq!(write_binary(&tags, utf8).unwrap(), expected, "code={code} value={value} utf8={utf8}"); } assert_eq!(parse(&expected).unwrap(), tags, "code={code} value={value}"); } @@ -83,7 +83,7 @@ fn text_encoding_has_independent_wire_expectations() { let ascii = [b" 1\r\n".as_slice(), text, b"\r\n"].concat(); let binary = [SENTINEL, b"\x01\0", text, b"\0"].concat(); assert_eq!(write_ascii_as(&tags, unicode).as_bytes(), ascii, "utf8={unicode}"); - assert_eq!(write_binary(&tags, unicode), binary, "utf8={unicode}"); + assert_eq!(write_binary(&tags, unicode).unwrap(), binary, "utf8={unicode}"); assert_eq!(parse(&ascii).unwrap(), tags); assert_eq!(parse(&binary).unwrap(), tags); } diff --git a/crates/dxf/tests/it/hardening.rs b/crates/dxf/tests/it/hardening.rs index 4d013f1f4f..c35067540a 100644 --- a/crates/dxf/tests/it/hardening.rs +++ b/crates/dxf/tests/it/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")]; @@ -107,19 +126,68 @@ 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.checked_f64(), None); + assert_eq!(nan_tag.checked_i64(), None); + assert_eq!(nan_tag.invalid_str(), Some("NaN")); + + let inf_tag = Tag::f(20, f64::INFINITY); + assert!(inf_tag.is_invalid()); + assert_eq!(inf_tag.f64(), 0.0); + assert_eq!(inf_tag.checked_f64(), None); + assert_eq!(inf_tag.checked_i64(), None); + assert_eq!(inf_tag.invalid_str(), Some("inf")); +} + +#[test] +fn invalid_numbers_with_dxf_escapes_roundtrip_through_ascii_write_and_parse() { + let tags = + vec![Tag::invalid(10, "12.34\\U+0020xyz"), Tag::invalid(20, "bad\\U+005Cpath"), Tag::invalid(70, "corrupted\\U+0041"), Tag::s(0, "EOF")]; + let ascii_out = write_ascii(&tags); + let back = parse(ascii_out.as_bytes()).unwrap(); + assert_eq!(back[0], Tag::invalid(10, "12.34\\U+0020xyz")); + assert_eq!(back[1], Tag::invalid(20, "bad\\U+005Cpath")); + assert_eq!(back[2], Tag::invalid(70, "corrupted\\U+0041")); +} + +#[test] +fn binary_integer_writer_reports_error_unless_lossy_normalized() { + let invalid_int_tag = Tag::invalid(70, "corrupted"); + assert!(invalid_int_tag.is_invalid()); + assert_eq!(invalid_int_tag.checked_i64(), None); + assert_eq!(invalid_int_tag.i64(), 0); + + // Binary DXF integer groups have no NaN marker, so write_binary reports conversion error + let res = write_binary(&[invalid_int_tag.clone(), Tag::s(0, "EOF")], true); + assert!(matches!(res, Err(craft_dxf::DxfError::InvalidInteger { code: 70, .. }))); + + // Explicit write_binary_lossy normalizes invalid integer to 0 + let lossy_bin = craft_dxf::write_binary_lossy(&[invalid_int_tag, Tag::s(0, "EOF")], true); + let back = parse(&lossy_bin).unwrap(); + assert_eq!(back[0], Tag::i(70, 0)); + assert_eq!(back[0].checked_i64(), Some(0)); +} + /// 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] @@ -139,7 +207,7 @@ fn hex_groups_pad_odd_digits_and_drop_junk() { assert_eq!(t[2].value, Value::Hex(String::new())); assert_eq!(t[3].value, Value::Hex("0aF0".into())); // The binary writer agrees with the reader: the odd digit is padded, nothing shifts. - let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true)).unwrap(); + let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true).unwrap()).unwrap(); assert_eq!(back[0].value, Value::Hex("ABC0".into())); } @@ -171,7 +239,7 @@ fn binary_sixteen_and_thirty_two_bit_values_wrap_in_range_and_clamp_outside() { Tag::i(90, -(1 << 40)), Tag::s(0, "EOF"), ]; - let back = parse(&write_binary(&tags, true)).unwrap(); + let back = parse(&write_binary(&tags, true).unwrap()).unwrap(); assert_eq!(back[0], Tag::i(70, -1)); assert_eq!(back[1], Tag::i(70, 40000 - 65536)); assert_eq!(back[2], Tag::i(70, i64::from(i16::MAX))); diff --git a/crates/dxf/tests/it/hex_chunks.rs b/crates/dxf/tests/it/hex_chunks.rs index 80e9e91933..e9f34fa0c4 100644 --- a/crates/dxf/tests/it/hex_chunks.rs +++ b/crates/dxf/tests/it/hex_chunks.rs @@ -52,7 +52,7 @@ fn check_ascii(code: i32, bytes: &[u8], utf8: bool) { } fn check_binary(code: i32, bytes: &[u8], utf8: bool) { - let wire = write_binary(&input(code, bytes), utf8); + let wire = write_binary(&input(code, bytes), utf8).unwrap(); let mut chunks = wire.strip_prefix(SENTINEL).unwrap().strip_suffix(FOLLOWING_BINARY).unwrap(); assert!(!chunks.is_empty(), "an empty payload must still have a tag"); let context = format!("binary code={code} bytes={} utf8={utf8}", bytes.len()); diff --git a/crates/dxf/tests/it/recovering.rs b/crates/dxf/tests/it/recovering.rs index 1dffd87f39..8df6a5231e 100644 --- a/crates/dxf/tests/it/recovering.rs +++ b/crates/dxf/tests/it/recovering.rs @@ -10,7 +10,7 @@ fn an_intact_file_reads_as_parse_reads_it() { assert_eq!(damaged, None); assert_eq!(tags, parse(WHOLE.as_bytes()).expect("reads")); // Binary files are read as before. - let binary = write_binary(&tags, true); + let binary = write_binary(&tags, true).unwrap(); assert_eq!(parse_recovering(&binary).expect("reads"), (tags, None)); } diff --git a/crates/dxf/tests/it/roundtrip.rs b/crates/dxf/tests/it/roundtrip.rs index d4b5883c00..2dc48bf274 100644 --- a/crates/dxf/tests/it/roundtrip.rs +++ b/crates/dxf/tests/it/roundtrip.rs @@ -23,7 +23,8 @@ fn check(case: &str, body: &[Tag]) { let mut current = original.clone(); for pass in 1..=2 { let context = format!("{case} · {version} · binary={binary} · pass={pass}"); - let bytes = if binary { write_binary(¤t, version.utf8()) } else { write_ascii_as(¤t, version.utf8()).into_bytes() }; + let bytes = + if binary { write_binary(¤t, version.utf8()).unwrap() } else { write_ascii_as(¤t, version.utf8()).into_bytes() }; assert_eq!(is_binary(&bytes), binary, "{context}"); let back = parse(&bytes).unwrap_or_else(|e| panic!("{context}: {e}")); assert_eq!(back.len(), original.len(), "{context}: tag count"); diff --git a/crates/exr/Cargo.toml b/crates/exr/Cargo.toml index 28a1649b8b..f5b5ee93e0 100644 --- a/crates/exr/Cargo.toml +++ b/crates/exr/Cargo.toml @@ -18,6 +18,7 @@ decode = ["dep:exr", "dep:half", "dep:thiserror", "zlib-inflate"] zlib-inflate = ["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 6a8e3b0c32..94efc864de 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. -//! - [`fn@write`] writes one scan-line part. +//! - [`fn@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 @@ -65,6 +66,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)] @@ -1072,7 +1077,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/decode_tests.rs b/crates/exr/src/decode_tests.rs index 3a20d7b7ef..59d2c08ff7 100644 --- a/crates/exr/src/decode_tests.rs +++ b/crates/exr/src/decode_tests.rs @@ -351,7 +351,16 @@ fn limits_are_checked_from_the_headers() { // is over; the 1 MiB slack always admits small pictures. assert!(ok(Limits { max_ratio: 0, ..d })); // A header claiming a huge data window over a few bytes of file is refused by the ratio. - let big = file(vec![layer(None, 4096, 4096, &["R"], false, exr::prelude::Compression::ZIP16)], (4096, 4096)); + // Only headers are read here: keep the large declared windows without encoding their pixels. + let mut big = file(vec![layer(None, 8, 4, &["R"], false, exr::prelude::Compression::ZIP16)], (8, 4)); + let window: Vec = [0i32, 0, 4095, 4095].iter().flat_map(|v| v.to_le_bytes()).collect(); + for tag in ["dataWindow\0box2i\0", "displayWindow\0box2i\0"] { + let tag = tag.as_bytes(); + let at = big.windows(tag.len()).position(|w| w == tag).unwrap() + tag.len() + 4; + big[at..at + 16].copy_from_slice(&window); + } + // At 1024 file bytes the default ratio admits 64 MiB, but ratio 1 plus 1 MiB slack does not. + big.resize(1024, 0); assert!(ok_big(&big)); assert!(matches!(parts(&big, &Limits { max_ratio: 1, ..d }), Err(Error::LimitExceeded(_)))); } diff --git a/crates/exr/src/layer_stack.rs b/crates/exr/src/layer_stack.rs new file mode 100644 index 0000000000..2e53f4d2c9 --- /dev/null +++ b/crates/exr/src/layer_stack.rs @@ -0,0 +1,372 @@ +//! 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_GROUP_DEPTH: usize = 100; + +#[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, + /// 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)] +#[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. + /// An empty prefix selects unprefixed channels such as `R`, `G` and `B`. + 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, + original_sample_depth: 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>, + #[serde(skip_serializing_if = "Option::is_none")] + original_sample_depth: Option, +} + +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, 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, original_sample_depth }; + 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(), + 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")); + } + 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, min, max) = match pixels { + PixelRef::Part { name } => (name, 1, 255), + PixelRef::ChannelGroup { prefix, .. } => (prefix, 0, 253), + }; + 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()); + } + 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_GROUP_DEPTH { + 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()), + original_sample_depth: None, + } + } + + #[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 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()); + 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 833bd79910..5db34a65fa 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. /// Bounded RLE expansion and inverse byte prediction for EXR blocks. @@ -53,9 +55,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..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 × @@ -293,6 +293,13 @@ impl Index { self.display } + /// 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.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])) + } + /// 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 @@ -386,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]; @@ -606,11 +613,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 +654,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 +667,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 +771,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 +782,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 +825,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 +837,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 +865,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 +909,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 +925,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 +951,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 +1225,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 +1489,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 +1516,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 0f48fdb386..2bb2ddb071 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() @@ -89,6 +112,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/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 new file mode 100644 index 0000000000..0e2daba2a4 --- /dev/null +++ b/crates/exr/src/write.rs @@ -0,0 +1,660 @@ +//! 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, SeekFrom, 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, MAX_HEADER_ATTRIBUTES, 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 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; + +/// 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. 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>], +} + +/// 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( + 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( + |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)?; + // 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) +} + +#[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)?; + 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); + } + 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..a9c2737441 --- /dev/null +++ b/crates/exr/src/write_tests.rs @@ -0,0 +1,453 @@ +use std::cell::Cell; +use std::io::{self, Cursor, Seek, SeekFrom, Write}; + +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}; + +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 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 }; + 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()); + } +} + +// 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 }; + 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"); +} diff --git a/crates/fcproj-format/src/lib.rs b/crates/fcproj-format/src/lib.rs index 4ac1b72439..11f7e5013f 100644 --- a/crates/fcproj-format/src/lib.rs +++ b/crates/fcproj-format/src/lib.rs @@ -1,6 +1,8 @@ //! FilmCraft `.fcproj` JSON envelope, version detection and historical migrations. //! Project and editor-view types are supplied by the caller. #![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))] +pub mod records; + use serde::{Deserialize, Serialize}; use serde_json::Value; /// The `format` tag written in every envelope. diff --git a/crates/fcproj-format/src/records.rs b/crates/fcproj-format/src/records.rs new file mode 100644 index 0000000000..971635cfa6 --- /dev/null +++ b/crates/fcproj-format/src/records.rs @@ -0,0 +1,138 @@ +//! Reversible record boundaries for a FilmCraft project. A bin owns an ordered list of +//! references; each project item (including a sequence) has one payload. Fields outside +//! those boundaries stay in their original JSON objects, including editor and extension data. +//! +//! These types describe logical records, independent of directory names, hashing, and commits. + +use crate::{FormatError, MIGRATIONS, check_supported, detect_bytes, migrate_with}; +use serde::Deserialize; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; + +type Result = std::result::Result; +type Payloads = BTreeMap; + +// Reassembly follows links between separately supplied records, outside the JSON parser's +// recursion limit. A repeated or cyclic bin is also rejected on its second visit. +const MAX_BIN_DEPTH: usize = 64; + +/// The envelope carries the root bin ID and a complete inventory of item IDs, including +/// items outside any bin. The map keys are persisted project IDs, never display names. +#[derive(Debug)] +pub struct ProjectRecords { + pub envelope: Value, + pub bins: BTreeMap, + pub items: BTreeMap, +} + +fn corrupt(message: impl Into) -> FormatError { + FormatError::Corrupt(message.into()) +} + +fn object_id(value: &Value) -> Result { + value.get("id").and_then(Value::as_u64).ok_or_else(|| corrupt("record lacks an unsigned id")) +} + +fn children(bin: &mut Value, depth: usize) -> Result<&mut Vec> { + if depth > MAX_BIN_DEPTH { + return Err(corrupt("bin nesting exceeds the supported depth")); + } + bin.get_mut("children").and_then(Value::as_array_mut).ok_or_else(|| corrupt("bin lacks children")) +} + +// Only nested bins change representation. Item references retain their original position. +fn nested_or_item<'a>(child: &'a mut Value, items: &Payloads) -> Result> { + let entry = child.as_object_mut().filter(|o| o.len() == 1).ok_or_else(|| corrupt("invalid bin entry"))?; + if let Some(item) = entry.get("Item") { + let id = item.as_u64().ok_or_else(|| corrupt("invalid item reference"))?; + if !items.contains_key(&id) { + return Err(corrupt(format!("bin references missing item {id}"))); + } + Ok(None) + } else { + entry.get_mut("Bin").map(Some).ok_or_else(|| corrupt("unknown bin entry")) + } +} + +fn split_bin(mut bin: Value, bins: &mut Payloads, items: &Payloads, depth: usize) -> Result { + let id = object_id(&bin)?; + for child in children(&mut bin, depth)? { + if let Some(nested) = nested_or_item(child, items)? { + *nested = Value::from(split_bin(nested.take(), bins, items, depth + 1)?); + } + } + if bins.insert(id, bin).is_some() { + return Err(corrupt(format!("duplicate bin id {id}"))); + } + Ok(id) +} + +fn join_bin(reference: &Value, bins: &mut Payloads, items: &Payloads, depth: usize) -> Result { + let id = reference.as_u64().ok_or_else(|| corrupt("invalid bin reference"))?; + let mut bin = bins.remove(&id).ok_or_else(|| corrupt(format!("missing or repeated bin {id}")))?; + if object_id(&bin)? != id { + return Err(corrupt(format!("bin payload does not match id {id}"))); + } + for child in children(&mut bin, depth)? { + if let Some(nested) = nested_or_item(child, items)? { + *nested = join_bin(nested, bins, items, depth + 1)?; + } + } + Ok(bin) +} + +impl ProjectRecords { + /// Split supported project bytes, applying the same historical migrations as the + /// ordinary reader. Callers reading from storage must bound input size before parsing. + pub fn split(bytes: &[u8]) -> Result { + let version = detect_bytes(bytes)?; + let doc = serde_json::from_slice(bytes).map_err(|e| corrupt(e.to_string()))?; + let mut envelope = migrate_with(MIGRATIONS, doc, version)?; + let project = envelope.get_mut("project").and_then(Value::as_object_mut).ok_or_else(|| corrupt("missing project"))?; + let Some(Value::Object(payloads)) = project.remove("items") else { return Err(corrupt("missing project items")) }; + let mut items = Payloads::new(); + let mut inventory = Vec::with_capacity(payloads.len()); + for (key, value) in payloads { + let id = object_id(&value)?; + if id.to_string() != key { + return Err(corrupt(format!("item key does not match id {id}"))); + } + items.insert(id, value); + inventory.push(Value::from(id)); + } + project.insert("items".into(), Value::Array(inventory)); + let root = project.get_mut("root").ok_or_else(|| corrupt("missing root bin"))?; + let mut bins = Payloads::new(); + *root = Value::from(split_bin(root.take(), &mut bins, &items, 0)?); + Ok(Self { envelope, bins, items }) + } + + /// Reassemble a complete set, refusing missing, extra or misidentified payloads. + /// A successful result preserves the migrated document as JSON, including unknown + /// fields; the application still validates timeline and media semantics on load. + pub fn into_document(mut self) -> Result { + let probe = crate::Probe::deserialize(&self.envelope).map_err(|e| corrupt(e.to_string()))?; + check_supported(crate::probe_version(&probe)?)?; + let project = self.envelope.get_mut("project").and_then(Value::as_object_mut).ok_or_else(|| corrupt("missing project"))?; + let root = project.get_mut("root").ok_or_else(|| corrupt("missing root bin"))?; + *root = join_bin(root, &mut self.bins, &self.items, 0)?; + if !self.bins.is_empty() { + return Err(corrupt("unreferenced bin payload")); + } + let Some(Value::Array(ids)) = project.remove("items") else { return Err(corrupt("missing item inventory")) }; + let mut items = Map::new(); + for key in ids { + let id = key.as_u64().ok_or_else(|| corrupt("invalid item inventory entry"))?; + let item = self.items.remove(&id).ok_or_else(|| corrupt(format!("missing or repeated item {id}")))?; + if object_id(&item)? != id { + return Err(corrupt(format!("item payload does not match id {id}"))); + } + items.insert(id.to_string(), item); + } + if !self.items.is_empty() { + return Err(corrupt("unreferenced item payload")); + } + project.insert("items".into(), Value::Object(items)); + Ok(self.envelope) + } +} diff --git a/crates/fcproj-format/tests/it/main.rs b/crates/fcproj-format/tests/it/main.rs new file mode 100644 index 0000000000..cdccb7abf6 --- /dev/null +++ b/crates/fcproj-format/tests/it/main.rs @@ -0,0 +1,78 @@ +//! Original, generated project fragments exercise record ownership and preservation. +use craft_fcproj_format::{FormatError, MIGRATIONS, SCHEMA_VERSION, migrate_with, records::ProjectRecords}; +use serde_json::{Value, json}; + +fn project() -> Value { + json!({ + "format": "filmcraft.project", "schema_version": SCHEMA_VERSION, "view": {"tabs":[12]}, + "generator": "test", "extra": [null, {}], + "project": { + "root": {"id":0,"name":"Cut","children":[ + {"Item":12},{"Bin":{"id":19,"name":"Cut","children":[{"Item":4}]}} + ]}, + "items": { + "4":{"id":4,"media":{"path":"../offline/shot.mov"},"label":"A"}, + "12":{"id":12,"sequence":{"nested":[4],"duration":123}}, + "9":{"id":9,"name":"Unfiled","extra":{}} + }, + "next_id":20, "transcripts":{}, "new_project_field":{"value":null} + } + }) +} + +fn split(doc: &Value) -> ProjectRecords { + ProjectRecords::split(&serde_json::to_vec(doc).unwrap()).unwrap() +} + +#[test] +fn changing_one_sequence_preserves_all_other_records_and_the_view() { + let original = project(); + let mut changed = original.clone(); + changed["project"]["items"]["12"]["sequence"]["duration"] = json!(124); + let before = split(&original); + let after = split(&changed); + assert_eq!(before.envelope, after.envelope); + assert_eq!(before.bins, after.bins); + assert_eq!(before.items.keys().filter(|id| before.items[id] != after.items[id]).copied().collect::>(), [12]); + assert_eq!(before.into_document().unwrap(), original); + assert_eq!(after.into_document().unwrap(), changed); +} + +#[test] +fn legacy_uses_the_same_migrations_and_future_versions_are_refused() { + let mut bare = project()["project"].take(); + bare["version"] = json!(1); + assert_eq!(split(&bare).into_document().unwrap(), migrate_with(MIGRATIONS, bare, 1).unwrap()); + let mut doc = project(); + doc["schema_version"] = json!(SCHEMA_VERSION + 1); + assert!(matches!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()), Err(FormatError::TooNew { .. }))); +} + +#[test] +fn incomplete_or_conflicting_records_cannot_be_reassembled() { + let make = || split(&project()); + let mut missing = make(); + missing.items.remove(&9); // Unfiled; a bin traversal alone cannot detect the lost item. + assert!(missing.into_document().is_err()); + let mut extra = make(); + extra.items.insert(11, json!({"id":11})); + assert!(extra.into_document().is_err()); + let mut cycle = make(); + cycle.bins.get_mut(&19).unwrap()["children"] = json!([{"Bin":0}]); + assert!(cycle.into_document().is_err()); + let mut mismatch = make(); + mismatch.items.get_mut(&4).unwrap()["id"] = json!(19); + assert!(mismatch.into_document().is_err()); + let mut detached = make(); + detached.bins.get_mut(&0).unwrap()["children"] = json!([]); + assert!(detached.into_document().is_err()); +} + +#[test] +fn conversion_refuses_ambiguous_bins_and_dangling_membership() { + let mut doc = project(); + doc["project"]["root"]["children"][1]["Bin"]["id"] = json!(0); + assert!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()).is_err()); + doc["project"]["root"]["children"] = json!([{"Item":100}]); + assert!(ProjectRecords::split(&serde_json::to_vec(&doc).unwrap()).is_err()); +} diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index bae6ecb65d..4911e2f2b1 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -529,6 +529,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); @@ -579,6 +580,8 @@ fn flow_paras_in(doc: &Document, p: &Paragraph, opts: FlowOpts) -> Vec { wrap: None, index: None, group: 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() { @@ -952,9 +955,50 @@ 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); + // 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, 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 => true, + }; + if !kept { + 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. + *at = [None; 9]; + } + 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; @@ -969,7 +1013,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; @@ -980,7 +1024,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 { @@ -1105,6 +1149,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 7dc83c99d8..238a455fb8 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::{ @@ -210,4 +211,149 @@ 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 + } + + #[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] + 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 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() { + 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/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index 3d27d521f3..303dc022cc 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; if p.rtl { out.bidi = Some(true); @@ -766,6 +769,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 { @@ -779,7 +788,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; } @@ -795,7 +811,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 7def87e344..357c9c6ff4 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -716,6 +716,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 @@ -1107,3 +1110,14 @@ 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. +/// 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() && matches!(p.kind, Kind::Normal | Kind::Heading(_)) => 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 e734f26005..a876f2bc0b 100644 --- a/crates/html/src/doc/export.rs +++ b/crates/html/src/doc/export.rs @@ -433,7 +433,19 @@ fn blocks_html(blocks: &[FBlock], out: &mut String, depth: usize, spaced: bool) // 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(¶_html(q, false)); + 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/html/src/doc/tests.rs b/crates/html/src/doc/tests.rs index 4f471588e5..58f821cb99 100644 --- a/crates/html/src/doc/tests.rs +++ b/crates/html/src/doc/tests.rs @@ -985,6 +985,18 @@ fn hostile_style_sheets_never_panic() { } } +/// 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}"); +} + #[test] fn conflicting_mso_vmerge_declarations_last_wins() { let html_restart_wins = "
    A
    "; @@ -2153,6 +2165,28 @@ fn the_fragment_spaces_only_top_level_paragraphs_and_headings() { assert!(fragment.contains("
    • Item
    "), "{fragment}"); } +/// A list item's further paragraph keeps its alignment and page break in the fragment, without +/// spacing or indents, as the item itself. +#[test] +fn the_fragment_leaves_a_list_items_further_paragraph_unspaced() { + let chr = craft_wordmodel::CharProps::default(); + let mut d = Document::new(); + let num = std::sync::Arc::make_mut(&mut d.numbering).add_list(craft_wordmodel::ListKind::Bullet); + let mut item = craft_wordmodel::Paragraph::with_text("Item", chr.clone()).styled("ListParagraph"); + item.props.numbering = Some(craft_wordmodel::props::NumRef { num, level: 0 }); + let mut more = craft_wordmodel::Paragraph::with_text("More", chr); + more.props.list_item = Some(0); + more.props.align = Some(craft_wordmodel::Align::Center); + more.props.page_break_before = Some(true); + more.props.indent_left = Some(72.0); + more.props.space_after = Some(6.0); + d.body = vec![craft_wordmodel::para_block(item), craft_wordmodel::para_block(more)]; + let fragment = export_fragment(&d); + let more = fragment.split("
  • Item").nth(1).and_then(|s| s.split("
  • ").next()).unwrap(); + assert!(more.contains("More") && more.contains("text-align:center") && more.contains("break-before:page"), "{fragment}"); + assert!(!fragment.contains("margin-"), "{fragment}"); +} + /// Code blocks and the paragraphs of a table cell keep the fragment's plain markup, whatever their /// spacing. #[test] diff --git a/crates/image-codecs/tests/it/heif.rs b/crates/image-codecs/tests/it/heif.rs index c5cd36c234..07c15f65eb 100644 --- a/crates/image-codecs/tests/it/heif.rs +++ b/crates/image-codecs/tests/it/heif.rs @@ -127,15 +127,14 @@ fn container_rotation_is_applied_once() { #[test] fn exif_and_xmp_survive_and_exif_orientation_is_not_applied_twice() { - let img = decode(with_exif()).unwrap(); + // HEIF's EXIF Orientation repeats what irot says; the container is the authority. + let tagged = with_exif_orientation(with_exif(), 6); + let img = decode(&tagged).unwrap(); assert_eq!(img.dimensions(), (2048, 1536)); let exif = img.meta.exif.as_deref().unwrap(); assert!(exif.starts_with(b"MM\0*"), "TIFF-structured EXIF, without the HEIF offset header"); assert!(img.meta.xmp.as_deref().unwrap().contains("x:xmpmeta")); - // HEIF's EXIF Orientation repeats what irot says; the container is the authority. - let tagged = with_exif_orientation(with_exif(), 6); - let img = decode(&tagged).unwrap(); assert_eq!(img.dimensions(), (2048, 1536), "not turned by the EXIF tag"); assert_eq!(exif_orientation(img.meta.exif.as_deref().unwrap()), 1, "rewritten so exports don't turn it either"); let raw = decode_with(&tagged, &keep()).unwrap(); diff --git a/crates/imaging/src/ui/select/lasso.rs b/crates/imaging/src/ui/select/lasso.rs index ec6037b6b0..a198630116 100644 --- a/crates/imaging/src/ui/select/lasso.rs +++ b/crates/imaging/src/ui/select/lasso.rs @@ -1,7 +1,7 @@ //! [`LassoTool`]: the freehand Lasso with Alt-latched straight segments, and the pieces the Polygonal Lasso shares. use craft_behavior::geometry::{ConstrainStyle, DraftEvent, DraftKind, DraftPoint, DraftReach, OutlineDraft, SelectionOperation}; -use craft_behavior::{CancelReason, Cursor, PaintedCursor, PointerButton, PointerGlyph}; +use craft_behavior::{CancelReason, Cursor, CursorIcon, PaintedCursor, PointerButton, PointerGlyph}; use craft_keymap::{Key, Mods}; use craft_ui::canvas::{CanvasTool, ToolAccess, ToolAction, ToolClaims, ToolContext, ToolKey, ToolPath, ToolPointer}; use craft_ui::primitives::{Draw, PaintShape, StrokeWidth, ToolIcon}; @@ -53,7 +53,8 @@ pub(super) struct LassoCursor<'a> { /// The arrow with its tip on the point the outline starts from, the lasso icon below and right of it and the /// operation's badge beside the icon: the latched one while an outline is open, else the live modifiers'; -/// Cmd is the Move tool's, so it shows none. Over the selection, the cursors of [`cursor_over`]. +/// Cmd is the Move tool's, so it shows none. Under the canvas's precise cursor, the crosshair with the badge. Over the +/// selection, the cursors of [`cursor_over`]. pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &ToolContext<'_>) -> Cursor { let LassoCursor { icon, draft, operation, bar, inside, rule } = shown; if !draft.is_open() @@ -69,6 +70,11 @@ pub(super) fn cursor(shown: &LassoCursor<'_>, probe: &dyn SelectionProbe, cx: &T } else { SelectionOperation::resolve(*bar, cx.mods, probe.has_selection()).badge() }; + // Under the canvas's precise cursor (Other Cursors > Precise, swapped by Caps Lock) the pointer is the crosshair, + // its centre the point the outline takes, with the operation's badge. + if cx.precise() { + return badge.map_or(CursorIcon::Crosshair.into(), |badge| PaintedCursor::badged(CursorIcon::Crosshair, badge).into()); + } PaintedCursor::pointer_tool_badged(PointerGlyph::Arrow, icon.icon(), badge).into() } diff --git a/crates/imaging/tests/it/select.rs b/crates/imaging/tests/it/select.rs index c9ef917fac..1a8c4d0961 100644 --- a/crates/imaging/tests/it/select.rs +++ b/crates/imaging/tests/it/select.rs @@ -951,6 +951,37 @@ fn the_magnetic_lasso_shows_the_width_circle_under_the_precise_cursor() { } } +// The Lasso and the Polygonal Lasso follow the canvas's precise cursor too (Other Cursors > Precise, swapped by Caps +// Lock): the crosshair, its centre the point the outline takes, while it is on; the arrow with the lasso icon otherwise. +// Before, Caps Lock left the arrow and icon in place. +#[trial] +fn the_lassos_show_the_crosshair_under_the_precise_cursor() { + use craft_behavior::{Cursor, CursorIcon, PaintedCursor, PointerGlyph}; + fn check(mut rig: Rig, what: &str) + where + for<'a> SelectToolPass<'a, T>: CanvasTool, + { + let over = rig.canvas().center(); + let ctx = rig.fixture().ctx().clone(); + rig.fixture().frame(vec![pointer::moved(over)]); + for caps_lock in [false, true, false] { + craft_ui::runtime::windows::WindowHost::of(&ctx).set_caps_lock(Some(caps_lock)); + rig.fixture().frame(Vec::new()); + rig.fixture().frame(Vec::new()); + let cursor = craft_ui::runtime::cursor::current(&ctx); + let crosshair = matches!( + cursor, + Some(Cursor::System(CursorIcon::Crosshair) | Cursor::Painted(PaintedCursor::Badged { base: CursorIcon::Crosshair, .. })) + ); + let arrow = matches!(cursor, Some(Cursor::Painted(PaintedCursor::PointerTool { pointer: PointerGlyph::Arrow, .. }))); + assert_eq!(crosshair, caps_lock, "{what}, Caps Lock {caps_lock}: {cursor:?}"); + assert_eq!(arrow, !caps_lock, "{what}, Caps Lock {caps_lock}: {cursor:?}"); + } + } + check(rig("Lasso", LassoTool::new(), Fake::empty()), "Lasso"); + check(rig("Polygonal Lasso", PolygonLassoTool::new(), Fake::empty()), "Polygonal Lasso"); +} + /// The cursor `rig` shows over the middle of its canvas with `mods` held. fn lasso_cursor(rig: &mut Rig, mods: Modifiers) -> Option where 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..9b4ade84ac 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); } @@ -682,21 +695,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 only a plain paragraph is read as a further one. 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 076f9dcdd3..59be1be9f9 100644 --- a/crates/markdown/src/export.rs +++ b/crates/markdown/src/export.rs @@ -335,6 +335,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 { @@ -365,6 +369,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; @@ -387,6 +393,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 { @@ -408,6 +418,22 @@ 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 = 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()); + } 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..309fda157f 100644 --- a/crates/markdown/src/tests.rs +++ b/crates/markdown/src/tests.rs @@ -793,3 +793,90 @@ 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(" 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(") -> std::fmt::Result { + match self { + Error::NotBink => f.write_str("not a Bink file"), + Error::Bink2 => f.write_str("Bink 2 files are not supported"), + Error::Io(e) => write!(f, "I/O error: {e}"), + Error::Invalid(e) => write!(f, "invalid Bink file: {e}"), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Io(e) => Some(e), + _ => None, + } + } +} + +impl From for Error { + fn from(e: io::Error) -> Self { + Error::Io(e) + } +} + +/// Result alias for this module. +pub type Result = std::result::Result; + +fn invalid(msg: impl Into) -> Result { + Err(Error::Invalid(msg.into())) +} + +/// Whether `head` starts like a Bink 1 file: `BIK` and a lower-case revision letter. +pub fn sniff(head: &[u8]) -> bool { + head.get(..3) == Some(b"BIK") && head.get(3).is_some_and(u8::is_ascii_lowercase) +} + +/// The main header. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Header { + /// The four signature bytes: `BIK` and the codec revision letter (`b`, `d`, `f`, `g`, `h`, `i`). + pub signature: [u8; 4], + /// The frame count the header declares. + pub frames: u32, + /// The size in bytes of the largest frame, as declared. + pub largest_frame: u32, + /// Picture width in pixels. + pub width: u32, + /// Picture height in pixels. + pub height: u32, + /// Frame rate numerator. + pub fps_num: u32, + /// Frame rate denominator. + pub fps_den: u32, + /// The video flags as stored; see [`Header::has_alpha`], [`Header::grayscale`] and + /// [`Header::scaling`]. + pub video_flags: u32, +} + +impl Header { + /// The codec revision letter (`b'i'` for `BIKi`). + pub fn revision(&self) -> u8 { + self.signature[3] + } + + /// Whether frames carry an alpha plane (flag bit 20). + pub fn has_alpha(&self) -> bool { + self.video_flags & (1 << 20) != 0 + } + + /// Whether the video is grayscale (flag bit 17). + pub fn grayscale(&self) -> bool { + self.video_flags & (1 << 17) != 0 + } + + /// The display scaling mode (flag bits 28 to 31): 1 height doubled, 2 height interlaced, + /// 3 width doubled, 4 width and height doubled, 5 width and height interlaced. + pub fn scaling(&self) -> u8 { + (self.video_flags >> 28) as u8 + } +} + +/// An audio track header. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AudioTrack { + /// Samples per second. + pub sample_rate: u16, + /// The track flags as stored; see [`AudioTrack::stereo`] and [`AudioTrack::dct`]. + pub flags: u16, + /// The track ID. + pub id: u32, +} + +impl AudioTrack { + /// Whether the track is stereo (flag bit 13). + pub fn stereo(&self) -> bool { + self.flags & (1 << 13) != 0 + } + + /// Whether the track uses the DCT form of Bink Audio (flag bit 12); otherwise the RDFT form. + pub fn dct(&self) -> bool { + self.flags & (1 << 12) != 0 + } + + /// Codec parameters for a decoder: the codec, sample rate and channel count. + pub fn codec_params(&self) -> crate::CodecParams { + let id = if self.dct() { crate::CodecId::BinkAudioDct } else { crate::CodecId::BinkAudioRdft }; + crate::CodecParams::new(id).with_sample_rate(u32::from(self.sample_rate)).with_channels(if self.stereo() { 2 } else { 1 }) + } +} + +/// Where one frame lies in the file. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Frame { + /// Absolute file offset of the frame. + pub offset: u64, + /// Size of the frame in bytes: its audio packets and its video packet. + pub size: u32, + /// Whether the index marks the frame as a key frame. + pub key: bool, +} + +/// An opened Bink file: header, audio tracks and frame table. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BinkFile { + /// The main header. + pub header: Header, + /// The audio tracks, in file order. + pub audio: Vec, + /// The frames that lie completely inside the file, in order. Shorter than + /// [`Header::frames`] when the file is truncated. + pub frames: Vec, +} + +/// One audio track's packet in a frame. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AudioPacket<'a> { + /// The count stored before the packet: the size in bytes of the PCM the packet decodes to. + pub decoded_len: u32, + /// The Bink Audio packet. + pub data: &'a [u8], +} + +/// The packets of one frame, borrowed from the frame's bytes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FramePackets<'a> { + /// One entry per audio track; `None` when the track has no audio in this frame. + pub audio: Vec>>, + /// The Bink Video packet. + pub video: &'a [u8], +} + +fn le32(b: &[u8], at: usize) -> u32 { + match b.get(at..at + 4) { + Some(&[a, b, c, d]) => u32::from_le_bytes([a, b, c, d]), + _ => 0, + } +} + +fn le16(b: &[u8], at: usize) -> u16 { + match b.get(at..at + 2) { + Some(&[a, b]) => u16::from_le_bytes([a, b]), + _ => 0, + } +} + +/// Reads the headers and the frame index of a Bink 1 file. +pub fn open(src: &S) -> Result { + let len = src.len(); + let mut head = [0u8; HEADER_LEN]; + if len < HEADER_LEN as u64 { + // long enough to tell the signature apart, too short to be a file + let mut sig = [0u8; 4]; + if len >= 4 { + src.read_at(0, &mut sig)?; + } + return match sig { + _ if sig.starts_with(b"KB2") => Err(Error::Bink2), + _ if sniff(&sig) => invalid("file shorter than the header"), + _ => Err(Error::NotBink), + }; + } + src.read_at(0, &mut head)?; + if head.starts_with(b"KB2") { + return Err(Error::Bink2); + } + if !sniff(&head) { + return Err(Error::NotBink); + } + let header = Header { + signature: [head[0], head[1], head[2], head[3]], + frames: le32(&head, 8), + largest_frame: le32(&head, 12), + width: le32(&head, 20), + height: le32(&head, 24), + fps_num: le32(&head, 28), + fps_den: le32(&head, 32), + video_flags: le32(&head, 36), + }; + let tracks = le32(&head, 40); + if header.width == 0 || header.height == 0 || header.width > MAX_DIMENSION || header.height > MAX_DIMENSION { + return invalid(format!("picture size {}x{}", header.width, header.height)); + } + if header.fps_num == 0 || header.fps_den == 0 { + return invalid("zero frame rate"); + } + if tracks > MAX_AUDIO_TRACKS { + return invalid(format!("{tracks} audio tracks")); + } + let tracks = tracks as usize; + + // three tables of 4 bytes per track: (unknown, channels), (sample rate, flags), ID + let mut audio_head = vec![0u8; tracks * 12]; + src.read_at(HEADER_LEN as u64, &mut audio_head).map_err(|_| Error::Invalid("audio track headers cut off".into()))?; + let audio = (0..tracks) + .map(|t| AudioTrack { + sample_rate: le16(&audio_head, tracks * 4 + t * 4), + flags: le16(&audio_head, tracks * 4 + t * 4 + 2), + id: le32(&audio_head, tracks * 8 + t * 4), + }) + .collect(); + + // the index: one absolute offset per frame and one for the end of the last frame + let index_at = (HEADER_LEN + tracks * 12) as u64; + // `len` was taken before the reads above: a source that reports less than it serves (a file + // still being written) must not make this wrap + let Some(room) = len.checked_sub(index_at) else { return invalid("audio track headers cut off") }; + if header.frames == 0 { + return invalid("no frames"); + } + // as many entries as the file declares and could hold + let mut left = (u64::from(header.frames) + 1).min(room / 4); + let data_start = index_at + (u64::from(header.frames) + 1) * 4; + // The index is read in pieces and each entry checked as it arrives, so a hostile frame + // count costs one piece, not the index it claims. The table grows as entries prove valid. + let mut frames = Vec::new(); + let mut at = index_at; + let mut previous: Option = None; + let mut piece = Vec::new(); + 'index: while left > 0 { + let entries = left.min(INDEX_PIECE_ENTRIES) as usize; + piece.resize(entries * 4, 0); + src.read_at(at, &mut piece)?; + for bytes in piece.as_chunks::<4>().0 { + let entry = u32::from_le_bytes(*bytes); + if let Some(start) = previous { + let (offset, end) = (u64::from(start & !1), u64::from(entry & !1)); + if end > len { + break 'index; // truncated file: keep the frames that are whole + } + if offset < data_start || end < offset { + return invalid(format!("frame {} at {offset}..{end}", frames.len())); + } + frames.push(Frame { offset, size: (end - offset) as u32, key: start & 1 != 0 }); + } + previous = Some(entry); + } + at += (entries * 4) as u64; + left -= entries as u64; + } + Ok(BinkFile { header, audio, frames }) +} + +impl BinkFile { + /// Codec parameters of the video: [`CodecId::BinkVideo`], the picture size, the signature as + /// `tag` (its fourth byte is the codec revision) and the video flags, little-endian, as + /// `extradata`. + /// + /// [`CodecId::BinkVideo`]: crate::CodecId::BinkVideo + pub fn video_params(&self) -> crate::CodecParams { + crate::CodecParams::new(crate::CodecId::BinkVideo) + .with_tag(self.header.signature) + .with_size(self.header.width, self.header.height) + .with_extradata(self.header.video_flags.to_le_bytes()) + } + + /// Reads frame `i`: its audio packets and its video packet, as stored. [`split_frame`] + /// separates them. + pub fn read_frame(&self, src: &S, i: usize) -> Result> { + let Some(f) = self.frames.get(i) else { return invalid(format!("no frame {i}")) }; + // `open` checked the frame against the length the source had then + if f.offset.checked_add(u64::from(f.size)).is_none_or(|e| e > src.len()) { + return invalid(format!("frame {i} past the end of the file")); + } + // A frame can be up to 4 GiB. Reserving it can fail, and on a 32-bit target a size past + // `isize::MAX` cannot be asked for at all: that is an error, not a panic. + let mut data = Vec::new(); + let reserved = usize::try_from(f.size).ok().and_then(|size| data.try_reserve_exact(size).ok().map(|()| size)); + let Some(size) = reserved else { return invalid(format!("frame {i} of {} bytes is too large to read", f.size)) }; + data.resize(size, 0); + src.read_at(f.offset, &mut data)?; + Ok(data) + } + + /// Separates the packets of a frame read with [`BinkFile::read_frame`]. + pub fn split_frame<'a>(&self, frame: &'a [u8]) -> Result> { + split_frame(frame, self.audio.len()) + } +} + +/// Separates the packets of a frame of a file with `tracks` audio tracks. +/// +/// Each track has a 32-bit length; when it is not zero, a 32-bit decoded size and the packet +/// follow, and the length covers both. The video packet is what remains. +pub fn split_frame(frame: &[u8], tracks: usize) -> Result> { + let mut rest = frame; + // a track takes at least its 4-byte length, which bounds the table + let mut audio = Vec::with_capacity(tracks.min(frame.len() / 4)); + for t in 0..tracks { + let Some((len, after)) = rest.split_first_chunk::<4>() else { return invalid(format!("audio track {t}: length cut off")) }; + let len = u32::from_le_bytes(*len) as usize; + if len == 0 { + audio.push(None); + rest = after; + continue; + } + let Some((packet, after)) = after.split_at_checked(len) else { return invalid(format!("audio track {t}: packet of {len} bytes cut off")) }; + let Some((decoded_len, data)) = packet.split_first_chunk::<4>() else { return invalid(format!("audio track {t}: packet of {len} bytes")) }; + audio.push(Some(AudioPacket { decoded_len: u32::from_le_bytes(*decoded_len), data })); + rest = after; + } + Ok(FramePackets { audio, video: rest }) +} diff --git a/crates/media/src/bink/tests.rs b/crates/media/src/bink/tests.rs new file mode 100644 index 0000000000..9280c1a401 --- /dev/null +++ b/crates/media/src/bink/tests.rs @@ -0,0 +1,317 @@ +use super::*; + +/// One frame of a hand-built file: its audio packets (decoded size and data) and video packet. +struct TestFrame { + key: bool, + audio: Vec)>>, + video: Vec, +} + +/// Builds a Bink file with one `(sample rate, flags)` pair per audio track. +fn bink(signature: &[u8; 4], tracks: &[(u16, u16)], frames: &[TestFrame]) -> Vec { + let bodies: Vec> = frames + .iter() + .map(|f| { + let mut b = Vec::new(); + for a in &f.audio { + match a { + None => b.extend_from_slice(&0u32.to_le_bytes()), + Some((decoded, data)) => { + b.extend_from_slice(&(data.len() as u32 + 4).to_le_bytes()); + b.extend_from_slice(&decoded.to_le_bytes()); + b.extend_from_slice(data); + } + } + } + b.extend_from_slice(&f.video); + // bit 0 of an index entry is the key frame flag, so a frame starts at an even offset + assert_eq!(b.len() % 4, 0, "frames are built in whole 32-bit words"); + b + }) + .collect(); + let data_start = HEADER_LEN + tracks.len() * 12 + (frames.len() + 1) * 4; + let total = data_start + bodies.iter().map(Vec::len).sum::(); + let largest = bodies.iter().map(Vec::len).max().unwrap_or(0); + let mut d = signature.to_vec(); + for v in [total - 8, frames.len(), largest, frames.len(), 320, 240, 2997, 100, 1 << 20, tracks.len()] { + d.extend_from_slice(&(v as u32).to_le_bytes()); + } + for &(_, flags) in tracks { + d.extend_from_slice(&0x0e00u16.to_le_bytes()); + d.extend_from_slice(&(if flags & (1 << 13) != 0 { 2u16 } else { 1 }).to_le_bytes()); + } + for &(rate, flags) in tracks { + d.extend_from_slice(&rate.to_le_bytes()); + d.extend_from_slice(&flags.to_le_bytes()); + } + for t in 0..tracks.len() { + d.extend_from_slice(&(t as u32 + 7).to_le_bytes()); + } + let mut at = data_start; + for (f, b) in frames.iter().zip(&bodies) { + d.extend_from_slice(&(at as u32 | u32::from(f.key)).to_le_bytes()); + at += b.len(); + } + d.extend_from_slice(&(at as u32).to_le_bytes()); + for b in &bodies { + d.extend_from_slice(b); + } + assert_eq!(d.len(), total); + d +} + +fn sample() -> Vec { + bink( + b"BIKi", + &[(22050, 0x7000), (44100, 0x4000)], + &[ + TestFrame { key: true, audio: vec![Some((1024, vec![1, 2, 3, 4])), Some((512, vec![9; 8]))], video: vec![0xAA; 16] }, + TestFrame { key: false, audio: vec![None, Some((512, vec![8; 4]))], video: vec![0xBB; 12] }, + TestFrame { key: false, audio: vec![None, None], video: vec![0xCC; 20] }, + ], + ) +} + +#[test] +fn reads_header_tracks_and_frames() { + let d = sample(); + assert!(sniff(&d)); + let f = open(&d).unwrap(); + assert_eq!(f.header.signature, *b"BIKi"); + assert_eq!(f.header.revision(), b'i'); + assert_eq!((f.header.frames, f.header.width, f.header.height), (3, 320, 240)); + assert_eq!((f.header.fps_num, f.header.fps_den), (2997, 100)); + assert!(f.header.has_alpha()); + assert!(!f.header.grayscale()); + assert_eq!(f.header.scaling(), 0); + assert_eq!(f.header.largest_frame, 8 + 4 + 8 + 8 + 16); + + assert_eq!(f.audio.len(), 2); + assert_eq!((f.audio[0].sample_rate, f.audio[0].stereo(), f.audio[0].dct(), f.audio[0].id), (22050, true, true, 7)); + assert_eq!((f.audio[1].sample_rate, f.audio[1].stereo(), f.audio[1].dct(), f.audio[1].id), (44100, false, false, 8)); + let a = f.audio[0].codec_params(); + assert_eq!((a.codec, a.sample_rate, a.channels), (crate::CodecId::BinkAudioDct, Some(22050), Some(2))); + let a = f.audio[1].codec_params(); + assert_eq!((a.codec, a.sample_rate, a.channels), (crate::CodecId::BinkAudioRdft, Some(44100), Some(1))); + + let v = f.video_params(); + assert_eq!((v.codec, v.tag, v.width, v.height), (crate::CodecId::BinkVideo, Some(*b"BIKi"), Some(320), Some(240))); + assert_eq!(v.extradata, (1u32 << 20).to_le_bytes()); + + assert_eq!(f.frames.iter().map(|f| f.key).collect::>(), [true, false, false]); + assert_eq!(f.frames.iter().map(|f| f.size).collect::>(), [44, 28, 28]); + assert_eq!(f.frames.last().map(|f| f.offset + u64::from(f.size)), Some(d.len() as u64)); +} + +#[test] +fn splits_a_frame_into_its_packets() { + let d = sample(); + let f = open(&d).unwrap(); + let frame = f.read_frame(&d, 0).unwrap(); + let p = f.split_frame(&frame).unwrap(); + assert_eq!(p.audio[0], Some(AudioPacket { decoded_len: 1024, data: &[1, 2, 3, 4] })); + assert_eq!(p.audio[1], Some(AudioPacket { decoded_len: 512, data: &[9; 8] })); + assert_eq!(p.video, [0xAA; 16]); + + let frame = f.read_frame(&d, 1).unwrap(); + let p = f.split_frame(&frame).unwrap(); + assert_eq!(p.audio, [None, Some(AudioPacket { decoded_len: 512, data: &[8; 4] })]); + assert_eq!(p.video, [0xBB; 12]); + + let frame = f.read_frame(&d, 2).unwrap(); + let p = f.split_frame(&frame).unwrap(); + assert_eq!(p.audio, [None, None]); + assert_eq!(p.video, [0xCC; 20]); + + assert!(matches!(f.read_frame(&d, 3), Err(Error::Invalid(_)))); +} + +#[test] +fn a_file_without_audio_has_only_video_packets() { + let d = bink(b"BIKf", &[], &[TestFrame { key: true, audio: vec![], video: vec![1, 2, 3, 4] }]); + let f = open(&d).unwrap(); + assert!(f.audio.is_empty()); + let frame = f.read_frame(&d, 0).unwrap(); + assert_eq!(f.split_frame(&frame).unwrap(), FramePackets { audio: vec![], video: &[1, 2, 3, 4] }); +} + +#[test] +fn a_truncated_file_opens_with_its_whole_frames() { + let d = sample(); + let f = open(&d[..d.len() - 1]).unwrap(); + assert_eq!(f.frames.len(), 2); + assert_eq!(f.header.frames, 3); + // cut inside the index: no frame is known to be whole + let index_at = HEADER_LEN + 24; + assert_eq!(open(&d[..index_at + 6]).unwrap().frames.len(), 0); +} + +#[test] +fn refuses_what_is_not_a_bink_1_file() { + assert!(matches!(open(&b"RIFF"[..]), Err(Error::NotBink))); + assert!(matches!(open(&[][..]), Err(Error::NotBink))); + assert!(matches!(open(&[0u8; 64][..]), Err(Error::NotBink))); + assert!(matches!(open(&b"BIKi"[..]), Err(Error::Invalid(_)))); + let mut d = sample(); + d[..4].copy_from_slice(b"KB2g"); + assert!(matches!(open(&d), Err(Error::Bink2))); + assert!(!sniff(b"KB2g")); + assert!(!sniff(b"BIK")); + assert!(!sniff(b"BIK1")); +} + +#[test] +fn refuses_invalid_headers() { + let set = |at: usize, v: u32| { + let mut d = sample(); + d[at..at + 4].copy_from_slice(&v.to_le_bytes()); + open(&d).map(|_| ()) + }; + assert!(matches!(set(8, 0), Err(Error::Invalid(_))), "no frames"); + assert!(matches!(set(20, 0), Err(Error::Invalid(_))), "zero width"); + assert!(matches!(set(24, 32768), Err(Error::Invalid(_))), "height past the limit"); + assert!(matches!(set(28, 0), Err(Error::Invalid(_))), "zero frame rate"); + assert!(matches!(set(32, 0), Err(Error::Invalid(_))), "zero frame rate divider"); + assert!(matches!(set(40, 257), Err(Error::Invalid(_))), "too many audio tracks"); + assert!(matches!(set(40, 200), Err(Error::Invalid(_))), "audio headers past the end"); + // a frame that starts inside the index, and one that ends before it starts + let index_at = HEADER_LEN + 24; + assert!(matches!(set(index_at, 8), Err(Error::Invalid(_)))); + assert!(matches!(set(index_at + 4, 0), Err(Error::Invalid(_)))); +} + +#[test] +fn a_frame_count_past_what_the_file_holds_is_refused() { + let mut d = sample(); + d[8..12].copy_from_slice(&u32::MAX.to_le_bytes()); + // the index now claims to run far past the file, so every offset lies inside it + assert!(matches!(open(&d), Err(Error::Invalid(_)))); +} + +#[test] +fn split_frame_refuses_cut_off_packets() { + assert!(matches!(split_frame(&[1, 0, 0], 1), Err(Error::Invalid(_)))); + assert!(matches!(split_frame(&[9, 0, 0, 0, 1, 2], 1), Err(Error::Invalid(_)))); + // a length too short to hold the decoded size + assert!(matches!(split_frame(&[2, 0, 0, 0, 1, 2], 1), Err(Error::Invalid(_)))); + assert!(matches!(split_frame(&[], usize::MAX), Err(Error::Invalid(_)))); + assert_eq!(split_frame(&[], 0).unwrap().video, [0u8; 0]); +} + +#[test] +fn hostile_input_never_panics() { + let seeds = [sample(), bink(b"BIKf", &[], &[TestFrame { key: true, audio: vec![], video: vec![1, 2, 3, 4] }])]; + for (i, s) in seeds.iter().enumerate() { + craft_media_testkit::hostile::hammer(&format!("bink seed {i}"), s, 30_000, |d| { + if let Ok(f) = open(d) { + let n = f.frames.len(); + for k in [0, n / 2, n.saturating_sub(1), n, usize::MAX] { + if let Ok(frame) = f.read_frame(d, k) { + let _ = f.split_frame(&frame); + } + } + } + }); + } +} + +/// A source that reports a shorter length than it serves, like a file growing while it is opened. +struct Understating<'a> { + data: &'a [u8], + reported: u64, +} + +impl ByteSource for Understating<'_> { + fn len(&self) -> u64 { + self.reported + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + self.data.read_at(offset, buf) + } +} + +#[test] +fn a_source_that_understates_its_length_is_an_error_not_a_panic() { + let mut d = sample(); + d[8..12].copy_from_slice(&u32::MAX.to_le_bytes()); + // the header and both track headers can be read, but the reported length ends before them + for reported in [44, 50, 67] { + let src = Understating { data: &d, reported }; + assert!(matches!(open(&src), Err(Error::Invalid(_))), "reported length {reported}"); + } + // at the end of the track headers there is room for no index entry: no frames, no error + let src = Understating { data: &d, reported: 68 }; + assert_eq!(open(&src).unwrap().frames.len(), 0); +} + +/// A source of zeros of any length that counts the bytes read from it, with `head` at its start. +struct Zeros { + head: Vec, + len: u64, + read: std::cell::Cell, +} + +impl ByteSource for Zeros { + fn len(&self) -> u64 { + self.len + } + fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + if offset.checked_add(buf.len() as u64).is_none_or(|end| end > self.len) { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "past the end")); + } + self.read.set(self.read.get() + buf.len() as u64); + for (k, b) in buf.iter_mut().enumerate() { + *b = usize::try_from(offset).ok().and_then(|o| self.head.get(o + k)).copied().unwrap_or(0); + } + Ok(()) + } +} + +#[test] +fn a_huge_frame_count_is_refused_after_one_piece_of_the_index() { + // 2^28 frames declared in a 4 GiB source of zeros: the first entries are invalid, and the + // gigabyte of index the count claims is never read + let mut head = sample()[..HEADER_LEN].to_vec(); + head[8..12].copy_from_slice(&(1u32 << 28).to_le_bytes()); + head[40..44].copy_from_slice(&0u32.to_le_bytes()); + let src = Zeros { head, len: 4 << 30, read: std::cell::Cell::new(0) }; + assert!(matches!(open(&src), Err(Error::Invalid(_)))); + assert!(src.read.get() <= HEADER_LEN as u64 + INDEX_PIECE_ENTRIES * 4, "read {} bytes", src.read.get()); +} + +#[test] +fn an_index_longer_than_one_piece_reads_like_a_short_one() { + // enough frames of four bytes each to span three pieces of the index + let n = INDEX_PIECE_ENTRIES as usize * 2 + 100; + let frames: Vec = (0..n).map(|i| TestFrame { key: i % 1000 == 0, audio: vec![], video: (i as u32).to_le_bytes().to_vec() }).collect(); + let d = bink(b"BIKi", &[], &frames); + let f = open(&d).unwrap(); + assert_eq!(f.frames.len(), n); + for i in [0, 1, INDEX_PIECE_ENTRIES as usize - 1, INDEX_PIECE_ENTRIES as usize, INDEX_PIECE_ENTRIES as usize + 1, n - 1] { + assert_eq!(f.read_frame(&d, i).unwrap(), (i as u32).to_le_bytes(), "frame {i}"); + assert_eq!(f.frames[i].key, i % 1000 == 0, "frame {i}"); + } + // cut inside the third piece: the frames before the cut are kept + let cut = f.frames[n - 50].offset as usize; + assert_eq!(open(&d[..cut]).unwrap().frames.len(), n - 50); + + // an invalid entry at the start of the second piece is named by its frame + let piece = INDEX_PIECE_ENTRIES as usize; + let entry_at = |k: usize| HEADER_LEN + 4 * k; + let mut bad = d.clone(); + bad[entry_at(piece)..entry_at(piece) + 4].copy_from_slice(&0u32.to_le_bytes()); + match open(&bad) { + Err(Error::Invalid(message)) => assert!(message.starts_with(&format!("frame {} at ", piece - 1)), "{message}"), + other => panic!("{other:?}"), + } + // an entry past the end of the file ends the table there, whatever follows it + let mut cut_off = d.clone(); + cut_off[entry_at(10)..entry_at(10) + 4].copy_from_slice(&0xffff_fff0u32.to_le_bytes()); + assert_eq!(open(&cut_off).unwrap().frames.len(), 9); +} + +#[test] +fn a_short_bink_2_file_is_named_as_such() { + assert!(matches!(open(&b"KB2g\0\0\0\0"[..]), Err(Error::Bink2))); + assert!(matches!(open(&b"KB2"[..]), Err(Error::NotBink))); +} diff --git a/crates/media/src/id.rs b/crates/media/src/id.rs index e93b7e3272..f7dee2bec2 100644 --- a/crates/media/src/id.rs +++ b/crates/media/src/id.rs @@ -46,6 +46,8 @@ pub enum Container { MpegPs, /// Sierra VMD (Video and Music Data). Vmd, + /// Bink (BIK). + Bink, } impl Container { @@ -69,6 +71,7 @@ impl Container { Container::MpegTs => "MPEG-TS", Container::MpegPs => "MPEG-PS", Container::Vmd => "VMD", + Container::Bink => "Bink", } } } @@ -111,6 +114,10 @@ pub enum CodecId { Vorbis, /// Speex. Speex, + /// Bink Audio, RDFT form. + BinkAudioRdft, + /// Bink Audio, DCT form. + BinkAudioDct, /// H.264 / AVC. H264, /// H.265 / HEVC. @@ -141,6 +148,8 @@ pub enum CodecId { VmdVideo, /// Sierra VMD audio (8-bit PCM or 16-bit DPCM). VmdAudio, + /// Bink Video (Bink 1). + BinkVideo, /// A codec this crate has no identifier for. Unknown, } @@ -165,6 +174,8 @@ impl CodecId { CodecId::Opus => "Opus", CodecId::Vorbis => "Vorbis", CodecId::Speex => "Speex", + CodecId::BinkAudioRdft => "Bink Audio (RDFT)", + CodecId::BinkAudioDct => "Bink Audio (DCT)", CodecId::H264 => "H.264", CodecId::Hevc => "HEVC", CodecId::Av1 => "AV1", @@ -180,6 +191,7 @@ impl CodecId { CodecId::Apv => "APV", CodecId::VmdVideo => "VMD video", CodecId::VmdAudio => "VMD audio", + CodecId::BinkVideo => "Bink Video", CodecId::Unknown => "unknown", } } @@ -205,6 +217,8 @@ impl CodecId { | CodecId::Vorbis | CodecId::Speex | CodecId::VmdAudio + | CodecId::BinkAudioRdft + | CodecId::BinkAudioDct ) } @@ -226,6 +240,7 @@ impl CodecId { | CodecId::Dnxhd | CodecId::Apv | CodecId::VmdVideo + | CodecId::BinkVideo ) } } diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 1d76c6bd68..80345b7ae2 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -9,6 +9,7 @@ //! - `matroska` (feature `matroska`): a clean-room Matroska (MKV) and WebM demuxer and muxer. //! - `ogg` (feature `ogg`): a clean-room Ogg demuxer with Ogg Opus and Ogg Vorbis stream mapping. //! - `avi` (feature `avi`): a clean-room AVI (RIFF) and OpenDML demuxer. +//! - `bink` (feature `bink`): a clean-room Bink 1 (BIK) demuxer. //! - `mxf` (feature `mxf`, enables `chrono`): a clean-room MXF demuxer and writer (OP1a, OP-Atom). //! - `mpegts` (feature `mpegts`): a clean-room MPEG-2 Systems demuxer (transport streams and //! program streams) and transport stream writer. @@ -20,11 +21,13 @@ //! - `FileReader` (native): a pooled file `ByteSource` so many clips can be open without holding a //! descriptor each. //! -//! `bitstream` and `isobmff` are on by default; `matroska`, `ogg`, `avi`, `mxf`, `mpegts` and `vmd` are opt-in. A crate that needs +//! `bitstream` and `isobmff` are on by default; `matroska`, `ogg`, `avi`, `bink`, `mxf`, `mpegts` and `vmd` are opt-in. A crate that needs //! only bit I/O uses `default-features = false, features = ["bitstream"]`. #[cfg(feature = "avi")] pub mod avi; +#[cfg(feature = "bink")] +pub mod bink; #[cfg(feature = "bitstream")] pub mod bitstream; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/media/tests/main.rs b/crates/media/tests/main.rs index 599b71b306..eed5978134 100644 --- a/crates/media/tests/main.rs +++ b/crates/media/tests/main.rs @@ -16,6 +16,8 @@ mod mpegts_mux_readback; mod oracle_avi; #[cfg(feature = "avi")] mod oracle_avi_mux; +#[cfg(feature = "bink")] +mod oracle_bink; #[cfg(feature = "isobmff")] mod oracle_demux; #[cfg(feature = "matroska")] diff --git a/crates/media/tests/oracle_bink.rs b/crates/media/tests/oracle_bink.rs new file mode 100644 index 0000000000..d2aaffcbee --- /dev/null +++ b/crates/media/tests/oracle_bink.rs @@ -0,0 +1,72 @@ +//! Real Bink files against ffprobe: every frame is read, and the stream, size and key flag of +//! each packet match the packets ffprobe reads. Packet contents are not compared. +//! +//! No tool here can write a Bink file, and existing files are not ours to commit, so the test +//! reads `*.bik` files from the directory named by `CRAFT_BINK_SAMPLES` (searched +//! recursively) and is skipped when that is not set. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use craft_media::bink::open; + +fn samples(dir: &Path, out: &mut Vec, depth: usize) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() && depth < 8 { + samples(&p, out, depth + 1); + } else if p.extension().is_some_and(|x| x.eq_ignore_ascii_case("bik")) { + out.push(p); + } + } +} + +/// `(stream index, size, key)` of every packet ffprobe reads, in file order. +fn ffprobe_packets(ffprobe: &Path, path: &Path) -> Vec<(usize, usize, bool)> { + let out = + Command::new(ffprobe).args(["-v", "error", "-show_entries", "packet=stream_index,size,flags", "-of", "csv=p=0"]).arg(path).output().unwrap(); + String::from_utf8_lossy(&out.stdout) + .lines() + .filter_map(|l| { + let mut f = l.trim().split(','); + Some((f.next()?.parse().ok()?, f.next()?.parse().ok()?, f.next()?.starts_with('K'))) + }) + .collect() +} + +#[test] +fn real_files_match_ffprobe() { + let Some(dir) = std::env::var_os("CRAFT_BINK_SAMPLES").filter(|d| !d.is_empty()) else { + return craft_media_testkit::skip_test("bink oracle", "CRAFT_BINK_SAMPLES is not set"); + }; + let Some(ffprobe) = craft_media_testkit::ffprobe() else { return }; + let mut files = Vec::new(); + samples(Path::new(&dir), &mut files, 0); + files.sort(); + assert!(!files.is_empty(), "no .bik files under {}", Path::new(&dir).display()); + for path in files { + let file = std::fs::File::open(&path).unwrap(); + let bink = open(&file).unwrap(); + assert_eq!(bink.frames.len(), bink.header.frames as usize, "{}", path.display()); + + // ffprobe numbers the video stream 0 and audio track `t` 1 + t, and its audio packets + // start at the decoded size + let mut ours = Vec::new(); + for (i, f) in bink.frames.iter().enumerate() { + let frame = bink.read_frame(&file, i).unwrap(); + let packets = bink.split_frame(&frame).unwrap(); + for (t, a) in packets.audio.iter().enumerate() { + if let Some(a) = a { + ours.push((1 + t, a.data.len() + 4, true)); + } + } + ours.push((0, packets.video.len(), f.key)); + } + let theirs = ffprobe_packets(&ffprobe, &path); + assert_eq!(ours.len(), theirs.len(), "{}: packet count", path.display()); + if let Some(at) = ours.iter().zip(&theirs).position(|(a, b)| a != b) { + panic!("{}: packet {at} is {:?}, ffprobe has {:?}", path.display(), ours[at], theirs[at]); + } + } +} 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..e3b8ea04a9 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). @@ -43,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) } @@ -65,6 +79,7 @@ impl<'a> Be<'a> { self.pos = end; Some(()) } else { + self.eof = true; None } } @@ -624,6 +639,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 +677,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 +1465,41 @@ 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 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() { + 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() { + if r.eof { + reason = Some(TruncationReason::PrematureEof); + } else { + halted_for_record_error = true; + } + break; + } + if r.eof { + reason = Some(TruncationReason::PrematureEof); break; } } - if stopped_early { + if !reached_end && !halted_for_record_error && reason.is_none() { + reason = Some(TruncationReason::OpcodeLimitExceeded); + } + if !reached_end { q.truncated = true; + q.truncation_reason = reason; } q.flush(); let pic = @@ -1473,6 +1507,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 405d0d32d2..47b82428c5 100644 --- a/crates/metafile/src/tests/limits.rs +++ b/crates/metafile/src/tests/limits.rs @@ -194,3 +194,79 @@ 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)); +} + +#[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); +} + +#[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)); +} 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] diff --git a/crates/odf/Cargo.toml b/crates/odf/Cargo.toml index 8b5702c464..39d949c8dc 100644 --- a/crates/odf/Cargo.toml +++ b/crates/odf/Cargo.toml @@ -63,6 +63,9 @@ optional = true [dev-dependencies] # The tests build archives, hostile ones included, by hand. zip = { version = "9", default-features = false, features = ["deflate-flate2"] } +# The `text` tests export ODT input to HTML and Markdown, to check list items stay whole there. +craft-html = { workspace = true, features = ["flow"] } +craft-markdown = { workspace = true } [target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] # The browser clock for tracked-change dates (`text` feature; `SystemTime::now()` panics there). diff --git a/crates/odf/src/text/body.rs b/crates/odf/src/text/body.rs index 565c0f7642..639e213765 100644 --- a/crates/odf/src/text/body.rs +++ b/crates/odf/src/text/body.rs @@ -219,6 +219,16 @@ pub(super) struct Body<'a> { 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(); @@ -417,6 +427,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 } @@ -1057,21 +1075,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) { @@ -1752,6 +1764,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(); @@ -1761,8 +1774,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/import.rs b/crates/odf/src/text/import.rs index 8154875c76..a719f78a94 100644 --- a/crates/odf/src/text/import.rs +++ b/crates/odf/src/text/import.rs @@ -1166,11 +1166,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 da49b30541..78237b7439 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() }; @@ -313,14 +314,198 @@ pub(super) 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>, + read: &std::collections::HashMap, +) -> String { + 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, 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()) + }; + 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 +/// 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( + 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)); + } + // 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 mut out = BTreeMap::new(); + 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) { + 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. + "style:name" => Some(name.clone()), + _ => theirs.get(&(family, v.to_string())).cloned(), + }) + }); + out.insert(key.clone(), def); + } + 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 +/// 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(|| name.to_string()); + } + } + 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 @@ -328,8 +513,9 @@ pub(super) fn with_common_as_read(styles: &str, defs: &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 98a1a8cb06..5c62886ae9 100644 --- a/crates/odf/src/text/package.rs +++ b/crates/odf/src/text/package.rs @@ -818,17 +818,53 @@ 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 (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); + (changed, rewritten) } /// The package files the file's own definitions refer to, and those the markup written as read @@ -846,20 +882,24 @@ 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) - }; + // 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; } @@ -1068,6 +1108,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)); @@ -1190,6 +1232,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.stacking = w.stacking; hw.accents = accents; hw.variables.clone_from(&w.variables); diff --git a/crates/odf/src/text/tests_more/kept.rs b/crates/odf/src/text/tests_more/kept.rs index 2efbad9977..1bcf22b0ed 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#""## + ); + 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 { + 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 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); +} + +/// 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)); + } +} + +/// 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)); +} + +/// 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] +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] +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] +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: +/// editing the shared id rewrites only the definitions that were read into it. +#[test] +fn many_styles_sharing_an_id_keep_unedited_definitions() { + 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 saved = styles_of(&export(&d).unwrap()); + 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 @@ -480,3 +940,58 @@ 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}"); +} + +#[test] +fn rewriting_shared_style_names_scales_linearly_in_name_lookups() { + use std::{ + cell::Cell, + collections::{BTreeMap, BTreeSet}, + sync::Arc, + }; + let lookups = |n: usize| { + let defs: BTreeMap> = (0..n).map(|i| (format!("common:Name{i}"), Arc::from(""))).collect(); + let ids = defs.keys().map(|key| (key.clone(), "Shared".to_string())).collect(); + let changed = BTreeSet::from(["common:Shared".to_string()]); + let calls = Cell::new(0usize); + let ours = |id: &str| { + calls.set(calls.get() + 1); + id.to_string() + }; + let rewritten = super::super::kept::rewritten_defs( + r#""#, + &defs, + &changed, + &ids, + &ours, + ); + assert_eq!(rewritten.len(), n); + calls.get() + }; + let small = lookups(16); + let large = lookups(128); + assert!(small > 0); + assert!(large <= 8 * small, "name lookups grew faster than the input: {small} -> {large}"); +} diff --git a/crates/odf/src/text/tests_more/lists.rs b/crates/odf/src/text/tests_more/lists.rs index 079413aa82..115914ea02 100644 --- a/crates/odf/src/text/tests_more/lists.rs +++ b/crates/odf/src/text/tests_more/lists.rs @@ -166,3 +166,316 @@ 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)); + 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:?}"); + } + // 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}" + ); +} + +/// A list item's further paragraph opening or closing a section kept as read ends the list there, +/// as an item doing so does: the section opens before it, or closes after it, not somewhere past. +#[test] +fn a_further_paragraph_opening_or_closing_a_section_ends_the_list_there() { + let styles = format!( + r#""# + ); + 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}"); +} + +/// 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}"); +} + +#[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()); + } +} + +/// 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/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/odf/src/text/writer.rs b/crates/odf/src/text/writer.rs index dc42829456..adf62a3ed5 100644 --- a/crates/odf/src/text/writer.rs +++ b/crates/odf/src/text/writer.rs @@ -97,20 +97,35 @@ 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; while let Some(FBlock::Para(q)) = blocks.get(i) { - let Some(li) = q.list else { break }; + 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) { + // (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; + } + continue; + } + _ => break, + } + }; let l = li.level.min(8) as usize; - 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); @@ -128,7 +143,40 @@ 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)) +} + +/// What is open in a list being written. +#[derive(Clone, Copy, PartialEq)] +enum ListPart { + None, + Item, + Header, +} + +/// 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(""); + } } /// The `xml:id` of the list markup `xml` (kept as read) begins with, if it does. @@ -239,6 +287,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. @@ -304,7 +355,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")).map_or(name, |n| x(n))); } if props.is_empty() { return None; @@ -329,7 +381,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).map_or(name, |n| x(n)) } (Kind::Normal, Some(n), None) => n.to_string(), _ => parent_style(p.kind).to_string(), @@ -799,7 +852,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(" { + 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) { @@ -938,23 +992,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(); + // 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 }; - 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(""); - } + 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()); @@ -981,23 +1027,19 @@ impl Writer { } else { out.push_str(""); } - stack.push(false); + stack.push(ListPart::None); } - if let Some(top) = stack.last_mut() { - if *top { - out.push_str(""); - } - *top = true; + // 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); } - 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(""); - } + close_lists(out, &mut stack, 0); self.close_wrap(closes.as_ref(), 0, out); out.push('\n'); } 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 05db88fbef..d74de97a99 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 "; @@ -260,26 +260,62 @@ 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] diff --git a/crates/pdf/tests/interpretation.rs b/crates/pdf/tests/interpretation.rs index cd3b7185ce..612559266b 100644 --- a/crates/pdf/tests/interpretation.rs +++ b/crates/pdf/tests/interpretation.rs @@ -3,6 +3,11 @@ #![cfg(feature = "read")] #![allow(clippy::unwrap_used, clippy::panic)] +// A CID that is its character's vertical form draws a substitute's vertical glyph. +#[cfg(feature = "interpret")] +#[path = "interpretation/vertical_forms.rs"] +mod vertical_forms; + #[cfg(feature = "interpret")] mod device { use craft_pdf::interpret::{ diff --git a/crates/pdf/tests/interpretation/vertical_forms.rs b/crates/pdf/tests/interpretation/vertical_forms.rs new file mode 100644 index 0000000000..dd6511f6af --- /dev/null +++ b/crates/pdf/tests/interpretation/vertical_forms.rs @@ -0,0 +1,322 @@ +//! A CID that is its character's vertical form draws a substitute's vertical glyph (vendored +//! hayro-interpret, PdfCraft patch 107, PdfCraft #7167). Adobe-Japan1 gives 「 (U+300C) CID 686 +//! and its vertical form CID 7911; a font the PDF doesn't embed draws both through their +//! character, so a vertical column showed the horizontal 「, and 」、。ー…() and the small kana +//! the same way. +//! +//! The substitute is the fonts-build fixture `Tiny-glyf.ttf`, whose own `vert` feature replaces +//! 「 with `uni300C.vert`. Other tests replace its GSUB with one written here, whose lookup +//! replaces 「 with the fixture's "A", so which glyph is drawn tells the forms apart. + +use craft_pdf::interpret::font::{FontData, Glyph}; +use craft_pdf::interpret::{ + BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask, TransformExt, +}; +use kurbo::{Affine, BezPath, Rect}; +use std::sync::Arc; + +const TINY_GLYF: &[u8] = include_bytes!("../../../fonts-build/tests/fixture/subset/Tiny-glyf.ttf"); + +/// The glyph indexes drawn, in order. +#[derive(Default)] +struct Glyphs(Vec); + +impl Device<'_> for Glyphs { + fn set_soft_mask(&mut self, _: Option>) {} + fn set_blend_mode(&mut self, _: BlendMode) {} + fn draw_path(&mut self, _: &BezPath, _: Affine, _: &Paint<'_>, _: &PathDrawMode) {} + fn push_clip_path(&mut self, _: &ClipPath) {} + fn push_transparency_group(&mut self, _: f32, _: Option>, _: BlendMode) {} + fn draw_glyph(&mut self, glyph: &Glyph<'_>, _: Affine, _: Affine, _: &Paint<'_>, _: &GlyphDrawMode) { + if let Glyph::Outline(glyph) = glyph { + self.0.push(glyph.glyph_id().to_u32()); + } + } + fn draw_image(&mut self, _: Image<'_, '_>, _: Affine) {} + fn pop_clip_path(&mut self) {} + fn pop_transparency_group(&mut self) {} +} + +/// The fixture's glyph for `c`. +fn glyph(c: char) -> u16 { + let face = ttf_parser::Face::parse(TINY_GLYF, 0).unwrap(); + face.glyph_index(c).unwrap_or_else(|| panic!("the fixture covers {c:?}")).0 +} + +/// The fixture's own vertical form of 「. +fn vertical_bracket() -> u16 { + let face = ttf_parser::Face::parse(TINY_GLYF, 0).unwrap(); + face.glyph_index_by_name("uni300C.vert").expect("the fixture has a vertical 「").0 +} + +fn u16s(values: &[u16]) -> Vec { + values.iter().flat_map(|v| v.to_be_bytes()).collect() +} + +/// How the `vert` lookup's single substitution is written. +#[derive(Clone, Copy, Debug)] +enum Subtable { + /// Format 2, a list of substitutes. + List, + /// Format 1, a delta, reached through an extension lookup (type 7), as large CJK faces have it. + DeltaInExtension, +} + +/// A GSUB table whose one feature, tagged `feature`, is in the `DFLT` script's default language +/// 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(from, &[(feature, to)], subtable, &[(b"DFLT", &[0xFFFF, 1, 0])]) +} + +/// 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); + } + [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 { + Subtable::List => [u16s(&[2, 8, 1, to]), coverage].concat(), + Subtable::DeltaInExtension => [u16s(&[1, 6, to.wrapping_sub(from)]), coverage].concat(), + }; + let (lookup_type, body) = match subtable { + Subtable::List => (1, single), + // Extension format 1: the type it holds, then a 32-bit offset to it. + Subtable::DeltaInExtension => (7, [u16s(&[1, 1, 0, 8]), single].concat()), + }; + [u16s(&[lookup_type, 0, 1, 8]), body].concat() +} + +/// A `cmap` table whose one subtable (Windows Unicode BMP, format 4) maps `character` to `glyph`. +fn cmap(character: char, glyph: u16) -> Vec { + let code = u16::try_from(u32::from(character)).unwrap(); + // Two segments: the character, and the closing 0xFFFF one. + let subtable = u16s(&[4, 32, 0, 4, 4, 1, 0, code, 0xFFFF, 0, code, 0xFFFF, glyph.wrapping_sub(code), 1, 0, 0]); + [u16s(&[0, 1, 3, 1, 0, 12]), subtable].concat() +} + +/// The font file `font` with its table `tag` replaced by `table` (or added, or, for `None`, removed). +fn with_table(font: &[u8], tag: &[u8; 4], table: Option<&[u8]>) -> Vec { + let count = usize::from(u16::from_be_bytes([font[4], font[5]])); + let mut tables: Vec<([u8; 4], Vec)> = (0..count) + .map(|i| { + let record = &font[12 + 16 * i..28 + 16 * i]; + let offset = u32::from_be_bytes(record[8..12].try_into().unwrap()) as usize; + let length = u32::from_be_bytes(record[12..16].try_into().unwrap()) as usize; + (record[..4].try_into().unwrap(), font[offset..offset + length].to_vec()) + }) + .filter(|(t, _)| t != tag) + .collect(); + tables.extend(table.map(|table| (*tag, table.to_vec()))); + tables.sort_by_key(|(t, _)| *t); + let count = tables.len(); + let power = 1usize << count.ilog2(); + let mut out = font[..4].to_vec(); + out.extend(u16s(&[ + u16::try_from(count).unwrap(), + u16::try_from(power * 16).unwrap(), + u16::try_from(power.ilog2()).unwrap(), + u16::try_from((count - power) * 16).unwrap(), + ])); + let mut data = Vec::new(); + let start = 12 + 16 * count; + for (t, bytes) in &tables { + out.extend(t); + out.extend([0; 4]); + out.extend(u32::try_from(start + data.len()).unwrap().to_be_bytes()); + out.extend(u32::try_from(bytes.len()).unwrap().to_be_bytes()); + data.extend(bytes); + data.resize(data.len().next_multiple_of(4), 0); + } + out.extend(data); + out +} + +/// A page showing `code` in a Ryumin-Light of Adobe-Japan1 that the PDF doesn't embed. +fn pdf(encoding: &str, code: &str) -> Vec { + let content = format!("BT /F1 40 Tf 20 60 Td <{code}> Tj ET"); + format!( + "%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj +4 0 obj << /Length {} >> stream +{content} +endstream endobj +5 0 obj << /Type /Font /Subtype /Type0 /BaseFont /Ryumin-Light /Encoding /{encoding} /DescendantFonts [6 0 R] >> endobj +6 0 obj << /Type /Font /Subtype /CIDFontType0 /BaseFont /Ryumin-Light /CIDSystemInfo << /Registry (Adobe) /Ordering (Japan1) /Supplement 2 >> + /FontDescriptor 7 0 R /DW 1000 >> endobj +7 0 obj << /Type /FontDescriptor /FontName /Ryumin-Light /Flags 6 /FontBBox [-170 -331 1024 903] /ItalicAngle 0 /Ascent 752 /Descent -271 /CapHeight 742 /StemV 54 >> endobj +trailer << /Root 1 0 R >> +%%EOF", + content.len() + ) + .into_bytes() +} + +/// The glyphs drawn for `pdf`'s page with `face` as the substitute for every font. +fn glyphs(pdf: &[u8], face: &[u8]) -> Vec { + glyphs_with(pdf, face, InterpreterSettings::default()) +} + +/// [`glyphs`] with `settings`, whose font resolver is replaced. +fn glyphs_with(pdf: &[u8], face: &[u8], settings: InterpreterSettings) -> Vec { + let data: FontData = Arc::new(face.to_vec()); + let settings = InterpreterSettings { font_resolver: Arc::new(move |_| Some((data.clone(), 0))), ..settings }; + let pdf = craft_pdf::open_slice(pdf, None).unwrap(); + let page = &pdf.pages()[0]; + let cache = InterpreterCache::new(); + let mut context = Context::new(page.initial_transform(true).to_kurbo(), Rect::new(0.0, 0.0, 100.0, 100.0), &cache, page.xref(), settings); + let mut device = Glyphs::default(); + craft_pdf::interpret_page(page, &mut context, &mut device).unwrap(); + device.0 +} + +/// 「 by its vertical form's CID, through a `-V` CMap or as `Identity-H` or `Identity-V` CID 7911 +/// (0x1EE7, an old Japanese document's column, PdfCraft #7167), draws the substitute's vertical +/// glyph; by its horizontal CID, 686 (0x02AE), the ordinary one. The substitute's lookup is read +/// as the fixture writes it, as a format 2 list, and as a format 1 delta in an extension lookup. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn a_vertical_cid_draws_the_substitutes_vertical_glyph() { + let bracket = glyph('「'); + let a = glyph('A'); + let faces = [ + ("the fixture's own vert", TINY_GLYF.to_vec(), vertical_bracket()), + ("a format 2 vert", with_table(TINY_GLYF, b"GSUB", Some(&gsub(b"vert", bracket, a, Subtable::List))), a), + ("a format 1 vert in an extension", with_table(TINY_GLYF, b"GSUB", Some(&gsub(b"vert", bracket, a, Subtable::DeltaInExtension))), a), + ]; + for (which, face, vertical) in faces { + assert_ne!(vertical, bracket, "{which}: the vertical form is another glyph"); + for (encoding, code, expected, form) in [ + ("UniJIS-UCS2-V", "300C", vertical, "vertical"), + ("Identity-H", "1EE7", vertical, "vertical"), + ("Identity-V", "1EE7", vertical, "vertical"), + ("UniJIS-UCS2-H", "300C", bracket, "horizontal"), + ("Identity-H", "02AE", bracket, "horizontal"), + ("Identity-V", "02AE", bracket, "horizontal"), + ] { + assert_eq!(glyphs(&pdf(encoding, code), &face), [u32::from(expected)], "{which}: {encoding} <{code}> is the {form} 「"); + } + } +} + +/// A face whose vertical forms are under `vrt2` alone substitutes them too; a face with no +/// vertical substitution, or one whose `vert` covers other glyphs, draws the character's +/// ordinary glyph, as before. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn a_face_without_a_vertical_glyph_draws_the_ordinary_one() { + let (bracket, a, comma) = (glyph('「'), glyph('A'), glyph('、')); + let vrt2 = with_table(TINY_GLYF, b"GSUB", Some(&gsub(b"vrt2", bracket, a, Subtable::List))); + assert_eq!(glyphs(&pdf("UniJIS-UCS2-V", "300C"), &vrt2), [u32::from(a)], "vrt2 stands in for vert"); + let other = with_table(TINY_GLYF, b"GSUB", Some(&gsub(b"vert", comma, a, Subtable::List))); + let other_feature = with_table(TINY_GLYF, b"GSUB", Some(&gsub(b"smcp", bracket, a, Subtable::List))); + let none = with_table(TINY_GLYF, b"GSUB", None); + for (face, which) in [(&other, "a vert lookup for other glyphs"), (&other_feature, "another feature"), (&none, "no GSUB")] { + assert_eq!(glyphs(&pdf("UniJIS-UCS2-V", "300C"), face), [u32::from(bracket)], "{which}: the ordinary 「"); + } +} + +/// A language system may list `vert` only as its required feature (`requiredFeatureIndex`, with +/// 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, 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 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, 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 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"); + } +} + +/// 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 +/// fixture's `cmap` is replaced by one that draws “ with the glyph its own `vert` substitutes. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn a_vertical_cid_only_the_ucs2_cmaps_name_draws_the_vertical_glyph() { + let (quote, vertical) = (glyph('「'), vertical_bracket()); + let face = with_table(TINY_GLYF, b"cmap", Some(&cmap('\u{201C}', quote))); + for (encoding, code, expected, form) in [ + ("UniJIS-UCS2-V", "201C", vertical, "vertical"), + ("Identity-H", "2057", vertical, "vertical"), + ("UniJIS-UCS2-H", "201C", quote, "horizontal"), + ("Identity-H", "006C", quote, "horizontal"), + ] { + assert_eq!(glyphs(&pdf(encoding, code), &face), [u32::from(expected)], "{encoding} <{code}> is the {form} “"); + } +} + +/// A caller's CMap resolver may have the UCS-2 CMaps and not the UTF-16 ones: the UCS-2 pair +/// alone then tells the vertical forms from the horizontal ones. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] +#[cfg_attr(not(target_arch = "wasm32"), test)] +fn the_ucs2_cmaps_alone_tell_the_vertical_forms() { + use hayro_cmap::CMapName; + let (bracket, vertical) = (glyph('「'), vertical_bracket()); + let resolver = InterpreterSettings::default().cmap_resolver; + let settings = InterpreterSettings { + cmap_resolver: Arc::new(move |name| match name { + CMapName::UniJisUtf16H | CMapName::UniJisUtf16V => None, + name => resolver(name), + }), + ..Default::default() + }; + for (encoding, code, expected, form) in [ + ("UniJIS-UCS2-V", "300C", vertical, "vertical"), + ("Identity-H", "1EE7", vertical, "vertical"), + ("UniJIS-UCS2-H", "300C", bracket, "horizontal"), + ("Identity-H", "02AE", bracket, "horizontal"), + ] { + assert_eq!(glyphs_with(&pdf(encoding, code), TINY_GLYF, settings.clone()), [u32::from(expected)], "{encoding} <{code}> is the {form} 「"); + } +} diff --git a/crates/pdf/tests/main.rs b/crates/pdf/tests/main.rs index bbecb5d6dd..b56550c30b 100644 --- a/crates/pdf/tests/main.rs +++ b/crates/pdf/tests/main.rs @@ -9,6 +9,7 @@ mod crypt; #[path = "filters/main.rs"] mod filters; mod font_tables; +mod image_default_spaces; mod interpretation; mod knockout; mod knockout_backdrop; 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..409462ccdc 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,49 @@ 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, 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 { + 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); + let area_fell_back = area.width == 0 || area.height == 0; + if area_fell_back { + area = Rect::new(0, 0, w, h); + } + 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) + } +} + /// 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 @@ -720,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"))] 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 e528085135..dfd71f5fbb 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())); +} diff --git a/crates/scraft-format/README.md b/crates/scraft-format/README.md index c2df56206b..9ddea451ab 100644 --- a/crates/scraft-format/README.md +++ b/crates/scraft-format/README.md @@ -11,5 +11,14 @@ fields, 256 MiB session byte limit, character limits, and duplicate/exhausted ID fields use `craft_time::soundcraft`, the exact sample-index time API retained by `craft-time`. MIDI sequence values use `craft-midi`'s serde representation. +## Format versions + +A session file declares the lowest `format_version` able to read it back, not the writer's own +version: `Session::to_json` writes 1 unless the document holds a `Route::Instrument` (an +instrument's auxiliary output bus, used as a track input), which serializes an enum tag v1 cannot +parse — those files declare 2. A reader refuses anything above `Session::FORMAT_VERSION` with +`SessionError::Version`, so an older build fails such files with the newer-version message rather +than a generic parse error. + The application still maps sessions to UI state, engine state, media paths and audio pools. The session schema and its format-specific parsing, writing, sanitization and validation live here. diff --git a/crates/scraft-format/src/mixer.rs b/crates/scraft-format/src/mixer.rs index efdaf2d17d..0db71d9e84 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. @@ -561,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 { @@ -664,6 +681,33 @@ 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 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); diff --git a/crates/scraft-format/src/session.rs b/crates/scraft-format/src/session.rs index 9ba0909584..665f334ae7 100644 --- a/crates/scraft-format/src/session.rs +++ b/crates/scraft-format/src/session.rs @@ -3,7 +3,7 @@ use crate::clip::{bound, bound_sequence}; use crate::soundcraft_time::{FrameRate, GridScale, GridValue, Range, SampleRate, Samples, TempoMap, TimeFormat}; use crate::{ - Bus, BusId, ChannelFormat, Clip, ClipId, Group, GroupId, MarkerId, MarkerKind, MemoryLocation, OutputPath, Source, SourceId, SourcePool, + Bus, BusId, ChannelFormat, Clip, ClipId, Group, GroupId, MarkerId, MarkerKind, MemoryLocation, OutputPath, Route, Source, SourceId, SourcePool, TRACK_COLORS, Track, TrackId, TrackKind, VideoSource, }; @@ -406,11 +406,17 @@ impl Default for Session { } impl Session { - pub const FORMAT_VERSION: u32 = 1; + /// Highest session version this build reads. Newer files get `SessionError::Version`, + /// not a parse error. + pub const FORMAT_VERSION: u32 = 2; + + /// The version a session declares when nothing in it needs a newer reader. Today only + /// `Route::Instrument` (an instrument's auxiliary output bus) is unreadable to v1. + const BASE_FORMAT_VERSION: u32 = 1; pub fn new(name: impl Into, sample_rate: SampleRate) -> Self { let mut s = Session { - format_version: Self::FORMAT_VERSION, + format_version: Self::BASE_FORMAT_VERSION, name: name.into(), sample_rate, bit_depth: BitDepthSetting::Int24, @@ -752,7 +758,30 @@ impl Session { // ---- persistence --------------------------------------------------------------------- pub fn to_json(&self) -> Result { - serde_json::to_string_pretty(self).map_err(|e| SessionError::Format(e.to_string())) + let version = self.saved_format_version(); + if version == self.format_version { + serde_json::to_string_pretty(self).map_err(|e| SessionError::Format(e.to_string())) + } else { + let mut session = self.clone(); + session.format_version = version; + serde_json::to_string_pretty(&session).map_err(|e| SessionError::Format(e.to_string())) + } + } + + /// The lowest format version that can read this document back. `Route::Instrument` writes + /// an enum tag a v1 reader does not know, so a file holding one must declare v2: a v1 + /// reader then refuses it with `SessionError::Version` rather than a generic parse error. + fn saved_format_version(&self) -> u32 { + if self.uses_instrument_routes() { Self::FORMAT_VERSION } else { Self::BASE_FORMAT_VERSION } + } + + /// Any `Route::Instrument` on a track's input, output or send. + fn uses_instrument_routes(&self) -> bool { + self.tracks.iter().any(|t| { + matches!(t.mixer.input, Route::Instrument { .. }) + || matches!(t.mixer.output, Route::Instrument { .. }) + || t.mixer.sends.iter().flatten().any(|s| matches!(s.target, Route::Instrument { .. })) + }) } /// Parse a session; decoded audio must be attached separately (`pool`). @@ -1222,6 +1251,32 @@ mod tests { assert!(matches!(Session::from_json(&v.to_string()), Err(SessionError::Version(999)))); } + /// `Route::Instrument` writes an enum tag a v1 reader cannot parse, so a file holding one + /// declares v2: an older reader then refuses with `SessionError::Version`, not a generic + /// parse error. Sessions without one stay v1 and open in older builds. + #[test] + fn a_session_with_an_instrument_route_saves_as_v2_and_round_trips() { + let mut s = Session::default(); + let instrument_track = s.add_track(TrackKind::Instrument, ChannelFormat::Stereo, Some("Keys")); + let aux_track = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, Some("Keys Out")); + s.track_mut(aux_track).unwrap().mixer.input = Route::Instrument { track: instrument_track, bus: 1 }; + + let text = s.to_json().unwrap(); + let head: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(head["format_version"], serde_json::json!(Session::FORMAT_VERSION), "v2 so a v1 reader refuses by version"); + let back = Session::from_json(&text).unwrap(); + assert_eq!( + back.track(aux_track).map(|t| &t.mixer.input), + Some(&Route::Instrument { track: instrument_track, bus: 1 }), + "the route survives a full save/load" + ); + + let mut plain = Session::default(); + plain.add_track(TrackKind::Audio, ChannelFormat::Stereo, None); + let head: serde_json::Value = serde_json::from_str(&plain.to_json().unwrap()).unwrap(); + assert_eq!(head["format_version"], serde_json::json!(Session::BASE_FORMAT_VERSION), "nothing v2-only stays v1"); + } + #[test] fn the_version_is_checked_as_before() { // #892: the version is read without building the whole document as a tree; the errors @@ -1252,7 +1307,7 @@ mod tests { assert_eq!(format(t), want, "{t}"); } let mut v = serde_json::to_value(Session::default()).unwrap(); - for (ver, want) in [(serde_json::json!(2), 2), (serde_json::json!(1u64 << 40), u32::MAX)] { + for (ver, want) in [(serde_json::json!(3), 3), (serde_json::json!(1u64 << 40), u32::MAX)] { v["format_version"] = ver; assert_eq!(Session::from_json(&v.to_string()), Err(SessionError::Version(want))); } @@ -1263,7 +1318,7 @@ mod tests { // A newer version is refused even when the rest would not parse. assert_eq!(Session::from_json(r#"{"format_version":7,"tracks":5}"#), Err(SessionError::Version(7))); // An older or the current version loads as it did. - for ver in [0, 1] { + for ver in [0, 1, 2] { v["format_version"] = serde_json::json!(ver); assert_eq!(Session::from_json(&v.to_string()).map(|s| s.format_version), Ok(ver)); } diff --git a/crates/sketch/src/rest/path.rs b/crates/sketch/src/rest/path.rs index a8e48dc316..201bab37da 100644 --- a/crates/sketch/src/rest/path.rs +++ b/crates/sketch/src/rest/path.rs @@ -18,7 +18,7 @@ use super::tree::{Cx, base, layer, layers, local, size}; /// Farthest a point or handle may be from its layer (the REST importer's own range). const MAX_COORD: f64 = 1e7; /// Most points read from one path. -const MAX_POINTS: usize = 100_000; +pub(super) const MAX_POINTS: usize = 100_000; /// What a path layer becomes. pub(crate) enum Shape { @@ -56,8 +56,9 @@ fn shows(style: Option<&Value>, key: &str) -> bool { /// open path gets a closing segment and a fill region, as Sketch fills it. pub(crate) fn network(cx: &mut Cx, l: &Value, w: f64, h: f64, fill_open: bool) -> Option { let pts = l.get("points").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); - if pts.len() > MAX_POINTS { - cx.warn(format!("paths with more than {MAX_POINTS} points were cut")); + let max_points = cx.max_points; + if pts.len() > max_points { + cx.warn(format!("paths with more than {max_points} points were cut")); } // Far points stay within the importer's coordinate range (a product could overflow). let fit = |v: f64| if v.is_finite() { v.clamp(-MAX_COORD, MAX_COORD) } else { 0.0 }; @@ -65,7 +66,7 @@ pub(crate) fn network(cx: &mut Cx, l: &Value, w: f64, h: f64, fill_open: bool) - let mut vertices = Vec::new(); // Per vertex: its handles (relative to it) when it has them. let mut handles: Vec<((f64, f64), (f64, f64))> = Vec::new(); - for p in pts.iter().take(MAX_POINTS) { + for p in pts.iter().take(max_points) { let Some((x, y)) = at(p, "point") else { cx.warn("path points that couldn't be read were skipped"); continue; diff --git a/crates/sketch/src/rest/tests.rs b/crates/sketch/src/rest/tests.rs index 6c134facd4..42fcdb231b 100644 --- a/crates/sketch/src/rest/tests.rs +++ b/crates/sketch/src/rest/tests.rs @@ -177,11 +177,48 @@ fn the_layer_cap_holds() { #[test] fn a_path_past_the_point_cap_is_cut() { - let pts: Vec<(f64, f64)> = (0..100_005).map(|i| (f64::from(i % 2), f64::from(i) / 100_005.0)).collect(); - let z = sketch_zip("50.2", 103, document(&["P"]), &[page("P", "P", vec![shape_path("L", 0.0, 0.0, 10.0, 10.0, &pts, false)])], &[]); + fn path_zip(point_count: u32) -> Vec { + let pts: Vec<(f64, f64)> = (0..point_count).map(|i| (f64::from(i % 2), f64::from(i) / f64::from(point_count))).collect(); + sketch_zip("50.2", 103, document(&["P"]), &[page("P", "P", vec![shape_path("L", 0.0, 0.0, 10.0, 10.0, &pts, false)])], &[]) + } + + let note = "paths with more than 4 points were cut"; + let z = path_zip(9); + let out = tree::to_rest_with_point_cap(&Archive::open(&z).unwrap(), "f", Options::default().max_nodes, None, 60_000_000, 4); + assert!(out.warnings.iter().any(|w| w == note), "{:?}", out.warnings); + assert_eq!(out.networks[0].as_ref().map(|n| n.vertices.len()), Some(4)); + + let z = path_zip(4); + let out = tree::to_rest_with_point_cap(&Archive::open(&z).unwrap(), "f", Options::default().max_nodes, None, 60_000_000, 4); + assert!(!out.warnings.iter().any(|w| w == note), "{:?}", out.warnings); + assert_eq!(out.networks[0].as_ref().map(|n| n.vertices.len()), Some(4)); + + // The ordinary entry point must not inherit the small test budget. + let z = path_zip(5); + let out = map(&z); + assert_eq!(out.networks[0].as_ref().map(|n| n.vertices.len()), Some(5)); + assert!(!out.warnings.iter().any(|w| w.starts_with("paths with more than ")), "{:?}", out.warnings); + + // Exercise the actual default boundary without making 100,000 vertices or formatted point strings. + let mut path = shape_path("L", 0.0, 0.0, 10.0, 10.0, &[], false); + path["points"] = Value::Array(vec![Value::Null; 100_001]); + let z = sketch_zip("50.2", 103, document(&["P"]), &[page("P", "P", vec![path])], &[]); let out = map(&z); assert!(out.warnings.iter().any(|w| w == "paths with more than 100000 points were cut"), "{:?}", out.warnings); - assert_eq!(out.networks[0].as_ref().map(|n| n.vertices.len()), Some(100_000)); + 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] diff --git a/crates/sketch/src/rest/tree.rs b/crates/sketch/src/rest/tree.rs index cb82a60916..a054859598 100644 --- a/crates/sketch/src/rest/tree.rs +++ b/crates/sketch/src/rest/tree.rs @@ -66,6 +66,8 @@ pub(crate) struct Cx { /// Layers mapped so far, and the most the file may give. pub nodes: usize, pub max_nodes: usize, + /// Most points kept from any one path. + pub max_points: usize, /// Finds installed faces by PostScript name, and what it found (or didn't) so far. pub fonts: Option, pub font_cache: std::collections::BTreeMap>, @@ -123,6 +125,18 @@ pub(crate) fn to_rest(archive: &Archive, name: &str, max_nodes: usize, fonts: Op /// [`to_rest`] with a work budget of `max_work`. pub(crate) fn to_rest_within(archive: &Archive, name: &str, max_nodes: usize, fonts: Option, max_work: u64) -> Map { + to_rest_with_point_cap(archive, name, max_nodes, fonts, max_work, super::path::MAX_POINTS) +} + +/// The same mapping with explicit work and point budgets; public entry points keep the default point cap. +pub(super) fn to_rest_with_point_cap( + archive: &Archive, + name: &str, + max_nodes: usize, + fonts: Option, + max_work: u64, + max_points: usize, +) -> Map { let symbols = super::symbols::Symbols::read(&archive.document, &archive.pages); let shared = super::shared::Shared::read(&archive.document); let mut cx = Cx { @@ -142,6 +156,7 @@ pub(crate) fn to_rest_within(archive: &Archive, name: &str, max_nodes: usize, fo too_old: false, nodes: 0, max_nodes, + max_points, fonts, font_cache: std::collections::BTreeMap::new(), }; diff --git a/crates/sniff/src/detect.rs b/crates/sniff/src/detect.rs index d97baf1269..793041a163 100644 --- a/crates/sniff/src/detect.rs +++ b/crates/sniff/src/detect.rs @@ -2,7 +2,9 @@ use crate::Kind; -/// How many leading bytes [`identify`] reads at most. Every signature it knows lies within them. +/// How many leading bytes [`identify`] reads at most. Every signature it knows lies within them, +/// except for container formats like OpenRaster whose distinguishing payload may be pushed past +/// this window by variable-length ZIP extra fields (which fall back to [`Kind::Zip`]). pub const HEAD: usize = 4096; /// The largest universal Mach-O architecture count taken as Mach-O rather than a Java class. @@ -25,6 +27,11 @@ const TS_SYNC: u8 = 0x47; /// headers, MPEG transport stream packets), so a file is never named by a weak signature when a /// strong one matches. /// +/// OpenRaster (`.ora`) archives require an uncompressed `mimetype` entry as their first file, +/// but permit variable-length ZIP extra fields. If ZIP metadata pushes the `image/openraster` +/// payload beyond [`HEAD`] bytes, `identify` falls back to [`Kind::Zip`] as an intentionally +/// bounded format hint rather than reading an unbounded stream. +/// /// `CAFEBABE` starts both a universal Mach-O and a Java class file. The next big-endian 32-bit /// value is a Mach-O architecture count or a class file's version: up to 44 is taken as /// [`Kind::MachOFat`], 45 and over as [`Kind::JavaClass`]. A caller that knows the file name @@ -54,7 +61,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 +97,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 +108,83 @@ fn checked(b: &[u8]) -> Option { } } +/// `PK\x03\x04`: an OpenRaster archive when the first entry is a stored `mimetype` holding +/// `image/openraster` within [`HEAD`], 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/lib.rs b/crates/sniff/src/lib.rs index b95e11591a..c62bb405ab 100644 --- a/crates/sniff/src/lib.rs +++ b/crates/sniff/src/lib.rs @@ -15,9 +15,14 @@ //! Which kinds an app supports, and what it does when the name and the bytes disagree, stay //! with the app. //! -//! [`HEAD`] bytes are enough for every signature; passing more changes nothing, passing fewer +//! [`HEAD`] bytes are enough for almost every signature; passing more changes nothing, passing fewer //! only loses the signatures that sit further in (TAR's at byte 257, MPEG transport streams' -//! third packet). Any input is fine: nothing here allocates, panics or reads past the slice. +//! third packet). An exception is OpenRaster ([`Kind::Ora`]): the OpenRaster specification requires +//! an uncompressed `mimetype` entry as the first file in the ZIP archive, but permits variable-length +//! ZIP extra fields. If ordinary ZIP metadata pushes the `image/openraster` payload beyond [`HEAD`] +//! bytes, [`identify`] safely falls back to [`Kind::Zip`] even if the full file was supplied. +//! Downstream callers can distinguish an intentionally bounded format hint from an exhaustive +//! format guarantee. Any input is fine: nothing here allocates, panics or reads past the slice. //! //! Written from the formats' public specifications and registrations (IANA media types, ISO/IEC //! 14496-12 brands, the EBML and Matroska specifications, RIFF, the ELF, PE and Mach-O headers). diff --git a/crates/sniff/src/tests.rs b/crates/sniff/src/tests.rs index 2c5d2da8d3..dd980c8cfd 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,187 @@ 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 openraster_extra_fields_boundary_and_zip_fallback() { + // OpenRaster specifies that the first entry must be an uncompressed "mimetype" file, + // but permits arbitrary ZIP extra fields. + // When extra fields push the "image/openraster" payload past HEAD bytes (4096), + // identify safely falls back to Kind::Zip even when the complete file is supplied. + + fn ora_with_extra(mime: &[u8], extra: &[u8]) -> Vec { + let mut b = b"PK\x03\x04".to_vec(); + b.extend_from_slice(&20u16.to_le_bytes()); + b.extend_from_slice(&0u16.to_le_bytes()); + b.extend_from_slice(&0u16.to_le_bytes()); + b.extend_from_slice(&0u16.to_le_bytes()); + b.extend_from_slice(&0u16.to_le_bytes()); + b.extend_from_slice(&0u32.to_le_bytes()); + let len = u32::try_from(mime.len()).unwrap_or(0); + b.extend_from_slice(&len.to_le_bytes()); + b.extend_from_slice(&len.to_le_bytes()); + b.extend_from_slice(&8u16.to_le_bytes()); + let extra_len = u16::try_from(extra.len()).unwrap_or(0); + b.extend_from_slice(&extra_len.to_le_bytes()); + b.extend_from_slice(b"mimetype"); + b.extend_from_slice(extra); + b.extend_from_slice(mime); + b + } + + fn make_ordinary_extra(total_len: usize) -> Vec { + let mut extra = Vec::with_capacity(total_len); + // Ordinary Info-ZIP Extended Timestamp (0x5455): flag (1 byte) + modtime (4 bytes) + if total_len >= 9 { + extra.extend_from_slice(&0x5455u16.to_le_bytes()); + extra.extend_from_slice(&5u16.to_le_bytes()); + extra.push(1); + extra.extend_from_slice(&1_700_000_000u32.to_le_bytes()); + } + // Fill remaining extra field space with ordinary Info-ZIP Unix metadata (0x7875) + while extra.len() < total_len { + let remaining = total_len.saturating_sub(extra.len()); + if remaining >= 4 { + let data_len = remaining.saturating_sub(4).min(u16::MAX as usize); + let data_u16 = u16::try_from(data_len).unwrap_or(u16::MAX); + extra.extend_from_slice(&0x7875u16.to_le_bytes()); + extra.extend_from_slice(&data_u16.to_le_bytes()); + extra.resize(extra.len().saturating_add(data_len), 0); + } else { + extra.resize(total_len, 0); + break; + } + } + extra + } + + // Header (30) + "mimetype" (8) = 38 bytes before extra fields. + // "image/openraster" = 16 bytes. + // Total before payload end = 38 + extra_len + 16 = 54 + extra_len. + // At HEAD = 4096: + // extra_len = 4096 - 54 = 4042: payload ends exactly at byte 4096 (inside HEAD). + let extra_at_boundary = make_ordinary_extra(4042); + let ora_at_boundary = ora_with_extra(b"image/openraster", &extra_at_boundary); + assert_eq!(ora_at_boundary.len(), HEAD); + assert_eq!(identify(&ora_at_boundary), Some(Kind::Ora)); + + // extra_len = 4043: payload ends at byte 4097 (crosses HEAD by 1 byte). + // Even when the full 4097 bytes are supplied, identify caps at HEAD and falls back to Zip. + let extra_past_boundary = make_ordinary_extra(4043); + let ora_past_boundary = ora_with_extra(b"image/openraster", &extra_past_boundary); + assert_eq!(ora_past_boundary.len(), HEAD + 1); + assert_eq!(identify(&ora_past_boundary), Some(Kind::Zip)); + + // extra_len = 4100: payload starts at byte 4138 (entirely beyond HEAD). + let extra_well_past = make_ordinary_extra(4100); + let ora_well_past = ora_with_extra(b"image/openraster", &extra_well_past); + assert_eq!(identify(&ora_well_past), Some(Kind::Zip)); +} + #[test] fn every_prefix_of_every_sample_is_safe() { - let mut samples = vec![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 +507,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); } diff --git a/crates/stream-codecs/src/jbig2/decode.rs b/crates/stream-codecs/src/jbig2/decode.rs index b718863c65..5954ba1383 100644 --- a/crates/stream-codecs/src/jbig2/decode.rs +++ b/crates/stream-codecs/src/jbig2/decode.rs @@ -228,12 +228,15 @@ mod tests { }) .collect() }; + // Every globals input is a prefix of the same 11-byte segment records. + let all_globals = globals(MAX_SEGMENTS - 1); // The image's page information and region, and in random access its end of file segment. for (flags, organization, image) in [(0x01, "sequential", 2), (0x00, "random access", 3)] { let data = with_file_header(&embedded, flags, Some(1)); - let (at_cap, past_cap) = (globals(MAX_SEGMENTS - image), globals(MAX_SEGMENTS - image + 1)); - assert_eq!(decode_jbig2(&data, Some(&at_cap), w, h, max).unwrap(), bits, "{organization}: at the cap"); - let refused = decode_jbig2(&data, Some(&past_cap), w, h, max).unwrap_err(); + let at_cap = &all_globals[..(MAX_SEGMENTS - image) as usize * 11]; + let past_cap = &all_globals[..(MAX_SEGMENTS - image + 1) as usize * 11]; + assert_eq!(decode_jbig2(&data, Some(at_cap), w, h, max).unwrap(), bits, "{organization}: at the cap"); + let refused = decode_jbig2(&data, Some(past_cap), w, h, max).unwrap_err(); assert!(refused.to_string().contains("too many segments"), "{organization}: {refused}"); } } diff --git a/crates/suite-account/src/accounts.rs b/crates/suite-account/src/accounts.rs index fb8ce5d7de..a30d2d7941 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 6a6ba1a19a..155f7413fc 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(); diff --git a/crates/svg/src/doc_style.rs b/crates/svg/src/doc_style.rs index 156dbce241..39b3e9208c 100644 --- a/crates/svg/src/doc_style.rs +++ b/crates/svg/src/doc_style.rs @@ -138,8 +138,51 @@ pub const STYLE_PROPS: &[&str] = &[ "stop-opacity", ]; +/// Normalize only numeric CSS length-unit suffixes in the properties this cascade resolves. +/// Raw SVG attributes and opaque CSS values keep their existing spelling and compatibility. +fn css_length_units(property: &str, value: String) -> String { + if !matches!(property, "font-size" | "stroke-width" | "stroke-dasharray" | "stroke-dashoffset") { + return value; + } + let separator = |c: char| c == ',' || c.is_whitespace(); + let finite = |number: &str| number.parse::().ok().is_some_and(f64::is_finite); + let supported = |unit: &str| matches!(unit.to_ascii_lowercase().as_str(), "px" | "pt" | "pc" | "mm" | "cm" | "in" | "em" | "ex"); + let numeric_length = |token: &str| { + finite(token.strip_suffix('%').unwrap_or(token)) + || token.len().checked_sub(2).is_some_and(|split| token.get(..split).is_some_and(finite) && token.get(split..).is_some_and(supported)) + }; + let eligible = if property == "stroke-dasharray" { + value.split(separator).filter(|token| !token.is_empty()).all(numeric_length) + } else { + numeric_length(value.trim()) + }; + if !eligible { + return value; + } + let mut out = String::with_capacity(value.len()); + for part in value.split_inclusive(separator) { + let token = part.trim_end_matches(separator); + if let Some(split) = token.len().checked_sub(2) + && let (Some(number), Some(unit)) = (token.get(..split), token.get(split..)) + && number.parse::().ok().is_some_and(f64::is_finite) + { + let unit = unit.to_ascii_lowercase(); + if matches!(unit.as_str(), "px" | "pt" | "pc" | "mm" | "cm" | "in" | "em" | "ex") { + out.push_str(number); + out.push_str(&unit); + out.push_str(&part[token.len()..]); + continue; + } + } + out.push_str(part); + } + out +} + /// Collect the declared properties of an element: presentation attributes, then CSS rules /// (by specificity and source order, bounded by `charge_css`), then the inline `style` attribute. +/// Supported numeric length-unit suffixes are normalized only for CSS declarations; raw +/// presentation attributes retain their existing spelling and length compatibility. pub fn declared(n: roxmltree::Node, css: &StyleSheet, charge_css: impl FnMut(usize) -> bool) -> HashMap { let mut out = HashMap::new(); for a in n.attributes() { @@ -147,9 +190,15 @@ pub fn declared(n: roxmltree::Node, css: &StyleSheet, charge_css: impl FnMut(usi out.insert(a.name().to_string(), a.value().to_string()); } } - css.apply(n.tag_name().name(), n.attribute("id"), n.attribute("class").unwrap_or_default(), &mut out, charge_css); + let mut css_values = HashMap::new(); + css.apply(n.tag_name().name(), n.attribute("id"), n.attribute("class").unwrap_or_default(), &mut css_values, charge_css); + out.extend(css_values.into_iter().map(|(k, v)| { + let v = css_length_units(&k, v); + (k, v) + })); if let Some(st) = n.attribute("style") { for (k, v) in declarations(st) { + let v = css_length_units(&k, v); out.insert(k, v); } } @@ -470,6 +519,124 @@ mod tests { assert_eq!(d.get("fill").map(String::as_str), Some("blue")); assert_eq!(d.get("stroke").map(String::as_str), Some("red")); assert!(!d.contains_key("transform")); + + // SVG1.1 length syntax distinguishes CSS unit case from raw attributes: + // https://www.w3.org/TR/SVG11/types.html#DataTypeLength + let primary = roxmltree::Document::parse( + r#""#, + ) + .unwrap(); + for id in ["lower", "upper"] { + let node = primary.descendants().find(|n| n.attribute("id") == Some(id)).unwrap(); + let mut st = Style::default(); + cascade(node, &StyleSheet::default(), &mut st, 200.0, 100.0, |_| true); + assert_eq!(st.stroke_width, 16.0, "{id}: CSS unit case must not change stroke width"); + } + + let close = |actual: f64, expected: f64| { + assert!((actual - expected).abs() <= 1e-12 * expected.abs().max(1.0), "{actual} != {expected}"); + }; + // Every supported suffix, through both CSS origins and every length property. + // Absolute factors are CSS px/unit; relative factors use the inherited font. + let units = [ + ("px", "pX", 1.0, 0.0), + ("pt", "Pt", 4.0 / 3.0, 0.0), + ("pc", "pC", 16.0, 0.0), + ("mm", "Mm", 96.0 / 25.4, 0.0), + ("cm", "cM", 96.0 / 2.54, 0.0), + ("in", "In", 96.0, 0.0), + ("em", "eM", 0.0, 1.0), + ("ex", "Ex", 0.0, 0.5), + ]; + for (unit, mixed, absolute, relative) in units { + for inline in [false, true] { + let separator = if inline { " " } else { "\t" }; + let values = format!( + "font-size:2{mixed};stroke-width:3{mixed};stroke-dasharray:1E1{mixed},{separator}+2.5{mixed};stroke-dashoffset:-5e-1{mixed}" + ); + let inline_style = if inline { format!(" style=\"{values}\"") } else { String::new() }; + let xml = format!( + "" + ); + let doc = roxmltree::Document::parse(&xml).unwrap(); + let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let mut css = StyleSheet::default(); + let rule = if inline { ".a { stroke-width:1px; font-size:1px; }".to_owned() } else { format!(".a {{ {values} }}") }; + parse_css(&rule, &mut css).unwrap(); + css.index(); + let d = declared(rect, &css, |_| true); + assert_eq!(d.get("font-size"), Some(&format!("2{unit}"))); + assert_eq!(d.get("stroke-width"), Some(&format!("3{unit}"))); + assert_eq!(d.get("stroke-dasharray"), Some(&format!("1E1{unit},{separator}+2.5{unit}"))); + assert_eq!(d.get("stroke-dashoffset"), Some(&format!("-5e-1{unit}"))); + let factor = |font| if relative == 0.0 { absolute } else { font * relative }; + let font = 2.0 * factor(20.0); + let mut st = Style { font_size: 20.0, ..Style::default() }; + cascade(rect, &css, &mut st, 200.0, 100.0, |_| true); + close(st.font_size, font); + close(st.stroke_width, 3.0 * factor(font)); + let dash = st.dash.as_ref().unwrap(); + assert_eq!(dash.len(), 2); + close(dash[0], 10.0 * factor(font)); + close(dash[1], 2.5 * factor(font)); + close(st.dash_offset, -0.5 * factor(font)); + } + } + + let raw = roxmltree::Document::parse( + r#""#, + ) + .unwrap(); + let rect = raw.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let d = declared(rect, &StyleSheet::default(), |_| true); + assert_eq!(d.get("stroke-width").map(String::as_str), Some("12PT")); + assert_eq!(d.get("font-size").map(String::as_str), Some("2EM")); + let mut st = Style { font_size: 20.0, ..Style::default() }; + cascade(rect, &StyleSheet::default(), &mut st, 200.0, 100.0, |_| true); + assert_eq!((st.font_size, st.stroke_width, st.dash_offset), (2.0, 12.0, 3.0)); + assert_eq!(st.dash, Some(vec![1.0, 2.0])); + assert_eq!(attr_len(rect, "width", 'x', &st, 200.0, 100.0), 12.0); + assert_eq!(length("12FURLONG", 'x', 20.0, 200.0, 100.0), Some(12.0)); + assert_eq!(length_strict("12PT", 100.0), None); + assert_eq!(parse_font_size("2EM", 20.0, 100.0), None); + assert_eq!(parse_dash_array("1PT 2PT", 100.0), None); + + let opaque = roxmltree::Document::parse( + r##""##, + ) + .unwrap(); + let rect = opaque.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let d = declared(rect, &StyleSheet::default(), |_| true); + for (key, value) in [ + ("stroke-width", "var(--Case)"), + ("font-size", "1e999PT"), + ("stroke-dasharray", "NaNPT, 2qU"), + ("stroke-dashoffset", "12FURLONG"), + ("fill", "url(#PaintID)"), + ("font-family", "MiXeD"), + ] { + assert_eq!(d.get(key).map(String::as_str), Some(value)); + } + let opaque_dash = opaque.descendants().find(|n| n.attribute("id") == Some("opaque-dash")).unwrap(); + let d = declared(opaque_dash, &StyleSheet::default(), |_| true); + assert_eq!(d.get("stroke-dasharray").map(String::as_str), Some("var(--Case, 12PT )")); + + // A normal matching rule is charged once, before its values are merged. + let mut css = StyleSheet::default(); + parse_css(".a { stroke-width:12PT; }", &mut css).unwrap(); + css.index(); + let doc = roxmltree::Document::parse( + r#""#, + ) + .unwrap(); + let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let mut charges = Vec::new(); + let d = declared(rect, &css, |cost| { + charges.push(cost); + true + }); + assert_eq!(charges, [1, 1, 1, 1]); + assert_eq!(d.get("stroke-width").map(String::as_str), Some("5px")); } #[test] diff --git a/crates/svg/src/paths.rs b/crates/svg/src/paths.rs index c165884541..013c6a252b 100644 --- a/crates/svg/src/paths.rs +++ b/crates/svg/src/paths.rs @@ -684,12 +684,12 @@ fn import_node<'a, 'input, K: Kind>( } if !state.display_none && !state.visibility_hidden - && let Some(path) = geometry_for(node, context.path_name)? + && let Some((path, drawable)) = geometry_for(node, context.path_name)? { context.charge_segments(&path)?; let transformed = transform_path(&path, state.transform); validate_import_path(&transformed, context.path_name)?; - context.shapes.push(Shape { + context.shapes.extend(drawable.then(|| Shape { path: transformed, kind: state.kind.clone(), label: label(node), @@ -699,7 +699,7 @@ fn import_node<'a, 'input, K: Kind>( fill_rule: if style.get("fill-rule").is_some_and(|value| value == "evenodd") { FillRule::EvenOdd } else { FillRule::NonZero }, clips: state.clips.clone(), layer: state.layer.as_deref().map(str::to_string), - }); + })); } for child in node.children().filter(|n| n.is_element()) { import_node(child, state.clone(), depth + 1, context)?; @@ -891,7 +891,7 @@ fn clip_region( } continue; } - let Some(path) = geometry_for(child, context.path_name)? else { + let Some((path, drawable)) = geometry_for(child, context.path_name)? else { continue; }; let mut child_space = space; @@ -908,13 +908,13 @@ fn clip_region( if context.clip_pieces > MAX_SVG_CLIP_PIECES { return Err(svg_error(context.path_name, "SVG clip paths exceed the 100,000-piece limit")); } - pieces.push((path, rule)); + pieces.extend(drawable.then_some((path, rule))); } context.clips.push(Clip { pieces }); Ok(Some(context.clips.len() - 1)) } -fn geometry_for(node: roxmltree::Node<'_, '_>, path_name: &str) -> Result, Error> { +fn geometry_for(node: roxmltree::Node<'_, '_>, path_name: &str) -> Result, Error> { let tag = node.tag_name().name(); let number = |name: &str, default: f64| -> Result { match node.attribute(name) { @@ -922,6 +922,8 @@ fn geometry_for(node: roxmltree::Node<'_, '_>, path_name: &str) -> Result