From cb7e8c5ec104845ac9858a2cdaf1314f8f298fc6 Mon Sep 17 00:00:00 2001 From: el-j Date: Mon, 16 Nov 2026 01:25:17 +0100 Subject: [PATCH 01/79] craft-audio: DSD audio (DSF and DFF) to PCM. Closes #1539. --- crates/audio/Cargo.toml | 6 + crates/audio/src/dsd/dsdiff.rs | 329 +++++++++++++++++++++++++++++ crates/audio/src/dsd/dsf.rs | 323 +++++++++++++++++++++++++++++ crates/audio/src/dsd/filter.rs | 216 +++++++++++++++++++ crates/audio/src/dsd/mod.rs | 221 ++++++++++++++++++++ crates/audio/src/lib.rs | 5 +- crates/audio/tests/dsd_oracle.rs | 345 +++++++++++++++++++++++++++++++ 7 files changed, 1444 insertions(+), 1 deletion(-) create mode 100644 crates/audio/src/dsd/dsdiff.rs create mode 100644 crates/audio/src/dsd/dsf.rs create mode 100644 crates/audio/src/dsd/filter.rs create mode 100644 crates/audio/src/dsd/mod.rs create mode 100644 crates/audio/tests/dsd_oracle.rs diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index fe28cec3f8..2e5e068e8f 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -58,6 +58,8 @@ ac3-encode = ["craft-media/bitstream"] eac3-encode = ["craft-media/bitstream"] # MPEG-1/2 Layer III (MP3) encoder (`mp3`). mp3-encode = ["craft-media/bitstream"] +# Direct Stream Digital (DSD) files: DSF and DSDIFF decoders and DSD-to-PCM decimation. +dsd = [] # Multi-resolution waveform overviews (`peaks`). peaks = [] # Encode AAC channels in parallel (with `aac-encode`). @@ -96,6 +98,10 @@ required-features = ["flac-decode", "flac-encode"] name = "qoa_oracle" required-features = ["qoa"] +[[test]] +name = "dsd_oracle" +required-features = ["dsd"] + [[example]] name = "info" required-features = ["decode"] diff --git a/crates/audio/src/dsd/dsdiff.rs b/crates/audio/src/dsd/dsdiff.rs new file mode 100644 index 0000000000..bd593e13ec --- /dev/null +++ b/crates/audio/src/dsd/dsdiff.rs @@ -0,0 +1,329 @@ +//! Philips DSDIFF (Direct Stream Digital Interchange File Format, `.dff`) parser and writer. +//! +//! DSDIFF files use an IFF-style big-endian chunk format starting with `FRM8` of type `DSD `: +//! - `FRM8` container chunk containing: +//! - `FVER`: format version (typically 1.5.0.0). +//! - `PROP`: properties chunk with subtype `SND `, containing: +//! - `FS `: sampling frequency (e.g. 2,822,400 Hz for DSD64). +//! - `CHNL`: channel count and 4-character channel ID codes (`SLFT`, `SRGT`, etc.). +//! - `CMPR`: compression type (`DSD ` for uncompressed, `DST ` for compressed). +//! - `DSD `: audio data chunk containing channel-interleaved 1-bit samples (MSB-first). +//! - Optional `DIIN`: disc and track information (title, artist). + +use super::{BitOrder, Error, Format, MAX_CHANNELS, MAX_DECODE_BYTES, MAX_SAMPLE_RATE, MIN_SAMPLE_RATE, Metadata, RawAudio}; + +/// Decodes 4-byte ASCII channel identifiers into human-readable channel names. +fn channel_id_to_name(id: &[u8; 4]) -> String { + match id { + b"SLFT" => "FrontLeft".to_string(), + b"SRGT" => "FrontRight".to_string(), + b"MLFT" => "Mono/Left".to_string(), + b"MRGT" => "Right".to_string(), + b"C " => "Center".to_string(), + b"LFE " => "LFE".to_string(), + b"LS " => "LeftSurround".to_string(), + b"RS " => "RightSurround".to_string(), + b"CO " => "CenterOverhead".to_string(), + b"LH " => "LeftHeight".to_string(), + b"RH " => "RightHeight".to_string(), + _ => { + if let Ok(s) = std::str::from_utf8(id) { + let trimmed = s.trim(); + if !trimmed.is_empty() { + return trimmed.to_string(); + } + } + format!("Channel {:02X}{:02X}{:02X}{:02X}", id[0], id[1], id[2], id[3]) + } + } +} + +/// Parses the metadata from a DSDIFF file. +pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Error> { + if bytes.len() < 16 { + return Err(Error::UnexpectedEof("DSDIFF file is too short")); + } + + if &bytes[0..4] != b"FRM8" { + return Err(Error::InvalidHeader("missing 'FRM8' magic chunk")); + } + let form_size = u64::from_be_bytes(bytes[4..12].try_into().map_err(|_| Error::UnexpectedEof("FRM8 size"))?); + if &bytes[12..16] != b"DSD " { + return Err(Error::InvalidHeader("invalid FRM8 form type (expected 'DSD ')")); + } + + let total_file_data = bytes.len().saturating_sub(12); + if (form_size as usize) > total_file_data { + return Err(Error::UnexpectedEof("FRM8 chunk extends beyond file size")); + } + + let mut pos = 16; + let end = (12 + form_size as usize).min(bytes.len()); + + let mut sample_rate = None; + let mut channel_names = Vec::new(); + let mut num_channels = None; + let mut is_compressed_dst = false; + let mut dsd_data_offset = None; + let mut dsd_data_len = None; + let mut title = None; + let mut artist = None; + + while pos + 12 <= end { + let chunk_id: [u8; 4] = bytes[pos..pos + 4].try_into().map_err(|_| Error::UnexpectedEof("chunk ID"))?; + let chunk_size = u64::from_be_bytes(bytes[pos + 4..pos + 12].try_into().map_err(|_| Error::UnexpectedEof("chunk size"))?) as usize; + pos += 12; + + if pos + chunk_size > end { + return Err(Error::UnexpectedEof("subchunk extends beyond container bounds")); + } + + let chunk_data = &bytes[pos..pos + chunk_size]; + let pad = chunk_size & 1; + pos = pos.saturating_add(chunk_size).saturating_add(pad); + + match &chunk_id { + b"PROP" => { + if chunk_data.len() < 4 { + continue; + } + if &chunk_data[0..4] != b"SND " { + continue; + } + let mut prop_pos = 4; + while prop_pos + 12 <= chunk_data.len() { + let sub_id: [u8; 4] = chunk_data[prop_pos..prop_pos + 4].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk ID"))?; + let sub_size = u64::from_be_bytes( + chunk_data[prop_pos + 4..prop_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk size"))?, + ) as usize; + prop_pos += 12; + + if prop_pos + sub_size > chunk_data.len() { + return Err(Error::UnexpectedEof("PROP subchunk extends beyond bounds")); + } + + let sub_data = &chunk_data[prop_pos..prop_pos + sub_size]; + let sub_pad = sub_size & 1; + prop_pos = prop_pos.saturating_add(sub_size).saturating_add(sub_pad); + + match &sub_id { + b"FS " => { + if sub_data.len() >= 4 { + sample_rate = Some(u32::from_be_bytes([sub_data[0], sub_data[1], sub_data[2], sub_data[3]])); + } + } + b"CHNL" => { + if sub_data.len() >= 2 { + let n = u16::from_be_bytes([sub_data[0], sub_data[1]]); + num_channels = Some(n); + let mut ch_pos = 2; + while ch_pos + 4 <= sub_data.len() && channel_names.len() < n as usize { + let id: [u8; 4] = [sub_data[ch_pos], sub_data[ch_pos + 1], sub_data[ch_pos + 2], sub_data[ch_pos + 3]]; + channel_names.push(channel_id_to_name(&id)); + ch_pos += 4; + } + } + } + b"CMPR" if sub_data.len() >= 4 => { + if &sub_data[0..4] == b"DST " { + is_compressed_dst = true; + } else if &sub_data[0..4] != b"DSD " { + return Err(Error::Unsupported("unknown DSDIFF compression type")); + } + } + _ => {} + } + } + } + b"DSD " => { + dsd_data_offset = Some(pos - chunk_size - pad); + dsd_data_len = Some(chunk_size); + } + b"DST " => { + is_compressed_dst = true; + } + b"DIIN" => { + // Parse optional disc info for title and artist. + let mut diin_pos = 0; + while diin_pos + 12 <= chunk_data.len() { + let sub_id = &chunk_data[diin_pos..diin_pos + 4]; + let sub_size = u64::from_be_bytes( + chunk_data[diin_pos + 4..diin_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("DIIN subchunk size"))?, + ) as usize; + diin_pos += 12; + if diin_pos + sub_size > chunk_data.len() { + break; + } + let sub_data = &chunk_data[diin_pos..diin_pos + sub_size]; + let sub_pad = sub_size & 1; + diin_pos = diin_pos.saturating_add(sub_size).saturating_add(sub_pad); + + if sub_id == b"DITI" && title.is_none() { + title = Some(String::from_utf8_lossy(sub_data).trim().to_string()); + } else if sub_id == b"DIAR" && artist.is_none() { + artist = Some(String::from_utf8_lossy(sub_data).trim().to_string()); + } + } + } + _ => {} + } + } + + if is_compressed_dst { + return Err(Error::Unsupported("DST compression in DSDIFF is not yet supported")); + } + + let sample_rate = sample_rate.ok_or(Error::InvalidHeader("missing sample rate ('FS ' chunk)"))?; + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidHeader("sampling frequency out of range")); + } + + let channels = num_channels.ok_or(Error::InvalidHeader("missing channel info ('CHNL' chunk)"))?; + if channels == 0 || channels > MAX_CHANNELS as u16 { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + + let data_offset = dsd_data_offset.ok_or(Error::InvalidHeader("missing audio data ('DSD ' chunk)"))?; + let data_len = dsd_data_len.ok_or(Error::InvalidHeader("missing audio data length"))?; + + let bytes_per_channel = data_len / (channels as usize); + let sample_count = (bytes_per_channel as u64).saturating_mul(8); + + if channel_names.len() < channels as usize { + for c in channel_names.len()..(channels as usize) { + channel_names.push(format!("Channel {}", c + 1)); + } + } + + let metadata = Metadata { format: Format::Dsdiff, sample_rate, channels, sample_count, channel_names, title, artist }; + + Ok((metadata, data_offset, data_len)) +} + +/// Parses a DSDIFF file into raw 1-bit planar channel streams. +pub fn parse_dsdiff(bytes: &[u8]) -> Result { + let (metadata, data_offset, data_len) = parse_dsdiff_header(bytes)?; + let channels = metadata.channels as usize; + let bytes_per_channel = data_len / channels; + + if bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES { + return Err(Error::MemoryLimitExceeded); + } + + let end_offset = data_offset + data_len; + if end_offset > bytes.len() { + return Err(Error::UnexpectedEof("DSD sound data extends beyond file bounds")); + } + let data_slice = &bytes[data_offset..end_offset]; + + let mut channel_bytes: Vec> = Vec::with_capacity(channels); + for _ in 0..channels { + let mut ch_vec = Vec::new(); + ch_vec.try_reserve_exact(bytes_per_channel).map_err(|_| Error::MemoryLimitExceeded)?; + channel_bytes.push(ch_vec); + } + + // De-interleave byte-by-byte: Ch0, Ch1, ... Ch(N-1), Ch0, Ch1 ... + for chunk in data_slice.chunks_exact(channels) { + for (c, &byte) in chunk.iter().enumerate() { + if let Some(ch_vec) = channel_bytes.get_mut(c) { + ch_vec.push(byte); + } + } + } + + Ok(RawAudio { metadata, bit_order: BitOrder::MsbFirst, channel_bytes }) +} + +/// Encodes 1-bit planar audio channels into a valid Philips DSDIFF (`.dff`) file. +pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result, Error> { + if channels.is_empty() || channels.len() > MAX_CHANNELS { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidData("sample rate out of bounds")); + } + + let num_channels = channels.len(); + let bytes_per_ch = sample_count.div_ceil(8) as usize; + let data_size = bytes_per_ch.saturating_mul(num_channels); + + // Build PROP subchunks: + // 1. 'FS ' (4 bytes + 12 chunk header) + let mut fs_chunk = Vec::with_capacity(16); + fs_chunk.extend_from_slice(b"FS "); + fs_chunk.extend_from_slice(&4u64.to_be_bytes()); + fs_chunk.extend_from_slice(&sample_rate.to_be_bytes()); + + // 2. 'CHNL' (2 + 4 * num_channels + 12 chunk header) + let chnl_data_len = 2 + 4 * num_channels; + let mut chnl_chunk = Vec::with_capacity(12 + chnl_data_len + 1); + chnl_chunk.extend_from_slice(b"CHNL"); + chnl_chunk.extend_from_slice(&(chnl_data_len as u64).to_be_bytes()); + chnl_chunk.extend_from_slice(&(num_channels as u16).to_be_bytes()); + for c in 0..num_channels { + let code = match (num_channels, c) { + (1, 0) => b"SLFT", + (2, 0) => b"SLFT", + (2, 1) => b"SRGT", + (_, 0) => b"MLFT", + (_, 1) => b"MRGT", + (_, 2) => b"C ", + (_, 3) => b"LFE ", + _ => b"C ", + }; + chnl_chunk.extend_from_slice(code); + } + if !chnl_data_len.is_multiple_of(2) { + chnl_chunk.push(0); + } + + // 3. 'CMPR' (4 + 1 + 3 + pad = 8 bytes + 12 chunk header) + let mut cmpr_chunk = Vec::with_capacity(20); + cmpr_chunk.extend_from_slice(b"CMPR"); + cmpr_chunk.extend_from_slice(&8u64.to_be_bytes()); + cmpr_chunk.extend_from_slice(b"DSD "); + cmpr_chunk.push(3); // name len + cmpr_chunk.extend_from_slice(b"DSD"); + + let prop_payload_len = 4 + fs_chunk.len() + chnl_chunk.len() + cmpr_chunk.len(); + let mut prop_chunk = Vec::with_capacity(12 + prop_payload_len); + prop_chunk.extend_from_slice(b"PROP"); + prop_chunk.extend_from_slice(&(prop_payload_len as u64).to_be_bytes()); + prop_chunk.extend_from_slice(b"SND "); + prop_chunk.extend_from_slice(&fs_chunk); + prop_chunk.extend_from_slice(&chnl_chunk); + prop_chunk.extend_from_slice(&cmpr_chunk); + + // FVER chunk (4 bytes payload + 12 chunk header) + let mut fver_chunk = Vec::with_capacity(16); + fver_chunk.extend_from_slice(b"FVER"); + fver_chunk.extend_from_slice(&4u64.to_be_bytes()); + fver_chunk.extend_from_slice(&0x01050000u32.to_be_bytes()); + + // DSD chunk (data_size payload + 12 chunk header) + let mut dsd_chunk_hdr = Vec::with_capacity(12); + dsd_chunk_hdr.extend_from_slice(b"DSD "); + dsd_chunk_hdr.extend_from_slice(&(data_size as u64).to_be_bytes()); + + let frm8_payload_len = 4 + fver_chunk.len() + prop_chunk.len() + dsd_chunk_hdr.len() + data_size; + let mut out = Vec::new(); + out.try_reserve_exact(12 + frm8_payload_len).map_err(|_| Error::MemoryLimitExceeded)?; + + out.extend_from_slice(b"FRM8"); + out.extend_from_slice(&(frm8_payload_len as u64).to_be_bytes()); + out.extend_from_slice(b"DSD "); + out.extend_from_slice(&fver_chunk); + out.extend_from_slice(&prop_chunk); + out.extend_from_slice(&dsd_chunk_hdr); + + // Interleave channels byte-by-byte. + for i in 0..bytes_per_ch { + for ch_data in channels { + let byte = ch_data.get(i).copied().unwrap_or(super::filter::SILENCE_MSBF); + out.push(byte); + } + } + + Ok(out) +} diff --git a/crates/audio/src/dsd/dsf.rs b/crates/audio/src/dsd/dsf.rs new file mode 100644 index 0000000000..4b1c1f003f --- /dev/null +++ b/crates/audio/src/dsd/dsf.rs @@ -0,0 +1,323 @@ +//! Sony DSF (Direct Stream Digital File) parser and writer. +//! +//! A DSF file consists of three contiguous little-endian chunks: +//! - `'DSD '` chunk (28 bytes): file identification, total size, and metadata offset. +//! - `'fmt '` chunk (52 bytes): sample rate, channel count, sample count, block size. +//! - `'data'` chunk (12 bytes + data): 1-bit audio organized into channel blocks. +//! - Optional ID3v2 metadata chunk located at `metadata_offset`. + +use super::{BitOrder, Error, Format, MAX_BLOCK_SIZE, MAX_CHANNELS, MAX_DECODE_BYTES, MAX_SAMPLE_RATE, MIN_SAMPLE_RATE, Metadata, RawAudio}; + +/// Channel configuration names for DSF channel types 1..=7. +fn dsf_channel_names(channel_type: u32, channel_count: u16) -> Vec { + match channel_type { + 1 => vec!["Mono".to_string()], + 2 => vec!["Left".to_string(), "Right".to_string()], + 3 => vec!["Left".to_string(), "Right".to_string(), "Center".to_string()], + 4 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "BackLeft".to_string(), "BackRight".to_string()], + 5 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "Surround".to_string()], + 6 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "BackLeft".to_string(), "BackRight".to_string()], + 7 => vec![ + "FrontLeft".to_string(), + "FrontRight".to_string(), + "Center".to_string(), + "LFE".to_string(), + "BackLeft".to_string(), + "BackRight".to_string(), + ], + _ => (0..channel_count).map(|c| format!("Channel {}", c + 1)).collect(), + } +} + +/// Attempts to parse basic ID3v2 title and artist tags if present at `offset`. +fn parse_id3v2(bytes: &[u8], offset: usize) -> (Option, Option) { + let Some(id3) = bytes.get(offset..) else { + return (None, None); + }; + if id3.len() < 10 || &id3[..3] != b"ID3" { + return (None, None); + } + + let mut title = None; + let mut artist = None; + + // ID3v2 size is 4 synchsafe bytes at offset 6. + let tag_size = ((id3[6] as usize & 0x7F) << 21) | ((id3[7] as usize & 0x7F) << 14) | ((id3[8] as usize & 0x7F) << 7) | (id3[9] as usize & 0x7F); + + let end = (10 + tag_size).min(id3.len()); + let mut pos = 10; + + // Scan ID3v2.3 / ID3v2.4 frames. + while pos + 10 <= end { + let frame_id = &id3[pos..pos + 4]; + if frame_id[0] == 0 { + break; + } + let frame_size = u32::from_be_bytes([id3[pos + 4], id3[pos + 5], id3[pos + 6], id3[pos + 7]]) as usize; + pos += 10; + if pos + frame_size > end { + break; + } + + let frame_data = &id3[pos..pos + frame_size]; + pos += frame_size; + + if frame_id == b"TIT2" && title.is_none() { + title = parse_text_frame(frame_data); + } else if frame_id == b"TPE1" && artist.is_none() { + artist = parse_text_frame(frame_data); + } + } + + (title, artist) +} + +fn parse_text_frame(data: &[u8]) -> Option { + if data.is_empty() { + return None; + } + let encoding = data[0]; + let content = &data[1..]; + match encoding { + 0 | 3 => { + // ISO-8859-1 or UTF-8 + let s = String::from_utf8_lossy(content).trim_end_matches('\0').trim().to_string(); + if s.is_empty() { None } else { Some(s) } + } + 1 | 2 => { + // UTF-16 with BOM or UTF-16BE + if content.len() < 2 { + return None; + } + let u16s: Vec = content.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + let s = String::from_utf16_lossy(&u16s).trim_end_matches('\0').trim().to_string(); + if s.is_empty() { None } else { Some(s) } + } + _ => None, + } +} + +/// Parses DSF file metadata, returning the metadata, audio data offset, and block size per channel. +pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> { + if bytes.len() < 28 + 52 + 12 { + return Err(Error::UnexpectedEof("DSF file header is truncated")); + } + + // 1. 'DSD ' chunk + if &bytes[..4] != b"DSD " { + return Err(Error::InvalidHeader("missing 'DSD ' magic header")); + } + let dsd_chunk_size = u64::from_le_bytes(bytes[4..12].try_into().map_err(|_| Error::UnexpectedEof("DSD chunk size"))?); + if dsd_chunk_size != 28 { + return Err(Error::InvalidHeader("invalid 'DSD ' chunk size (must be 28)")); + } + let _file_size = u64::from_le_bytes(bytes[12..20].try_into().map_err(|_| Error::UnexpectedEof("file size"))?); + let metadata_offset = u64::from_le_bytes(bytes[20..28].try_into().map_err(|_| Error::UnexpectedEof("metadata offset"))?); + + // 2. 'fmt ' chunk + let fmt_offset = 28; + if &bytes[fmt_offset..fmt_offset + 4] != b"fmt " { + return Err(Error::InvalidHeader("missing 'fmt ' chunk header")); + } + let fmt_chunk_size = u64::from_le_bytes(bytes[fmt_offset + 4..fmt_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("fmt chunk size"))?); + if fmt_chunk_size < 52 { + return Err(Error::InvalidHeader("invalid 'fmt ' chunk size (must be at least 52)")); + } + let fmt_size = usize::try_from(fmt_chunk_size).map_err(|_| Error::MemoryLimitExceeded)?; + if bytes.len() < fmt_offset + fmt_size + 12 { + return Err(Error::UnexpectedEof("fmt chunk extends beyond file bounds")); + } + + let format_version = u32::from_le_bytes(bytes[fmt_offset + 12..fmt_offset + 16].try_into().map_err(|_| Error::UnexpectedEof("format version"))?); + if format_version != 1 { + return Err(Error::Unsupported("unsupported DSF format version (only version 1 is supported)")); + } + + let format_id = u32::from_le_bytes(bytes[fmt_offset + 16..fmt_offset + 20].try_into().map_err(|_| Error::UnexpectedEof("format id"))?); + if format_id != 0 { + return Err(Error::Unsupported("unsupported DSF format id (only raw DSD id=0 is supported)")); + } + + let channel_type = u32::from_le_bytes(bytes[fmt_offset + 20..fmt_offset + 24].try_into().map_err(|_| Error::UnexpectedEof("channel type"))?); + let channel_count = u32::from_le_bytes(bytes[fmt_offset + 24..fmt_offset + 28].try_into().map_err(|_| Error::UnexpectedEof("channel count"))?); + if channel_count == 0 || channel_count > MAX_CHANNELS as u32 { + return Err(Error::Unsupported("DSF channel count must be between 1 and 8")); + } + let channels = channel_count as u16; + + let sample_rate = u32::from_le_bytes(bytes[fmt_offset + 28..fmt_offset + 32].try_into().map_err(|_| Error::UnexpectedEof("sampling frequency"))?); + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidHeader("DSF sampling frequency out of valid range")); + } + + let bits_per_sample = + u32::from_le_bytes(bytes[fmt_offset + 32..fmt_offset + 36].try_into().map_err(|_| Error::UnexpectedEof("bits per sample"))?); + if bits_per_sample != 1 { + return Err(Error::Unsupported("DSF bits per sample must be 1")); + } + + let sample_count = u64::from_le_bytes(bytes[fmt_offset + 36..fmt_offset + 44].try_into().map_err(|_| Error::UnexpectedEof("sample count"))?); + + let block_size_per_channel = + u32::from_le_bytes(bytes[fmt_offset + 44..fmt_offset + 48].try_into().map_err(|_| Error::UnexpectedEof("block size per channel"))?); + if block_size_per_channel == 0 || block_size_per_channel > MAX_BLOCK_SIZE { + return Err(Error::InvalidHeader("DSF block size per channel is invalid or too large")); + } + + // 3. 'data' chunk + let data_offset = fmt_offset + fmt_size; + if &bytes[data_offset..data_offset + 4] != b"data" { + return Err(Error::InvalidHeader("missing 'data' chunk header")); + } + let data_chunk_size = + u64::from_le_bytes(bytes[data_offset + 4..data_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("data chunk size"))?); + if data_chunk_size < 12 { + return Err(Error::InvalidHeader("invalid 'data' chunk size (must be at least 12)")); + } + + let payload_offset = data_offset + 12; + let payload_size = (data_chunk_size - 12) as usize; + if bytes.len() < payload_offset + payload_size { + return Err(Error::UnexpectedEof("data chunk payload extends beyond file bounds")); + } + + // Parse ID3v2 metadata if pointer is valid. + let (title, artist) = + if metadata_offset > 0 && metadata_offset < bytes.len() as u64 { parse_id3v2(bytes, metadata_offset as usize) } else { (None, None) }; + + let channel_names = dsf_channel_names(channel_type, channels); + + let metadata = Metadata { format: Format::Dsf, sample_rate, channels, sample_count, channel_names, title, artist }; + + Ok((metadata, payload_offset, block_size_per_channel)) +} + +/// Parses a DSF file into raw 1-bit planar channel streams. +pub fn parse_dsf(bytes: &[u8]) -> Result { + let (metadata, payload_offset, block_size) = parse_dsf_header(bytes)?; + let block_size = block_size as usize; + let channels = metadata.channels as usize; + + let target_bytes_per_channel = metadata.sample_count.div_ceil(8) as usize; + if target_bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES { + return Err(Error::MemoryLimitExceeded); + } + + let slice_size = channels.saturating_mul(block_size); + if slice_size == 0 { + return Err(Error::InvalidHeader("zero slice size")); + } + + let payload = &bytes[payload_offset..]; + let num_slices = payload.len() / slice_size; + + let mut channel_bytes: Vec> = Vec::with_capacity(channels); + for _ in 0..channels { + let mut ch_vec = Vec::new(); + ch_vec.try_reserve_exact(target_bytes_per_channel).map_err(|_| Error::MemoryLimitExceeded)?; + channel_bytes.push(ch_vec); + } + + for s in 0..num_slices { + let slice_base = s * slice_size; + for (c, ch_vec) in channel_bytes.iter_mut().enumerate() { + let ch_start = slice_base + c * block_size; + let ch_end = ch_start + block_size; + if let Some(block) = payload.get(ch_start..ch_end) { + let remaining = target_bytes_per_channel.saturating_sub(ch_vec.len()); + let take = block.len().min(remaining); + ch_vec.extend_from_slice(&block[..take]); + } + } + } + + // Handle any trailing partial slice. + let remainder = payload.len() % slice_size; + if remainder > 0 { + let slice_base = num_slices * slice_size; + for (c, ch_vec) in channel_bytes.iter_mut().enumerate() { + let ch_start = slice_base + c * block_size; + if ch_start < payload.len() { + let ch_end = (ch_start + block_size).min(payload.len()); + let block = &payload[ch_start..ch_end]; + let remaining = target_bytes_per_channel.saturating_sub(ch_vec.len()); + let take = block.len().min(remaining); + ch_vec.extend_from_slice(&block[..take]); + } + } + } + + // Pad with silence (0x69) if the file had fewer bytes than required by sample_count. + for ch_vec in &mut channel_bytes { + if ch_vec.len() < target_bytes_per_channel { + ch_vec.resize(target_bytes_per_channel, super::filter::SILENCE_LSBF); + } + } + + Ok(RawAudio { metadata, bit_order: BitOrder::LsbFirst, channel_bytes }) +} + +/// Encodes 1-bit planar audio channels into a valid Sony DSF file. +pub fn write_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result, Error> { + if channels.is_empty() || channels.len() > MAX_CHANNELS { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { + return Err(Error::InvalidData("sample rate out of bounds")); + } + let block_size = if block_size == 0 { 4096 } else { block_size as usize }; + + let num_channels = channels.len(); + let bytes_per_ch = sample_count.div_ceil(8) as usize; + let num_blocks = bytes_per_ch.div_ceil(block_size); + let payload_size = num_blocks.saturating_mul(num_channels).saturating_mul(block_size); + + let data_chunk_size = 12u64.saturating_add(payload_size as u64); + let file_size = 28u64 + 52u64 + data_chunk_size; + + let mut out = Vec::new(); + out.try_reserve_exact(file_size as usize).map_err(|_| Error::MemoryLimitExceeded)?; + + // 1. 'DSD ' chunk (28 bytes) + out.extend_from_slice(b"DSD "); + out.extend_from_slice(&28u64.to_le_bytes()); + out.extend_from_slice(&file_size.to_le_bytes()); + out.extend_from_slice(&0u64.to_le_bytes()); // metadata offset = 0 + + // 2. 'fmt ' chunk (52 bytes) + out.extend_from_slice(b"fmt "); + out.extend_from_slice(&52u64.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); // format_version = 1 + out.extend_from_slice(&0u32.to_le_bytes()); // format_id = 0 (raw DSD) + let channel_type = if num_channels == 1 { 1u32 } else { 2u32 }; + out.extend_from_slice(&channel_type.to_le_bytes()); + out.extend_from_slice(&(num_channels as u32).to_le_bytes()); + out.extend_from_slice(&sample_rate.to_le_bytes()); + out.extend_from_slice(&1u32.to_le_bytes()); // bits_per_sample = 1 + out.extend_from_slice(&sample_count.to_le_bytes()); + out.extend_from_slice(&(block_size as u32).to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); // reserved + + // 3. 'data' chunk + out.extend_from_slice(b"data"); + out.extend_from_slice(&data_chunk_size.to_le_bytes()); + + for b in 0..num_blocks { + let blk_start = b * block_size; + let blk_end = blk_start + block_size; + for ch_data in channels { + let available = if blk_start < ch_data.len() { + let end = blk_end.min(ch_data.len()); + &ch_data[blk_start..end] + } else { + &[] + }; + out.extend_from_slice(available); + if available.len() < block_size { + out.resize(out.len() + (block_size - available.len()), super::filter::SILENCE_LSBF); + } + } + } + + Ok(out) +} diff --git a/crates/audio/src/dsd/filter.rs b/crates/audio/src/dsd/filter.rs new file mode 100644 index 0000000000..3e39050e07 --- /dev/null +++ b/crates/audio/src/dsd/filter.rs @@ -0,0 +1,216 @@ +//! DSD-to-PCM decimation filter. +//! +//! Direct Stream Digital (DSD) uses 1-bit Sigma-Delta modulation sampled at high rates +//! (2,822,400 Hz for DSD64, 5,644,800 Hz for DSD128, etc.). Decimation to multi-bit PCM +//! involves low-pass filtering to attenuate high-frequency quantization noise followed +//! by downsampling. +//! +//! This module provides a 96-tap symmetric FIR decimation filter that downsamples 1-bit DSD +//! to multi-bit PCM at 1/8th of the DSD sampling rate (e.g. 352,800 Hz for DSD64). Further +//! integer decimation (to 176.4 kHz, 88.2 kHz, or 44.1 kHz) is supported via subsequent +//! downsampling stages. + +use super::{BitOrder, Error, MAX_DECODE_BYTES}; + +/// 96-tap symmetric FIR decimation filter coefficients for decimation by 8. +/// +/// Output is normalized so that alternating silence bits (0x69 or 0xAA) decode near 0.0, +/// and full-scale runs of 1s or 0s decode near +1.0 and -1.0. +#[allow(clippy::excessive_precision)] +pub const TAPS_96: [f32; 96] = [ + 2.9802322388e-08_f32, + 1.1920928955e-07_f32, + 3.5762786865e-07_f32, + 7.4505805969e-07_f32, + 1.3113021851e-06_f32, + 1.9371509552e-06_f32, + 2.1755695343e-06_f32, + 1.2516975403e-06_f32, + -1.9967556000e-06_f32, + -9.1493129730e-06_f32, + -2.1725893021e-05_f32, + -4.0739774704e-05_f32, + -6.5773725510e-05_f32, + -9.3966722488e-05_f32, + -1.1900067329e-04_f32, + -1.3050436974e-04_f32, + -1.1405348778e-04_f32, + -5.2779912949e-05_f32, + 7.0035457611e-05_f32, + 2.6643276215e-04_f32, + 5.3817033768e-04_f32, + 8.7043642998e-04_f32, + 1.2266933918e-03_f32, + 1.5456080437e-03_f32, + 1.7420351505e-03_f32, + 1.7137229443e-03_f32, + 1.3538300991e-03_f32, + 5.7008862495e-04_f32, + -6.9221854210e-04_f32, + -2.4250447750e-03_f32, + -4.5351684093e-03_f32, + -6.8288743496e-03_f32, + -9.0079009533e-03_f32, + -1.0681360960e-02_f32, + -1.1394292116e-02_f32, + -1.0672420263e-02_f32, + -8.0802738667e-03_f32, + -3.2847225666e-03_f32, + 3.8830339909e-03_f32, + 1.3377487659e-02_f32, + 2.4909228086e-02_f32, + 3.7942945957e-02_f32, + 5.1726281643e-02_f32, + 6.5348774195e-02_f32, + 7.7825516462e-02_f32, + 8.8196486235e-02_f32, + 9.5628470182e-02_f32, + 9.9507331848e-02_f32, + 9.9507331848e-02_f32, + 9.5628470182e-02_f32, + 8.8196486235e-02_f32, + 7.7825516462e-02_f32, + 6.5348774195e-02_f32, + 5.1726281643e-02_f32, + 3.7942945957e-02_f32, + 2.4909228086e-02_f32, + 1.3377487659e-02_f32, + 3.8830339909e-03_f32, + -3.2847225666e-03_f32, + -8.0802738667e-03_f32, + -1.0672420263e-02_f32, + -1.1394292116e-02_f32, + -1.0681360960e-02_f32, + -9.0079009533e-03_f32, + -6.8288743496e-03_f32, + -4.5351684093e-03_f32, + -2.4250447750e-03_f32, + -6.9221854210e-04_f32, + 5.7008862495e-04_f32, + 1.3538300991e-03_f32, + 1.7137229443e-03_f32, + 1.7420351505e-03_f32, + 1.5456080437e-03_f32, + 1.2266933918e-03_f32, + 8.7043642998e-04_f32, + 5.3817033768e-04_f32, + 2.6643276215e-04_f32, + 7.0035457611e-05_f32, + -5.2779912949e-05_f32, + -1.1405348778e-04_f32, + -1.3050436974e-04_f32, + -1.1900067329e-04_f32, + -9.3966722488e-05_f32, + -6.5773725510e-05_f32, + -4.0739774704e-05_f32, + -2.1725893021e-05_f32, + -9.1493129730e-06_f32, + -1.9967556000e-06_f32, + 1.2516975403e-06_f32, + 2.1755695343e-06_f32, + 1.9371509552e-06_f32, + 1.3113021851e-06_f32, + 7.4505805969e-07_f32, + 3.5762786865e-07_f32, + 1.1920928955e-07_f32, + 2.9802322388e-08_f32, +]; + +/// The number of filter history bytes (96 taps / 8 bits per byte = 12 bytes). +pub const FILTER_BYTES: usize = 12; + +/// Standard DSD silence pattern byte for LSB-first ordering (Sony DSF). +pub const SILENCE_LSBF: u8 = 0x69; + +/// Standard DSD silence pattern byte for MSB-first ordering (Philips DSDIFF). +pub const SILENCE_MSBF: u8 = 0xAA; + +/// Precomputes lookup table entries for byte position `k` (0..12) and byte value `v` (0..256). +/// +/// In LSB-first order, bit `b` of input byte `k` corresponds to tap `k * 8 + b`. +#[inline] +fn byte_lut(k: usize, byte_val: u8) -> f32 { + let mut sum = 0.0_f32; + let base_tap = k * 8; + for b in 0..8 { + if ((byte_val >> b) & 1) != 0 + && let Some(tap) = TAPS_96.get(base_tap + b) + { + sum += 2.0 * *tap; + } + } + sum +} + +/// Decimates 1-bit DSD audio bytes for a single channel to `f32` PCM. +/// +/// The default decimation factor is 8 (1 output float per input byte). +/// When `factor` is 16, 32, or 64, the 1/8 output is further downsampled +/// by 2, 4, or 8 respectively. +pub fn decimate_channel(channel_bytes: &[u8], bit_order: BitOrder, factor: u32) -> Result, Error> { + if !matches!(factor, 8 | 16 | 32 | 64) { + return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64")); + } + + let num_bytes = channel_bytes.len(); + if num_bytes.saturating_mul(std::mem::size_of::()) > MAX_DECODE_BYTES { + return Err(Error::MemoryLimitExceeded); + } + + // Build the 12 x 256 lookup table for fast convolution. + // 12 * 256 * 4 bytes = 12 KB, sits comfortably in L1 cache. + let mut lut = [[0.0_f32; 256]; FILTER_BYTES]; + for (k, lut_k) in lut.iter_mut().enumerate() { + for (v, cell) in lut_k.iter_mut().enumerate() { + *cell = byte_lut(k, v as u8); + } + } + + let mut stage1 = Vec::new(); + stage1.try_reserve_exact(num_bytes).map_err(|_| Error::MemoryLimitExceeded)?; + + // History buffer holds the most recent 12 bytes in LSB-first order. + // Pre-filled with silence (0x69). + let mut history = [SILENCE_LSBF; FILTER_BYTES]; + + for &raw_byte in channel_bytes { + let byte = match bit_order { + BitOrder::LsbFirst => raw_byte, + BitOrder::MsbFirst => raw_byte.reverse_bits(), + }; + + // Shift history left by 1 and push current byte to the end. + history.copy_within(1.., 0); + if let Some(last) = history.last_mut() { + *last = byte; + } + + let mut sample = -1.0_f32; + for (k, &hist_byte) in history.iter().enumerate() { + if let Some(lut_k) = lut.get(k) + && let Some(&contrib) = lut_k.get(hist_byte as usize) + { + sample += contrib; + } + } + + stage1.push(sample); + } + + if factor == 8 { + return Ok(stage1); + } + + // Secondary downsampling by ratio = factor / 8 (2, 4, or 8). + let ratio = (factor / 8) as usize; + let out_len = stage1.len() / ratio; + let mut out = Vec::new(); + out.try_reserve_exact(out_len).map_err(|_| Error::MemoryLimitExceeded)?; + + for chunk in stage1.chunks_exact(ratio) { + let sum: f32 = chunk.iter().sum(); + out.push(sum / ratio as f32); + } + + Ok(out) +} diff --git a/crates/audio/src/dsd/mod.rs b/crates/audio/src/dsd/mod.rs new file mode 100644 index 0000000000..38f89de7c4 --- /dev/null +++ b/crates/audio/src/dsd/mod.rs @@ -0,0 +1,221 @@ +//! Direct Stream Digital (DSD) audio: Sony DSF and Philips DSDIFF (`.dff`) readers and +//! DSD-to-PCM decimation. +//! +//! DSD stores 1-bit Pulse Density Modulation (PDM) sampled at high rates (e.g. 2,822,400 Hz +//! for DSD64, 5,644,800 Hz for DSD128, etc.). +//! +//! This module provides: +//! - File parsers for Sony DSF (`.dsf`) and Philips DSDIFF (`.dff`) containers. +//! - Raw 1-bit audio extraction with preservation of native bit ordering (LSB-first for DSF, +//! MSB-first for DSDIFF). +//! - Clean-room 96-tap symmetric FIR decimation filter converting 1-bit PDM to multi-bit PCM +//! (decimation by 8 to 352,800 Hz for DSD64, or downsampled to 176.4, 88.2, or 44.1 kHz). +//! - Reference encoders for generating synthetic DSF and DSDIFF files. + +pub mod dsdiff; +pub mod dsf; +pub mod filter; + +use crate::AudioBuffer; + +/// Maximum number of audio channels supported (1 to 8). +pub const MAX_CHANNELS: usize = 8; + +/// Minimum allowable DSD sample rate in Hz. +pub const MIN_SAMPLE_RATE: u32 = 44_100; + +/// Maximum allowable DSD sample rate in Hz (e.g. DSD1024 at 45.1584 MHz). +pub const MAX_SAMPLE_RATE: u32 = 45_158_400; + +/// Maximum safe block size for DSF channel blocks (16 MiB). +pub const MAX_BLOCK_SIZE: u32 = 16 * 1024 * 1024; + +/// Maximum safe memory allocation budget for decoded audio (256 MiB). +pub const MAX_DECODE_BYTES: usize = 256 * 1024 * 1024; + +/// Supported DSD container formats. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Format { + /// Sony DSF (Direct Stream Digital File) format. + Dsf, + /// Philips DSDIFF (Direct Stream Digital Interchange File Format, `.dff`). + Dsdiff, +} + +/// Bit ordering of 1-bit DSD audio samples within bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum BitOrder { + /// Least-significant bit first (LSB-first, as used in DSF). + /// Bit 0 is the earliest temporal sample; bit 7 is the latest. + LsbFirst, + /// Most-significant bit first (MSB-first, as used in DSDIFF). + /// Bit 7 is the earliest temporal sample; bit 0 is the latest. + MsbFirst, +} + +/// Stream properties and metadata parsed from a DSD container header. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Metadata { + /// Container format (DSF or DSDIFF). + pub format: Format, + /// DSD sampling frequency in Hz (e.g. 2,822,400 for DSD64). + pub sample_rate: u32, + /// Number of audio channels (1 to 8). + pub channels: u16, + /// Total number of 1-bit audio samples per channel. + pub sample_count: u64, + /// Channel identification labels (e.g. "SLFT", "SRGT", "Center"). + pub channel_names: Vec, + /// Optional track title if present in container metadata. + pub title: Option, + /// Optional artist name if present in container metadata. + pub artist: Option, +} + +/// Raw 1-bit DSD audio extracted from a file without decimation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RawAudio { + /// Stream metadata from the file header. + pub metadata: Metadata, + /// Bit ordering of the bytes in `channel_bytes`. + pub bit_order: BitOrder, + /// Planar 1-bit audio bytes per channel. + pub channel_bytes: Vec>, +} + +impl RawAudio { + /// Converts all channel byte streams to the requested bit ordering in place. + pub fn convert_bit_order(&mut self, target: BitOrder) { + if self.bit_order == target { + return; + } + for ch in &mut self.channel_bytes { + for b in ch.iter_mut() { + *b = b.reverse_bits(); + } + } + self.bit_order = target; + } + + /// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples. + /// + /// The default decimation factor is 8 (e.g. 352,800 Hz for DSD64). + pub fn to_pcm(&self) -> Result { + self.to_pcm_with_factor(8) + } + + /// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples with the given factor (8, 16, 32, or 64). + pub fn to_pcm_with_factor(&self, factor: u32) -> Result { + let mut channels = Vec::with_capacity(self.channel_bytes.len()); + for ch_bytes in &self.channel_bytes { + let pcm = filter::decimate_channel(ch_bytes, self.bit_order, factor)?; + channels.push(pcm); + } + let sample_rate = self.metadata.sample_rate / factor; + Ok(DecodedAudio { metadata: self.metadata.clone(), sample_rate, channels }) + } +} + +/// Decoded multi-bit PCM audio produced by DSD-to-PCM decimation. +#[derive(Debug, Clone, PartialEq)] +pub struct DecodedAudio { + /// Stream metadata from the DSD file header. + pub metadata: Metadata, + /// PCM sample rate in Hz (e.g. 352,800 Hz for DSD64 decimated by 8). + pub sample_rate: u32, + /// Planar normalized PCM samples in `[-1.0, 1.0]`, one `Vec` per channel. + pub channels: Vec>, +} + +impl DecodedAudio { + /// Converts the decoded PCM audio into an [`AudioBuffer`]. + pub fn to_audio_buffer(&self) -> AudioBuffer { + AudioBuffer { sample_rate: self.sample_rate, channels: self.channels.clone() } + } +} + +/// Errors returned when parsing or decoding DSD audio. +#[non_exhaustive] +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum Error { + /// Input data ended prematurely while parsing a header or chunk. + #[error("unexpected end of file: {0}")] + UnexpectedEof(&'static str), + /// Invalid magic bytes or malformed chunk header. + #[error("invalid DSD header or chunk: {0}")] + InvalidHeader(&'static str), + /// An unsupported feature, compression, or channel configuration. + #[error("unsupported DSD feature: {0}")] + Unsupported(&'static str), + /// Audio data length or structure does not match the header specification. + #[error("invalid audio data: {0}")] + InvalidData(&'static str), + /// Header or data requested exceeds maximum safe allocation budget. + #[error("memory budget exceeded")] + MemoryLimitExceeded, +} + +/// Inspects the magic bytes of `bytes` and detects whether it is a DSF or DSDIFF file. +pub fn probe_format(bytes: &[u8]) -> Result { + if bytes.len() < 4 { + return Err(Error::UnexpectedEof("input is too short to determine DSD format")); + } + if &bytes[0..4] == b"DSD " { + Ok(Format::Dsf) + } else if bytes.len() >= 16 && &bytes[0..4] == b"FRM8" && &bytes[12..16] == b"DSD " { + Ok(Format::Dsdiff) + } else { + Err(Error::InvalidHeader("unknown or unsupported DSD container format")) + } +} + +/// Parses the metadata from a DSF or DSDIFF file without decoding audio samples. +pub fn read_metadata(bytes: &[u8]) -> Result { + match probe_format(bytes)? { + Format::Dsf => { + let (meta, _, _) = dsf::parse_dsf_header(bytes)?; + Ok(meta) + } + Format::Dsdiff => { + let (meta, _, _) = dsdiff::parse_dsdiff_header(bytes)?; + Ok(meta) + } + } +} + +/// Reads raw 1-bit planar audio streams from a DSF or DSDIFF file without decimation. +pub fn read_raw(bytes: &[u8]) -> Result { + match probe_format(bytes)? { + Format::Dsf => dsf::parse_dsf(bytes), + Format::Dsdiff => dsdiff::parse_dsdiff(bytes), + } +} + +/// Decodes a DSF or DSDIFF file to multi-bit planar `f32` PCM audio using decimation by 8. +/// +/// For DSD64 (2,822,400 Hz), the output sample rate is 352,800 Hz. +pub fn decode(bytes: &[u8]) -> Result { + decode_with_factor(bytes, 8) +} + +/// Decodes a DSF or DSDIFF file to multi-bit planar `f32` PCM audio with the specified decimation factor. +/// +/// Supported decimation factors are: +/// - 8: 1/8th of DSD rate (e.g. 352,800 Hz for DSD64). +/// - 16: 1/16th of DSD rate (e.g. 176,400 Hz for DSD64). +/// - 32: 1/32th of DSD rate (e.g. 88,200 Hz for DSD64). +/// - 64: 1/64th of DSD rate (e.g. 44,100 Hz for DSD64). +pub fn decode_with_factor(bytes: &[u8], factor: u32) -> Result { + let raw = read_raw(bytes)?; + raw.to_pcm_with_factor(factor) +} + +/// Encodes planar 1-bit audio channels into a Sony DSF file. +pub fn encode_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result, Error> { + dsf::write_dsf(sample_rate, channels, sample_count, block_size) +} + +/// Encodes planar 1-bit audio channels into a Philips DSDIFF file. +pub fn encode_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result, Error> { + dsdiff::write_dsdiff(sample_rate, channels, sample_count) +} diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 93fbec58d3..8dcde9b0f8 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -30,7 +30,8 @@ //! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`, and //! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`), [`mp3`] //! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder; -//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files). +//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files), +//! [`dsd`] (`dsd`: DSF and DSDIFF files to PCM). //! //! The shared types below build with no features. @@ -41,6 +42,8 @@ pub mod ac3; #[cfg(any(feature = "alac-decode", feature = "alac-encode"))] pub mod alac; mod buffer; +#[cfg(feature = "dsd")] +pub mod dsd; mod layout; #[cfg(any(feature = "mp3-encode", feature = "mp3-decode"))] pub mod mp3; diff --git a/crates/audio/tests/dsd_oracle.rs b/crates/audio/tests/dsd_oracle.rs new file mode 100644 index 0000000000..55d3fef979 --- /dev/null +++ b/crates/audio/tests/dsd_oracle.rs @@ -0,0 +1,345 @@ +//! DSD (DSF and DSDIFF) decoding and decimation tests, including oracle tests against FFmpeg +//! (skipped when ffmpeg is absent, a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). + +use craft_audio::dsd::{BitOrder, Format, decode, decode_with_factor, encode_dsdiff, encode_dsf, filter::SILENCE_LSBF, read_metadata, read_raw}; +use std::process::Command; + +/// Generates a test DSD 1-bit stream with various features (silence, alternating tones, noise). +fn make_test_stream(num_bytes: usize, seed: u8) -> Vec { + let mut out = Vec::with_capacity(num_bytes); + let mut s = seed as u32; + for i in 0..num_bytes { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + let byte = match (i / 128) % 4 { + 0 => SILENCE_LSBF, // DSD silence + 1 => 0x55, // Alternate silence pattern + 2 => (s & 0xFF) as u8, + _ => { + if (i / 16) % 2 == 0 { + 0xFF // full positive level + } else { + 0x00 // full negative level + } + } + }; + out.push(byte); + } + out +} + +#[test] +fn roundtrip_dsf() { + let sample_rate = 2_822_400; + let block_size = 4096; + let ch0 = make_test_stream(8192, 42); + let ch1 = make_test_stream(8192, 99); + let sample_count = 8192 * 8; + + let dsf_bytes = encode_dsf(sample_rate, &[&ch0, &ch1], sample_count, block_size).expect("encode_dsf"); + + let meta = read_metadata(&dsf_bytes).expect("read_metadata"); + assert_eq!(meta.format, Format::Dsf); + assert_eq!(meta.sample_rate, sample_rate); + assert_eq!(meta.channels, 2); + assert_eq!(meta.sample_count, sample_count); + + let raw = read_raw(&dsf_bytes).expect("read_raw"); + assert_eq!(raw.bit_order, BitOrder::LsbFirst); + assert_eq!(raw.channel_bytes.len(), 2); + assert_eq!(raw.channel_bytes[0], ch0); + assert_eq!(raw.channel_bytes[1], ch1); + + let decoded = decode(&dsf_bytes).expect("decode"); + assert_eq!(decoded.sample_rate, sample_rate / 8); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 8192); + assert_eq!(decoded.channels[1].len(), 8192); +} + +#[test] +fn roundtrip_dsdiff() { + let sample_rate = 2_822_400; + let ch0 = make_test_stream(4096, 17); + let ch1 = make_test_stream(4096, 73); + let sample_count = 4096 * 8; + + let dff_bytes = encode_dsdiff(sample_rate, &[&ch0, &ch1], sample_count).expect("encode_dsdiff"); + + let meta = read_metadata(&dff_bytes).expect("read_metadata"); + assert_eq!(meta.format, Format::Dsdiff); + assert_eq!(meta.sample_rate, sample_rate); + assert_eq!(meta.channels, 2); + assert_eq!(meta.sample_count, sample_count); + + let raw = read_raw(&dff_bytes).expect("read_raw"); + assert_eq!(raw.bit_order, BitOrder::MsbFirst); + assert_eq!(raw.channel_bytes.len(), 2); + assert_eq!(raw.channel_bytes[0], ch0); + assert_eq!(raw.channel_bytes[1], ch1); + + let decoded = decode(&dff_bytes).expect("decode"); + assert_eq!(decoded.sample_rate, sample_rate / 8); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 4096); + assert_eq!(decoded.channels[1].len(), 4096); +} + +#[test] +fn decimation_factors() { + let sample_rate = 2_822_400; + let ch0 = make_test_stream(2048, 123); + let dsf_bytes = encode_dsf(sample_rate, &[&ch0], 2048 * 8, 4096).expect("encode_dsf"); + + // Factor 8 -> 352,800 Hz + let dec8 = decode_with_factor(&dsf_bytes, 8).expect("factor 8"); + assert_eq!(dec8.sample_rate, 352_800); + assert_eq!(dec8.channels[0].len(), 2048); + + // Factor 16 -> 176,400 Hz + let dec16 = decode_with_factor(&dsf_bytes, 16).expect("factor 16"); + assert_eq!(dec16.sample_rate, 176_400); + assert_eq!(dec16.channels[0].len(), 1024); + + // Factor 32 -> 88,200 Hz + let dec32 = decode_with_factor(&dsf_bytes, 32).expect("factor 32"); + assert_eq!(dec32.sample_rate, 88_200); + assert_eq!(dec32.channels[0].len(), 512); + + // Factor 64 -> 44,100 Hz + let dec64 = decode_with_factor(&dsf_bytes, 64).expect("factor 64"); + assert_eq!(dec64.sample_rate, 44_100); + assert_eq!(dec64.channels[0].len(), 256); + + // Invalid factor + assert!(decode_with_factor(&dsf_bytes, 12).is_err()); +} + +#[test] +fn silence_and_dc_levels() { + let sample_rate = 2_822_400; + // Pure silence + let silence = vec![SILENCE_LSBF; 1024]; + let dsf_bytes = encode_dsf(sample_rate, &[&silence], 1024 * 8, 4096).expect("encode"); + let dec = decode(&dsf_bytes).expect("decode"); + for &sample in &dec.channels[0][12..] { + assert!(sample.abs() < 1e-4, "silence sample should be ~0.0, got {sample}"); + } + + // Full positive level + let ones = vec![0xFF; 1024]; + let dsf_ones = encode_dsf(sample_rate, &[&ones], 1024 * 8, 4096).expect("encode"); + let dec_ones = decode(&dsf_ones).expect("decode"); + for &sample in &dec_ones.channels[0][12..] { + assert!((sample - 1.0).abs() < 1e-4, "ones sample should be ~1.0, got {sample}"); + } + + // Full negative level + let zeros = vec![0x00; 1024]; + let dsf_zeros = encode_dsf(sample_rate, &[&zeros], 1024 * 8, 4096).expect("encode"); + let dec_zeros = decode(&dsf_zeros).expect("decode"); + for &sample in &dec_zeros.channels[0][12..] { + assert!((sample - (-1.0)).abs() < 1e-4, "zeros sample should be ~-1.0, got {sample}"); + } +} + +#[test] +fn multichannel_dsf_and_dsdiff() { + let sample_rate = 2_822_400; + // Test 6-channel (5.1 surround) + let channels: Vec> = (0..6).map(|c| make_test_stream(1024, (c * 23 + 5) as u8)).collect(); + let ch_refs: Vec<&[u8]> = channels.iter().map(Vec::as_slice).collect(); + + let dsf = encode_dsf(sample_rate, &ch_refs, 1024 * 8, 512).expect("encode 5.1 dsf"); + let dsf_meta = read_metadata(&dsf).expect("meta 5.1 dsf"); + assert_eq!(dsf_meta.channels, 6); + let dsf_dec = decode(&dsf).expect("decode 5.1 dsf"); + assert_eq!(dsf_dec.channels.len(), 6); + assert_eq!(dsf_dec.channels[0].len(), 1024); + + let dff = encode_dsdiff(sample_rate, &ch_refs, 1024 * 8).expect("encode 5.1 dsdiff"); + let dff_meta = read_metadata(&dff).expect("meta 5.1 dsdiff"); + assert_eq!(dff_meta.channels, 6); + let dff_dec = decode(&dff).expect("decode 5.1 dsdiff"); + assert_eq!(dff_dec.channels.len(), 6); + assert_eq!(dff_dec.channels[0].len(), 1024); +} + +#[test] +fn dst_compression_rejected() { + // Construct a minimal DSDIFF with CMPR = 'DST ' + let mut dff = encode_dsdiff(2_822_400, &[&[0xAA; 64]], 512).expect("encode"); + // Find 'DSD ' in CMPR chunk and replace with 'DST ' + let mut replaced = false; + for i in 0..dff.len().saturating_sub(8) { + if &dff[i..i + 4] == b"CMPR" && &dff[i + 12..i + 16] == b"DSD " { + dff[i + 12..i + 16].copy_from_slice(b"DST "); + replaced = true; + break; + } + } + assert!(replaced, "should find CMPR DSD chunk"); + assert!(read_metadata(&dff).is_err(), "DST compression should be rejected as unsupported"); + assert!(decode(&dff).is_err(), "DST compression should be rejected as unsupported"); +} + +#[test] +fn id3v2_tag_in_dsf() { + let sample_rate = 2_822_400; + let mut dsf = encode_dsf(sample_rate, &[&[0x69; 128]], 1024, 512).expect("encode"); + let metadata_offset = dsf.len() as u64; + + // Append simple ID3v2.3 tag with TIT2="Test Title" and TPE1="Test Artist" + let mut id3 = Vec::new(); + id3.extend_from_slice(b"ID3"); + id3.push(3); // v2.3 + id3.push(0); // revision + id3.push(0); // flags + + let mut frames = Vec::new(); + // TIT2 frame + frames.extend_from_slice(b"TIT2"); + let title_bytes = b"\x03DSD Master"; // UTF-8 + frames.extend_from_slice(&(title_bytes.len() as u32).to_be_bytes()); + frames.extend_from_slice(&[0, 0]); // flags + frames.extend_from_slice(title_bytes); + + // TPE1 frame + frames.extend_from_slice(b"TPE1"); + let artist_bytes = b"\x03The Audiophiles"; + frames.extend_from_slice(&(artist_bytes.len() as u32).to_be_bytes()); + frames.extend_from_slice(&[0, 0]); // flags + frames.extend_from_slice(artist_bytes); + + // synchsafe size + let tag_len = frames.len(); + id3.push(((tag_len >> 21) & 0x7F) as u8); + id3.push(((tag_len >> 14) & 0x7F) as u8); + id3.push(((tag_len >> 7) & 0x7F) as u8); + id3.push((tag_len & 0x7F) as u8); + id3.extend_from_slice(&frames); + + dsf.extend_from_slice(&id3); + // Update metadata_offset at offset 20 of 'DSD ' chunk + dsf[20..28].copy_from_slice(&metadata_offset.to_le_bytes()); + + let meta = read_metadata(&dsf).expect("read metadata with ID3"); + assert_eq!(meta.title.as_deref(), Some("DSD Master")); + assert_eq!(meta.artist.as_deref(), Some("The Audiophiles")); +} + +#[test] +fn raw_audio_bit_order_conversion() { + let ch0 = vec![0b00000001, 0b10000000]; + let dsf = encode_dsf(2_822_400, &[&ch0], 16, 512).expect("encode"); + let mut raw = read_raw(&dsf).expect("read raw"); + assert_eq!(raw.bit_order, BitOrder::LsbFirst); + assert_eq!(raw.channel_bytes[0], ch0); + + raw.convert_bit_order(BitOrder::MsbFirst); + assert_eq!(raw.bit_order, BitOrder::MsbFirst); + assert_eq!(raw.channel_bytes[0], vec![0b10000000, 0b00000001]); +} + +#[test] +fn hostile_inputs() { + // Truncated headers + assert!(read_metadata(b"").is_err()); + assert!(read_metadata(b"DSD ").is_err()); + assert!(read_metadata(b"FRM8").is_err()); + + // Bad magic + assert!(read_metadata(b"RIFF\x00\x00\x00\x00WAVE").is_err()); + + // Truncated DSF chunk + let mut bad_dsf = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode"); + bad_dsf.truncate(50); + assert!(decode(&bad_dsf).is_err()); + + // Corrupted fmt chunk size + let mut bad_fmt = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode"); + bad_fmt[32] = 0; // bits_per_sample = 0 + assert!(decode(&bad_fmt).is_err()); + + // Absurd channels + let mut bad_ch = encode_dsf(2_822_400, &[&[0x69; 100]], 800, 4096).expect("encode"); + bad_ch[28 + 24] = 99; // channel_count = 99 + assert!(decode(&bad_ch).is_err()); +} + +#[test] +fn ffmpeg_dsf_oracle() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("dsd"); + + let sample_rate = 2_822_400; + let block_size = 4096; + let ch0 = make_test_stream(16384, 11); + let ch1 = make_test_stream(16384, 88); + let sample_count = 16384 * 8; + + let dsf_bytes = encode_dsf(sample_rate, &[&ch0, &ch1], sample_count, block_size).expect("encode_dsf"); + let dsf_path = dir.join("test_oracle.dsf"); + std::fs::write(&dsf_path, &dsf_bytes).expect("write fixture"); + + let raw_out_path = dir.join("ffmpeg_dsf.raw"); + let status = Command::new(&ffmpeg).arg("-y").arg("-i").arg(&dsf_path).arg("-f").arg("f32le").arg(&raw_out_path).output().expect("run ffmpeg"); + assert!(status.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&status.stderr)); + + let raw_bytes = std::fs::read(&raw_out_path).expect("read raw"); + let ffmpeg_floats: Vec = raw_bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); + + let decoded = decode(&dsf_bytes).expect("our decode"); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 16384); + assert_eq!(decoded.channels[1].len(), 16384); + + // FFmpeg interleaves L0, R0, L1, R1... + // Compare samples after filter startup (sample 12 onwards). + for i in 12..16000 { + let ff_l = ffmpeg_floats[i * 2]; + let ff_r = ffmpeg_floats[i * 2 + 1]; + let our_l = decoded.channels[0][i]; + let our_r = decoded.channels[1][i]; + + assert!((ff_l - our_l).abs() < 1e-4, "sample {i} left mismatch: ffmpeg={ff_l}, ours={our_l}"); + assert!((ff_r - our_r).abs() < 1e-4, "sample {i} right mismatch: ffmpeg={ff_r}, ours={our_r}"); + } +} + +#[test] +fn ffmpeg_dsdiff_oracle() { + let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("dsd"); + + let sample_rate = 2_822_400; + let ch0 = make_test_stream(8192, 33); + let ch1 = make_test_stream(8192, 77); + let sample_count = 8192 * 8; + + let dff_bytes = encode_dsdiff(sample_rate, &[&ch0, &ch1], sample_count).expect("encode_dsdiff"); + let dff_path = dir.join("test_oracle.dff"); + std::fs::write(&dff_path, &dff_bytes).expect("write fixture"); + + let raw_out_path = dir.join("ffmpeg_dff.raw"); + let status = Command::new(&ffmpeg).arg("-y").arg("-i").arg(&dff_path).arg("-f").arg("f32le").arg(&raw_out_path).output().expect("run ffmpeg"); + assert!(status.status.success(), "ffmpeg failed: {}", String::from_utf8_lossy(&status.stderr)); + + let raw_bytes = std::fs::read(&raw_out_path).expect("read raw"); + let ffmpeg_floats: Vec = raw_bytes.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); + + let decoded = decode(&dff_bytes).expect("our decode"); + assert_eq!(decoded.channels.len(), 2); + assert_eq!(decoded.channels[0].len(), 8192); + + for i in 12..8000 { + let ff_l = ffmpeg_floats[i * 2]; + let ff_r = ffmpeg_floats[i * 2 + 1]; + let our_l = decoded.channels[0][i]; + let our_r = decoded.channels[1][i]; + + assert!((ff_l - our_l).abs() < 1e-4, "sample {i} left mismatch: ffmpeg={ff_l}, ours={our_l}"); + assert!((ff_r - our_r).abs() < 1e-4, "sample {i} right mismatch: ffmpeg={ff_r}, ours={our_r}"); + } +} From 557f9f5fb1fbe9a89fe2dba35ed1154892a7b17a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:45:21 -0500 Subject: [PATCH 02/79] fix(audio): reject overflowing DSD chunk sizes and invalid factors --- crates/audio/Cargo.toml | 4 ++ crates/audio/src/dsd/dsdiff.rs | 24 +++++++----- crates/audio/src/dsd/dsf.rs | 10 ++--- crates/audio/src/dsd/mod.rs | 4 ++ crates/audio/tests/dsd_bounds.rs | 65 ++++++++++++++++++++++++++++++++ 5 files changed, 92 insertions(+), 15 deletions(-) create mode 100644 crates/audio/tests/dsd_bounds.rs diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 830398e37a..6718e55a0d 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -131,3 +131,7 @@ required-features = ["decode"] [[example]] name = "encode" required-features = ["lossless-encode", "aac-encode"] + +[[test]] +name = "dsd_bounds" +required-features = ["dsd"] diff --git a/crates/audio/src/dsd/dsdiff.rs b/crates/audio/src/dsd/dsdiff.rs index bd593e13ec..9041374eb4 100644 --- a/crates/audio/src/dsd/dsdiff.rs +++ b/crates/audio/src/dsd/dsdiff.rs @@ -53,12 +53,13 @@ pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Err } let total_file_data = bytes.len().saturating_sub(12); - if (form_size as usize) > total_file_data { + let form_size = usize::try_from(form_size).map_err(|_| Error::MemoryLimitExceeded)?; + if form_size > total_file_data { return Err(Error::UnexpectedEof("FRM8 chunk extends beyond file size")); } let mut pos = 16; - let end = (12 + form_size as usize).min(bytes.len()); + let end = 12 + form_size; let mut sample_rate = None; let mut channel_names = Vec::new(); @@ -71,10 +72,11 @@ pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Err while pos + 12 <= end { let chunk_id: [u8; 4] = bytes[pos..pos + 4].try_into().map_err(|_| Error::UnexpectedEof("chunk ID"))?; - let chunk_size = u64::from_be_bytes(bytes[pos + 4..pos + 12].try_into().map_err(|_| Error::UnexpectedEof("chunk size"))?) as usize; + let chunk_size = usize::try_from(u64::from_be_bytes(bytes[pos + 4..pos + 12].try_into().map_err(|_| Error::UnexpectedEof("chunk size"))?)) + .map_err(|_| Error::MemoryLimitExceeded)?; pos += 12; - if pos + chunk_size > end { + if chunk_size > end.saturating_sub(pos) { return Err(Error::UnexpectedEof("subchunk extends beyond container bounds")); } @@ -93,12 +95,13 @@ pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Err let mut prop_pos = 4; while prop_pos + 12 <= chunk_data.len() { let sub_id: [u8; 4] = chunk_data[prop_pos..prop_pos + 4].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk ID"))?; - let sub_size = u64::from_be_bytes( + let sub_size = usize::try_from(u64::from_be_bytes( chunk_data[prop_pos + 4..prop_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("PROP subchunk size"))?, - ) as usize; + )) + .map_err(|_| Error::MemoryLimitExceeded)?; prop_pos += 12; - if prop_pos + sub_size > chunk_data.len() { + if sub_size > chunk_data.len().saturating_sub(prop_pos) { return Err(Error::UnexpectedEof("PROP subchunk extends beyond bounds")); } @@ -147,11 +150,12 @@ pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Err let mut diin_pos = 0; while diin_pos + 12 <= chunk_data.len() { let sub_id = &chunk_data[diin_pos..diin_pos + 4]; - let sub_size = u64::from_be_bytes( + let sub_size = usize::try_from(u64::from_be_bytes( chunk_data[diin_pos + 4..diin_pos + 12].try_into().map_err(|_| Error::UnexpectedEof("DIIN subchunk size"))?, - ) as usize; + )) + .map_err(|_| Error::MemoryLimitExceeded)?; diin_pos += 12; - if diin_pos + sub_size > chunk_data.len() { + if sub_size > chunk_data.len().saturating_sub(diin_pos) { break; } let sub_data = &chunk_data[diin_pos..diin_pos + sub_size]; diff --git a/crates/audio/src/dsd/dsf.rs b/crates/audio/src/dsd/dsf.rs index 4b1c1f003f..eb4ae55d9d 100644 --- a/crates/audio/src/dsd/dsf.rs +++ b/crates/audio/src/dsd/dsf.rs @@ -55,7 +55,7 @@ fn parse_id3v2(bytes: &[u8], offset: usize) -> (Option, Option) } let frame_size = u32::from_be_bytes([id3[pos + 4], id3[pos + 5], id3[pos + 6], id3[pos + 7]]) as usize; pos += 10; - if pos + frame_size > end { + if frame_size > end.saturating_sub(pos) { break; } @@ -124,7 +124,7 @@ pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> { return Err(Error::InvalidHeader("invalid 'fmt ' chunk size (must be at least 52)")); } let fmt_size = usize::try_from(fmt_chunk_size).map_err(|_| Error::MemoryLimitExceeded)?; - if bytes.len() < fmt_offset + fmt_size + 12 { + if fmt_size > bytes.len().saturating_sub(fmt_offset + 12) { return Err(Error::UnexpectedEof("fmt chunk extends beyond file bounds")); } @@ -176,8 +176,8 @@ pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> { } let payload_offset = data_offset + 12; - let payload_size = (data_chunk_size - 12) as usize; - if bytes.len() < payload_offset + payload_size { + let payload_size = usize::try_from(data_chunk_size - 12).map_err(|_| Error::MemoryLimitExceeded)?; + if payload_size > bytes.len().saturating_sub(payload_offset) { return Err(Error::UnexpectedEof("data chunk payload extends beyond file bounds")); } @@ -198,7 +198,7 @@ pub fn parse_dsf(bytes: &[u8]) -> Result { let block_size = block_size as usize; let channels = metadata.channels as usize; - let target_bytes_per_channel = metadata.sample_count.div_ceil(8) as usize; + let target_bytes_per_channel = usize::try_from(metadata.sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; if target_bytes_per_channel.saturating_mul(channels) > MAX_DECODE_BYTES { return Err(Error::MemoryLimitExceeded); } diff --git a/crates/audio/src/dsd/mod.rs b/crates/audio/src/dsd/mod.rs index 38f89de7c4..01fa53aaea 100644 --- a/crates/audio/src/dsd/mod.rs +++ b/crates/audio/src/dsd/mod.rs @@ -106,6 +106,10 @@ impl RawAudio { /// Decimates the raw 1-bit DSD audio to multi-bit PCM `f32` samples with the given factor (8, 16, 32, or 64). pub fn to_pcm_with_factor(&self, factor: u32) -> Result { + // Validate before iterating: public RawAudio may contain no channels. + if !matches!(factor, 8 | 16 | 32 | 64) { + return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64")); + } let mut channels = Vec::with_capacity(self.channel_bytes.len()); for ch_bytes in &self.channel_bytes { let pcm = filter::decimate_channel(ch_bytes, self.bit_order, factor)?; diff --git a/crates/audio/tests/dsd_bounds.rs b/crates/audio/tests/dsd_bounds.rs new file mode 100644 index 0000000000..b57681ed17 --- /dev/null +++ b/crates/audio/tests/dsd_bounds.rs @@ -0,0 +1,65 @@ +//! Hostile container sizes must return errors, never wrap offsets or panic. +use craft_audio::dsd::{BitOrder, Error, RawAudio, encode_dsdiff, encode_dsf, read_metadata, read_raw}; + +#[test] +fn dsf_untrusted_sizes_are_checked() { + let original = encode_dsf(2_822_400, &[&[0x69; 8]], 64, 8).unwrap(); + for offset in [32, 84] { + // fmt and data chunk sizes + for size in [u64::MAX, u64::MAX - 31, 1 << 32] { + let mut bytes = original.clone(); + bytes[offset..offset + 8].copy_from_slice(&size.to_le_bytes()); + assert!(read_metadata(&bytes).is_err()); + assert!(read_raw(&bytes).is_err()); + } + } + let mut bytes = original; + bytes[64..72].copy_from_slice(&u64::MAX.to_le_bytes()); + assert_eq!(read_raw(&bytes), Err(Error::MemoryLimitExceeded)); +} + +#[test] +fn dsdiff_untrusted_top_level_and_property_sizes_are_checked() { + let original = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap(); + let prop = original.windows(4).position(|w| w == b"PROP").unwrap(); + for offset in [4, 20, prop + 20] { + // FRM8, FVER, nested FS + for size in [u64::MAX, u64::MAX - 31, 1 << 32] { + let mut bytes = original.clone(); + bytes[offset..offset + 8].copy_from_slice(&size.to_be_bytes()); + assert!(read_metadata(&bytes).is_err()); + assert!(read_raw(&bytes).is_err()); + } + } +} + +#[test] +fn dsdiff_invalid_optional_disc_info_is_ignored_without_overflow() { + let mut bytes = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap(); + let expected = read_metadata(&bytes).unwrap(); + bytes.extend_from_slice(b"DIIN"); + bytes.extend_from_slice(&12u64.to_be_bytes()); + bytes.extend_from_slice(b"DITI"); + bytes.extend_from_slice(&u64::MAX.to_be_bytes()); + let size = (bytes.len() - 12) as u64; + bytes[4..12].copy_from_slice(&size.to_be_bytes()); + // Optional malformed text is ignored on 64-bit; unrepresentable sizes may + // be rejected on narrower targets, but must never wrap or panic. + match read_metadata(&bytes) { + Ok(actual) => assert_eq!(actual, expected), + Err(Error::MemoryLimitExceeded) => {} + other => panic!("unexpected result: {other:?}"), + } +} + +#[test] +fn empty_raw_audio_rejects_invalid_decimation_factors() { + let bytes = encode_dsf(2_822_400, &[&[]], 0, 8).unwrap(); + let raw = RawAudio { metadata: read_metadata(&bytes).unwrap(), bit_order: BitOrder::LsbFirst, channel_bytes: Vec::new() }; + for factor in [0, 1, 7, 9, u32::MAX] { + assert!(matches!(raw.to_pcm_with_factor(factor), Err(Error::Unsupported(_)))); + } + for factor in [8, 16, 32, 64] { + assert_eq!(raw.to_pcm_with_factor(factor).unwrap().sample_rate, 2_822_400 / factor); + } +} From 83048a707e33d5b12a63b48cb696d59d7d224800 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 08:49:27 -0500 Subject: [PATCH 03/79] fix(audio): bound DSD writer and aggregate PCM buffers --- crates/audio/src/dsd/dsdiff.rs | 10 +++--- crates/audio/src/dsd/dsf.rs | 15 +++++---- crates/audio/src/dsd/filter.rs | 22 +++++++++----- crates/audio/src/dsd/mod.rs | 52 +++++++++++++++++++++++++++++++- crates/audio/tests/dsd_bounds.rs | 28 +++++++++++++++++ 5 files changed, 109 insertions(+), 18 deletions(-) diff --git a/crates/audio/src/dsd/dsdiff.rs b/crates/audio/src/dsd/dsdiff.rs index 9041374eb4..f1980d1367 100644 --- a/crates/audio/src/dsd/dsdiff.rs +++ b/crates/audio/src/dsd/dsdiff.rs @@ -249,8 +249,10 @@ pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> } let num_channels = channels.len(); - let bytes_per_ch = sample_count.div_ceil(8) as usize; - let data_size = bytes_per_ch.saturating_mul(num_channels); + let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; + let data_size = bytes_per_ch.checked_mul(num_channels).ok_or(Error::MemoryLimitExceeded)?; + // Fixed headers plus four bytes for each channel identifier. + let file_size = super::encoded_size(data_size, 110 + 4 * num_channels)?; // Build PROP subchunks: // 1. 'FS ' (4 bytes + 12 chunk header) @@ -310,9 +312,9 @@ pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> dsd_chunk_hdr.extend_from_slice(b"DSD "); dsd_chunk_hdr.extend_from_slice(&(data_size as u64).to_be_bytes()); - let frm8_payload_len = 4 + fver_chunk.len() + prop_chunk.len() + dsd_chunk_hdr.len() + data_size; + let frm8_payload_len = file_size - 12; let mut out = Vec::new(); - out.try_reserve_exact(12 + frm8_payload_len).map_err(|_| Error::MemoryLimitExceeded)?; + out.try_reserve_exact(file_size).map_err(|_| Error::MemoryLimitExceeded)?; out.extend_from_slice(b"FRM8"); out.extend_from_slice(&(frm8_payload_len as u64).to_be_bytes()); diff --git a/crates/audio/src/dsd/dsf.rs b/crates/audio/src/dsd/dsf.rs index eb4ae55d9d..b9115dea97 100644 --- a/crates/audio/src/dsd/dsf.rs +++ b/crates/audio/src/dsd/dsf.rs @@ -265,23 +265,26 @@ pub fn write_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_ if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { return Err(Error::InvalidData("sample rate out of bounds")); } + if block_size > MAX_BLOCK_SIZE { + return Err(Error::InvalidData("DSF block size exceeds maximum")); + } let block_size = if block_size == 0 { 4096 } else { block_size as usize }; let num_channels = channels.len(); - let bytes_per_ch = sample_count.div_ceil(8) as usize; + let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; let num_blocks = bytes_per_ch.div_ceil(block_size); - let payload_size = num_blocks.saturating_mul(num_channels).saturating_mul(block_size); + let payload_size = num_blocks.checked_mul(num_channels).and_then(|n| n.checked_mul(block_size)).ok_or(Error::MemoryLimitExceeded)?; + let file_size = super::encoded_size(payload_size, 92)?; - let data_chunk_size = 12u64.saturating_add(payload_size as u64); - let file_size = 28u64 + 52u64 + data_chunk_size; + let data_chunk_size = 12u64 + payload_size as u64; let mut out = Vec::new(); - out.try_reserve_exact(file_size as usize).map_err(|_| Error::MemoryLimitExceeded)?; + out.try_reserve_exact(file_size).map_err(|_| Error::MemoryLimitExceeded)?; // 1. 'DSD ' chunk (28 bytes) out.extend_from_slice(b"DSD "); out.extend_from_slice(&28u64.to_le_bytes()); - out.extend_from_slice(&file_size.to_le_bytes()); + out.extend_from_slice(&(file_size as u64).to_le_bytes()); out.extend_from_slice(&0u64.to_le_bytes()); // metadata offset = 0 // 2. 'fmt ' chunk (52 bytes) diff --git a/crates/audio/src/dsd/filter.rs b/crates/audio/src/dsd/filter.rs index 3e39050e07..f7d934d3ec 100644 --- a/crates/audio/src/dsd/filter.rs +++ b/crates/audio/src/dsd/filter.rs @@ -142,20 +142,28 @@ fn byte_lut(k: usize, byte_val: u8) -> f32 { sum } +// Both the first-stage samples and the secondary output coexist during filtering. +pub(super) fn allocation_sizes(len: usize, factor: u32) -> Result<(usize, usize), Error> { + if !matches!(factor, 8 | 16 | 32 | 64) { + return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64")); + } + let stage = len.checked_mul(std::mem::size_of::()).ok_or(Error::MemoryLimitExceeded)?; + let output = (len / (factor / 8) as usize).checked_mul(std::mem::size_of::()).ok_or(Error::MemoryLimitExceeded)?; + let working = if factor == 8 { stage } else { stage.checked_add(output).ok_or(Error::MemoryLimitExceeded)? }; + if working > MAX_DECODE_BYTES { + return Err(Error::MemoryLimitExceeded); + } + Ok((working, output)) +} + /// Decimates 1-bit DSD audio bytes for a single channel to `f32` PCM. /// /// The default decimation factor is 8 (1 output float per input byte). /// When `factor` is 16, 32, or 64, the 1/8 output is further downsampled /// by 2, 4, or 8 respectively. pub fn decimate_channel(channel_bytes: &[u8], bit_order: BitOrder, factor: u32) -> Result, Error> { - if !matches!(factor, 8 | 16 | 32 | 64) { - return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64")); - } - + allocation_sizes(channel_bytes.len(), factor)?; let num_bytes = channel_bytes.len(); - if num_bytes.saturating_mul(std::mem::size_of::()) > MAX_DECODE_BYTES { - return Err(Error::MemoryLimitExceeded); - } // Build the 12 x 256 lookup table for fast convolution. // 12 * 256 * 4 bytes = 12 KB, sits comfortably in L1 cache. diff --git a/crates/audio/src/dsd/mod.rs b/crates/audio/src/dsd/mod.rs index 01fa53aaea..e782b50f05 100644 --- a/crates/audio/src/dsd/mod.rs +++ b/crates/audio/src/dsd/mod.rs @@ -30,9 +30,33 @@ pub const MAX_SAMPLE_RATE: u32 = 45_158_400; /// Maximum safe block size for DSF channel blocks (16 MiB). pub const MAX_BLOCK_SIZE: u32 = 16 * 1024 * 1024; -/// Maximum safe memory allocation budget for decoded audio (256 MiB). +/// Maximum audio-buffer allocation budget (256 MiB). +/// +/// Raw readers limit their channel bytes; PCM conversion separately limits the +/// simultaneously live PCM output and scratch buffers. Caller-owned raw input, +/// metadata, and the small filter lookup table are not included. pub const MAX_DECODE_BYTES: usize = 256 * 1024 * 1024; +/// Maximum encoded container size, including headers and block padding (256 MiB). +pub const MAX_ENCODE_BYTES: usize = 256 * 1024 * 1024; + +fn encoded_size(payload: usize, header: usize) -> Result { + payload.checked_add(header).filter(|&n| n <= MAX_ENCODE_BYTES).ok_or(Error::MemoryLimitExceeded) +} + +// Account for retained channel output plus the current filter's two live buffers. +fn pcm_budget(lengths: impl Iterator, factor: u32) -> Result<(), Error> { + let mut retained = 0usize; + for len in lengths { + let (working, output) = filter::allocation_sizes(len, factor)?; + if retained.checked_add(working).is_none_or(|n| n > MAX_DECODE_BYTES) { + return Err(Error::MemoryLimitExceeded); + } + retained = retained.checked_add(output).ok_or(Error::MemoryLimitExceeded)?; + } + Ok(()) +} + /// Supported DSD container formats. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Format { @@ -110,6 +134,10 @@ impl RawAudio { if !matches!(factor, 8 | 16 | 32 | 64) { return Err(Error::Unsupported("decimation factor must be 8, 16, 32, or 64")); } + if self.channel_bytes.len() > MAX_CHANNELS { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + pcm_budget(self.channel_bytes.iter().map(Vec::len), factor)?; let mut channels = Vec::with_capacity(self.channel_bytes.len()); for ch_bytes in &self.channel_bytes { let pcm = filter::decimate_channel(ch_bytes, self.bit_order, factor)?; @@ -223,3 +251,25 @@ pub fn encode_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block pub fn encode_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> Result, Error> { dsdiff::write_dsdiff(sample_rate, channels, sample_count) } + +#[cfg(test)] +mod budget_tests { + use super::*; + + #[test] + fn pcm_budget_counts_all_channels_and_live_scratch() { + let quarter = MAX_DECODE_BYTES / 4; + assert!(pcm_budget([quarter / 2, quarter / 2].into_iter(), 8).is_ok()); + assert_eq!(pcm_budget([quarter / 2, quarter / 2 + 1].into_iter(), 8), Err(Error::MemoryLimitExceeded)); + assert!(pcm_budget([quarter / 2].into_iter(), 16).is_ok()); + assert_eq!(pcm_budget([quarter].into_iter(), 16), Err(Error::MemoryLimitExceeded)); + assert_eq!(pcm_budget([usize::MAX].into_iter(), 8), Err(Error::MemoryLimitExceeded)); + } + + #[test] + fn encoded_budget_includes_headers_without_large_allocations() { + assert_eq!(encoded_size(MAX_ENCODE_BYTES - 92, 92), Ok(MAX_ENCODE_BYTES)); + assert_eq!(encoded_size(MAX_ENCODE_BYTES - 91, 92), Err(Error::MemoryLimitExceeded)); + assert_eq!(encoded_size(usize::MAX, 92), Err(Error::MemoryLimitExceeded)); + } +} diff --git a/crates/audio/tests/dsd_bounds.rs b/crates/audio/tests/dsd_bounds.rs index b57681ed17..4be677dcad 100644 --- a/crates/audio/tests/dsd_bounds.rs +++ b/crates/audio/tests/dsd_bounds.rs @@ -63,3 +63,31 @@ fn empty_raw_audio_rejects_invalid_decimation_factors() { assert_eq!(raw.to_pcm_with_factor(factor).unwrap().sample_rate, 2_822_400 / factor); } } + +#[test] +fn writers_reject_unbounded_output_before_allocating() { + let channels: [&[u8]; 8] = [&[]; 8]; + for count in [u64::MAX, (craft_audio::dsd::MAX_ENCODE_BYTES as u64 + 1) * 8] { + assert_eq!(encode_dsf(2_822_400, &channels, count, 8), Err(Error::MemoryLimitExceeded)); + assert_eq!(encode_dsdiff(2_822_400, &channels, count), Err(Error::MemoryLimitExceeded)); + } + assert!(matches!(encode_dsf(2_822_400, &[&[]], 0, u32::MAX), Err(Error::InvalidData(_)))); +} + +#[test] +fn encoded_sizes_match_actual_bytes_for_odd_and_even_payloads() { + for channels in 1..=8 { + for len in 0..=9 { + let data = vec![0x69; len]; + let planes = vec![data.as_slice(); channels]; + for block in [0, 1, 3, 8] { + let dsf = encode_dsf(2_822_400, &planes, len as u64 * 8, block).unwrap(); + assert_eq!(u64::from_le_bytes(dsf[12..20].try_into().unwrap()), dsf.len() as u64); + assert_eq!(read_raw(&dsf).unwrap().channel_bytes, vec![data.clone(); channels]); + } + let dff = encode_dsdiff(2_822_400, &planes, len as u64 * 8).unwrap(); + assert_eq!(u64::from_be_bytes(dff[4..12].try_into().unwrap()) + 12, dff.len() as u64); + assert_eq!(read_raw(&dff).unwrap().channel_bytes, vec![data; channels]); + } + } +} From 25a882c1ce0b2aae806c068752e2b77458975f7e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 17 Nov 2026 10:12:56 -0500 Subject: [PATCH 04/79] fix(audio): stop DSF audio at the declared data chunk --- crates/audio/src/dsd/dsf.rs | 13 ++++++++++--- crates/audio/tests/dsd_bounds.rs | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/audio/src/dsd/dsf.rs b/crates/audio/src/dsd/dsf.rs index b9115dea97..34472001ea 100644 --- a/crates/audio/src/dsd/dsf.rs +++ b/crates/audio/src/dsd/dsf.rs @@ -99,6 +99,11 @@ fn parse_text_frame(data: &[u8]) -> Option { /// Parses DSF file metadata, returning the metadata, audio data offset, and block size per channel. pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> { + let (metadata, offset, _, block_size) = parse_dsf_header_bounded(bytes)?; + Ok((metadata, offset, block_size)) +} + +fn parse_dsf_header_bounded(bytes: &[u8]) -> Result<(Metadata, usize, usize, u32), Error> { if bytes.len() < 28 + 52 + 12 { return Err(Error::UnexpectedEof("DSF file header is truncated")); } @@ -189,12 +194,12 @@ pub fn parse_dsf_header(bytes: &[u8]) -> Result<(Metadata, usize, u32), Error> { let metadata = Metadata { format: Format::Dsf, sample_rate, channels, sample_count, channel_names, title, artist }; - Ok((metadata, payload_offset, block_size_per_channel)) + Ok((metadata, payload_offset, payload_size, block_size_per_channel)) } /// Parses a DSF file into raw 1-bit planar channel streams. pub fn parse_dsf(bytes: &[u8]) -> Result { - let (metadata, payload_offset, block_size) = parse_dsf_header(bytes)?; + let (metadata, payload_offset, payload_size, block_size) = parse_dsf_header_bounded(bytes)?; let block_size = block_size as usize; let channels = metadata.channels as usize; @@ -208,7 +213,9 @@ pub fn parse_dsf(bytes: &[u8]) -> Result { return Err(Error::InvalidHeader("zero slice size")); } - let payload = &bytes[payload_offset..]; + // The header validated this range. Trailing ID3 or other bytes are not audio, + // even if sample_count asks for more samples than the data chunk contains. + let payload = &bytes[payload_offset..payload_offset + payload_size]; let num_slices = payload.len() / slice_size; let mut channel_bytes: Vec> = Vec::with_capacity(channels); diff --git a/crates/audio/tests/dsd_bounds.rs b/crates/audio/tests/dsd_bounds.rs index 4be677dcad..c335c5d636 100644 --- a/crates/audio/tests/dsd_bounds.rs +++ b/crates/audio/tests/dsd_bounds.rs @@ -91,3 +91,25 @@ fn encoded_sizes_match_actual_bytes_for_odd_and_even_payloads() { } } } + +#[test] +fn dsf_audio_stops_at_the_declared_data_chunk() { + for channels in 1..=2 { + let input = vec![&[0x33u8; 8][..]; channels]; + let mut bytes = encode_dsf(2_822_400, &input, 64, 8).unwrap(); + // Ask for an additional block without extending the data chunk. + bytes[64..72].copy_from_slice(&128u64.to_le_bytes()); + let expected = read_raw(&bytes).unwrap(); + for c in &expected.channel_bytes { + assert_eq!(&c[..8], &[0x33; 8]); + assert_eq!(&c[8..], &[0x69; 8]); + } + let metadata_offset = bytes.len() as u64; + bytes[20..28].copy_from_slice(&metadata_offset.to_le_bytes()); + bytes.extend_from_slice(b"ID3\x04\x00\x00\x00\x00\x00\x00"); + bytes.extend_from_slice(&[0xff; 32]); + let file_size = bytes.len() as u64; + bytes[12..20].copy_from_slice(&file_size.to_le_bytes()); + assert_eq!(read_raw(&bytes).unwrap().channel_bytes, expected.channel_bytes); + } +} From 400b2f821d7b008dc41e27d6289d513c7f27dd24 Mon Sep 17 00:00:00 2001 From: texjer Date: Tue, 17 Nov 2026 13:00:47 -0500 Subject: [PATCH 05/79] craft-develop: the crate, with inpaint from LightCraft The first module of the shared develop pipeline (#587): lightcraft-inpaint at a75497d6, as craft_develop::inpaint. PatchMatch patch completion and the membrane fill it seeds from, with their tests. Only the paths in two doc links and two imports changed. A parity test compares both fills of one scene with what LightCraft's crate gave at that commit, through craft-render-parity at Tolerance::BASELINE. --- Cargo.lock | 22 +- Cargo.toml | 1 + NOTICE | 8 + crates/develop/Cargo.toml | 19 + crates/develop/README.md | 26 + crates/develop/src/inpaint.rs | 58 ++ crates/develop/src/inpaint/membrane.rs | 207 ++++++ crates/develop/src/inpaint/patchmatch.rs | 587 ++++++++++++++++++ crates/develop/src/lib.rs | 6 + .../tests/fixtures/inpaint-complete.f32le | Bin 0 -> 82944 bytes .../tests/fixtures/inpaint-membrane.f32le | Bin 0 -> 82944 bytes crates/develop/tests/inpaint_parity.rs | 60 ++ 12 files changed, 987 insertions(+), 7 deletions(-) create mode 100644 crates/develop/Cargo.toml create mode 100644 crates/develop/README.md create mode 100644 crates/develop/src/inpaint.rs create mode 100644 crates/develop/src/inpaint/membrane.rs create mode 100644 crates/develop/src/inpaint/patchmatch.rs create mode 100644 crates/develop/src/lib.rs create mode 100644 crates/develop/tests/fixtures/inpaint-complete.f32le create mode 100644 crates/develop/tests/fixtures/inpaint-membrane.f32le create mode 100644 crates/develop/tests/inpaint_parity.rs diff --git a/Cargo.lock b/Cargo.lock index da06541564..7c3df427ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1722,6 +1722,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-develop" +version = "0.1.0" +dependencies = [ + "craft-render-parity", + "rayon", +] + [[package]] name = "craft-dialogs" version = "0.1.0" @@ -2122,13 +2130,6 @@ dependencies = [ "flate2", ] -[[package]] -name = "craft-hdr" -version = "0.1.0" -dependencies = [ - "thiserror 2.0.21", -] - [[package]] name = "craft-har" version = "0.1.0" @@ -2137,6 +2138,13 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-hdr" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-heif" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c8cd94409b..7a6c6c8fa0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ craft-ssip = { path = "crates/ssip" } craft-ber = { path = "crates/ber" } craft-proto = { path = "crates/proto" } craft-render-parity = { path = "crates/render-parity" } +craft-develop = { path = "crates/develop" } acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` diff --git a/NOTICE b/NOTICE index 35085dcb30..49bb9c0e45 100644 --- a/NOTICE +++ b/NOTICE @@ -108,6 +108,14 @@ Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. The format imp clean-room work based on their public specifications; dependency licences and X.Org's `rgb.txt` attribution are listed in ATTRIBUTION.md. +crates/develop (craft-develop) is moved from LightCraft, module by module: +- src/inpaint.rs and src/inpaint/ from crates/inpaint (lightcraft-inpaint), with its tests, revision a75497d6. + https://github.com/storytold/lightcraft + Copyright (c) 2026 ArtCraft Team and the LightCraft contributors. + That crate ports the inpainting (PatchMatch completion) and Poisson membrane fill code of PhotoCraft + (https://github.com/storytold/photocraft, crates/algo/src/inpaint.rs and poisson.rs), Copyright the PhotoCraft + contributors, MIT OR Apache-2.0; the port was modified by the LightCraft contributors (2026). + crates/raw (craft-raw) is moved from LightCraft, with behaviour ported from two other readers: - LightCraft, crates/raw (src/lib.rs, dng.rs, dngwrite.rs, tiffraw.rs, unpack.rs, ljpeg.rs, jxl.rs, opcodes.rs, profile.rs, gaintable.rs, semantic.rs, preview.rs, vendor/crw.rs, vendor/hasselblad.rs, diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml new file mode 100644 index 0000000000..606fd437a3 --- /dev/null +++ b/crates/develop/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-develop" +description = "The raw develop pipeline, CPU path, moved from LightCraft module by module. So far: content-aware hole filling for spot removal." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +rayon = { workspace = true } + +[dev-dependencies] +craft-render-parity = { workspace = true } diff --git a/crates/develop/README.md b/crates/develop/README.md new file mode 100644 index 0000000000..4b85d3305e --- /dev/null +++ b/crates/develop/README.md @@ -0,0 +1,26 @@ +# craft-develop + +The raw develop pipeline, CPU path: the shared pipeline of +[#587](https://github.com/storytold/craft-libs/issues/587), moved from LightCraft one module at a time. No `unsafe`, +no panics on hostile input, no file I/O, and it builds for `wasm32-unknown-unknown`. + +```toml +craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "" } +``` + +## What is here + +| Module | From LightCraft (`a75497d6`) | Contents | +|---|---|---| +| `inpaint` | `crates/inpaint` | Content-aware hole filling for spot removal: `complete` (multi-scale patch completion with PatchMatch) and `membrane_fill` (a smooth harmonic fill, its seed and fallback). Interleaved `f32` buffers of any channel count, a fixed-seed RNG, the same result on any number of threads. | + +## Parity with LightCraft + +Each module comes with a test that its output is LightCraft's at the base commit, compared with +[`craft-render-parity`](../render-parity/README.md) at `Tolerance::BASELINE`. The expected pictures in +`tests/fixtures/` were written by LightCraft's own crate at that commit, on the scene the test builds. + +## Not here yet + +The rest of the pipeline: colour, raster, the sensor stage, raw loading and the render stages. No app uses this crate +yet. diff --git a/crates/develop/src/inpaint.rs b/crates/develop/src/inpaint.rs new file mode 100644 index 0000000000..460dfa3073 --- /dev/null +++ b/crates/develop/src/inpaint.rs @@ -0,0 +1,58 @@ +//! Content-aware hole filling (inpainting) for the Remove tool. +//! +//! * [`complete`]: multi-scale patch-based completion (Wexler, Shechtman, Irani 2007) with the +//! nearest-neighbour field found by PatchMatch (Barnes et al. 2009). See [`patchmatch`]. +//! * [`membrane_fill`]: smooth harmonic fill, used to seed the coarsest level and as a fallback. +//! +//! Buffers are interleaved `w × h × ch` floats in any colour model plus a `w × h` hole mask. +//! Everything is deterministic (fixed-seed RNG, results independent of the thread count) and never +//! panics on mismatched sizes: such calls return `None` or the input unchanged. +//! +//! Sources: C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman, *PatchMatch: A Randomized +//! Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009; Y. Wexler, E. Shechtman, +//! M. Irani, *Space-Time Completion of Video*, PAMI 2007. +//! +//! Ported from PhotoCraft (`crates/algo/src/inpaint.rs`, `poisson.rs`, MIT OR Apache-2.0, same +//! organisation; see `NOTICE`). + +pub mod membrane; +pub mod patchmatch; + +pub use membrane::membrane_fill; +pub use patchmatch::{CompleteParams, complete, complete_with}; + +/// A cancelled [`complete_with`]. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Cancelled; + +impl std::fmt::Display for Cancelled { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("cancelled") + } +} + +impl std::error::Error for Cancelled {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hostile_sizes_do_not_panic() { + assert_eq!(complete(4, 4, 3, &[0.0; 5], &[true; 16], &CompleteParams::default()), None); + assert_eq!(complete(4, 4, 0, &[], &[true; 16], &CompleteParams::default()), None); + assert_eq!(complete(usize::MAX, 2, 3, &[0.0; 6], &[true; 2], &CompleteParams::default()), None); + assert_eq!(membrane_fill(4, 4, 1, &[0.5; 3], &[true; 16]), vec![0.5; 3]); + // A hole covering everything: nothing to copy from. + assert_eq!(complete(16, 16, 1, &[0.5; 256], &[true; 256], &CompleteParams::default()), None); + // A tiny image smaller than a patch. + let _ = complete(2, 2, 1, &[0.5; 4], &[true, false, false, false], &CompleteParams::default()); + } + + #[test] + fn cancellation_stops() { + let img = vec![0.5f32; 64 * 64]; + let hole: Vec = (0..64 * 64usize).map(|i| (i % 64).abs_diff(32) < 4 && (i / 64).abs_diff(32) < 4).collect(); + assert_eq!(complete_with(64, 64, 1, &img, &hole, &CompleteParams::default(), &|| true), Err(Cancelled)); + } +} diff --git a/crates/develop/src/inpaint/membrane.rs b/crates/develop/src/inpaint/membrane.rs new file mode 100644 index 0000000000..4589d23479 --- /dev/null +++ b/crates/develop/src/inpaint/membrane.rs @@ -0,0 +1,207 @@ +//! Membrane (harmonic) fill: `Δv = 0` inside a hole with the known pixels as Dirichlet boundary. +//! Used to initialise the coarsest level of [`crate::inpaint::complete`] and as its fallback. +//! +//! Sources: the membrane interpolant of P. Pérez, M. Gangnet, A. Blake, *Poisson Image Editing*, +//! ACM SIGGRAPH 2003 (§3), solved by successive over-relaxation on the 4-connected grid, accelerated +//! cascadically (solve on a half-resolution grid, prolong bilinearly, a few SOR sweeps per level). +//! Ported from PhotoCraft's `algo::poisson` (MIT OR Apache-2.0). + +/// Convergence threshold (max per-sweep update) for the SOR sweeps. +const TOL: f32 = 2e-5; +/// SOR sweeps (cap) and relaxation factor on every level above the coarsest: tuned so a 96×72 disc +/// is within ~1e-3 of a fully converged Gauss–Seidel solve (below one 8-bit step). +const FINE_ITERS: usize = 30; +const FINE_OMEGA: f32 = 1.7; + +/// Solve `Δv = 0` on `unknown` pixels with Dirichlet values from the known pixels of `v` +/// (out-of-grid neighbours are ignored, i.e. a Neumann boundary). `v` holds the known values on +/// entry and the solution on exit. Cascadic multigrid + SOR. +pub(crate) fn solve_membrane(w: usize, h: usize, unknown: &[bool], v: &mut [f32]) { + if unknown.len() != w * h || v.len() != w * h { + return; + } + solve_rec(w, h, unknown, v, 0, &|| false); +} + +fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize, stop: &(dyn Fn() -> bool + Sync)) { + if stop() { + return; + } + let n_unknown = unknown.iter().filter(|u| **u).count(); + if n_unknown == 0 { + return; + } + let known: Vec = v.iter().zip(unknown).filter(|(_, u)| !**u).map(|(x, _)| *x).collect(); + if known.is_empty() { + return; // nothing to interpolate from + } + if w >= 8 && h >= 8 && n_unknown > 64 && depth < 16 { + // Restrict: a coarse pixel is known if any of its children is (value = mean of known children). + let (cw, chh) = (w.div_ceil(2), h.div_ceil(2)); + let mut cu = vec![true; cw * chh]; + let mut cv = vec![0.0f32; cw * chh]; + for cy in 0..chh { + for cx in 0..cw { + let (mut s, mut n) = (0.0f32, 0u32); + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let (x, y) = (cx * 2 + dx, cy * 2 + dy); + if x < w && y < h && !unknown[y * w + x] { + s += v[y * w + x]; + n += 1; + } + } + if n > 0 { + cu[cy * cw + cx] = false; + cv[cy * cw + cx] = s / n as f32; + } + } + } + solve_rec(cw, chh, &cu, &mut cv, depth + 1, stop); + // Prolong: bilinear sample of the coarse solution as the initial guess. + for y in 0..h { + let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (chh - 1) as f32); + let y0 = fy.floor() as usize; + let y1 = (y0 + 1).min(chh - 1); + let ty = fy - y0 as f32; + for x in 0..w { + if !unknown[y * w + x] { + continue; + } + let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (cw - 1) as f32); + let x0 = fx.floor() as usize; + let x1 = (x0 + 1).min(cw - 1); + let tx = fx - x0 as f32; + let a = cv[y0 * cw + x0] + (cv[y0 * cw + x1] - cv[y0 * cw + x0]) * tx; + let b = cv[y1 * cw + x0] + (cv[y1 * cw + x1] - cv[y1 * cw + x0]) * tx; + v[y * w + x] = a + (b - a) * ty; + } + } + sor(w, h, unknown, v, FINE_ITERS, FINE_OMEGA, stop); + } else { + let mean = known.iter().sum::() / known.len() as f32; + for (x, u) in v.iter_mut().zip(unknown) { + if *u { + *x = mean; + } + } + sor(w, h, unknown, v, 2000, 1.85, stop); + } +} + +/// SOR sweeps over the unknown pixels until the largest update drops below [`TOL`]. +fn sor(w: usize, h: usize, unknown: &[bool], v: &mut [f32], max_iter: usize, omega: f32, stop: &(dyn Fn() -> bool + Sync)) { + // Precompute the unknown pixels and which neighbours exist. + let cells: Vec<(u32, u8)> = (0..w * h) + .filter(|&i| unknown[i]) + .map(|i| { + let (x, y) = (i % w, i / w); + let m = u8::from(x > 0) | (u8::from(x + 1 < w) << 1) | (u8::from(y > 0) << 2) | (u8::from(y + 1 < h) << 3); + (i as u32, m) + }) + .collect(); + for _ in 0..max_iter { + if stop() { + return; + } + let mut max_d = 0.0f32; + for &(i, m) in &cells { + let i = i as usize; + let (s, n) = if m == 0b1111 { + (v[i - 1] + v[i + 1] + v[i - w] + v[i + w], 4.0) + } else { + let mut s = 0.0; + let mut n = 0.0; + if m & 1 != 0 { + s += v[i - 1]; + n += 1.0; + } + if m & 2 != 0 { + s += v[i + 1]; + n += 1.0; + } + if m & 4 != 0 { + s += v[i - w]; + n += 1.0; + } + if m & 8 != 0 { + s += v[i + w]; + n += 1.0; + } + if n == 0.0 { + continue; + } + (s, n) + }; + let d = omega * (s / n - v[i]); + v[i] += d; + max_d = max_d.max(d.abs()); + } + if max_d < TOL { + break; + } + } +} + +/// Map `f` over the channels of an interleaved buffer as planar slices (parallel on native). +fn per_channel(w: usize, h: usize, ch: usize, f: impl Fn(usize) -> Vec + Sync + Send) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + let planes: Vec> = if w * h >= 64 * 64 { + use rayon::prelude::*; + (0..ch).into_par_iter().map(&f).collect() + } else { + (0..ch).map(&f).collect() + }; + #[cfg(target_arch = "wasm32")] + let planes: Vec> = (0..ch).map(&f).collect(); + let mut out = vec![0.0f32; w * h * ch]; + for (c, p) in planes.iter().enumerate() { + for (i, v) in p.iter().enumerate() { + out[i * ch + c] = *v; + } + } + out +} + +/// Membrane fill (no source texture): harmonic interpolation of the known pixels into `hole`. +/// `img` is interleaved `w × h × ch`, `hole` has `w × h` entries; on a size mismatch `img` comes back +/// unchanged. +pub fn membrane_fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool]) -> Vec { + if Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) { + return img.to_vec(); + } + // no pixels: nothing to fill (and `ch` would otherwise size one plane per channel, whatever it claims) + if hole.is_empty() { + return img.to_vec(); + } + per_channel(w, h, ch, |c| { + let mut v: Vec = (0..w * h).map(|i| if hole[i] { 0.0 } else { img[i * ch + c] }).collect(); + solve_membrane(w, h, hole, &mut v); + v + }) +} +#[cfg(test)] +mod tests { + use super::*; + + fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec { + (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() + } + + #[test] + fn a_zero_area_image_comes_back_unchanged_whatever_its_channel_count() { + assert!(membrane_fill(0, 5, usize::MAX, &[], &[]).is_empty()); + assert!(membrane_fill(3, 0, 1 << 40, &[], &[]).is_empty()); + } + + #[test] + fn membrane_reproduces_linear_boundary() { + // A linear function is harmonic: the solve must reproduce it exactly inside the hole. + let (w, h) = (80, 60); + let unknown = disc(w, h, 40.0, 30.0, 20.0); + let truth: Vec = (0..w * h).map(|i| 0.2 + 0.005 * (i % w) as f32 + 0.003 * (i / w) as f32).collect(); + let mut v: Vec = truth.iter().zip(&unknown).map(|(t, u)| if *u { 0.0 } else { *t }).collect(); + solve_membrane(w, h, &unknown, &mut v); + let err = v.iter().zip(&truth).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(err < 2e-3, "{err}"); + } +} diff --git a/crates/develop/src/inpaint/patchmatch.rs b/crates/develop/src/inpaint/patchmatch.rs new file mode 100644 index 0000000000..5e9c73cb58 --- /dev/null +++ b/crates/develop/src/inpaint/patchmatch.rs @@ -0,0 +1,587 @@ +//! Hole filling for Spot Healing: patch-based completion, proximity match and texture synthesis. +//! +//! * [`complete`], content-aware fill: the multi-scale "space-time completion" EM scheme of +//! Y. Wexler, E. Shechtman, M. Irani, *Space-Time Completion of Video*, IEEE TPAMI 2007, with the +//! nearest-neighbour field computed by C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman, +//! *PatchMatch: A Randomized Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009 +//! (random init, propagation, exponentially shrinking random search). Each EM iteration finds, for +//! every patch overlapping the hole, its most similar fully-known patch, then re-estimates hole +//! pixels by a similarity-weighted vote of the overlapping matches. Coarse-to-fine over an image +//! pyramid (the coarsest level is initialised by membrane interpolation), so large holes stay cheap. +//! * [`best_offset`], proximity match: the single displacement whose surrounding ring best matches the +//! ring around the hole (sum of squared differences), i.e. an automatic Healing Brush source. +//! * [`synthesize`], create texture: patch-based texture synthesis in the style of A. Efros, +//! W. Freeman, *Image Quilting for Texture Synthesis and Transfer*, SIGGRAPH 2001 (blocks picked from +//! random candidates by overlap error, feathered overlap instead of a min-cut seam). +//! +//! Ported from PhotoCraft's `algo::inpaint` (MIT OR Apache-2.0); its proximity match and texture +//! synthesis are left out. +//! +//! All functions take interleaved `w × h × ch` normalised floats (any colour model/depth) and a +//! `w × h` hole mask, and return a full buffer equal to the input outside the hole. They are +//! deterministic (fixed-seed hash RNG, results independent of thread count). + +use crate::inpaint::Cancelled; +use crate::inpaint::membrane::membrane_fill; + +/// Below this many grid cells a level runs single-threaded (thread hand-off costs more than it saves). +#[cfg(not(target_arch = "wasm32"))] +const PAR_MIN: usize = 128 * 128; + +/// SplitMix64: tiny deterministic RNG. +#[derive(Clone)] +struct Rng(u64); +impl Rng { + fn new(seed: u64) -> Self { + Rng(seed ^ 0x9E37_79B9_7F4A_7C15) + } + fn next(&mut self) -> u64 { + self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); + let mut z = self.0; + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) + } + /// Uniform integer in `lo..=hi`. + fn range(&mut self, lo: i32, hi: i32) -> i32 { + if hi <= lo { + return lo; + } + lo + (self.next() % (hi - lo + 1) as u64) as i32 + } +} + +/// Parameters for [`complete`]. +#[derive(Clone, Debug, PartialEq)] +pub struct CompleteParams { + /// Patch radius (patches are `2r+1` square). + pub patch_radius: usize, + /// EM iterations at the coarsest level (finer levels use fewer, down to `min_em_iters`). + pub em_iters: usize, + pub min_em_iters: usize, + /// PatchMatch passes per EM iteration. + pub pm_iters: usize, + /// Levels where the hole is wider than this (in that level's pixels) only *refine* the upsampled + /// match field (one local PatchMatch pass and one vote), which keeps big holes tractable: the + /// structure is decided at coarse scale, fine levels just add detail. + pub refine_extent: usize, + pub seed: u64, +} + +impl Default for CompleteParams { + fn default() -> Self { + Self { patch_radius: 3, em_iters: 8, min_em_iters: 2, pm_iters: 2, refine_extent: 96, seed: 1 } + } +} + +/// One pyramid level. +#[derive(Clone)] +struct Level { + w: usize, + h: usize, + img: Vec, + hole: Vec, +} + +fn downsample(l: &Level, ch: usize) -> Level { + let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2)); + let mut img = vec![0.0f32; w * h * ch]; + let mut hole = vec![false; w * h]; + for y in 0..h { + for x in 0..w { + let mut n = 0.0f32; + let o = (y * w + x) * ch; + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let (sx, sy) = (x * 2 + dx, y * 2 + dy); + if sx >= l.w || sy >= l.h { + continue; + } + let si = sy * l.w + sx; + if l.hole[si] { + hole[y * w + x] = true; + } else { + for c in 0..ch { + img[o + c] += l.img[si * ch + c]; + } + n += 1.0; + } + } + if n > 0.0 { + for c in 0..ch { + img[o + c] /= n; + } + } + } + } + Level { w, h, img, hole } +} + +/// Summed-area table of a boolean grid (`(w+1) × (h+1)`). +fn integral(w: usize, h: usize, m: &[bool]) -> Vec { + let mut s = vec![0u32; (w + 1) * (h + 1)]; + for y in 0..h { + let mut row = 0u32; + for x in 0..w { + row += u32::from(m[y * w + x]); + s[(y + 1) * (w + 1) + x + 1] = s[y * (w + 1) + x + 1] + row; + } + } + s +} + +/// Count of set cells in the clipped window `[x0, x1) × [y0, y1)`. +fn window_count(s: &[u32], gw: usize, gh: usize, x0: i32, y0: i32, x1: i32, y1: i32) -> u32 { + let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize); + let (x1, y1) = ((x1.max(0) as usize).min(gw), (y1.max(0) as usize).min(gh)); + if x1 <= x0 || y1 <= y0 { + return 0; + } + let w1 = gw + 1; + s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0] +} + +fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize, usize)> { + let mut b: Option<(usize, usize, usize, usize)> = None; + for y in 0..h { + for x in 0..w { + if hole[y * w + x] { + b = Some(match b { + None => (x, y, x + 1, y + 1), + Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1)), + }); + } + } + } + b +} + +/// Per-level PatchMatch/EM state. +struct Solver<'a> { + w: usize, + h: usize, + ch: usize, + r: i32, + img: &'a mut Vec, + hole: &'a [bool], + /// Valid source centres: the whole patch is inside the grid and contains no hole pixel. + valid: Vec, + valid_list: Vec<(i32, i32)>, + /// Target centres (patch overlaps the hole), row-major. + targets: Vec, + /// Cancellation: checked per row band; a cancelled solve's output is discarded. + ctl: &'a (dyn Fn() -> bool + Sync), +} + +impl Solver<'_> { + #[inline] + fn is_valid(&self, x: i32, y: i32) -> bool { + x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize] + } + + /// SSD between the (clipped) target patch at `t` and the source patch at `s`, per sample. + fn dist(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { + let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); + let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; + let mut sum = 0.0f32; + let mut n = 0usize; + for dy in -r..=r { + let ty = t.1 + dy; + if ty < 0 || ty >= h { + continue; + } + let sy = s.1 + dy; + for dx in -r..=r { + let tx = t.0 + dx; + if tx < 0 || tx >= w { + continue; + } + let ti = (ty as usize * self.w + tx as usize) * ch; + let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch; + for c in 0..ch { + let d = self.img[ti + c] - self.img[si + c]; + sum += d * d; + } + n += ch; + } + // Early out: the mean can only be ≥ sum / (full patch size). + if sum > cutoff * full { + return f32::INFINITY; + } + } + if n == 0 { f32::INFINITY } else { sum / n as f32 } + } + + /// One PatchMatch pass over all target rows, in parallel bands (each band propagates within itself). + fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) { + const BAND: usize = 16; + let w = self.w; + let reverse = pass % 2 == 1; + let band_fn = |bi: usize, nn: &mut [(i32, i32)], co: &mut [f32]| { + if (self.ctl)() { + return; + } + let mut rng = Rng::new(seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40)); + let y0 = bi * BAND; + let rows = nn.len() / w; + let step: i32 = if reverse { -1 } else { 1 }; + for ry in 0..rows { + let ly = if reverse { rows - 1 - ry } else { ry }; + let y = y0 + ly; + for rx in 0..w { + let x = if reverse { w - 1 - rx } else { rx }; + let li = ly * w + x; + if !self.targets[y * w + x] { + continue; + } + let t = (x as i32, y as i32); + let (mut best, mut bc) = (nn[li], co[li]); + // Propagation from the already-visited neighbours (within this band). + let nx = x as i32 - step; + if nx >= 0 && (nx as usize) < w { + let c = nn[ly * w + nx as usize]; + let cand = (c.0 + step, c.1); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + } + let nly = ly as i32 - step; + if nly >= 0 && (nly as usize) < rows { + let c = nn[nly as usize * w + x]; + let cand = (c.0, c.1 + step); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + } + // Random search in exponentially shrinking windows. + let mut rad = search_radius; + while rad >= 1 { + let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad)); + if self.is_valid(cand.0, cand.1) && cand != best { + let d = self.dist(t, cand, bc); + if d < bc { + (best, bc) = (cand, d); + } + } + rad /= 2; + } + nn[li] = best; + co[li] = bc; + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + if w * self.h >= PAR_MIN { + use rayon::prelude::*; + nnf.par_chunks_mut(BAND * w).zip(cost.par_chunks_mut(BAND * w)).enumerate().for_each(|(bi, (nn, co))| band_fn(bi, nn, co)); + return; + } + for (bi, (nn, co)) in nnf.chunks_mut(BAND * w).zip(cost.chunks_mut(BAND * w)).enumerate() { + band_fn(bi, nn, co); + } + } + + /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches. + fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) { + let (w, h, ch, r) = (self.w, self.h, self.ch, self.r); + // σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this). + let mut cs: Vec = cost.iter().zip(&self.targets).filter(|(c, t)| **t && c.is_finite()).map(|(c, _)| *c).collect(); + let sigma2 = if cs.is_empty() { + 1.0 + } else { + let k = (cs.len() * 3 / 4).min(cs.len() - 1); + let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b)); + v.max(1e-6) + }; + let img = &*self.img; + let row = |y: usize| -> Vec<(usize, Vec)> { + let mut out = Vec::new(); + if (self.ctl)() { + return out; + } + for x in 0..w { + if !self.hole[y * w + x] { + continue; + } + let mut acc = vec![0.0f32; ch]; + let mut wsum = 0.0f32; + for dy in -r..=r { + let ty = y as i32 + dy; + if ty < 0 || ty as usize >= h { + continue; + } + for dx in -r..=r { + let tx = x as i32 + dx; + if tx < 0 || tx as usize >= w { + continue; + } + let ti = ty as usize * w + tx as usize; + if !self.targets[ti] || !cost[ti].is_finite() { + continue; + } + let s = nnf[ti]; + let (sx, sy) = (s.0 - dx, s.1 - dy); + let wt = (-cost[ti] / (2.0 * sigma2)).exp().max(1e-8); + let si = (sy as usize * w + sx as usize) * ch; + for c in 0..ch { + acc[c] += img[si + c] * wt; + } + wsum += wt; + } + } + if wsum > 0.0 { + acc.iter_mut().for_each(|v| *v /= wsum); + out.push((x, acc)); + } + } + out + }; + #[cfg(not(target_arch = "wasm32"))] + let rows: Vec)>> = if w * h >= PAR_MIN { + use rayon::prelude::*; + (0..h).into_par_iter().map(row).collect() + } else { + (0..h).map(row).collect() + }; + #[cfg(target_arch = "wasm32")] + let rows: Vec)>> = (0..h).map(row).collect(); + for (y, r) in rows.into_iter().enumerate() { + for (x, v) in r { + self.img[(y * w + x) * ch..(y * w + x + 1) * ch].copy_from_slice(&v); + } + } + } +} + +/// Content-aware completion of `hole` (see module docs). Returns `None` when there is no fully-known +/// patch to copy from (the caller can fall back to [`membrane_fill`]). +pub fn complete(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], p: &CompleteParams) -> Option> { + // Never cancelled, so never `Err`. + complete_with(w, h, ch, img, hole, p, &|| false).unwrap_or(None) +} + +/// [`complete`] that can be cancelled (checked per EM iteration, PatchMatch pass and row band) +/// (`cancelled` is polled per EM iteration, PatchMatch pass and row band): `Err(Cancelled)` once it +/// returned `true`. `Ok(None)` also for mismatched buffer sizes or `ch == 0`. +pub fn complete_with( + w: usize, + h: usize, + ch: usize, + img: &[f32], + hole: &[bool], + p: &CompleteParams, + cancelled: &(dyn Fn() -> bool + Sync), +) -> Result>, Cancelled> { + let check = || if cancelled() { Err(Cancelled) } else { Ok(()) }; + if ch == 0 || Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) { + return Ok(None); + } + let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return Ok(Some(img.to_vec())) }; + let r = p.patch_radius.max(1); + let psz = 2 * r + 1; + // Pyramid: shrink until the hole is a few patches across. + let mut levels = vec![Level { w, h, img: img.to_vec(), hole: hole.to_vec() }]; + let mut ext = (bx1 - bx0).max(by1 - by0); + let mut exts = vec![ext]; + while let Some(l) = levels.last() { + check()?; + if ext <= 2 * psz || l.w / 2 < 3 * psz || l.h / 2 < 3 * psz { + break; + } + let d = downsample(l, ch); + levels.push(d); + ext = ext.div_ceil(2); + exts.push(ext); + } + let nlev = levels.len(); + let mut nnf: Vec<(i32, i32)> = Vec::new(); + let mut prev: Option<(usize, usize, Vec)> = None; + for li in (0..nlev).rev() { + check()?; + let Level { w: lw, h: lh, img: mut limg, hole: lhole } = levels[li].clone(); + // Initialise the hole: membrane at the coarsest level, upsampled result elsewhere. + match &prev { + None => limg = membrane_fill(lw, lh, ch, &limg, &lhole), + Some((pw, ph, pimg)) => { + for y in 0..lh { + for x in 0..lw { + if lhole[y * lw + x] { + let (sx, sy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1)); + let (d, s) = ((y * lw + x) * ch, (sy * pw + sx) * ch); + limg[d..d + ch].copy_from_slice(&pimg[s..s + ch]); + } + } + } + } + } + let ri = r as i32; + let hs = integral(lw, lh, &lhole); + let mut valid = vec![false; lw * lh]; + let mut valid_list = Vec::new(); + let mut targets = vec![false; lw * lh]; + for y in 0..lh as i32 { + if y % 32 == 0 { + check()?; + } + for x in 0..lw as i32 { + let cnt = window_count(&hs, lw, lh, x - ri, y - ri, x + ri + 1, y + ri + 1); + let inside = x >= ri && y >= ri && x + ri < lw as i32 && y + ri < lh as i32; + let i = y as usize * lw + x as usize; + if inside && cnt == 0 { + valid[i] = true; + valid_list.push((x, y)); + } + targets[i] = cnt > 0; + } + } + if valid_list.is_empty() { + if li == 0 { + return Ok(None); + } + prev = Some((lw, lh, limg)); + nnf.clear(); + continue; + } + let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, hole: &lhole, valid, valid_list, targets, ctl: cancelled }; + // NNF init: upsampled from the coarser level where possible, random otherwise. + let mut rng = Rng::new(p.seed ^ (li as u64) << 20); + let pw_prev = prev.as_ref().map_or(0, |p| p.0); + let old = std::mem::take(&mut nnf); + let mut new_nnf = vec![(0i32, 0i32); lw * lh]; + for y in 0..lh { + if y % 32 == 0 { + check()?; + } + for x in 0..lw { + if !solver.targets[y * lw + x] { + continue; + } + let mut cand = None; + if !old.is_empty() && pw_prev > 0 { + let pi = (y / 2) * pw_prev + (x / 2); + if let Some(&(sx, sy)) = old.get(pi) { + let c = (sx * 2 + (x % 2) as i32, sy * 2 + (y % 2) as i32); + if solver.is_valid(c.0, c.1) { + cand = Some(c); + } + } + } + new_nnf[y * lw + x] = cand.unwrap_or_else(|| solver.valid_list[(rng.next() % solver.valid_list.len() as u64) as usize]); + } + } + nnf = new_nnf; + let refine_only = li + 1 < nlev && exts[li] > p.refine_extent; + let em = if li + 1 == nlev { + p.em_iters + } else if refine_only { + 1 + } else { + (p.em_iters >> (nlev - 1 - li)).max(p.min_em_iters) + }; + let pm_iters = if refine_only { 1 } else { p.pm_iters }; + let full_search = (lw.max(lh)) as i32; + let mut cost = vec![f32::INFINITY; lw * lh]; + for it in 0..em { + // Costs change as hole pixels are re-estimated: refresh before each PatchMatch. + for (i, c) in cost.iter_mut().enumerate() { + if i % (lw * 32).max(1) == 0 { + check()?; + } + if solver.targets[i] { + *c = solver.dist(((i % lw) as i32, (i / lw) as i32), nnf[i], f32::INFINITY); + } + } + // Wide random search on coarse levels / first iteration, local refinement afterwards. + let radius = if refine_only { + 2 + } else if li + 1 == nlev || it == 0 { + full_search + } else { + (4 * psz as i32).min(full_search) + }; + for pass in 0..pm_iters { + check()?; + solver.patchmatch(&mut nnf, &mut cost, pass + it * pm_iters, p.seed.wrapping_add((li * 1000 + it) as u64), radius); + } + check()?; + solver.vote(&nnf, &cost); + check()?; + } + prev = Some((lw, lh, limg)); + } + Ok(prev.map(|(_, _, img)| img)) +} + +/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the +/// ring of `ring` pixels around the hole, with the displaced hole fully inside the grid and outside the +#[cfg(test)] +mod tests { + use super::*; + + /// Smooth gradient plus deterministic fine noise. + fn texture(w: usize, h: usize) -> Vec { + let mut rng = Rng::new(7); + (0..w * h) + .flat_map(|i| { + let (x, y) = ((i % w) as f32, (i / w) as f32); + let n = (rng.next() % 1000) as f32 / 1000.0 * 0.04 - 0.02; + [0.3 + 0.004 * x + n, 0.5 + 0.002 * y + n, 0.4 + n] + }) + .collect() + } + + fn disc(w: usize, h: usize, cx: f32, cy: f32, r: f32) -> Vec { + (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() + } + + fn hole_rmse(a: &[f32], b: &[f32], hole: &[bool], ch: usize) -> f32 { + let (mut e, mut n) = (0.0f32, 0); + for (i, hh) in hole.iter().enumerate() { + if *hh { + for c in 0..ch { + e += (a[i * ch + c] - b[i * ch + c]).powi(2); + n += 1; + } + } + } + (e / n as f32).sqrt() + } + + #[test] + fn completion_fills_blemish_from_texture() { + let (w, h, ch) = (96, 96, 3); + let clean = texture(w, h); + let hole = disc(w, h, 48.0, 48.0, 9.0); + let mut dirty = clean.clone(); + for (i, hh) in hole.iter().enumerate() { + if *hh { + dirty[i * ch..i * ch + ch].copy_from_slice(&[0.02, 0.02, 0.02]); + } + } + let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); + let before = hole_rmse(&dirty, &clean, &hole, ch); + let after = hole_rmse(&out, &clean, &hole, ch); + assert!(after < 0.06 && after < before * 0.15, "rmse before {before} after {after}"); + // Outside the hole untouched. + assert!(out.iter().zip(&dirty).zip(hole.iter().flat_map(|h| [*h; 3])).all(|((a, b), h)| h || a == b)); + // Deterministic. + assert_eq!(out, complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap()); + } + + #[test] + fn completion_continues_structure() { + // Vertical stripes: the filled hole should keep the stripes (not a blur). + let (w, h, ch) = (80, 80, 1); + let clean: Vec = (0..w * h).map(|i| if (i % w / 4) % 2 == 0 { 0.2 } else { 0.8 }).collect(); + let hole = disc(w, h, 40.0, 40.0, 7.0); + let dirty: Vec = clean.iter().zip(&hole).map(|(c, h)| if *h { 0.5 } else { *c }).collect(); + let out = complete(w, h, ch, &dirty, &hole, &CompleteParams::default()).unwrap(); + let err = hole_rmse(&out, &clean, &hole, ch); + assert!(err < 0.15, "{err}"); + } +} diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs new file mode 100644 index 0000000000..85c5f18519 --- /dev/null +++ b/crates/develop/src/lib.rs @@ -0,0 +1,6 @@ +//! The raw develop pipeline, CPU path: the shared pipeline of craft-libs#587, moved from LightCraft one module at a +//! time. See the README for what is here so far. +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod inpaint; diff --git a/crates/develop/tests/fixtures/inpaint-complete.f32le b/crates/develop/tests/fixtures/inpaint-complete.f32le new file mode 100644 index 0000000000000000000000000000000000000000..3e2a4d70ad3ed317178a56bc9769ba387f26bca8 GIT binary patch literal 82944 zcmZ6!d7RGW_s2iNSce(Q7|bwZ%*KqFF=Nc;dJiH}mP95?QjHV|A0M>w5u!~gF;tW- zOCs5_4_RkqUqY4cd5a$9>q(&(_F1Q&Vh>;IWs2e0|m( zTh%w#syfwu{9~(vefV;x5FZ|UsiqH4%fIWJ&+fwe|DSRFv`@yGmTzmcIoKM(MTMob zAMmO=QNBJOTNUk_&*e_BK7QP#I3FKAwxN$-RVTrR{rmzI+qkwy8`suo<5u&v>6;hq zo2Q?jt&ujDJEi;j9CsnXXvF&_)eqZNN-&l{WYVX6BJ9YHoahE#zaQN8HKHI#!H09~j z&o5nh8`suoHfEPkwohyE~Dar+kXERR$Ex2ug+f3U58 zsj++p?<${rzOjsJYka@BvHXo}jhjz4R{f#vxtZWzU!&#P_kh!!&LBIWyUV%#Olf3c2nZH&+zKn0^J;CM^KE1K z+pSeRba7)D_b;{G@83ec+kPJH%av>)I#9x6?e3rE9{K}6~vJeF4c)gR40^auXL zjpj1$e(m$ZM~r(&`>gW;;~rJM^SgXj$CV#Ho;lkZ*NtJ$w#FNy8ms=$XQ!i#TUGlX zcaU+b>wMPiW!zxpuN5_yIfp18wX?a{)>Qt>v*8WR=#kjGG(`PsL&>z|inAu#O$A)VA<)_R! zLHWZ|o6ER?$`_|IZjkaJO&HhK*glzYt116x0-vF+aaA01wl!XfYOMOhSnb|m+zjn= z)GK^eS!%odzs)`Lhc*`nGiRr`?m*_8qxkU``FlmG?b8+beCjLzNg2MY(aP^C$+)&g zKR@PdYix2qS!^3>`xovctNt+7_KwXx^oQ@vUym?udu`LWE#r1nzHck$+)4RQoAX(9 zR=lrSa~U^H@y{ocW!!YdRewsBaczxl4l%B+@%4Slsy~eN?e1i;wKbmKnXLM=v~+i$ z{(#XO^aqU2pg-X0!%cq%hrZ=X4>J9MAK1_I2YyLu(;xU+fAd*AqPAmi^SA4)*fb$m zvFSi>hb_-O`hzXcJNg69GmifQ&vT9bfG3BU{(%3fZu$f6SIP7T+XV~wTTIaQ)n}Rh zz>l2H-^

Gl>3R%X5eS1Lj#nf51Fn=nu9$Q|J#o&k_0qKe3>>>JR+g@0+XsfS+B~ zT=fS$rvu~K8Y{P9TwCLa9Md1#*mr)l_R04g{ekDZjsAf7KBGTizQgDbnC~t6!+hTE zYx)C!^C`Y#{>u02X8Hp^<7Tqz54hYFzCTB`{~^C5tNy^-cg)sk->YJ6!*>b)hp}2k zn*PxKo7$#7;9AufH(2L3rXq6=QGB(O=?}Ku{>qVY?`og<`FvOJ>)K0A;=65YeCciG zW@|h$n(uZ=?We`7%(Il@MMIKRf9Nx3dyb47t^9(GIWlgn&a>L;9MvD@_Quj2)gSP$ z^K(>xz@5Lu?+8@ej~(OM8vjmX+^WhypUAk?w9kDpe1^8h>~Q96Yn&I7EaRqY`^*81 zo1u92b2+L%%(GIj9MvDj9p05WJMFW$J#)^{_K!Z4BjZLYe!nu@SBy*0_Hcfv>65EE_=NIdeRDWonS|vyI2mE8buO z&l5L1)gRhFblFq=fgeAfaczw^Mlr6fvF8ZJ&C-6h4PwsOij!Yp&bG$seUemv7A|<( zr$6=T^-(_u{eeew&>#5B0j57-{1f~iFn$RB4;XD>|Aj4n1^NS@aK!WnzNipQ$W`9_ zf!>Pw-A8|D&+j|>1Lk)e{lT`%HFV&6<(HmC2i7T%KH&e*p5IygA27eC=nt6RP5d9Q z>42^A!3Rx$;Cc4ZAI9Q$4gG=Vc}IW1{7#`i;0f}Kqd(xd9;QFo^814S1JCaW{tvu8 z%eF>-7tkNtgl^+Iyh8EXHGJn+EAGC8=W(st-kY7Q`a}DITYOLaJo@Z&F-P?WzQjqs z+a*2l%>6u5r4`%r=&$(XTE5Twwa+eHOn+#9vn}HuRi5V#{|7!Lg=fmv$g_t313x&_ z^asrIh5y5Rjy}z})paa;rh=6ZX~&#HlwavF=bDPUrkeiH56=$z1Ma_x@3yV6!V13I zCA9s51$?(lYM&3!NRoM$QvSk6Nvc2CE;wZF8-NXDUu@Cl>HbHB`RQ zN>BBN`R`un$+&^aKlmWy1}QF1XWXia-%McKYKrUCOH%#8c2h8OwlzLoAxXwf*RkSy zFm8sn-`>$v{b6o>TY0KK;4+!a*=d`(jhJ(e+O~@HWZX#Q*RDyF&!@if-IpY){$P7= zcA|`HYs}A2lsU&~`;7M!#n#q%WOSnH5A&QU?l1liwmI9K>JR)$akbGO_&1h1)gN%! zT&Ma2UMJfg{2y>i3gg-u_r)--t#NQD<7VkRgMyfIwzgkVnmOAVJKSre`tz~t=hGiB zJ`ef>#?L{2&ZfVwn#2AJp8XE`13$W@=?^?QgZ_XY*kSquW`BYI12&%|S8dG?>8(7z z2l_*w=n48mdwdM^2aI2V{($kZ(H}7WGx~$=u=h-V;Oo^h{eiz-#q{8d{cJ^=m? zJiq(s518M2^aoph-_aj#CPss3PFadI=&AMok1%~XHD%m3R<#_g!K6Z$q&{ekb*t(oc%V>NEuO!Wu;=MxDs zuC4Lg-3c;ohR$=`h6EWmOL6xl393KXCVr8i`h#t$NeQYy{@q{p=}*|U4;}Fw^aq~3 z75W3l&q05{Xb$=VCLV(SgDw6H`U6kA0{;gdok4%#i6`LyfF})QKhj$<`+f8W9&JH? zuw_4v{=lCeYx)Cke#koI*;5*#o_tDmvd!FCZW!fkH zGyV^4_}$01I{vNic z$MSo+U;E_u8vTLaRnqi__B{LO5BTR3JX5C>pWn$dSgiQ^%0$&4Y~(-&ypBHaz3_Kj6+^I$7^s?UUbA{2%(v4mbUw4bL_D1JCa!`U9VPzLDw= zxX*z`sy|?RmZP=J=jBa*u>I-}o~bzHm!9RBYN&m#+1pI@2iq;{i3bO2n>ihLmV*>8 z&SqR&{_2k`)gNrfkB^seZH<$L z#>==FI?w5S;$_?{?PpGhc$ssy;>FqVsz3CzDlT62XZWyTKK%i+=R$wFcA2a`5BdWi z($4e;-r}*-lqU{@{?G>B2K@mOS3!Tkv9Fu{U~7A#T;**a)LX}5?}Pr(p8XE`17?qd z{(#xn;QxTjWSaj&pZF)}4?J-O^aq}J0{R0_+yMOnn;-IlV)h{D4?MmH`hzWd4g4Q? z{0;O6o;?Nr4?I2w`UAclYx)Cbf6e|2%s!g^7q;e0*c#avqd)MayPN*d-hBSmYKxzb z{=lOZ_&;F$dGrTce0cN+9={#^f&Zn3=?}d51OD2k&qXKW?$>^X4db`_km41+dB%_G zeE8i*f3P(l`;_wLR~IXfFOC008-Cx>A8^-H(;u+uK(NkdzrX1Ze3fg>RDYOfr=!he z+`HN*zuo8$ZFu(af564*=zy)UUOm$vYJW~yoFL5$k^#|LW?b$MJpz>Y1@GJ-E{6BU)%eKaSF`SiE(>6gt393Kz+2J0~ zV~Fza7st!E>1umBmS;Ib`P3@esy~c1JRP1=4Pt?fK#Mz^angRw4sb^Yg|&AakI3~->x>0IcIB| zgd+`9f9SLSrUt4%6N{(%^ylJ7Z@4}GG5rB^-h}>uS9+#DV2cA!bJ%`f-t-6F&Qn?| z-*bfN4?O1=_&;FcE%-lRJ1^+1xM5|}ANoXR&>z}lr$$fkYTO<1m{2%Re8#=IB+kCJHe_*Zhr6wh+ z{?HG52lNMAO^(XYAMp6k(SeeR|9lf2DDBbbz<&54{>m4(H~oQ6IKprDAsy?Bbv)xo z6<43dbA4R#`0?n#DaH2(@a)?fU+&yU^@nls=g}Yf9Q6vmM0FkO=2PfEu;RY0(18%e z#~PUaVA~sSFJ`AzrJKL7VDI$&$O*%lqJH9nt+4wTY9k5@DOp-+C_ z(I5J}oW*Z?thVVLfeyqezu({VhxQL$&QkpWui2X=;|6N`(%pHMgA|X*;WypZcqJ-c z^@sMoE5xh*FxG)u|cIQoO_FC`kP{(y7OH;{2{jYWkGWX`t6oNpV5Z9{GU-INBZKaADs zXol(!wp-R`$hhsbP5SH%8MmY2MH4bqe`r&8V20`swjVv7q51>=^9j!R({-MmHpj`h zw#Fa6ij#4(w4aRk<5YiWzi3FD>JKCT=?{ERkm(Qj``?LaysPc)yuj8-3!$VIZ{P`uzjVj=?}cc37058YnurtfHH-+5Ul*4Z=wSs%Fli-TWo78 z|L8;6^1Z#Q^C>Fi_x--&p^N!Vw>8%J03EP3ZX1LS*cxB%j1H92K0}(s%eYb6=f%PN zrbjFO=y80BSjE|C=s=ueGy(sIwZC^aQ}u`Wrya|baRZfK(VO3NTjNtL_)WJpmZ?up zO*QR@-+K06*qRR58XwrvK*mj1e!oAyM27bH+OHX^KeUh9nW6dv-n|eVaN2&@d+0!p zVxE2Uhk4Gp$+KKv`8J1mmZO!wz7idkUoAUep(XO4!6F-^# za*^`*Ek|bUQ9NKK8nRz;yEll7<|`&HT2%O{+FCrs*2sB8YRW9-Id{m*o2%{F*G$Ww zueeK>L>c#@;vN&7jC)0K<^U(-UQ=82q{87F%HNK4GUq>(XU{UY**)cnSNQpDRLnjl zHD$Bn2OmU3wkl?CGA)0H+WPt7!xSoyhLrHzqx{-6#3jngT*v7iWbCDKif8UeLnnd+;iF|x-mWff{wLd0h(}GG4X*Ce%BP|<)It4 zM)nbX^KPqcy?XI7Zf)%|t_S;(FdeH*CK^&ld9>nkr*Opuw|JH#6thRDJ2q1B8%x<2 z_^Yk$3v7)+L1;)h<=G3Qrq~+s6LuF?RNDm$*cVh%Jbruw8JF1ZIPq!G0b+JDC0_`C zfc^P6i4UM5JTo)pcLxn=qI{W5G$c*&FEuh`+?tBfgwzyU=_@;TTV zQ&P~7aOH!7&=6bWZ&zbwTyk#4$sQjaXsLL=f4cmQS}9(7wyBKUT5Ts5G?h8GQGUS8 zrefPx`F3wKmG!b`8z-N8toOWphrmCdh>`#2cXymyy9Q0LHRk8X$eeAB!-mC(ZK}5E z(j`X5?V^45n3yKxc2z!eK$?u(O>s!OG#NKn@$J|&nR9o=`~B0zwx`-IJ==uO$7Q}h z%cnmxZ%&ZkS<@eQ@^jE1cw)=w514qeXq{qW$mkC|abxrcTVloN4?OW<^amczL4V-w zEa_{-30Lu3@)Q%F*#9FW{duS(HZmyOl%hY z0hT{=nn6pg-V%k;Fx3Dh|&z{edS=g8pD@@zVL)h8QXO z15Z2z{h>XvQ1l0ke}evicQ0(F`UB={0{y|3y$t#TkDj1E@Yh!of7q%#XA0;KZHQH( zKVagM=nt5fB>ICb`xNvCp4cP$15dmW{eic*L?y*r)}sS~iVsiCl5x*zpTr-~A8gr! zpg-82-`P<02man{{0CcOz({5A4T&q>j#KbW8Rl;mS`A zGyS2@ul_&>B9&jWmwkc1;yE4IkCausDvte#t#MaL(;sZvJD@*|i~oTBz?Yg7C*w9! z-rJ5pkfgZtm-qw8it!oHA8dzrO;`QF_MIeri8SRuFP|>s*3>@n6VM;pPwzvXa;W0P z*|G9D)KR=C7+=EHXud&&+MeGTqxyqwWQnG#Ka7=jjAyx(+O}Pe4zyN`CZIpGAJ`8a zXsdX1%QV#=Z2NDDR{f#P$m!&XC+S#|hDOVrZH;p}M9Z9QjjQ6KRexx|t7No{+eP~< zli5VZ?W(plt2L2vyD6V=HC6S8vApf6sz2C1_GPNr_S81dy_U-7BXQaHeEI_>4;lXl zOim#BGdOgf=H;S4@SK&SKk%Gep+E2yC!79&$=gJKz~oP&KVbYE^aoosXZFiqD?fCL z=?^?{VDyLf$E%tCfQiqbKVZub8Kszg6Z(Vg{Q;&ww85W2f8dw@*YpP-ox%SBlV5@V z1AgzWQ~w8i@JG&N^3~Sjv7c%iJC~WM{Mg(0A-2Y%LVi!?Y8&Dw_&@a1bA;&+7;Qm+ zm{0I%(;s-wH_;#Xxs6PJ;IEc4{Q+|hg8qPsi=sc^&l;NkVEao6(;xVRBlsbO+9!J% z^ap<37~-O3JutCN^aniby)4xq@P=oIhXhF8+C2Hazz?aUZ8`*+{=iQ;m#O+gd-f^l z5BTpi(;sl_0Mj4v`^7x_w#GxN8>s%k*ZH7<>JNS5Z=gT$ho|C8)KSbH1pR^U+X_D< zLh(1XO@FZc<2w5Sf8}fR$CoIp^M9%ZzJ#rDUI>0j1#N?0f&S2E(;wIu*cwMpkCky7 zsqM8Qe2FA&lRg_?B3b!SuQXNt!FGGcrm8>Sz!?0HG;QDQuQVCAregdD^oMzFcr-@! zhxTRa$Eg0mcesZR*czwoK?iJ&r{+e>xN^QC?K>T9qWS~Q|E7ujjaq4+r^liLt+h>D z4|Jf7@`D;T5!<%PuP)m}^#|J{qoY)Rz~Q-3sz2c86Qg8YTjP?_Q8MQgwY_t!zUmM2 z%=xyyjN3)|rDs!Q+^&l6e$RcAZi<_Km?GomDxT1ndmr6(KKq(+N2aIpwd76&`V$oN zp-+DnE?Dqy4s*2fqcAXGZuxU}7@p516wd{2%({ zJP7@PCzgx;z>{ai{tJHkaMK^~Z&%sNe5!o^O~hkujpSpXKiIM-LVsv)=QZ<{=Zpsb z2cB~o^aspY4E_(8_zC(0X79uPi#~~&;QzqmtDryd?03)~_=jh(m)WYA*a-d)JbN7U z2aJD${$R_Q2>Juhz6Sk)=j;Rj2cGi|^aqSjg8qPyK8+s|sJLsY=?}K-U(g@g#J=7@ z#=Wd#;fJvQg0EN4^ao5F1OEpcx-Cxi2V8IqUm{HBgYSX^28|c ze`u3h#qF&fOY>mVs&>z~c2SI=6^Ywi(sz31eX2;05jkL|o{rD0|io@pO zOC&3vK0HnJ2V3?U?7y&`9EKl~rhQhqruz%!iPNAzv?)&K&Q_@6-W8%%f8c*UfezRj zyDvcpY>j9I`omanEX9{-skVQ25Gmu@8rQCglsTtp`;7M^Rexx+qIaa~54JrfHkNU_YMY}^ zbKj(!j@31_v5cFm{C@w&sz2CvI!cauPvv(nWG_=wzP}&)^auP)3G;u>rZ09=_n7{` zKRm(C0tZO@H8*p2ZKTBspn|C3cM;66nDPkIs;1=bZM5o}fSQ zoP(f0VD>WT54J0M<9pZ|pHDRXfv@#r5!0xsc=O3<)gR_FbaAwd z+emr*4fF@TPHXhly9bq;#a}599VZP*3%THCCThPsX)1ZW~lj=A5E^j>xH}`a}DM zmFubgfXm34GWr8vU6%VM-4wrgI7!CMRogJhYsLSe&7S{|qux{b(Jk4_)RbJWr9S<6 zGhwRU+hYF(CWjgS2WLzznsudr6-ukI#et&?jf*=nuA*4?IsX_ioT1c=Ghn zA29b^i2q=VpM(DckLKY2!2i_F_FwRJmOV<_aDI*d1J9W?{tp=62K~X7v*|167dpSh zDQ@1V9PimZU%N}+PH|PA&+%S5{*4l4>4TXIexSms7u$#P&+ zO!Dq6ebsGfF~#kBD#?51pSN6%it}8hU5Vb?+vRU~agrPUfSgaw`O+n4%y5O#jl3Vr zeCw_(pX9PWO7O~U|HGAibB;T>Bhw4`yrfqvf3n+jFw#PVM5 z)v3<=D#Ht^Skdb+ZHj9%F2fu8YJm4b<{~$^Z-)2B!>8Oo>!vt&P4Zid&bZwlEpoBv zc$T;7df)D3`or2et3`iUJLfX!4?JhG_&@NR!{YzIbM}h=17^R2{{yy|Y9+;2OPT&) zd+^6})gRh?>`Z^)UoB_)1K;OBtm+T=;TiZIH*^l1mEixthcq$$!8Wc3dzmmD%l0yL zbe?})#}5ft{^VNxkO;+F-@*@xRJ`~x;=cZhiEp4k^x64c_A<7{tS9h8DkxvC9x;uI z+P>VCDAgb4bA4r$>JPZYNqmVUZS(7VVj9V6yXQZtsz0<@>7}avFxKbg@k7$I{kVg= zzfg?7f&S3GVP)>Ghbpf6Q>1(jw#Iw2BUOKBb9x|tNQ92HBQsLQZLaO{G0-2{Y>MZ; zZ7aoJ{ecd&Ry?r)9cZJr!`@34+qTO0>c*ZTUir{%5vo7*Q)*I#>JRu*j|kNt@V=M` znRANTe*b&8>JMxDVqLiE4{es7O;r7X&;KS-#_gul^ajQw53M+2Rk~mCJM8fA=)< zu6+B2+h6>NdwNrXcc|eqm;KNz*Y9?`ckk#u_t#sZC;w!4Wr|9BZ#=)$?K>^G>VKE_ zdIn5)Pe|;dUbz6TM&U9SJw4sa7%l!r>U0-1G~IjnUS+S_v1x8V$8>M>OTW11UYX|Z z?2Yw)iu~1;n>XFn+{m-MRo6~V7yb|H z5BdY&V&0eOQ z;u`(&LnZ|_HCw>V2kBvo4BT3uuUdUc1S@FfeDXKrTFO!*~`U8%X zy#xA#ZO(R{k(&RG#a^bi@*VHhQ~j~A>Z$&K$B)Mk3D@>>I^c)c8aD;klX07?E&c}j zV`H(GX{EfkJxRuGt$dG(+&gQdctltHkhY2^hw)6sD;_^ST=j=}&gsCJo2_wEaJY<{ ztbP7`qOQz2Mcdz-U03yoaclIiE8})izQ@EyGHzGJ!@F|dq?_7K4r?Ui<|@DREP2=6 zmEXOP9Ic+pUmQ%VvZlM$c7{)Xz}!_wf56<^LVv)P!<-_yaH}+*2mOI3hlltNJaHcM z2OggX{Q;AogZ_Xmmw16V9Om_{2$s7&q06SZErP1dAkQRLb2u2j8aVg4ElpD zIWzb_*mACo{{v5M%o8zlTc5AR#yo=-~h);D?6)u{cMYcJR!B;zVc63`Qb0znw$*p{-gfhnf%Y(dO4q+Kd^!~Z_rE^ zl929&l@IU|LT9+hYfZf;7gX{_Z&~Hee$&)j@^GMcT70Sz1Dkr!$$sa3nH%wn*Iv8e zrp3*013u?j-m3F&pKSWW+SwDKKdg)M9sD17azgNb;EAiCKVWh{@PEMMd!RpHJKL=! zIcBS555hhuQ2EDSY%1fP(>|FG`a}EOlZmfhRvexiqxu6sIMnn9%zg*`q0j2GqE&z3 zCl;`m3DdDGrdmhGYTTB6P`KhT6-|F=fAB~AkVxfYKH_}XUv1G7{2$tUv5vh=IpuGR z!Vj@E;*;S2(B_jera$2GJ0n$pz4fB~L^8rW7 ze8!B*bMb4wbODVd7qP@k?(HAHa7}L|dY9UbcGJ$RbXBV*dZR{u;Ce0n!aaH?!E3jB zrfWBGiTiMAy!XP5Z`~UUzi@-*HT2$X_>U_cw8C8;mf?+f&fj~g_zU;nKIvW^dEU3m z{71@p3eP+9ER#vxqmmadc*5N@?~*+4@YPnQdC$o6o*?*Td6s*>bHUwydaY}Dif4JN zt}*co&U$tzCfphVRsDg#`#rIg3d(c7^Z%a@ZQhgl zpg&;dgZ_Zg7W9Wc?;In(dRckScJY7U{kyaGxuN{KwM>7ot@=}x>JPZ!7JHd6?Z54E z_A+&JKJ0hUAKG+HWgirw{D~X*A(6^IyNud#oa%al|6<7E60TVt0l z#8fLPf4mwwM3uBp;vx7y^ixH?+vpEC{~Pu)$%^X^OjiAYpW7%|^@lYkNbVW_5B##P zHNK&J1_iN~sjd9fJ>jZ9w5jt!xatqs{197X!^-#}w#ILF*OhUbt8Jf)+#zkLef~P1 z`);k2AJ`8+q_yJPvG^fv6uLvV=P^CJHlOdSmJpE-9Sw~+j2c&kT2{lks&yjcD-Jb8oU zKZD5?B>x#~`GK7kTYZvTwY4*>-pX_DiTr2!!sLy-j;pe19BhsS>gY0KL7l) zLFcop@^|j_5_8>~wLLGX-UfI2$@#8hlJi!yDst(!=D39=n|VJhJK<{kFLlLpvb@G; zueyxB-?%TDW_sO67q}O1&vBhM#(7&C{pj*)e&uRD&7S3`>nmefe%EoGXOol|@1K88 zDu3;2w3jCL9hm>Z1<~GHl5gBk+J7j1LWJZSv&Ki?Xd)U?LcT*A^=ydzXLw?{|x{Ab!^4j@iT{X^-8d6nx^o0Cp_@Y8I#Ma2ZhWi)r4?Y+!<8mf9SH3^^AsK4>ON~VNthmED zSK^b6M7u1n%l0zVw%{2=Lvj@F_vefQedPO$AA+woSH92WE!rA?K7oeV8uRnf5b_T; z%AC;w$)JQvR13Xh>(}XYMCglUUna z`EJw}&er(b)mkzxIaqV$yHQKVwKeAD)si{e*=@agwdDV8jX$5LDbKRh0=YTgr$3qR zZx$cP^aq}Ldgu?h(Mr=FFmyhn15Z#~^```{d1!lA zZQf@0+QB66+&;OF_QC>}^J$Xzsm$jyX`e6i`Rkvj+~c6^^;;{?p`p_sE(I z@1w-cEFYL;07kF)xyT3lh`%Lub3+aEdCTuSf8y{3TCp zvz$em{=l#3&ED;hexCC}I43%)pB4Eh=nrki%Y4uu@Cca?`UC#I`OqhOBJ>BI`Jg}W zZ<F9V*YVt#RmL@~LB$&&vyyIoleas1qu- zw#GJxYODS*R-cOvRDT%jG4VsVe*xd}Nn(Q?6{l8dp!x$JwUfIWos|zBjee);e9#c| zhc>$>*OYNHl;7}ZO&QnLxTJJV)gRh?u?}r^+J4f|5Y?X}qrdj)5185-_&ecygGz{{<#*8T|p1tBn4DEkC)l+T!z|Kk$pQO@HWfCPE@q@43Gts6$Lu9O#l3%)0p7*0N&toT|L<3Li{7X)X@{;6vKO}ry>nLxu z_#1}>|3~sY&>zKVWnQ{bB9o%A!B;mLE%Q9-m>Fd^h&%XTmuV`U7vduSa!U z@?Fs%c#GwpQofYT2mOI(KKMUi@=wqoFlRvM4|vOZ;<3RxA7ZxX4?O3^=nwNuJH}rA zuJ)NC&l&ndo80rnWBs)K$mzsmZH>fc(I0Ggl{EdK{q>a*sz2}+kBwH_=UyWo8>{#o ziQS<;wCC&w{Q(m{L4UCQ>k;<#fyxtiMStMKbBV{=8i|>pKiKx)R7dp(JZWehv9&d> zimM~zrmHP+67+{Q30JvqlBN7(U&gEczz^>lulfTfHiG_ux2z{`JW}zd;84{c=5u~0 z_c?5h0VDB4sDHRkeG>Es+uZZ`A-2Ym(`%{z!0%odr}_iF@f7*q?bWtcHDZGu)z;h2 zy^l`HKlfU!>JRPTNy5(}$MS3WZNi^TSG+hoL_RB9Jon1c zA9%at*;#R3p6L&~ouT(uK2+{~qd(ZP&q9A_Lw*kW15a%S^aq~%Q20M!?q8!nVD4F? zKVa@tqd(YkZ~DwLkGrY8SGrdMlDv}RySaVqm%G<~le-na^l($he&?qDnCQJ*vX9%k zcbPl+sodLoVyVk}e7mbEze}4UzH`rqEOpW=bd%EI5S1}U#x3; zN1o*plGC+R@&-ANE~%LNIOq>;EHBPq`D;Z@`aaHyj_T(|&Kvpz z&p8qP5BU9J_CCdGd*P%1cRmATKIqT?%?JIVy`2XID}G}s`=AiToFk(@v`Lk^aOe-V zd3ofS+}E)<_d$Q)IWI3gGq^wdAY0?$ z&@dS{UE8qVL4Ro9=_vP2vJ@|x&`|XU+cKHNQk?SmC+H9Sx@qKXl4H44_P^|9>MMSD z278%k#dA8;l5uT~etztOY>nNQ;D^{6SM;u_`a_?Y17cNw=yP%y`QGidpKC=iGHyr3 z?cU(tM<>N|8^x&pU|T|SrP7p7NvR>@QvYzLd^dt+TwCLXkAh`fTjPTd2CM!s){L9% z%WaMKW>;7Jd3eTmKK(hHzFX=QnEt@O_N(a+Ja;S5A9(Il;QxTRLxKMT=H3MQ1Lm#- z`h%_AkLawt)wiMk;coSL*niRf+0RUWz~mvLKVWhK(I2q;rA9+v1mKB%ud z`1)$sL(U5xtpAkALUdwy5tlmFGRP-*Q*>*GSc$cCxOg z)7+?`r?V zThJf+Y0x@CzE^(QhBF}a2V3?;=nrjvYR5jPl=3g!;aoUM`N$HS2SqDh_BFATSj8=$ zWFHi#n79i1L!Zwq<6JmF`I}Es_k;R}yIuDs#8QHkztn?Rimj1&Ec(M7Dy#@q{Q*z! z!#>E?7+*P5^#`8#3Hn2yL$`3>Bui~e4{D(LLz~HA?1P;0?03)~_~rj4Z!=PDL$|S) zsjvK^A;iz3mCp`mA7pDRD#Q=5HTE14BDM{+{gtQ?)gSsqPpH4jeA14QZ`oekY<(+Q z^#{IdD)&A*DSz%%lstMvmoo;u}|&aV1AY@Jnx3SN*~E@3iVNuC4L?;%cft z@O3^QW@c+#oLx=z=govwKK%hlq?`VL&z&;;0WX?h`V+QouN&0Z^anoenCTC^)#7d~ z=U1!bEYI`@Y;`+3D^I;#_FwSS(?fr-T{Oh>2cEkR=np)3$mkDz)K1eM@WsLA|A4=# zZTbTqx`lh$;Oz4cBbZ~0Gs-6_AF zu1hZo^h6GDW#8WG5~LnQwrI}d3etSW|8~7Alti`S>T@7v(feVIm;{g zWue=;VUN49Ce!o3^pgwfwZT=98Yx4QFSxm}dtAjaO}$RudiO!tdiTVj7;jgjovzM; zb#B}AD6h?lgYKF4SG&${)c0O!a?JItu*T(=t?x||{psTU=*H(qYW(^3{gv+5bjh=m z{SKeWV{+!p{%fSHD^zMcqCc$h%TI~Jl+-rl<)T0E+y^B7gYEC1q{??=zkVk8Gw2U( zI=@Sd_o!lY2K|Bm`2=woYCP_Bv&Ip7DOUdZMAIL5&Y;mB+Siu(pg-W#V~N8AE9RUC z{|BD@So8JgDv?d z=nrk4+)6AZR>!J4kbO{`@@H$1m(ox%=f&s`?FaUw?nj_vv<3a4&po|}rPvxjDHE#t z1K)i~ZPg!a!*kgO*&2T-QCr4M*M9c<6HCcZoc|5?O|rDlUftqUf3S@#!9IxkhkGSo zg)_<=ZNK<2@;1q_TqW8YqWS}_+=f_+t&#l>`h#tLehrzkt?{WA?1QL(xL5pvVAUUN zt6Ymx{Q)1IO1@=#?f~o-s>QC1$2YvdpcFh|3E}8zoQ-_)T7rfQb zn4*|GAN(J9atrZ)z?^g8|6pr5%#SE<_p>@H&siV(Lwn2N>8+SMp6tKitsccP#niDu zf9R8a7W*&S*j=i1%5#4T{|BBsQ|J#^atCCr35vNJRr2JsZp)$FuC>&+IaI!%yYasx zu5ed^_t3Bb?&Y>S-4jz2yx<=OJHMbq&hOC#ugfp1UCjC&ZgA^t@5<%1?(XU%Zp4`^ zFZnNtC%?1D{SlDmb=_3xCRW(tE|tyns$D;3Mr5BIxAN{i-Xp{o)$;%e(cwF`_?L>aKNT{+BFg_f@^e2#^1IgP858;gw);Wk z=B<%4cix4xUq3g_mCzq}yZb}^!-MkP9nO`GD^E-Y{h>|55n?aJieq1|CmIr@eR6(; z{$Sfm=7avw-r_LSKRhTtKXI54<;i0~e`u2^bzIROF!?X&517~s`hzX`D)>L}zg=Y? zM2*LTnxlgLz!#^JmlCDe@=~G|mpDl*B~~%HDCiHiw`5O*{$P8psG;f){Kdi45F^KO zjm)FAjB9IL(Yv;cTUGfbrE9DH(1x=f&cCp=eUPnj#?6{CF7*!&%3hCHN`~65n?}BO zmg1FOtm+T_EIrG;GpGE*3G9P%)D~X_{h`gUVZ>6Xe|S*hal}$=jr}+A{xMr)p3DXP zp?&WP?1OBL-Ir8X{lWH)rS(;RXfwPk`Igi_JSg9dNEx@I+76gW-gPI%eOpDU{?NY9 z#d@kg;1u~h&>w6Qj#QCxZH=+7SCMh$*$}>7y(+3dv=80JS)#2mxPOr9&&{?QeEI{X zo-^?uFz=c{f8H-XqV<;9f58)TMt|U`hm8KfQxgOI0aLG-{TG-xGv{Am@|MvbY^|0> zZ{@jHj{d+CTgLyPJ@t6eA22m2&>t}Ma*6+dsdI(?U`st)^aq~$Gw2WeDycV{IO+wr zzSm)wot5ALTVue;AQ?A9`Rwo@88=ID|4o51=WOkBdLL>>*&271 z3{?GTbfmziKidZ#*Y|CqKk&SJ0{sDVw-o&WbDtFb0o(hMawNx$@2lw#JomQHA9%}Q z?yT*p*@gblhWa_|zrfV8K!3paJm?R$!`?Iffv0XK`U7uwIjMhGp!YY?A24?|(H}7P zG|?Y0cQg0wddanY>YV%WlX&m71w-7Qi;uad+sOThCBt2hhL_yHI}N=T&%Ewxe}B}~ znAOmm*=K_bop8nFevs*X`BH)F_s>tRaotQWy301V`|HClZm7iDLW|t4r;fVji_^W% z;|{rnuOD{vBu_YK+iBOa;G8=hp62~p_^oSneYbmddz4qb<3{)Kk)Pd1!|QvqjupCV z3ESNxZ6dv^VTatkxLxj{SL%6_+yCq~?kjL^Q-sEU_CCAS^=J|y--jTt;`yK4;oA1R zC(F8~$-Nu&hc$ApjsAeStBC%9?S7)aK`7LIA@&d5B%w|JNOsO3|u6;N1(^2Z_rlwvF4e z52F5If#jbMbEE#@afxqKSN(x+`U9~PTjTUT?1QL(SRg(m`ygB6v!AgKvNi6=tg8A$ znJPZq-<4Eim=cj4k^t@}Fr#ojvYfz*A3;{AYOT=5>8( zqAPv>n)~d7Wbf|T39jhP3of{NqIdi6F)nw`DK}(8y!Yk8|G6t?Pr9sa4ZN^&1#a|* z;v+4|@P_@h#g%yWjvJMo;XPk_yW3gzq{|(d?j;Q`bg8ZGNKB)t*RS(_xA^XHm$@L# z+r09a%dh{lJ9;P8>vU^{3tE2A#jT3*HnuBrUcwRgWEt_1FP(8spFZtg%WdFwzI)SM znI(I`Q4PJy7as7&uRG>~m&begUzYU>n{IO*)+TrZr<`>UmD}MawU6+ow?6AioZjZ9 zl_UR+b@MkOhC}^B{zmMfBsWQT_E6lv02dYV8&_7o2mFoLyOmQM*MmJ&1^G-*$!CQR zL;XYkM))w)Kjd%39*W;EY^fQ0?%#34HUAktKcAS)<$uSmtNG8^78c^S+)y5!;r<1@ zpI;prm$PL4Mw~~7{W~t_(d5|iyZe)BEz;{0`wynLzBS{b zA>2LVv%-fVH;*}U?-hTD=ZJlftJhPe2=4=c7!L~S^yDHQ_+@ZBB&>wiKLr(p}9kSOW zPB=<2^?}hJcxr>AKVa(Hpg-7B(>q7@aSc8^?_TxK@`j2Z718Zam-}X>H&^y??KYot zbNn)OABW#hjm_u9kIIv0Y>NDz;77e6nA(`TrH*tz!Q8vN|Ib9pRX*oR$nVc9&wS#V z9=h+kXUm?w-wf9v;_g{A(FHH4rHNNhO=O1;8K27n;zj)s@&-lrO z&uZ*ln^e*po4D8QU7PIv^+s9mp+S4yRmtanWmpC8#l}CoFv*R4zVivUf6flq_|tH2 z^8=?{otY=y4bSw4^;(`D^$&MQ{)6ccYbSpO{ef?vZ2ALFtOosoueKT=rh?+)_NG7Z zc9u>3!yQuZnmtsY@=iB= z7+YhDSMgz}@mMT>N6wO{f4D>5eMT(T)`$;-{=gG^L4UwQx8TDht8L3C@nKSwCzgx; z(C6u~_%PHz+#zQoC8f2aBqT zE%gtJ-BT^9s{YWvtN1PG4>(HpzvvJ6##8t()IZ!I&p3J4ZPfO|cep#&R{7o$#Ma`K z_wOF4`a}Bz*DA}nw#HfGD$BUkKa`kfC_ap>G3VP#Vw{n%rF_3`iI4G z7mxG4ZfZOGxlq*~+6?)VyvOd!H~+A<>JNNi46!xp9~SxaXK?6w@$1b0fw%W-$ID#K zOMH?#gw#JQ5_UIQ)XzbGz`XB(`(N1h-(>m&PaSgf2Y$#e4OM^OsSk|)fM-7^Ie|Z{b~h^h z?*5#Y>HQ&R;~}Z%-Mpww@6X>ixJwxqT+*xzZ%^gT?#`ZbZdQ1P_d>yVcRu$o*C0F2 zd-At;+?MheUDsuDr#oh%ThQw-SEE6!7dLQ{TVCO!dt+vdSL@akx1!!TH~&(!cmMbd zH~p0}?j@-)HK5=Zm%OCdJvK7cyMFAdd-%{5S7Ka>7rXe5`{(d67xZ~!FCesp_xQ(W zU9&C8-p3!6_U^rR(AE4)^5v$M^;Q(`b(Q6Pf4_fr*p;lZ$EAK5?u~f-nETKCLicK0 z(;wDOJ}~|d>!p4R{tuWuJ@f~>don&Y^$&|AR!{7xoaC6Dm*>~?2fpN2?4hWCcwW9^ z?4hU)SmY{5jYsqcTuIIf(Ooci711B?l_=96Y>CgHKk#;+=!X7{*f*g+@b?FVs{VlS zXV4#Tg4Ak8f57Mr`a_?VmrHFxx%V=gv!qDnv(w1SCC9Qz@^J7wY>l=4<~*AEhedM! z%Xu{Q4~rx&%2`rHwT=FcSgx%xu5}F=m->h2^$Z&Qq5YFvsRNd*xK}sstWg`VNc6D2 z>JRw2*NEk&scpYX_@dN5ERr|?ahTf5w>eZ*^#}fu=c}szfIHr+qWS~w{4TLvTjLXT zs;K@jANEA(4{hH1oO~zhAD)+(ZMclvTKS0u{L$mw9i#qXk?iBRyAiJ#ZNdM+ zcIaaKK3n669QH)iKRhq_U;#2`TjQu_15|(LXUy%2GA{KGi{!Vdwv0>t!y?HO;JmM! z+O95JTlEKi-8AwZyDPsjzLwbb)b?A}^SeO(!@WNJ0oywSqm`%52L2B`@A5-`7B0A` zdCuq$JTYghe|S;mWBLP6U1jtKOg=OE17^>K{(y-yF{KQ@->4?I2( z`UAFipNLwUEo;t($KiE>c5B-6sZm`uqWULGsm->f$<@u7FO{qTyrtXB*KisRe zCaAv(kDo*RG5WMRy)%`kj)c`eyeOX`HT32xPhK(gSFxpzuGK$etR^xp^$!^$rvBkY`3zJ3t$)a8h%ZczC4Vo@!Kr`9--{X!TmK!)^aoqwHs}v+ zxLb|>z<0dI?<2JV8H?CaImH(TC(1KLZ9v8{{Q=v(q)L)wc2Pb<(;s+hDWE?#R+#D! zJUMvyKj4n{LREjj#F|H{^DTr4XA&}Sanr@uw_q#{=iQTt0T75 zKjb^l-3{s=GFE`<4>-7gfa(vpbbOBS-yBZU4V#O@C+;($4e;JnmqI>JRwl zQ>H)k+2^9~MbEaaer$>#)0}@xEhTdFV zBXzFOANcvFqf~$B6V0*uhX*9D()5QmwNIp|{(z~Mi~fNBxZYUx2ixaf<6W^Em0z%c zb13Q`UX}V?ra!bFw}Cw29opt*Thkx-J_o{8f53Zsnf_o)J}~+NfAB}{B~_4|w5xIt zh%- zoSEB-?;NY8`a}DP1?0m}|L}msuE~d~qw{(3FmV`a10IkXu$*O6|M05B+lj+a|L}nP z{-XcnSRRmPgnSt4A07~&nS2;qo>5Wthc>I?D$2Ojc)Tj_u&yBE+8RH06=cpSYWu*B@~S_y zf4Osc)gLh0g8zf<&@G(zQUCCOyazl)#-;w@RmtJ0q51>A;h7q$Kj4I`whmn9(2jBcsj#fq%7}=?~c612sb1+dChre|SXpXr@2d@@^*lA9&uog#QE2 zJC*Q%;A>Sg{Q*-02mJw4_Xht5OsyOA2V3gfpg-``v_XI1sbhox1J79m`U9q(9{K}b zG{p1=jGu%4U>ho$gZ~4+;Th8(cyfu+A9(7_Q2!ZBZ5i|jZ1rSpjaEZutM+MiV|Hkp z3M%BhkN&`ur-%N) zQ_BVYf!`+IZT4T_7w(W7b6GL>lGuO2lQV<Z(8Rr^k{fP*ZZOj`{SbYnNM+H)#3;&pVOPAMn~WraxfrS)e~)-a~=@U^_tGH-Y}Z z%b!m52cG*B=np*ST<8zj?od$w@R-Eu4MJLr1~ zY>lz6oBm+y=V$sud+s%$Kk&Rqfc+Oddn@z@jGu%4fYBWGU*Jrst&RR*%bf-E2maz< z(;s;5Dd7LW4-Tb<)mFuJUz_@e$3&w{f57DOvH!w$UySJwJa-V#ANWNR66BepHsCRd zGjJavKyi`+tEV>LG5KzAmPGwSz8ev$ zKiJOPAFlcXKfEh(80sJ15?vx^vZl7@{0RM_&5_ZSRe!)sN>^6>0goR~9LCnzy8>|- zTVuxi0WvQ24{ynLBUJT=_EoMC%Wb87UK~surnTaNTkM0Ve|Suu{aRw%R&9s;NxYr< zhkQ56tNzgEz1ihdf8h7Ul#_97jSCi(l{r)Y@R%E&P*(K^+!wu`Tk0Pkll>ZJd^P3of6}KvU}}!x|GZy(N9&BC zKk(g`nEt>&pJ@66&-=E}AMm0Hra$1-Wlev;Ti-JM!It_w=np)1)$xDe?cP?N^1NRg z{h`gNxu!p0&bEmEfQj>wjG9P|es%|U;_)VV@`z|^+F{{dS)tIcX_HLSKOZ*{A7D4+2@=ir6Pb6*?%!M5|e z#0SbsZrDl5>Ea!xEQ**iuUh{Q=|Kpg-Vs zW5~_Bte8AK^oKr=jOOgg)=2&g`U8JsREX*iww!CDKVZ9;R7WxAP3RANr=!GyBXm9% z2PQY~q~t$vFTh{q#;vXV{Q;F! zf9SK^l>pTr+FKmP)>!`%ahM2gpZr2a8MnFOzO6V*YN>q=-9jw4mGYxo5{GH6{KNwC zuG=X8S##nrZ51!rNW48>@%zPPReuS{7>H^mX@oi2VN0AD{ehn})bt0QciW*q@HP6I{(z~kj{bnB_c8qe6I(`qux-2C z^aq~z#Gya%yBC`Nz*F-a{Q-CW()0&RJQ@7~FV3bOj;)be<>(JQ_r%$M(dW>`oP9{m zB;i-Znf`!@A)`NF;yLIKn7tMHgDrjz`U8*Vpg-{B6{A1!)Vad{0q-hl=U?CesXs&f z2i)Nv=TL=eYvnH5B&L^c&Ap_nsn^auX>${MOa*pfek{=k1OdB6BS z@SJO-Kk$)qR~P*ObKZpi1ODm{@q>m0cpp^V<9bWX8U4Ywgo# zy#VSTo^d-%n*M;v<+c_PG!`K?n?<5XG{lok68CH;SsegDzW4!1O z`0&)4@;9RX;Tc!68gUrvAD)rVkT^^mwVhF(I1Kd<&&X#;yq)@o_vKkGqxu7%9bQJp zwKa~M?l0p~|L}~Q5%|mB%hp(GQfbv6Y+DDEmT{?n$g_;ENd3e6viGbi<5K^SXPGm* zT*bq?R#E+dU$ZwzY^i^EMzq@QUy$GOfAtT^d!gnb`Oom&`6B-rp7(Z<{|s+6oTn+~ z%!~UM@T`OT7hv8&O#U;ryg!Tk7w}e-ka~lD9_L)-Kf|-pAiN*+Z3(&(Y7L&K3F3@DmHz zLzPx+F&uxzZ%A!e@}FtLb3pzxwhul?KG;#^*-w%G3~#x7wnnRKXKSREoz*`)r*Rwd zpXrm@4&*;$Yj>JBTRNw{4f)UT-6d_m)11Q zJM~IsFKYE(w@UJyAD9v7)jPM#?b=k^o3SIv%lPtyt6I6Xw`ob77cjZV^;lisi>n*& zP2C~CQ=KBcr{9+Mk*qu5o;woZJ#{h3D|36ln&|$=2AVOMpC&>Dq>v4EfLWIpF{4>C6Lr zuKzf`*@bQF-psJsuwjm5=IHZYIU*Gja#T_&#ZO4lMRbTlL`k8Ngyg8)_s!hoocm~) zbLQTDugB}9{(JW9{rY^qpKafV_vih7ydyNqHELvKL-o_UAL zQr+?c=8e{iZGv!=`U}Q{hm%vuzlA<-*f8cW?Emo{EG|D!auN8<%wgz%$lr6IaDe`Y z{B1;Q{xh*QhoS%B8Oe=d4%1q%c|DamOdIukO<@kxR`uyveg@=No{@iZ{bZ~?+0U+yI{|FymuMp4?cC2@Q3j)&gXpaXw}p=QGbEI>|5TU;#5<2 z0Dp*$(X}%AALeR4aMso0?(ID%z4hP4yB$MHx-q4;c_YK(-9I5AZgbh=UZms@emXkT zJ^kZ$?>DKjs^wGKbv(Dl>v1F21+0?(J{@;>*)uA+l3gBfZ+g4Excp>S`mWT)#h&*r zOa9)Z@9Mc?z6ZVRUWxAOR~oo^yRUh_zFFR#&3MS2TYJ=t{2#f=^gqni^%?lX=X`b` z?@;!Pyf?ug{J*;L4rR~Cddc9VFjn`XA=XoQgRN_3yqeJDWL7n)(B? zn8Q&2?&~W55up5G{GFju${+Of8_Z$of0*mFd!0E9{SR|xUynHq_3ys!x2KrHv{k>; zdU#CzyRXb2_;=5qad;bFxvxEAy>&ivU-}>B${Mnd@&}#Ru}FAr&p05f(1SnqNBYTJ z;t~1V=3Lf1*>|Rg{Al&*v&#Gj-}k8T2YvEM;}4p1)tUdG-`{2Y;hN7sV*J6+nrHmM zx1OlW#8Gnc+hZ+9hlh4Ea2cNwy_=C?n5Az>1a~}AE zzB<_WgXVl~_(Lo`NZ}7YeMjLBKD|bn|KL+s&in^WjVJs;Q*Xum2c6c%_(N<-sbOLM zgMXo+@duyYeeegLy>j@2X5WhW58Bp{7pZ1F2mTPtyA}LljP(chariKY`42vQJK+y{ z*|)6W(El(``{}_S^x$_`E8DHttUr={aQYwSNo@{w3J27`+lw_E`XA=Wzv<-i*)v*S zP5K|^X)jIdf0(CxQt*e*^TjRB2dDpGp1d>i4i%$5>o)KQpZX^FgN~B9%7V2%&iCLk zFZD#M>vz}B%{=?JSEpK>`yoww#_rwkdBJh+=8EEO(*E7v^q*s0cI^(CwoAl@^gz+ z&H4=d!4K@rJCr>m?@jOre^Y~CgI|IfErZ*Qm?&M^PMCm#m>pgXN+FDXlZ zZjCa?S)%_T>xMzfAFlcLBIdL7Kg^SNeCkf<@t7wJ50KAH|HC}lI}VUo`XA;=4;+8x z53#Q_ja2^Nvkn7)@T*mdQ2yYDj0;!(pfCD|D}T`2-=zMA{)c(;ZxeGwIWJ0L_gpTL z+6;TfZ*~-V@CU!soO>SgAI6s-&D_?W@p$h$%AbhvEC0=Z(EaWhf6&yN!k_l-q>u1! z;}8AbaQz5F6Xm=0A*Kp9}ur^UlTl7yd^f z#ve52b;2Js=W@ay^v2fm+`=DXk1jR-;BU?5?A_1QKbdL#!MF1dN5{J~f{32cL5%ng5{a?+1U-m$%l|`48G^IqezA&w)Sq?3KeG zuF1X?^B;WHkl_!S^&I$v=G}_<51M%n{2>MtXuPVpxZg` zh zZ&xqyeyS4aj*gceaJMddb*AxMrpHKt%=3elKRjc*cEQRYbk9}nWyk6B4oxqq{J~#+ zopqS{8hhXc*4rEEn9EyZl|NiFr~!M~p8Dmcv6m!g(Mc@(O7I6=u_EihDXKF^@@`#O zui5H0J@`}A@7~>C`NK8e-{mK<)ztsW^HctCo!x;E${+N(zN~jWsbhSPhADrDjg=fE z=0A+7v7of_2ft}@Y2^=o_wI%AzL%+E#(MXZKlrO+?ka!K7cbsc{t%n6f%j~C#uk%r zDt{iEoc|wx`X&T9dOkD%!KcqN{6X6pg7iPkm$gUZ4|?A>#vfwo=L3K6n}r&G@W=GG z`47JJWbUYAsx~wJ;P;HlpT5WNhw=0}X8waFZwLOM>16?b(A1T~A7VLk0si2# zo(zBR^Pe~V;M*Bbb94+jf$#^P{2cg$X0IIn5X-(5{K01p8UEn2o&$gI=^+e%(DV(4 zKWLc4{0E&O{UzWJu|pagfACp1hCldM7LX5rK<`CAJ@~^I%O$4&AwNU@Ew*Q*moNMw zc3e5*4`Wy>X8wbpevx_v`XBN$OmWk$M!HtT0$t_WDem1$F|Nf!K60j6ihFNnzBm7Q z`CIKB?P^8c@xDHL(aXz=cCCLe@{ZI!GOFy@0_f-w~p0_;ih5N?1 zXOrZ6()yBjME1N!m6qNL?ee_!qbj&9|EuFNgU)%E?@4ZwoSk;8!42=%FXP?$!UisO zz!h)1yw{|5leL#?Mc!NMV%*7<&Mo_1{+60V3v(r>Ip5Fy@Uy?WF6W2UD|W{_Qq$ip zezdY1dp6%Yw#-lY!!!Qes-*l3?HMmGU@tpPpS@9H3FQyZPM!?>LEn3v^>%s#=F8k8 zM)`vtSB|}GPh*csZVddvPrpdc05v8-4$i{m?rgYPzmDSx=;h+1LFAN+malve(rlYPm1r2k>Q%wtO_f6$9}QkP7PNswEz zET@dtgbug!mmeSIG}JS+8@7aAIW@S8L-{xE*sbmI@YS*X2#p*KiB z1o(q){x^GA<7HpCxZ5PT_wWawo?Y+viZ441e$s%N`2+A(pkB`H;WsvAd#+Ssv*gd9I{u8kX!*%3bpMRV|c-fhf20 zqkL~pKUqVUUY#9|-Soz}0_k@YjBMhiA-hQ9}8H?mwG#;5dEuf{5bEAD(^6Zu0T!tDlq^qx`}D@w;f{53$L<>}7j8 zX6nnV181qOw3$7-WYx@P;198d8SFDuRv*s5AABDl)`8R1|L`SWiLIu(*d`z45BHk& zS!v}Dy1J~TGyfrW_EV*lKln8kkayHZ{ol)mDu3{64W?&6hF&u~oO6@pTwd`b4&G4y zprd~(Q2ubun4Xf$CGTJOadq>RKlt&5SCv0AXO#SJ{b#B0jGpt%f6(-qXa0lc+;;ZA z(A2rJ{!A=;?$-bCj_!Fe|G`h+Z~S3A_3W%aqpgQVN7Yut-c@yAXX6jC)UEUW#dzMi znE&8&UODey`0TCo{)M(2=9Q|+=VAVX&+ml!53#KCF#o}4&cpf-K0Vms4?cN=@CQwA zQuu>rKMVe#Z4X_}*^yY@v)~Uty)2mj;8Rx)fAFdCggT@51PK^@CQwQ8~8&k^;7T%|DzD&4?Z>E z@CScGAL?-qsD6J}tnvrndW_pMT3>N{MtX_EAI8v65B_k?2P2F>_*M@UqhqEBa~3uY zbH7grcC)@sa&N2&cROX>qQ;ygx8j1VQ?3heqi06Arll`>+1GvCVA(4_z4?kaxqXn^ z)HTxWPQBv|{PmVs_+y0YI5yB7$}jY)Nk7k@rH|F`2k&_cJ4Co157clcw- zIRQb+A2j<-@CV&AIa>LHW*wOIA7X7Uo8EwT~G35`s zYj82;4?3nN>%jCsyd!H4KFS|rho-X*O#j0>GRH0Q*#E+hYgtP9gTHNNsPYH>Q3!i> z^gp~K`*Zck{-9^fxT^d?$Moc# z&7N^c`eo%$ev6|2=06+ygt$j97=Q2|Xkq-pFE`EjgI~hW_=C=W-uQ$5tE9fABdw znE4Mr=Xk;&d^=O`Gu51L1%L24YX<(HIrjnn5K9ks_=8VBWcY*sN>k&H`ag2sbdHYk ziliP|_=8XX9QcE#mj(PGmb!BIgU|We%zyA_^)vq9bM7ttK@UwQZ*7rk&ZC4s_#MwC zD1V5xbK>X?SS0K1Rh2*ZoZke0@N3AK%kT%yxhn7n9ngn-gWY;fm;--^owtoTsRQbN zU(NV~KWrGiJ?$CaJWc(AJ>&C_7=O4XeLLX~`nhK~2Qb@{a@;1K^?p|n6+Fk1D=T?pnbLpR^yVVs6y_`47xE6oa zag9Hc{l4E~+|*5(?(c6)y4?>+&-h)9T)7^;?rdxMUJv(N*wB)$;L~t-Nxtv@Z1!>Q zuM3ki*OFbYcLLqw6F%-A;m^YzeBAclKJFFak5979tNnbGKRnl0UXbz!P5uo0;n`oi z8KC^ZXI~rs;P)sMrToEXzX|@J-A2}d=?z#UJ=s_XrvG7))J0Oek*u-%hp?AT|HC4w z{UQINvih?du@0Q7ew{k31E;Ajk#|oxK>x!c$>Y7N{6WJR`p@%udiMxX{@{07&zgB_ z^_wP>cSQfgBAN4)RQ{mL=CJQijwRo(Ysw$=nEqFlKV0+GnzC*s>(BUJ?j_|9e$-DF zl|T6By5uQ;VuhXmzJH-P^Md&gnsY9g|DczBYy3HtS<2SLkj0K~t*^f6&xz!5=g^ z%v2(Ie}yYO7_iXS8z- z>=`-BfcX#iqD~6_5c}yQ`eH?^rf=u|tPr>1ScJRQp@OUScc{BMpp>iDqk_w5Q`-G7 zIn>3EsNmK-ebPJoc8L2pKFrOja@zY!)|l7S2y^wGIP2}5P}1d23Uj{#l4KaHZw`e(%M($Hs)X{^LU3rFY}qmQVfM#aD{E??y{a z)U9G}r|0jUy;}$gx{B1K?2ln*m$$k_3!7ue3wHwK*13I&pouazstL$Z0R{eQA z>%gfRn=ScM@Q2vYLGrF5{NY|t*1oO$!Dl`Lf6!r7f|WmLI0Jvstq+t?{t(;effC9e z{4Yn)*DXV@87}L~%zt$JnoG(b^qBq^l|SfRRq~WS=!k>ol|Njw?dRuYd>M%kll3;M zKP8`N*f7g~#y=uGH^_g+uT#hJpKXl%9;E&YO+RPypV9QzApe%r=?&P@KZ zeV!_E-!-bcjLMMvaweOfd>;1DH>>$L?vG&)eYg5S4LFx`g8HmSlK*U< zhduNus@cyX{~5nd9s1QxyZ?FE!}|69m=bNBC6L!LKJed@}|e9nLc*>E?C3abbkzM$l0n{L#F=1#;~``Isv~6 z@^DJXXXjq5;jn+qy;wsIRlmz9)^JMQA45GRe=mGydbe5*8vP~6f40vPA@{v-|6bu* ze}PY*z0Z0FyF07G-H$EHxtiaXc7xt8>puOgybG&w$_oyWe!%~fa+$5pcv+1~x%bzW zaz~q-_a2mYg>>nQ6?^)I*EmV$;Xjpj1Ah&2lg384M_PothxbLgv6G9tRh`1!dnIDs z-Y0@(?I*>b+Ai~MJPZo`JLc9fu+{2A&`@$1y#9V+qu7~Y|hGNkt z!@{XuB)6WP``3gCwbk$5{i-m;o-s@~L;o?xFIjTQBmdbxPoUhl{r%6weD4|cgBk?L zeLJe(Wfc4Voz51QHs_@m?XeC;)=$q9r%#FC!_e;C7Fxz)diOKwK2@&}(aWcY)o zcOU#gbM^}SL37>;{NbAPw}C(SjWUcs`0GCTvPW=UX zL!U5r<>pZ@>XNM4d|JwV_Us9-(uWc5u+&=Cmp&9#W|enu-c4|~yGJL|g?s&2J4#TWJUy#_4|l6#c!x?lAFes6B=1no)KBZeI~4Wr;gT;`Qu#xyS48e~bsfX{4E(`=>hr70 zA2jbx@Q2vNRDQ~w?= z^Q&UYAN<8T$yY2RYq5d<@u&XCNOx_p@dtn2HscSvZ-Vg$U0Ztb!5{RM1;!s@54>Rf z!JqKE@dy8zdySMo_;D?bKj?km7=O@TpJ^b!i|%^O^!-(J{zGhDCF2icX7w}v;P+f* z{K2nQ+W3P$FExzJf6%)FjX&tIPaA)TZTq9~2S4I6d+0l4?=I5qe8~8N|K$kd51O-P z;18N}AK(vqTAa;)i0$6p_=8{h5B9Kr)oY%X-caxdpPpUt2mOWg&w)Q^dRf39G3!=KlWT%ms>WavaI_2FjN8?=3)@b)=-Qw=bE0M0uqXDkMty1pt zMX7HuEav7lj&^|wQSL+ezCZkHyqgqN(runB-|N8gZuU{>Z~K+(XCx)L*hh-H)eCQV zf2@7j<-8u^;#UN_cTYd!PV^3SN4EvLn1aSGdTxNbbthQ)!!zC)$~#nD{h3hT1b^_~ ztq{)lOMU7NnE&u|*zp`|M+vIQ2ZlfRlk=&qNz~YKlBWlM@V~EiNBP4w7q}4R5B^(U z&$MwQu%{_J(YK;=Ia0X7Vl6k^qOz3C3m{I`m6)PAFeqr=(6&MSk`CY4|=SZ zr~EJ~=c4)Y(homcg% zYI>8xA7XjWfAChkT z!RM?f_``Vm;lLj>XF|arH2YS}f6%su94z^4(i2_QbKnoY^){EehWPZlfj{_7lZ`)U z`rE)Cbb$00=KTvzPaF6{>_yq+?e8VZq^i;*M-Nr6=5;%^)Dp9FD2d;muKzUA=cduD(||@ zh;#`r$vu_@xVQb{-1?FJ?&-!MZtU^WZq*yIXY_r9+uJh2^=>J-jUD3L_@`pr%1L*< z-=$A+zwd(Gxth1VyNQWz`H=`0T6DwPl=85v+(c?tZAZh2=2R^EP>uC>ao`2|fHhTr>&z0$AFjFjI{W_3)nDL>D}RWc`5C#> z)z!av@uKnvf1l(f^ZrHbs+bGPAN(28qmcJ6{IOoH@(2IDU1ya)=q{s*DSyzd5BMs7 z&`qV`Df}U}elPa@JL`SB{I5u2pH;tEG3Iz>WM3}!KmL$Q_3S|75Bif8#ve52xx*jy z!Is7!V*SS$fABe<9sb}Ce#iKOKVzlw2faJc_=CRpxbX*FWvuas*wpupKlp9d7=Q5J zEn)n@|GAaTf6&{;8Gq0>4^>wFpj&=m{2{jgT5*t?T(&j(-oSzPV7|+?k@CRL1 z*1q5mn)Aou54u^X&3}k}qpk4=e}bI*0Dti5!Or{#pMJ>j2koTZ9R8qtlrsLH>8}od zh~>O*_=A7uSenj%@WZMYfAHBihd<~B@_m9o=$F1{4VnJyC520@A!q9~7p571@Q+K5 zAN=8(?3KeGeD|8#<1s^Qqo_$T$u_Yflv3wc#zMNk* zcw3Sy-!IPf35j)YJ}tGKy<*+zFUzljxnvYd+?li(hcJ*N4?{M^L7(QeBg zKewY+3D-;NOA3m7-Sz*KcDc*sJteQm>)I*WJ@9L!+jaAfw=gQ+z5Z4ycP{akmsz~L z^NvYP_QC?M?_18Td@;h!?Jd9i6Irr$E$iLC@-9PfgZ3X|{6TlyLq5+yjkP|^ zgY}x^Gc*6;n)K&k{=<0InVJ8fsoR1-Xv<;Vs+xQr_(LpvTkwZ5oE;2*@MEQaGW@}R zYc_l6_KbTjvxokZ`kb8ye;8xu<^8I$^k9cS_?(Lef4C-R;W7Wg&yf6N_=BeJG5kU2 zKX3d&xBU^`a>inu%>Af?uxC8GnLVua>Ng8D{xF_C#_$Kt`E<;G(40vJf6(OTz#p#3 zUOD{1XWxqX4}MSs;}8DJ@6nGUOvkKUPR`O9y(aS<_`?{O1AmBJm}dOJr@syS!S6qt znyCUEzvr^_Bb0r#H||t)V?)Zw_bbwk$*$n`)`)X+17yG7zpNYoO04_)LX7Kuy@IRU zSLQCVw!Gtqcvtm}XqS?b;7XTFbP0)3E=bl^W}S$0U9*HgO#jCCo)MDDY0qkiXG>QEpc< z?=rRYdDAaak5F4RIm7UW=Q`iFwDJet;!kq)Q&SN`DNdpt<_gWqLTpnT@$8oOjC z>%c8k$4Ajaqq=HpL3#fow#&eOlt09lEj*+A!QVgRwDJdke9$T754!E=(o;s(f6y;( zD)M;$LMJ|1=&}Ao?2%n}l|T3sJKRzJ;CDQHOZkHz`vQzDBl)fTTV(6c=nc{fi~eJ1 zdXDk_g}x-cXyDIGS^FHCZv4TI?P>hMr?(jV!GEQx@dwSB$nXa}YPInPoh)aG^8Q8a z0y#^R_b>d46^%dme|0tf;6FCm_=7%@Lk{y`9nU)#{J{_GZ2Td1_4NmpKltq*H2&aQ zAF!=D{)4&X5bjV-?=Senc+M+_KWO@3z#n3NZe{$zuP^mk@CScuHs?4^)A5`&!~BOa zocjQO(ClZyA9T}X;}5aCXTcx*UQ^PPKlr{!Q+57>Kdzkd2hAQY{6T-^8Gq2J@6&5^ zlYXA1OQPj7W$PIFals$1c~W{q!5_wx69|9M7B^F zXsEo;8h`NVM*)BEndiVCbgVFk_b>E}8N74ZGg3bVe~8^B`@i%*WDLEt;7`XaS?BId zZB(=?>08cC7#QQ)NFLFslw|k)_-J=t>R5x~Qe3y+qg>$mc=yUL2`=bE$szP9^0rh; zapyJ_bFa!==$X~=uKuIGZic*voK7z%f0IRC&l2)8n;Ywn`$`X>E#b0`RmSz$dDHv& zqPz#sFX!$C7RYz1hJKz8=28zu|M_^Cdr*&1Tm5M@N-KZx8%RGf)_?f?mdlr+y4yK= zh?P-2LHdipAI7YTxvBgiHg{}+@&`X$_o3)NAMY|pvJaJ{Q@FZrsr|x55AXsRQZFyu>3vc5B|}Kca%Tq;$?0tf6z6@-&FpfJ4D`4{t!E8 zG>k1Hxo7MJ8h`kA?5_0xgg^M}rW=3oIolNepgGT!`45^iOqu_nIky!45X)Jm%zyBw zzHI!#r?!;&4?eYB@CQwv5Bx#1=EMFw`qi4oA7X32X8ggo8q&dfFYCiRRL9ekkogZ| zs2gSegQixU`45`9E%v{-rsXj2P@jAr_=ErYKAv%c`qoSNJJrm2nE!B{@2eSq(446U ze~7j7I)BwMoHYY~@TtjyKaA%rPUb&o&fkPTX!3TL|Da1fXZ#^{-#74frTVPxz#sgq zc`@>HTd#fzshNU5#Bx?9{6W*x82+F+6BGUr%Q=|v2cNSq;SWCNUBVxH`r*JI^t%;| zKj_At$XPn0*F2eN{2`WiEBM2hw`86JfAC=r{J{@OG5(-;NDT)3K~twm|1tE4T5;~f z9no&ufJ&~|ifFg~VR=V+Sk|AV?tIH{ak8IY(VaUaHTPf3`7X!GyLytpS7rHKFKK3y z`?_W^H)etCXE(0mZb?1sYI|6 zQc9n_Q6ldYHS{yol)6j!!{@nig+9!+Rj;gGO8J97T=t~k56}42kL*Kb=$M2YdWe-# z|LwPLD1R7VBJaBL2R*S{zVZj1zMp-lM2%hk1p81)c1_8vVf}|O-wvRMPh<68oKGLH zrs`L}DEnB#AI4lyWgn`!>J=}t57k2Tuu0@jSJ&9qw@)d57=OI?N#zfp|IO3Kl|T3a zosTJh&|mL3qWnRpHOo={pi8}ZTlqum1%=m+T;!)!d zy5$GPA7WelY5c)|^g?~*4}QW1;}3p(A$wc>^mE45HU8ko_O$sAI{GJSD27VTUU?UJ zu#)lzzdNOvXu=x-E11*d{=vsq~Kg0%hrkC<}I^JJ;IKUtL zVw=bz{7HSz@q|Cba;6^hA2jD%!5?(8uknZ2q)g)veudt~AN+FDQk6gWWo3@X{ujDT zl<^0BN$S4g4?0ikIN=Ym=ernx@N>s<&Rw?pXQhS+{@|bXHU6MO1%J@YbKnoxggMNA z@VAXCq5Q$Wo@)HT&wrkJ@bdb3u8wETJW=&!+2^AFA!9E3Q_GO7pXWluDEHi;BCq9B ziSFSE)I-U7tz2`(6XcoLGcNy#dQ5x9B}>R9miGX;&f=@&5|>iFFwIB#L+sI|)I-%$ zKj#|tP_^}%hwkV95PRT-5akbg-#6s)W$5_5+v(+AM)lLu6PfuB*KD)qn(~M7Pu9Mw z{K0>0GW$^Wj7>wy<+Epetvr~b+xV%IKbAF7%9tFKGmr0@rS zWp(zUTByJLMV`01>eTm7D1W$S^7&)RA9P~Jqskv*6E@^1fAHh#9#;O~NBwkA`Gf!B zrW?v1^mFwJlt1XsKl9GmQSa3u@|yC8*tQ>DQT{Nd^`%Ri|4i=KzxmHR|ESfL|BO%1 zL-L=|oUKg#7n<{w$$z$3Pkz@~`m>|AA^Fev)OlI|L%zH8ylShyj}JYZJE|tnko;%H zckfE?;cQ} zTr~2Z?Y^ALa7;DdQTDCyCrk*H`*L<~qHu#V1bII0OJ8(5OW1n)#i(z6iQ`l=&!PVh z<6#c{5797#{)b$%PMsk6Z+k}iI&=Oz{vudb1P4XSdf5vCshWuw@N3G@^ zD(il%zdSGf4-@5Q&OTI%`b9-&HUF7ddJ&TUjLy#H9m<}OHGcA+E%vx@prwv^YGI*A z{xiP4Lp`Z}g^ziMYOVUC^S6W{ZB(Cc!#h;l`?1upXJ~A9{oAo;%+B5;_pPsf9r^pB z{({dlVS=3BCiSQ2qN44Z|7@RmoAQUXfq(gfUc21*Q%?4L(k~i+@W+)i{@_z{0e|pc ze$V)W{<)R$2OT=d_=Bd-0{#%oxfSpSzgej92Y+@W;}1Ty74Qc={YE|I51RhW@CQAh zz43?G;~yJ;@LT+8{J|eK%=m+UWdS+NpKEN#v*ZwtR=q05_`{g0&5S?9j_Ggw!RI_a z_=7*9mhlHa|9RsNn!IKBgQkBn{6TY$C;TCn^B}0dz~6J3JuLbkCOP_Dz#sgdTN!`Q zp@ZnzyHx%DvtyJ$_;xOykK}YE$-2Gq2Y=r;>|yz-?>15g5g_?s{0vz`4pbdh#rT8I z*>>;;y)Z3IelG{~^CWg;59_e{b}j?`50m6)$QrUeW5=^nFCqLPmh%_j5Be$Ts{?<~ zOLo%JFGfF4vhWH;17P!ReT@q8TVYK z4~D<`jS|VNt)%y|T87H%XB=V;Csp<2lExpd6DW0K@CQwQ3HZY^?)!%IwJ`P5_p=X9 z|HCAi)3SzR&$w;e4doB9lk=}DfAl)CR?NQ{=&X5Hl|RJJJ;gp$ef7&k1u1{G<79mp{@{1-enR#157%Tr9sV$$vxDIe+Ri1P zquS0Qw`b)1ari?lHCfDm7$09qKVlefeC2VFLYJuF|DQU&T5&ID)vgU>nO@Q3ks_V)qRoH+%5@L4xx{)2v3)^6bsv2k^cKln$N(o>ZF zhsm;*MPKx2y;r>UMUPRvz|m7QPBmvm!5?CIw}L;!GS7iO_*P3rkH=)mtE8uvJ)@V) z_fh&{$e6=X#vk;+EOKirsc(5Wl{Gf!8f!SI>c3NgHRLq)W2LSG{t)};Thub7t7Z)c z{@{~)1AovPrGF6o;q&;9VGRcs#>l$XHRTWffGpN<>>2;~`m*weF;jL+KDO`&{ZNtQ zM#}sLeW+@H@<(IavxeiTA3cOzKKdUf%Q_+NjLGV^l64#AKg14iLm%$Ss@G0GuKd9- zD&if=p0PoPBg!BA{<9A&f4F9`<+qeS_>H1(Du2)edh!m{TCX{84ewBGROiL>4%Jpa zPikLk*fZ1*lXFku57%t@>UQN1*ZE|{R^<Lm!*};7^!f{K4FWD#jnQ z^+6r2{@ZUGe~6{`Dg0qf!iEaUAAI_q!XNx|eT_e8`VGP#^r+RTjJHto-3#7cUkle~A6cV-3fik^L$7gMTDP&MB1lFEl+R;198>?_X5@;PXBOfAC*8 z=db+1e=x#d`Gck&3jUz?zrY$!mgioiXEt@`o|4ZgVC8{SPb2ckQV12Y-&s9=ze#ce5bya9J4C!oeIVu{2`5vKlojPjX(IW)-?X0-)L+6LBIXB@drI3k|{8e8a?4$f4mfn5vhcQ(v zv4$-Bh~hucf;Hqc_3QVdmZ6&JhrgtjAzgKgKT9fqh;4N{U-?7qbC1x|Mrzl@|KD(W z`$p+Csgr^~_#@&kDu2)uyIoNJpg)+)K6rf{^YLCkEI){`$_>a7MK>5Qp+pO8A{K02# z!}${((|WXTrg5B?^<&B`D2!Im49 zKj?qPu2=q`ZyZ{y{2?|dWsUM@GC~lCOKxQ@;77r!H=tJ{K0S6&iI2rroZtAy=|QF2mN4#@dw@K0pky`v!62l z;GgSj{K2m>*7$?}(tP6&`t7%kKj=TcHvXWmEFgz@w0_R?{k)Him0Y+4>DfXKA^i_i z-7j&*AN-JU#vgQxKgl7?(ea<`C5Pvj>ebh)Du0MAiZ=c*zEOtp2fy`g=45kp{O9q; zAI5BIVEjP`b~gT?A9>gKL+qf5Q9A#@KOJlQ!B5IG{@_3NjPVCOaR6(J0g`XR-aUI* zfvTexv1i8_i>dN&bSa(xFy^K2$(N)5VXD0Eu!nV6Kj#tIM}|L)i7%A?V!|JEhw{cB z^s;Z`lt0AYTFe>W6zn^Bnkt4|CuT{_~HJ+h0lbxN_tHR#v_9A$n@1sxI{$J+;y_w&e%ZGE`Il(@E4a zq^rMnIXzU#u}qME$H~K?HZ(!j2I*-Nsrsi+E-8QT6E@^2fA~D(f-We3@WYy)Q~u!h zlHRfK2Y<#&>0c)AU+6Q(e3d`wWMB6EJ@ubYB9}NzKTrLk^m0#DziTl2;PgLCmGAgr zAaL2u38ulzwb3*D#uL9cjXukwf35zVeDfAIZ3y{!Df|6l`iw$^&D8$s;5 zwNd>>^Yh9d#-AIOtNcNShi_8;5Ielh2IY@lbIdyB5B~eR)+m4Q3nEr4f6#BVU8(#z zl2h(K{-C$bH2$FJ`ON#*OsU7>oG<1-_)^}X?_c=jJhT6WPj6@VgSImSA6Ly;?W{lJ zv**S7GqL13v;Ko0+tc`C_o}DsKlsVM#ve3mKCC~Zt%t@k)zot_{~?y#Lf*d^!#)@D zAG??F2j6PAM(Y?m%Wtge+tQy0{xGKJD#^!}`46$wZSnqvZ#m5LKjdD#d?WyGO%)fsx_R#5nSXF+8%m)^!&zc?cAFi`1#`t6Rq7Ibv z)3_IV=)RJBR#o4#nE&9Dw*!Chlcfe0{@{-*XZ%64w!``ly7g`H}&i%TTkN{^*Lt>{t!E$J-vg-%_}EAL;6(Q(rePw zf%y;q&#l-)w`ZikAN;}R%mw&^rjHf;;hOu0NDoBe4}OsLqo{oUUi70#y?-zIQKYHv zGK!vB)l_erNi9RVYI2O>57(sc1pKjkQ4da!NA8uU{J~$kCm+}Yw;-*W=A9S-~7nMKgstuX5wbt0sH_s`5@UP7JNBP4w z_nzj=vyA)qTCee<^LEpH-8Oq;EE?EW112_HO+P`VDe;a#XhpGyV{J zJ=OTbnC~Ap{@^$6WcC?mf z2R&>U?<2=l*ZiS`@(2HKIbfUpFJhAj@ex8W~$h&48tAg}7 ziB$febAP2z#Vx&l_wMA#-PLCg9mIaSkBWRsNv+hM!UXpjSR}O8GQ8O8T=_%n)xk@ZKj^G^i&HM*{i=Xia|Cc!9 z5B{vrj6djMlZ-#;m*yLP&{-R)Azdc~f0!iSUvdcPe^^8Qex&AH=0A)dd6M^$MXEWk9RA>QcCht7 zOp?E6>Og%Y$E=3DdnU?v*;nR|N%C(8=K|CJu!gMFbEYR}93{zjs+{r%{q-4nzZL$V zADc`a7X1&Cq-RL5-1mTfo?@FyDu3{gNWV?^!!;Mn*?`P{@W%%kf6x;L&{LiMhe^^G zB3k)_Zu_I`#|wXm6(QT`A+wBlLi4}QbPPb+`$uk}Bv z{K20&`MB~29WHYl>whR`MK@TX{K5b5rDbwod&bO>OO!wOmlrHj{&3Cd#}~->G7?`) z=Gb-QXPziIV9By)ZTZjWcI_`)qnbYN7^gm?ZjQ48#A2JUvEBBqEv7Dbp{xiOhPrUq$rm0VTI{DA|6)Q^Z zw&Xvf={HFI1-jRiN^;-Js@YGc{({dlYIU-FX8Iq>nU_+ZMgB8Bb?DSz;7^e61o_YC z88g^Jr~hHH%+IO0rvG8GtmU$Ym94S7XOaJme@S}cP=CQS$rU938NY#?IY|C9nlpdN ze@1hjIQ19kUQ^h^3e(sR<}zoa|Do-hQ~$*^-+ntl?o0o}Wcl0h*ZgPngbD0hT~nVv z>f}G;FO@uG>Mw{TCy@FJeDZV1f5xX@I{DA|X|iuc{xg~$>Eu77SdkZWt~saV#K z>!^P{l{MtL>RUZH{SWzj*8VoC*%K%K8NXu1Bf>6fp7^dE7IxV)cJIy_jy>b2!&t-N z_gzbVzkdq{=zo~(%74s0cw^OBzmQ8z|HEY0P2Q)-e@1_NUe3If{AXf+3B4e(E!5vs z^PD^{{SRx&?_!hYKQn&G68nCjkL0YA`_lg~S@!YQ$Y-`^tXOfi#6GC8O`5Ef`_liA z{MH<~FZ~Z|xdT~;9gzEWR9*gK*1hR}nC!BC*(5B`cLj6eAF{Gt8}|M6FiKWNVOf!q4}Man@dr)s9r%O(?J46Anj9YZLoEGv;17O>^2Q(h z@2eSq@TtjyKj^B>j6di%+8Te*QC4~zbXDKdX!4~zbXwRLR={@~xZ!X6g6 zc`1^|!kmr%hbc1e4bb`vG`TwPhgi;~qW%IueLwqF^mwf8`kkilXo33FKENNwq)8q! z{6Uiw2!GJz=fEFg*(--X`0QK3AN*mmh75o3IbVugYV_Vk)EUv^QR-FqTvq;|VGjHu z_MH-W${+lo6y8T_sNe4nc{sH+c2RNGkZY?hie?SDj%s?{z#n2q)S`BSvx#fFpWfB} zHtOf(P|HC7!`iOL%|pr`#ur2!RQ{lC4Tt`RDXvs=)^O|@CwAMT{2_K=-7Cr;#stWj zXYdDq%xf@{{)Z{TsPoDn^vub*${%#S#pEv1|1d@7Q5%#$#NNwTr~hu?4{x(Z`GX(R zbCvQ3|Hn^OD1Xp3e^{pcL5IG1Q2B$NFmk{0huF%$!px3(uX$_sD1Y$1BfFG8jNfu| zhw_KBX#V97dUhk@54vhI;}81hR>q(DBkO3*Df1uviQSAp_*ol`Kln>_8h_9kdWPUH zI-YY&ng8IYU!;fpZ<2dfNAsNF4?eY}@CU#DY-+pusefgG@rN-zR~diMXE!Iyn4vnR z+n$O#{~bc;VzbpAu^+T}3wn)>7|!yo)5JCk(&!}yFtyfd!U zF~f$1DSz<&$FPS^|HI1CD~3JvO&WW9DtqYkKdh|%E|~vt&C3f|51}VnW#OUm2OU<$ z_=6@t8UCQ{Tu$kcDzQTv8-MWcJ#PHL=UhDIKlq#dj6djRp~fHdsu<%Bni@~|LoD@H z@CTp%#_$K9JY@KTPfj5GL2r}%9QcD~uN?lM*|&l}#9A$5Qpryt*^{K21`&l(Q>59_$Ef>^_`XZ&39ikbf~X3y!1 z${+ORn-`Qn=vBcmvzf*&EYBKFa~(gsHfuQaKa^fYO-?I+82^~871MtM?dGjk{-Eov zTPgRoXH4I}T=_$6^7*C8AI8KNE>`~FciXg2`Gfz=;l0Wqbn8pIl|Sfa#aQ?5toLdZ zy+ip!Y@O6?{Cp(GtnPpO`Aqt_pUgD=;D6;AfAE_$G5(-A=K}tqskvbOgZ^Ny@rT$N z3yeSb^fqMvgFkAu@dw}O85X~3?B%WX{9heiLxRM~TnlHb=Ey=Idp#vfwyTac4X|3m&Zis}3Z zzg;`_&FvXE#{vE@rst|cSr4H%V5G^B?pZx`u4e$a)U^;qyFDhn}J#I)?s!@W(#?S>+G0y93Dstfgay zhOmZQTlIqxFtd*8O*IQ;4X3WgrpaCv{2_KkGio==s6Rp0)!+~Qt*QHzKj=<#_9}nS zR?A?|Sat(zIQES1@7k{XVNA{O7nDDI&e1>62bKPZsqV7uPr)B_n}w`<)BiA4@_bGy zf6$TJ$z80jpNID;_=7(reWmh;Yo5$puKdAo++?Zp2R*gbV&xAypz}iI4|-wwy~-bA zef6&7w8Gq2drWk*SZTq9mfABM>8h`NfTNr=v54JS^ zpjSL${6YWR%J_pG-p2St>>F*3KlmTaHU8kgIN$h#-{Ma`^H#}ut19cF)Ns-Nu&S)L zQ$s;+URB9sVV`b-;<4<5fLlrMUe3s>*kkIxPAhR+V*N_OR%GSXK5H z*ux4HR@IaDFZQtLe^^!4uGzy1Q~$kxB9%Y*nIom|pv-^JB%&<~_iOO>I1VKwcqrTVS6$-^nDu@AqySNX&E zkU_hZKU{PF5Na9h8GrnQS_XT@{|(=&{9*j?X6KYY=ys3&qx>N@@yRpFAN=!ePAPxz z|7v$a`GfyqM{*ad>*u*Wb%pW=f9>>T${+OTSxb~Z#CDpqNcn?b>5m1`Gel~_73F_`loldDSyzt24yRMh|L_jS^0zS_vuFE54k!2@@M49Oz8<={K0>< zrtt?&&oS12(BD@x{-7788GneS&zSW;l)b_s#vlAzgN;9oZ~1}o2hCaSynmtX+^+7b z$&Y0ILoEG#nEx>5mpJ1O{;C+`4?b%?%zw}Y(nrhsA6A$3N#hUx)2|zUi0$3O_=7+E z72^;7)R&Dv_?$fff6#LRj6dite#Rg4X{o7X{zEML9?XC6soR1-_~bCN{)0bI&Om4W zgC6^|@dwR15Bxzh=Yc=Oo_x~ygMaUF;}1UlzL@{um&jueeZA_G^X#E-Qcb@d_`{fv zXG#&*7$+G$Mip}F8j!Llt1X}sm32-?OZB)16Fs{Dj9$9 znJjl|RI$HQOq&^gpaFc_~|zKlrB$&MJTK$ zr-k|(J_xy{s?lO|=Mc)Bie?|{YH~!3=(Libw zj6e7lD;j_B`z9EF@K?ncf6$z*WBm`)<$G=X!9VbV@rT&7F2*1H0qu=H_#0c>{0INi zMS0H`{-C{F&IjzLnlq7k|H3~ab(g$<5zF~F@CX0>T}jFx{DM^D4}Q~R;}6=-!J+?Q zy6$r^|3UN4#r%iZk3x(;_%ozm8|y##x2IA=F-6C7#tr;o%!CQC${#f66vH2M{gK8W zVmZqO{^0vcJqYt3eEPb>AN(o16O}(``VI2_g?1a+Ct0bQ?+W}O_OGtSAI1boeHQ$| zZ`aQFgHPTd^B*+lmBSx2`&rC?(96DM4?S3N&l>1^7V{tcE~D5(r~hFCJ!^*f4?gEU z@cxD7d>QzI?werzL35@I>(9hitVkZOJ>$xlyUHK@uEDpJKaA(>80J6d0qr@{p}gvi zt@+G}s^ePH%R=^nCH9r3)RMDrlP)X`)cFrSIf3v8zmw$Wz#lYw(`7W)`cafs ze^-^A${()TCtzYt z@TuEk{)499GW>Av|FEX4 z!;`~9|HGQ{GbD#6TVpRTD53npe`_}9Bhde_k>)DHAN=Vz=;alxI{l*b;}HJf+nIXw zKddP~L(T;b(^$@$fj{`q{>S@^1JU1}cBh`OgO^f6$XP580lPoIv=4 zKTq;=;1Bm&vgD-l2cPh5#;l~$lQ~sb+&Sxush)v(WS^0xcZ8-eF&ziSh`GY^P19>=& z^*TQ{Ij;P{pIw{JO#egq{>q*>>p#S<4nCy(!QXOozw!rvX!=6s5B`Ywzmz}d@j-vc zeQWD=Cg;yp{@_nP{=4#r*m>K2Q~uzWdULb#2S4V8jmjVVq$l~z9rZeC4c97v@av?m zR{o$Lie{~w{)g=M8-Gq^deTqN_=EpTobd<$g<#_ketcmK`8%(#v3sO8ll5o(1i9nTqm z@Q1fC{^0kTV*Ei@8EgDOAOG0+gPu6R_(SZ|uTw)xZeDHaeQNx{pPbKGqVzwkE$=ea za7|Gid5|1t`XAPo_2(Gn5Bif8)KL5?IeVV`{X{8$@RNOwKlnM<lUlE#(h>$Fl{>AM~izC6qtt7JqW41N{$cOI{^sIwb1nT=p%! zEa(kbTXG%gWkLT#Pu}tUl|T4Hr1pXN5Bj>~A;TXuIf3v8os&aP;}DH)v*xJs2Y=mk za#|!eP_8*#){x;3KI=K~2i;fRt>6!uc@F$RcNFHpA7ZzzB6phphqYy|f1C0LzuTT{ zks`~`Gf8}=TGGivD?PYSN`BPes`|immZIv`?Krs${+l+X1^(a(BD^^ ssr*5|xM_p(2mSZ#b;=)NANy*J@&|v}z*Wj0{Myg2Q2yZm++>;ef2yxwkpKVy literal 0 HcmV?d00001 diff --git a/crates/develop/tests/fixtures/inpaint-membrane.f32le b/crates/develop/tests/fixtures/inpaint-membrane.f32le new file mode 100644 index 0000000000000000000000000000000000000000..46ac5cdddddb41dd8aa77447bdf4ba902ad0f99f GIT binary patch literal 82944 zcmYhEd3=r6_W$D|W)edrM1&X;WIPc`#D0QOsx?$8HB_~wTCU={=;&%G9cZ;$Q%h?e zD>cuA#?T}+#E_zf7+O@RsZ`tFdau>*dHw$Tygv5Y>)COh&slrzwbvQe;$0UIFxK^+ z(#o6v@&_(2_ff^i=6&eLWsiOA$FA&WemtzjOuubFK&J9OpU)dOpsn)Ye3_3q!O6a^ zemrwVPd^R_=;z1B=B@J2S?<_s<#{$&cD@9 zf1bSD_x*f8z=wW5*=K8H{D1+U`p3Ak$NX~+Yw?30&wu%p|9OtjJLBie9xL+muIwd0 zpO?E_G4lrmtn%YzpREyo;DB}h=b1TUqkl|(?iN2k|K&gZb6)Kd;QinK*Z3>N{J8e` z;(oj#qNMn<|KG|{yYXm3zY>nW^@g4kgZi;x!@9Xgm9sT%fm(G4X;Yt@jjvU|BZ#!T>it@}E z5Rj_8`L#8gUt1$MKR3fae!u`*Bm6MYAMfX`e*H0X}*|q}D-%o8{E#niv zs}vVL)5=4C7+5Y>uYAu-N#fVmIJqcE{*P>pyG|#m{xJUc6G^h(V>)N|Wc>c1w(lk2_mtwDP4Ih0 z@ttV?Rz->%*XNlpscpYHt;Fwg+o+p19ejDig#TVl@T5;<9mLB@Um?3jp%KO+@ZNHk$Gsh}_ zYD4QYEZLH&8{5?_i2VZ+TxAf2-J~MwlirXPgcoZe*FQX zIp_}lBPfKHU8pn^{Cp8zr+7sSH-3YJr$b{ z^mEwq?xR20^1h=#@Vw*1Kk&TQ=nr^WEz=+H-_=Ziz=JB9{$RUwDgPIfbbPgWra$m+ z&f@>e*2p`E{$R^{NBjfkT|j2MSpmncL$pO zz~6eB&sd=HeS4Vxz|XmrsQLpg^9!G!LY;rag+$dKc>9dm8trpcq+|Fj5&z(;O_b>m z}6~7_+Y;Tw6nL`y{D`EPBZI3@Q#qT|xbH)rls}FSTC8qM(wl)6yU7pR> zczhh6?czF5t55{j3PNL2k{&dj};;N$2p@#eoZH*a`JhQEFQD~z0P1W(~L-3oX zc>eR5sy{qu#lD%UKlmNpoo9ABXHiFB+x`U! z;@8%gmzyBZ9HV2JeVZV*jdjj1w5N$8TrFBmVGIe|XMQ zH$BxK#y@=3Q~iOTI1#_L#+zgDYisN?2EWa9o;|~O<_yJ&FY?T`###LnRDYH&eb=u) zb?f%mI0yZKM|030`1B#BKVae$;vX<^2=NaXZDId~EpY|<10Q?b^anmK7ftA?yu}0k z6!X20{xF{Jck~C$_c;24ZRP9ez$WFh&Z7fcl}8_le;CjAEb$MR?^E;#%=aeo57>0T z*7(pvra$n!`{)n8_+CSQ;CbKCA28oj=nr_3yyNH(IHtGh54L>25dXmQJwp5gZ|}0L zk?#fchcV%M_zbU8yk#?=`HhNut>S&$qPF+vC#wE1KKnMGlK_u7`(Msf{edrbn$LD| z4?OoU?^H>}_C5wGKD~v{^I@H{TQ}1m#@}j>-$Lbi?}&fkeLmhPTO;op@elm)aMK?! z?-%h8&r|peeygc3d#6H_5ADD+hbq6`r}_i#Qs{}_XdQDsk9R6YZKq`OPBm6OZoQ}a z!}I4a^TcnE@((?P-(bZ>srap;_^nv{R#jZLZi4C$wmU<3W?SPk$G%udHFjN_Rz)wWHPCw`-p-?BMg{yz1T@3ksk^#|Mg^W(*@ zt#QVTczNa+9iKKiUTkfR$H&F1{_vc0CHy7+!8UWRQ~iNIEul901OG;rQ~d$gTIf`N zz*}Y8L;M5w`S5FNJk$`sw#MP%_-(Gw863t`{Hu?i5enx+=9rc0f4}9Iara$m^Dx3bmTfAy(BnBYh`kN#lG_dEIn&v!cd1JCz3`U8(9u>S&ob}>`+2mI2pOw}K7^})Q$w#F;HO@H9G zKW6&Foc5i&QRm@%7X4ui->t+yVBUB12h4XU@ej6qZ=yf&yyNH({Cf#}#|0|iua4;t zV|cIGe}T^|dE)n;&KVG3`U78ZozJ$damiUe+r@OA*AMa8wl#Ly6|efk z8XK&MSN*{@s+j2y{M{S8Q_*UhdyaQ1MltUo`os8`onWhtA!3Y z9Y3fd&zz~){oO+RMk)UJ<2cnHY`4B0r}~5K)RA%G*VZ^-K%6{tjQVQ+WSrRA8Y{Jn zQ~klV{InLTKj5?DTd4kk*Z#MK`0cE=lLod>{ekb>qlM}ZzLMIvQ2l}b@l>q%wKaZ| zA1i*-^f@PNj}^bo757>dtNMd&{Fkw+KiHO-8msyf*z0A#{?yv@kt3gj{=l=hLVv)- zIp_}<%|U;_Bf8fbi5dXlVGw2UI`2^x0@YIp)NBSvdzmNXFqb=wUw(Q5z zANaH5O@H7m4%wwhWe)Na&72Y)c z0TVx*G~_u;qP6e;6Nojd!`4`bs&$ zI~Afl-?QisV|d4jf52V8az|6T%qJL^2tYGtVYz<*ITL-hx|_-=F6A8aR1Y$ASbjZ;T95x;5r zoU{5j5x>oKo&}wn$TMdsUYXHE^@n*j#57U;89i#0Uw^>txzL~P-KJ^GgZ{vWb};>c zw|wkO<;laKKa3%^L4UyHRnQ-B^y{WS*xH_`r}DNB>ZiWg`=CFJXTO8~fZ5}qKVbGX z#6RFt=@$PmC-DjT15cg-{edT+fd0UfH$Z>D7KePOm^}#k15fOM{$R^qgZKxYcmw@` zXHP-=15b>B{($d9oBn{=U$g%LvyW!~g{{RBwnp~F=ns6!UZy{cx0rvU+7joZKk#S; z@ei1I9{s_V7#{tBCvHc7;4f4+{eic5AW+BjzwE^CVV!5xD89RoDqh!*cf3%ahwpv# z2V0A=&nRzkb&>MK(!@WE;rku^0e4R}{Q;W}gy{1e4mACNuYA3Q>JQJ^rLcwgy{B{X z-HrY*hIgO%2V9hj4%iy&);0aXwqH5ZAI8kN6|4FK&-+gP2fj@d-|5kc-!5v_$^HdDvPuWv4XqZB{%5btt5 zo%5|&-ep_k&Jg@YD<2Sm4#enq_j6;hwKcwesIlq~^IxdmT=fSWRSdr!)wciTbn)9+ zZRZ|NSN-8RPj5+A{b78qh3Tq4V4uv5{(y&vHx|FP##JTp+g#`T^;#o&<_sMZd%ThA z4|5LQ*+}(gO3`$`{#^d}4R_!_raxfLo6sNdde8I+Y{!_y)4k8W-RKBRA=?{GDalX5cs;@7%@{SiOt~QVN z`lRBC6VZV)iXRN&-M2Nq+%-=12fxJg=nr#_eT7(}n)*My5a5 zb_z26!FI+BzTY3HuL^JSogScb{_i<-z}9%HJvv}(d?6kkD4}zntZMqhoP58dKg@Zx zIp68gI;LM8bRb6g!-1whjDPrQbJZX4=7Y_}Z;*~J*^75MSn-%lzSC`uztnG{`os8s z<(jDe;H%&|@1w1;-OJR*nr#R+=CjOtI^@o|3r**k2u=6r~M;K}o#Kk&pn?7!eSZ({!i z=4_Yv2TYtp`~yaFh<~uPkC}L#6OH7o7p%H&FcX z6T}kHiZfEsff&VT0`U)P|KMJ_>JQJKaw1*)1}VR;AK&S=#;05Hoo;I^RgapQsyYwf z_3Xc}H65@u{%c<&@tdmr;Xq=EG@bLcpVCx+7+-&Xn(7ZYe;GR9bo{6f(1A?Fy!+@6 z&pGE7?{Yom+a2XyZlL^)_2_`DafWCQ`oo;9UPT8QE56b@M)e1N>&#TuALe}iwN&xj zQO8v5n<{=g>zwPoRMj8G_p6ht`U5UgJXQ4vJaJ;Q__Z}Az8EcjZH+&4h!(%ib=&yvrCV$Q9SeLkrZoBK}= zIZb);IrCrsTzSr*kIkE_JoOdjj?Gide#(_yq?mJ}VJ(&_wmsAewY^ZCebWHt?HqQn z@}ou(pNvr6;+Zju?ObN8Vss|i_m<*cuO*1zU24mo$d%or{NX^fYrpd3Pv*azr#x}X z@p%Un51EUG99G=n4f3Kh6q6Ut%bl&ZmJhKtavqWFo2NYI4g&@()bZ?VX3kimxLdb) z@q1Zu?UwQHs0RcM{vrkF(?Na>E zLug2jV)iC8XY5nkfB<5cT;Z?>b8WN#AT5+{Yq~h$`yvubIvqz{sK1%T$S?mh})z;;m2wnpNF{M_0-D2eLU~BaG(2z*w zgM-l!TjQ_SqQx&YHxp!!j}Ej}d^j*w{*T%y&N|;r{I*rwDcQ~BncFEpWNtIDZLfTX zH=472c%q=?_{%BK%W5x+eYhjvI2zdaS-iB6Gc?xpx}V2arGQQNHZP5Jw{^vU!5`ZM>| zB>A2-{eh=G2mOI3w~YRP$tR1}DJF-E{=kzrMt`s+SB(C^lOINZ;L#lP2j0$-Rw$0W zM%*$$G5MMN+`)<)wKe_0mVMLA8Do^UT<%z%lXwRGVNP_CIf3UTD=@K17juicYCm(|T zFrHi}`U56DL4Uyc%UY=ZfH|8$f3RgQgZ{vyC+H9SjrHUoa+K#x0sUbNxk~g0Onwsm z0h5zNf3Rhrg8smhdqjWW$v2`u@RpaTsCf4_bRbCavFXjl??s)H`~&)fEqf632ir^g z8>{}n-=9zXU~8=KCNaYu9TVBJvFZ=wdrx6MQcLF_I*9#9gg(!>*6c?jm7iA2^oKbY z-$e(al;3=ieLy zDDL_d@j#+tVg~dF+tJ-qRe!L3FM(JhMfoqvri$M%os&2L{bBs9{?sXlD_)rqEq{jy z#XCcYC2Wlr8`M$TOZywD{$LwbteNT$zEV!`F1JzJ_G{6Bwu;dN^oQ|72cZM)6_0D3 zqWXjF;GGRre;D)TEb7D))YsIJ4dj_^jSD(8kY~0vZis21`os9|iZ>9y-E_`U=}pCN zceM?x+Eo1ZP(Jorvg!}MyuHb)KiEG0RkGOj(J{}zmdxKr^0FWJ^#@EHGVu?Xnn3ht zc=#f%%SC_SIV(qh;5oNKf8fhcGyMTmw~79Msh>oDz{EM|54LE|{FhfKKXSL}4?KBb z^oQ{$tD63R${@|X| z_y>ICd(LHMsIBE=XX_X{mzk^l_&dZQw#K|%zE2kF81g5?Kg`o-jOh;;Z9#u{o{({- zKk%GyqCfBp<4k|xuaz+U0do$5{(#AgqCeoz8=L-Md!d-=4}9!#;*eaOlf4Z31Hbic z@}i|ZFu6_i2R!P7=Bhv7?az`AsUUT0i{$%)IHaPE=@ex81OM5@bk!fmvrj>Pz<;Hf z{(#$7F#Q2fF5=y{H6GpANc9Ik;=@L&Kg>zIf&RcBn@%hdp_n}g`U5|(4RJ^v#b4Jn z{lWI`4fX|r%2yvuEKypY|LIo561K)gp~NBObPRC?`oo;fzGYuvYkYH7wD^rv+v|D6 z5(zpcbw05~qVi*3X{P#v?cUDKRDZxh4T(cibbOCLQ^aqWV&Vt%hv(e>SVPqx#+Rzs zQ1u7C(|vTn*7(^0bimelW?=*IE9WaRzDr?K)gSPTubayMQ5&7}?09sbt&WN5jSjR^ zeppgdv2CyX#?nnyf3Q71uD8t#MV!`tr;^wf+4>J=GtcGxM8z z;sJFf57B<&>t{oSm+P7?6Zh};4OzdPkHh==np(~GUyN3ayTm# zZ=GrS1J8a6{b5dOKG}c4TOHaM6p+Ah_%!v30Oil*<0dqD){KK4_2cbXk zml+2f!;VB!<> z2V2fW&>wjAHRumKXCK5r@SJy`KVV`K^aot{3~@-1;_k_&KiIN=L4Oz%{dyzudsTfA zhp_*GuUpsj2TUG=_y-)mCr0%LoPC>EqLw}nu?PACPrd^E!B_ea;*dJZlcOO1VN7ym z(;u+qC2Wl)dy$v0HIj=!e;C6a1pQ&o*AF#R{eizfzoGbz(=l@o6H6p0uC4}8gCra$mjXFgcRWPW4% z18+6nW0YUeiGBH4wS6+e^oKEJeu-E8VNTAV(I5EFE;`j8F!d+s514Zz^as51anm1c z`_(c1fk$W1ANX1QO@H7!CYt_$$+w_CV5`MiqWHPbsk6GQww&#vKaBb9(+t%g<|H4B z{=j!nHvIvYDQ@}$wsV;sItFb)f3Uq%+4P4oOU{z(*r$B2Rm35=I-dOw`ooy*kD2~} zXN^u*{Q*Dru;~wT{$0)V2R`dOaY#j}Nn0toYvPa~4?bjEn!Gy~bx!mI{ekBk1pNWC zmqCB9UDuD;!`Aphyy*{ojlZH*e;7}G1N{LnzDq0-q4=pB;*dzi<);yc)Y0eJ{w#4w zl=8!pn#tckPuuW6dA8-xXgP=d)+;h6WP}^?Zh$U(&U#cE=WW$x;^jkgE zAI1;fi4NErBR;Gr&s;~xALv_8{I*oQd=jxlYqjm$gIJ=C@<9!WL)t2zeH$HUr~Js> z=sJMwIHm|PuwKeV;R#%?cr*n?UtgHIN_{Np$s{VjW z$(b_x1KwDg`zAdUzjQ1?{PtAaT2j|a{KJ?7|Di^`kMiSMvzG~zTCXg>{=5}CUGHtN z{{mCPO#B13ds05db{{ZJZS7vt=gJfFpg+vXSvmTHtRt)hR8! zlXG+2tcO2$1IA`}fByShHzwf=S0<^s7u0lzyY~2ex8Q85x9iOnu2#3XZfKIv%M4xO z_GZj?i$bJ!F>i@WI`z4`-ZH`K6S~563YhKARZj5AU;W0_6a3To1g~h#R#!*Hq^Bf# zr{6s4z7yN31Dna(&$@>mpX)xVn&$1lebM!4Ip6Ibo91;abJ?~1>2sIeI?X%Qhq@40~>ypzbuj9-7QeX9l=ee=IzUmLS z*lA*k1Re9!5^@@eYJ1>6$*Mn$S??vQ{^0A2vcw@NI)1_t-Crms-avmC-?$R@*TWT8 z`5{XF4z|Yo^P^OM7;|O%u`}&9n~N3mELt!f53+t){$rSsqLoUB2|A_@cwiguee_b?DTo^NK8jOLkfR8bocAoh{&erQ zR`#Ksp*K*ToHP0Z&p8+SFUGUyV*dr+8DjAdnA|e@1ExL){lS)f7W*%F>V(lBc&p`G zq5QO3raz2fZ-xGViF42&Fq%XD2U|Ob8mm0{Ve|*S`e4%^^JV%29^Kt}y$9`bUv{4B zK71j=dnk8@^L6;reYQE>tJ7wid;PtyTy4>WOe=E@|`T8dJp5QxwCwiOnce%FH zzjCWP`n)f`Kj7xQJKv>GYU&ND^n?4Q@qG8D#P(TNPrIss4bYWbc6fV4Jy@cO>i|U+iUSD&P5j zUDY4+Raf-~JaHm%NTiNm(1|$2*0?jIuJ~=Kw!|CgkNILR(?)r3Z-V%3t97lmMYQ>4)p2}yPr|!C!^7+fC(dwi8<>BNi!`$umbNu=P z=B_&W1Locq`UAEaW}no;ZP0oi^aq|A9`Zl%l&%@5YPBO?~NyMyI3max%%b!&lZ_-K+h`P*&ouHc^*C3$nxa$LEQ z3*E3+ecpR#@?D>pMJ{VrvUjTWQP(GPkt_RBQ}5!66Yj}`MXvG|$t&Ld(Jg#?p*#0> zQ?Ks1)9%Ac3tfYC$)4|Txocl-p}Q%cg~!Six`G!Ly1%a`c<*dD=%yT9;2y7J=kKhs zW1{H~YiCb{{=jp-L;M3zO$hN1Jb4xL2Tbh;@ei1K5A+9YXS)@p#%zP^LD&ZcDgVSv z&E)^Sxz-V zeI>PL9~7zh?eeBSj6d={aY&T%4L|05I8bfT6XGAne7TjqOc~{GjwKGUH4>8$|1jp$ zQl>xPOZ%f#f581OvzJLw+tn-B%OvXflEacze|Ua!9prx)Z*fS9;(MDkzoEEpUG_3H z6_2=3NA(BWZx`2*zk{tYWH50^r22Xxo;akAjwkj&f0#d6Vr=vWJmCnjL>tA&rW1#> zRoj@}#3AjJf2B5YNPFdT&rw_6MEP6oYpeb+PumK$Re!+K4@9W`fPeltLiLB|On)*$ z^#}g_8WE~L@TJmYRe#`n{K>gS51oJMjwY%<@PEA3MD+*!*u&Il_0i|~qAa<}FsU)y z;@6+J<6lXgp6L%f{b$f0_&xGBC;kD`7XtkO7hLCFpkpF>4bI>37dRO99f56nwpg-WJ za$0!4ZtGl)rxv?I@1=UV8LM512}|5i`M&y3gVipj#8UU^f~MZ`NvmD|rzICHxxOmZ z*SOAOmb#=pKJU)xwXW&&OWm`TeO~wA4em^>rOvl3$xC>!+1Anzr z^H`F%X4oG0s*HK1m(L4nn(sal+lqhtyw`^nxa?P#y3=Emy`m|FuJ(&E&*o$==h0Jc zUBjiW!RN`|nz5(d4|kThQ{lT=cKgMgKd%e|7NN`@b@;6ODU&3=R4>R ze5rKuFclSlaE~}7NO9GTDXKq=L0ixt=KTEx`PHlHm$O~sANast?0s%3|9%bAA8f1q zP+#>2oPC?UOf8+i{aW@i5&AsrchDckbWdgYU_5h<});vV6ADAMlK?*~=sqZYvzMu<{PY8nsy~d0_%KrS2W)YOt+8<>;t*ToH~F>2 zZ%ei9f0;X^t#!_ymT=##jq*bW5r?!@d?%VXq@Ci|eu@>__KJ%yrnbC^+CEb*LiGo~ zm-bU{m7x5;->oHnZH>3u*OF)UsqL#}YN`G({$KmT#cwy|v(7gbzuna~bv}8;9?EZj zwz2r_seGF#?tS!9KKEQBvF)R{>sNOFf}H99^*;oM$~`aYpTYFOp#GV27itTse}=by z6!bsbA)imHe}<=SkospZwSv??gRMTWt77X<(o=2i46C2=+PWce4(! zaLF=fg{^YFc6x>L{U|x5!^hp%1v0*Jve&KgDc4}*3inm@WbaPi8P|I03YYe)&kHYe z-aU3`g}brb=QZAY$-OpvrCacx&rAF9nu|G><-#(PMMH|oXK06>4N?Eh+R5co{|s+2 zOrY}Aq*4FO7|wvGe+FCaS)pRii>ZIc*5@Oadq(+Ruc0CIKinZ_UJb-=u+B-`Lj5!I zba;bv;cAMlJ|sjj+Cu#^ww&Wo|IGOGA>?W4e@OpIVv+~yYvM#=m;fC^tU~>>Ju@+k zt&uYt>YuS4HHvc?@;H1pIF}&@v_n46#4wz%^LZwQq1I=ie4g3MaEF0sW-r5i&V}-M z=5BJ3+RhLSp#B-YTQ@YMit^|Q_0RBmxoC*3k$nyKFW?_~C{p}#Cbv*N&%_~VYI~u2 zy!@@W!?{rMlX0S5R@Y^F8G2jr4x%BMiVp{J#(_Tac_t1aR$C~aXX+MhjX$13Lu`#R zW}qR|AMB84Mni0k!NIj;y&cr{PIMEke`X%jkdDd^nTv*WR@<1~Xh;|3FH}cEx+*{S zFtwWG+7`-Zqo#1S#$T`15Wm!5EtJnj4e@Jh95A4UJhPqM)~#DZ{@vF23v~Kj66araxf%Tyg&b9MsVC2V3rVqCfE5w?cp5x%y9R0zTb1Uv&z>`Bpf8fdIaQ_0Hy%qWcCeA^Bz*Y}DNpY1Q zV!bw%B%htM%FPwOFK_wM)qFV1RoW=$jeQooM_$Zwy<`s+(|v{e@8B$#BXyOpOvrLC z56p6Z$v&&=+iP8T?<_Z6dhW%q+UUX`&2ry7mgH6SWY6VgxsQ4$d0V|*?tsg3Meihe zyFcIS8n?@G6ZR*0-!{y5|9V35tI`v4*B6If-5y!4;xj()V8L-WvU8SOJHzL-+kVQG z5Zh7PectAA=iHtKS#Hb;pZDCvOYWo6S*~R1WN+QlU)=uftK8OClfB*lz2n}P{k8jP zMpM-v)?4!wF-&o(?^+_YSi~?T7617tF-)M;iS3fJNYfw2tm{V}=BWNX7lm?8RH%O| z>QB%g#!Q^ZXZ(!fF`1@6@Gt&eU-gGM*%P5Z@FRC~E?iB0QDesa3wYud^auR#ReHCE zDNdbFp7x&39}r;r!<;wPlaCG1F_w=lrgI)@NDO0Z+;y5MQ1K7yZH4 z_GgJ}5ig|0|`o_)S$?^aTB3Oc}W&kN$w~ZHiU>0h15m{snWMXhe-@rjE%y z$605T@}D^3kb26$eJ5PrWn1IOmDE#5D?eaBxIDA1@yUpAv9&d}J6coq2Vea!H&Xq< z*W(h0aQ_0n^;6^qJ1b7E+(`8YzW#phZgf>XWE}dPqR)edpg)YspB5&5)0E%-SeW>= zHLfZdruxH}FSnx2PRCCj8LIkoeB27Z{($MNLHsj3e2?sBO@H92Z6^MKr=A)8fv1L< z`(I${meC(DwaVxZ*y@wJsx2`O`UAf*!}Nza>G?qX15bSp`UB>y9Q^@vj}rX>TP^Wc zos;@u^aq}rVf2SNsT1b@DLl2oH@AP{n(SWfZnlc|R{!z2J9uo3Ya#c%PCT~2ZMwb2 z)oz;TO>)cJ$2Zov`O_1<%pR-ULs!Q!9)9z*~JRwR!vvQ{=O8SpO!R6QMuw zR{L70e>dt~(I0rr<(^T##8mRPMasvtHT_`>^(W{Lm@^>s2fTY5`PdMB9&)zm4?O3^ z=nv1Ca)Q15J)P4h?-}tAV|rd99~+?K-<(B0wwPjav*-`D-xW9gVf>BtbyR=gEg#!J z$3OoX`PgX1?V zf51~mMu@GgaYIam_)S$?@+9aFV`8sy-=w+nkAKxf^#^`*_a>@8U~(hq4|w-B>c*oK z?+gi7{o#2o?dLv+t+B$J#3A%Q+@moG`h#uHOT;0z#y4lxQ2l|=UlybK1HSn*_1+!T zwnkNQgPqmZ+snO=F3LauTD0m9(K*-SO>VBQ8d z;lBx9nLn4fKSpnGWo{&Rz2E=ZO&z+yy_lNly|Q?X8$5V}3y|;Au-O}3-$5JPC^_>Q zGjp3;HeiGMVxfHJZrkOCKfl369ZvM_m)qx>3172pl2>PRzAO8}2KP-n>92V6u*()4 z{9cmx?x;dHP{u6&UUaGQY4_aI8{Ew>*>nAJ-hI|(gKPXBpZE78S6r2*8=Oz}V$rYv z=FVJP?>fv$_A)o$cUfE3xo4)D{;*!orqLfT_i@l4)^2rify!UcYbu`&`XBC>_|Wu+ z@vk4^oTyO$Zq&S?Kk%Fr5&wWE7qRy#Qrn+DuBY)2{E)fiVd#IjUp^burBqX2b{-U> z_>C;~L7|E{M@E0JO_siJ=nu9722f}6Kz(uUgZ{vCUX1=Qe$*)TLAFNDh>3sTV~=w# zTwk%B3pY^P^3%x2Mk~)*F#5xs*|*81G*-Tr1l;Hk^Nf*m9P|ggbSe4RV8wyG$j90m z$)BJKOJr=nvz&6ms9Bx#H!M8msR2FREqLGUv=?I|HJ+A*$5H8 zw#J`74iUe$#)lpXQT@T!oLlV6ZH@QmS5y6YWX>AD{+v(EmwpANKk%>pWcmZo-3s&v zp8FKUKVa@q5dVO=H-Y|uxhsMGU~Bgyx+-t|ZRmfPuQ3n%FUCLjx#I%M<*OidvA z19pG6Q2oKy?lNpup8E^v4?K4k&>zNI|CULLxtkF9=Tvw8kxgz~dYo7Nvsv!Me>S_^ z%y{pYYV%z6U7Ov*l84KlxWp|!z1eM%@69{Duie;RHoHgnNQ@*g$edf7-K1Mm=QBe3 zW8B&7W=bv4u(!6k27>=9`^{h1?Q+k_m>L5Uy{D?|bBk_nc6UEd^y*K^cUOd8b~4d> zDZIeVzq{G(sGa0BTUY3&-rwwge?G~(_u^@H=+DjWisby4KXbuNF15w=3i5etk6v+u zlD4>KKJa;G%ieTRSGTyt^ki>!tv}ogRd={0a`r<0hqdo$V*10{shvZAz;>1tsF<33 z^amcDA^ySEYVQk`r`{g@fww%&8RbKpn*LzB&WLSK*w+fg#KX5o(TP6%nu#d2bEC% z#osv>uCIJlG0uY;C|pXIFDB9IO1Tr|J7a|HFLOYZbYa zVCAp$CYNGsBp-|Z@C@bFg{%I6XZ2?vWNU0vDO~jjp8N^=!<-{`bKj)7+Lj#FNcD#? z(`vB~a>}#cL4V-a{+GJVD76jW!(OJI^2afq$4&zMlLZLH&e zsUNEP!<^^|{a1OOloQljcGNLB?=(>Tf$yHoy^k)+Up!M^^#|KgACP0C#&V6s#?{1c zs^WjYTTS%`+rLt(iC!h0gfG?gg{Q)nZ zWcpKU&p|gV$@B+4<%H=Ey!GO4E9X}m;*IV9u{-;roW+!m z^Dfq(?OMIC%@tOS_hLVt=N?qq?k?oUdl@H}xCc*ccm2{6yr;W-?K%(N?&gk2@S=LG zaqs_cyL;rL1n+mrKY#wtcK7?D1aDOPZEn|u?d~J#^}T7rF4unCcK5^e1aHtEdtJbr z+uehhL~q6?`L6TW?d~DjpPo!DaJ^*wV_CAND=c(FCvSHXZc7~Xzte8}wC(P>=1JbU zCoj0cv$wlD?Z|rp_CYbqpRZ0` zN@K;G7o$InA3BJ>A3=)I7W9WX5A-FMVr%@gRJiI7e6LkCRe!LJ?8!dJ)_9>OA8cpLs4mZJYkayD`yl!s9+Y?>MD+*T%Gc|w{(z57r{1!o&i{GK`r@~< z;{KPZyY8a44JFnk|HJsJ&B=eKC_iyxRq<@L+-<+(pa`~%OO zDf9;{wFBa7l49;g_00Rk{rlOS?t=8poLTA%w^Pom=Cz3THfAnx)4$Jlp^_7*7_iKJ z|4X*3*(AYBJN2~-E4j;k)I7l((SMD5xB4zuv8lvAcQ?4C+PmB{Npfy^e5)%{bC>(8 zRf5-4xXP7wxqX8ZynEaBy069d!g7hDCQDoyxXV?!m*7q8QQ)dp+2y`!o#+MLEp+9h zcDa{jA6I+OY4=pzE>~}Z;KK86nB1@EbT!d?fBt1xn7GUJY?kDe?03VxQ*oDjVVl%N ztiR_D-{0xpk#jNPAJ%Jm;NproV?ux6?S2rod7I_To!>$_tbaGomCzq}yZb}`!z1#$ zJDe+>RGyp+`ooym{~B<3d%6ROWZ9Si!y zn0V>qivED9e?fo1+74!$bD3!XD`iiYCrGesNr^%&6 zE2b6&{lWIO?1|7HY_I1vR{ep$Je(e4)L2Rkyt$_M4OYCaUrq5_Me(YVHC2BY!&wjK zU)b6{$ksULR+#vu|KSnY>yb-IQ`@aGsrPQKc)b^``ola~=ec+0lwUT9eNd*_604v; zj2ShGTnhaUk4Qd_T#Bu6@J@bz%+@$So(273e7|z+gKUkxR#j8|!S;=;da6H+8QqE0WoHP0ZPd{Yz z2cDi7=nt5F#q7Vpj#ip4>9=598^_i~fM=L4p2&>6c6X z2TY$U^aoq|*`h!2^q)b0;5SIW*{71GyVaZayGQ27dF?NM>5AUmrs5Gi&&rIS}cn9p6#3Mo|%#3o{=8uJs;oe4*xI5?TC`vQrUma8JFW;e<#6vWL|;0 zJuAm$pOIW><`3?vEjeyPc%pat@zbthUXFWNa^P40DsrI*bKK!%skdGGlbd=z$6c1+ zf7w6in)~S8J?`<*iQen^cU(l)es@;(Zs-qdhedEh|hZ#`}L!x(D* z(I0T5w$#ZKDkk@f{$Oi$xo4E$5M%lSe`$Xm)gNp#rT!NE0S_I-SyDB{bIMW=6QVeO z8F`pceNJ+`=nvy#ZwzWNtb6(Aa{C-wKXtp8!Q>~~Cm z7{lFC^asp+QuGIGzn7FLHD-KXO@H9Iw}t+|TMctp9Z%0L^oKF@&td-srk4f!119D{ zf3O|(f$0xCeLK+~c)QC<|HEv(zlr{UxwDD>fVroM{(!lg88UjVTN$;_otAf`YgxIU zUV6VP{dA(&@wpW)@7_KaA-#s~-}u_?zO&CoZc6aNv$NdHhWp*lzv8`|TdQ5U7x%jo zz2m*FYOi;jUfu5=zZ>Vpj^6AhJip(S`!UX&U1FyjS!=)BF26bQxuDR zw@s3p5!@>>!Rz(h5w};yj1+x7S@nd=6x+Dta-VD7X?J?`e%CcO!TTkw$fZ2J-+lQ? zg12(t1-G}ve%J7Bymuk{C#ji~`|Z*@u}8~a-8;SZy4H7imy1bFSGJyOqd#EoDiZ&I z?S5jQ)PtRr{V8>%^gqm&GXm2ec)NR8s66)#(I3YAc#1p>{SULHcADHT{SUL{_a#k# zuqB>Bf8eS&g3Nrn{cJ&JOLG%WcShoZHNa=rgQu3TJ zsz2~&$5T5)jb*lcUvs8R|HEwezvsy1+8QquwlOn-?N+t(f{zI)Kykj z{lRwbVR9*HI#0=A4OD;N2UTpK`UB2i#y&_wMzKw5&pwF$huKnpLe7o;hbJY!QBCy+ zzS+0rQf!U0`m+zB|6#VoknDqOjn93~KFHR%FTIND4`ZH8uB-aPoSP5UQT>6hJ+zMM z5BTl!byR=AKP`z={Q*DrFn!=s^m!&u3=+TeKg@Q&)DIHB^glf59^X|-{L=q0TWUNi zss4a#{8dr)2mI!&iZVV-{?Bvddxt(}k&5Ya$o&gGbM%U*{+TiSt|Il%@YdHo?H^mK ze`XB*2C07r(^ruCXR!6bSfsYuw>iV2Uqz1S9yL7lKRhG0)C~?$-ujRaR?NL}>Yo{J z=UHPE)90W1XKdMLQUA;s`s{K40-k<))IY=1H*aE@_3qwpx$YUMms=O75uaS$9^>>8mVB@c#VcoC}T1cZt8nd(oeq zbC0&qbLGVEx1XMN&0}-j|GsJB-JD(M_V(TH3Iph+!@BuDB8Nl&L;jE0L***Z9*X-H zjLFO8JFc{R4){MJ4_roZOmFs3<>YUAM*ddBF!Vp<|A-id{)hY@v4`S23|s21FaF~< zQtO}LXUrfcbM+s;wYB~k+uU5@mYd3>Gu*#`4+w}5znmrWf5drot$+M-9!-rMpDXrI zeD3i}3}c!|jU4sQ@VjnP7Z<3{X?1b7#@t+D7+WK?aMV9Do^vAVpTRTao)-1bJde*8 zCVuHYeC+h+k^9+bVxM zn*ZN+%1_BgL)!miOKzY3hdB;Swf={^`@}G|#=KlK#MU@qK#)8$y1@StF%0)xu&pG1 zyD9EHB|`jmSA08~dV?N{r)1X>zdhA9M)LO5KVzGHo9~D|%J-f^ZjJtjMSlI6duyNG zc}IW1+;c~N!1g;?KE?KXlxb>fze`2`!+r8SX!^sP^k7GS;H@9>BE?q2O#j1uTF-<2 zfH~Vjf3Ph|<*v$L<>_UC{=i!w@-fQWZw-u9On+eXhk57?j{bn@Z-f3|OHc2>mOI?M zEl1spyPJ7cAKvOZUOMQ0k@}hEdvA7WwGOyevS(>}Wxf0H!uReEspt7@YL+`%bifs4 zNDR~VYj<=1A@{A+iM`Zc_GQl<%)#=gyaG%CD=nreBeg^%4@0e)%15d67{eiE#kr<|&;-ZeGKk#;zP5;Av((jr* zRFKq|6-iuS`U6jXhWi)ryH0a9P5;AvS`Wkh3vfR3?}`?Pir{Q)P8wi0Kd5@-XyxERx@JBZjdxwtAHqh8~Ya zlB?t_iT;QCTavntg!+nwm=6B=if4I;6Hnytj54Jl)h+%AvA1<#Vw)8(Na!@{Zl|^%y~o|L_R9CGLvF2!@`1gARDT#> zaJ`cFwKdM0P)YpK|8Sq=mxy6(jhWw6RQ=(3Dz&Sq`oow~>9xc!{SS-eE*|H7^grAu z`;l74D5YqoJ zPvUUy)}<+KTfyQVcz$b!_y;^ne)j?W!ImEE-2Z~-cNK|$;K#ML_y>N%5z`+qJ-g5! zF#U7TA27dn!2K_52k+#ZVyyD?AxD4UM_g#E`onno1EW9S`Ol|&&6a%Y{`Ky0H|tQU z7Zv`kd(h&rd+$HZyd{-(yHz6(y7_nHetKOwk9zT-dvC1NDz9Je-jXpjCp{&$J{V$l)jJ>SUt>C$pnW@@3^EoU72PJZJCCmnVv?HhTMc5iiWbUWyt z-rLx#w(6*RO7JMjlZ^W0tScpBzHKXK?yp~R-+xr-`c6pl`W(3IepzzFHHl2}$_>8a zG8PuPF69%wp7sBgUrxVV>mb$pe>>8na9C{+j;47hlXCivEX}YUtFM1SCasc-s&E%_Pr2j1=z-PGq~--Q0aKNu3O`U57OL4Uxp(yJN$ z0i!eM4|7^wF1-Qsq-O|cNm0sYq)?Yjjb)zH;ShJ&8f*N;c{KeG^W^-O^Jw}X=1J`n zXG!JNw!s>5xwgibw$;Ti{SPnc88rIC_@{E{1D2?`Zx8OQ(Hk&N^st`l5BT}l$mOP} z?VyUpqVzw^lRN-<82TSxlHawgqWS~>=nGX;f54sZS62N2cYU8+uC4LOh{~!z*s>== ze;D)57t}k^|L~IJY$L^QTji%@Q+M4?@yAbacZ~jrd9sh=?nV>EXbbTVwj);(_t_f9 zWU?os|KTO62df~@Y-=3*Tm{u1=6U;0dGSmC!#w$JswsZyf0!qA0-X2tP}_~AYpVXh zZ=FfqBmECANqtBSvF)SdcW>i+f&PaF{rUs8-wjQ)VBXGVX(?77e%u+=cH&^f8+A^w4X@puAsFvnl<@!1SH4{)Y#(*984n z;ps0y|1svYKD~35r;mj7KfEk|Lwe|O*Nwj+vG)?i^wG8chxlqLe(8URuVnFiUFYO{ z%K9H3l)s@*o|*oKm*sEh`=|dQe?wwnYApHx;v9U}KfdVUkn@i((;sZf+n_&;=WaFn z1K;^R-;eYL#22}vGKwz`kC%6f-hlWr{Q=v(q>55wc3J+0ra$oXQb2#qS1r{acxv#7 zf54sZhpYa8Cr;%2`lj;K@uEN2-k)Dn^@lONr%(?=|3iG4{=ieOi~fL1rN_u;o8Ev2 zC0W8*6192!e^HkksJ2#@YiryYV)|pgIFGh9QagwKV9WUt`U57%i~fL1rIUwA&^a^r zavn`@Kz!9x{bA0m^HHil@Z@#TA8=GL^7+(Q^8ZC1hW>~6sw{t>aGi5Or^@nopvNPh zdGJQ^D52xOM{)hOgt@?v4dm{7)ep;;vv8DeZ zpLy;4YRs2t zz}xSY`xNur!RQY>zvGGifUnE%YZL!q+qZ}54?Mqni~hj#yAS9OJU!Uie}UQ$4^A5{(y@~%*p->+o6NV!%&-7ApK7IKj0rakcY7~wmVu${L=rhK(q1+A1dBg8smN zc9DHhd&MP(ad)GMKF=d_%B%h`W>14dhjf3O|7oAW;U9~Q{(fQO1-`X64C8lLK^Kk(b1t*-h5j=e^mK$z5haqemP zXD~f~$p3)(-7fT})}9;k`LXy1p5H4+f8e>>h5o?vJ6Y%tn4Ays518NAMt{K6_Mku5 za&HU$fv1KU{eeF|&f*{VSIe0GfbDmn#^`wa%}4ql9+y3u=?}L2HWTp=Jiog{`~%N# zDiQy{*N{GA#6Mtq;GjQX`rZ)#fa!IE{$NXg8}tXBo;K(YJbi44f8aTbK!3pW(?fs2 z%SV|0fQfU^A8f-#bBKT7w?Aw815Yh6`U6j&8Tvni=`Dl)fUTd5tJdCZ8+za{xUw#_7T>2kM--Mdf z8?;f|u3v@AGt>X@xa82t!_fcmhMYyR4{EP`MoLZ9AI7ZfS5EZ@-1Aad)gSPKA!Ws{ zt#Qt+GV;vyKRhn^mNKe8%z2?$8Py;7tn=(uyX%-IUgEs3hvK_8Ld0)R#j{3J_t;CH zr^VmZRDZBNJDxfL`X8R~>reM?x20~-^aq~bL`HwWTQ-~ifVpRZ{($)%3iJnCes2Q( zftUX})gO57Q=mWaoO7W+V7o&>|HBiK>offUb8mwE7q{b4-!8qgnjen)`)7d(3_^ao6wgZ_Zg9O55vy7bmYf3W4w0{R1g zdAR8hJoglcf8d9Q)59u9vEA3E|KSPIDAOM>wS4Tquszh!^aq|h2hb7*$Y+B*aHR5YWRVA^H{c1)&!9ixcp}uIWG?<57Sn0_HFh-?G(=%T|;c!tL=zC$hXt~ zkk3Y0)gR`(KfjFX5B#BqWyG(oap}_1^0%V@;R!b`wzTRGxYw#u;^ZQNc511ZY#6MvA zZlOQe(rXL-fv3L~@ejQHUea9U->~HF%SoNs?~<$MK0*cMtv^gf<>@O${DUpMq|hHQu?_kI z-ugDRc~=!vr-%M9=kalzJ=q$mpFw}%Z;lOB{lS)VZS)6h_mUzMbKZphz;`Jm4_rr| z$MV3`=AD*19o!2DRKD|l&XR16ea7%Pw>7@_J9(ILI)2nB?gf-r{Pvy7sy{r>)RC1{ zf0z@UL4V+ne9u`@qK+@>7^(WhnCp49Re!*LK1v>j+Pu?}tEXl%Ol^O?R#E)cRQ|z` zimE@%S>~4tsy~dkJdCZe-WBpNb##2cz!1i{ejP4X8Hq9&vWz#-1RHdA29i3^as2$gMK)+MtYT_Kk(cWXaB{VBUf_v zAw83X-wJeq_4z*AR@{=n1ciuecoU2*zf(f{zA z_MajD1MYO6bEsUkrG6OwfiJjDet`am4Sxd& z#(W`lzr;WAoNJ>$@KMD~f54nK5&wV}-;MG*3<>rkdi~}a&b0F{Y>Q9jESvs^=cMO@ z=@0zGiQEgI|KT~ezqsiSm^xnKAMhB7XV4$;=7XFiCF=8_Gn{|HXYP$q{b9~=t*M8h z|KU0J?KWyAsj)n#`Cjw~9NDvi{C&a|_b(`~`h)F)PUK;1jhFV5hoS%B1Nj@4Q~kk~ z954Cp!lW#;W;^H36%dYTVsi-B~^d0ZCjzF_@)0L?=rC>{SP0=-m{AMrT-!C zGG}%@6_4&-S@j2g^TA-TrT^hM(Q3PYF+je<{;&Tb_3rdMwEl+|C4R8_XLx?Mi~48A zTMy@%iaGP*{slaFEbd=``3+*~pRwilv$%f&Z#@a=e;D9#&PDw*JbNzcpTT#c`8}G| ziigalhKK%#7qy;;`e$r8+v5HOJb51KpW%slsDFmH-@=}xnBTPJ_ut{|_o3+V$TM@l zj~;b|F5Sr574pf{`l-O%)T#XFvc>2!6aiWJ(t2nDr8Gks8<`wRp%{yW!%Ih_Aato8Wyl6yTP`9JSa-ts+qIr>~t|BOFo4ewC?s%;J@ zK=q*c@O-yklivgOUl7}*3H4wH)aQMQ`e%Hr<+EqBzIOJE^s=-5hi7!&hWckdm);K4 zKND+vnpj&pqqzQ~!*g(1N-8+xofG>9PL;pLeL5hh?s*&1FxAwJC1l;dnQt z=)9-JrE+fE&?Hy*_<7H{3&Mm_Nv_7q3!cCi%DVh5(eCnNS3GT{=BM2|;jT|Yv1dy+ zng8h??xr2Ppr|1>E0~4;;DB##$7s+;M#n7-ZLeUc~SZwo{`@v_MI^o?4|!p ztsee+?@0add=(UUVerj6>;@q7o= zSe}u;xxO;io^keUANgE+#tIdD$~#{+Knjl|PJcm~H$)pZl2{@)sT7BcGl&_Kd7sJzASR{@%{!kQeJ1=5xN8v{ZfG zt>6#WA2A7A*pDX(4hoS&ZH#`X(yZ9l&3i4`6mTodiu zw7=}BBE2ux)QxjKLoRzhI-l%H+Qhk{X+@s?Q_Hyb8ppV(jaNNMoOJm57&HIdJK~P;5S-e{K2=LsPsQ9)SiU!2Tgw-_=7ImX8b|#dd&DkEH%vV2cLQ# z@*jNGw%`vw^E~7~XmTF-gT6Y%_=DzrZTLehJxJjXK7B{w4?ev{$$#+KS5E$eW{)TQ zLDNT+{0E)U+4w_jY1zX<{)2x}`f0!)e0ul6AAHuz;SZX1EAk(-%^@#U&3q30AvRQc zd%_>aSbtzIhYxeefAHzs34hQlzF`iB{)dIyPY?c}hrG{R*>1gNz0s_L)Bmtg_U5op z;eh)0dNPMY|HDH0o6ft8J)`y2r2k=|_R=K(L9-?Wf4HCj-sXI8`X3g`J0tHi6O9#RpeC9X~4L{D(%l zIsdul`DAPvcS7p<`ft4E@rfPUAjWm<66f+-Uh{Ok9_`Yn#<@|uuXz4i66NlD zqTRI@iadvBvkqm?_{0aH^1VgtJu^Q8f4KjEPP{|eGxFX9fABZg4_5y0osiGKAN)n{ zGT+`nHJl;;!KWSu{-9sjz*L*@+wl|NkbuchR(^gk?=cYOAp(BrXC z8166kO#j0|Sv&TZSo$9pN)H@AcfAFhSic|z^0$c`F-K$f6qU%{4130}cRujIAFlbry!#&VAI6s*OKxk=c%s)`w!NJ8jMV4AAAHuz;Sbkj-HQANpE+dsgJwPl{-AlcBL6{?=fEFgVGjJk-yLB5 z!KbGL{K5A=#$4HMy$=2K;17O4C*u#A^(pv6Ec>D04?cS>$$#*>1Se?zgU|aE{6Q~q z#viopsf<(qRJ`$r*t^3jx}QqLxe9;X^+cDXx-K$r(=y?fr*f;ZE-*R5{oVMcXHjml zJ99<$3ADQDx!9_VYxh!=Yd`R&=ffY9+_?WnyPUk6p3cI?)%9ZB{PMRv>vtu%$^&BD zn9;KC@I|~^JTu1Sue#+qn=4!ijCE7KxaIjy)?(^@AM5sH-14mRl{xD4I9D+7rl;?j zC|5Ty&PBJm>FL-%(luHu>ojuBIeo(2+smWf-@f-eV`Lo){&4@Ef?(wj&)BYAu<{4p zBcHYG1byCNnWdFK_-n2+4^vNL4|HX|y@8G?+7_?;;hKTNu73CKe##%N`Oz+4iLIvommXi`57*fp5T*PSS)jo#vk;)uZ=&% z($5F};OB-KfAGikxBLg+dNOy^F;#PoKluIU8h_B|`xt+S%|1j85B(2|Wq!~2gKss= z^gk@tdLHs0G;3SrKWOH8;18OdhxadHt%k>*k-25~gHPXM_``U59h3i{soQ}+XnI+| zA2j>Q;SaH#xd4CgnNNm4_{Flnp8N;j&Ul)qnwmiPgHL@9{6Vu;4u6Pc-3tETGlvX+ z@R`qnKlttI&!-{TExj2_U(#wthLF)A0k8um4 zN<1y!mNjQ#%Ytk7JX`LjxR2h6bZ?!x>v_I>vb!`p((U>5t|#h1lDqV7l>4yXUC)$* ziLPsfX@-jxyNJbg*@T6sT9i*>&VHuQT1 zHYmm&do<2{yW*~A&P&m*(Zo0xHvX>X#cEORwQ+GSWc6Lo+v_4+*V1wB!OnZ0OJ%~{ z&s}3(gZvUt)GMK``TiK^AK>dwEH(b{j6bw2E#IL%W6=`UvJ>>#8z#sg~OVkXo$0X3f8Tf-gxtpKz2Yq%6^Dy*3 zEY>+0@*niz$;`u4)7UM(KFS|_w<$vT!!<|MictRG@B2Dj`GZdLrtXpchsBb|hADs0 z%l>3vGJ8w{U0&W@F3 zYsMee=w5o>_=A6Jx#d6jT~dud_$NLw{-EoPHvXWOU1bl~)B5=hIv9V5U7p7tu8!(A zEN}e5U-7Z=huGJe8h_B|em4G~-v~4QpwIWQ{D;`L_EE#LTCaJrf$;~wNfYA_v+3$(znpByv#Mc zLN`B$qod%2mxR@qF)_=q9v?cFh}?cs}$? za6_byq))pNPr84+>u@~AoqDsx^Xvo3cfO8wJNlG(s$Y$9Z?%v-=RYN$r%y(^4n=Y9 z)fOe5_qRp4r9I=_^z0JPi5Zb@(X@CM*1W_M(=NhQ?-TEQrJhE3*!&ZSlqmn@(102F7v<%`s_ENf|Nfz`!sn6gg=Z)&52X~;7|WH zR{4XU=FM8RN5{`U-+!8^Ztdl8s^oispld8!ROzE{D)ZPdB}h8$$6On!KVj1 z{K2Pg5dNU)O$vX|tY^U=w5_2Z(OBNI;152%EXaSjCi}|a4?cT5$$!vxJ`_D3@5=if zeMIdU**^|{h_#;QOLYu=&fyO}`>Nm%vDS~mOIUtaewL~!f6(+Thd*fg+rS@U**^t; z@IMYQ{@}9*9RA>M?9G0h1FApT6|elkw;tp6jMi7&o{?VS@P{$<(}O=;^U)~d55Db( ziqkREc2{s0=103H+e)q`YfNn~N4f=wP;q!42=|?Y@3I(v6Eq zbbmDUc7x+0Tv&FZdr(p4Y*&Q2d0P@(-cB#qO@0U4_KtTaca(Uh_!xh9#wJaIls`N> z>)P-Kf1ZD!@(0a&6Z}CpmAs7n2hBV%^FPGeS~k4_@5N3B&CZ3|ZZ5c^{d`j=#@-(6}b;1B+;D%X`i#Ci&@DSyzjXJ1wR zpyPV*&SuXzG_y$gQ!LE?C;!>lJH$PC(fEV^NOR*4e#(!=AN*3j#vgR?%f=t{;x3l| zpub;X{2})9B;ybMd+%BPgWqird$_vD-w^qmm1X=vcROES`GbDuN#hSXXQuIoSk5bl zKlq#-O#Xw&$) zAJH)$Ip-bz;L|?`{-Eh)0e^^PUpf52=X`DQAN*hX8h`LP_ZI%3hhww z1L}WQ&G>^qd^o*5?HT)>X8(dcR@E?t;;7(VH zbeBH%aX|-CT&2&#T~0?|w_;KmcdkdctNpI8%S%pjakBQbu$!-Y=SG5i>OzDY`?Rmi zych5GdPli@=j*~x z*w=mWeYD%NDBk7C{7253D0g*Ff(w4c*PS~N>1Ljj9{6Q^-QRa3-0{P*E>-N~QUfB~ z-jQWo?_YdegTgSkcXAnbJI%)({v_0OsgdM{Rr7XFylnj8xxVxSDu2+_&%hs^{monc z${&2zwc!u`8(}fZAAHuE;1AkuVjh^@fF;tCjd@`DAC}0zNcL`|Y3%-?tYy>xutfI$ zP=8Tb{kaX92ToVNc5UW?GgOxV2+0^E~hepPUE&pgH#e{-Ei>4u8<>k0Afynw;qXfABfS0si3AvkU&< z(?19Ppy_1+f6&bBz#nwd1Nz}C)L72fhCldr=E73-?cCet>T|XN`43|_Pl5L@G-oLA z{)Oh;1o*@KG)*)9;M-oR0QEoJ%Y6H8y$*Q}{9z2tfj{UKAJZf2uxi`OV9#jh8rU;( zmI3(>pT#~Y_(SYxQ|OBotD3%@-{%%uBg4;DA%)OB0?^eAN@6yvE+++U!E??$zy2(4zx%+t?qJmak}f46g8wDXCJci~a~?vV7g7}i(jWWxR3l{!&w z=LyOA{QTWp10!AaZn9=y=;to2k8nLMC%eKma+XFyg!}BnvhL@8es1Gi;cl?h7}Y-O z>n8px?_$TwyG(h1ys#+L-8x;)b=v9e-d}I?&pbPIdhiEb@q(Z72TlD9{6YWsc9imm z?~QeB_=CTF4)ees{XSW5fGgh6Ad43_0RZ6 zrRN6q&-k@#Tm7?*p@)1u_37tK{WCtjHK>0kmO5wZpYiDxPyI7~=P?cCcUjIn7k~b# z1`;c05$l)+^1IMob#3|1sDH*EKAic|z8ZV<2CnNOzv8O?qx>YvfYwei*vmm_y#GnmJ_ZpKT0lyUY{tZ$TYkDYPmkY;9k2O?ot<5bl!mhZil>=r4Pz*-$(kpPQH=yUDba0{qPP|N540Fhsu8V z{ZMz!+M#`4)IamR4Il0!-%qk?>Sx%0ieI}n?@;9*j^Q0DRb!Xum3Y{H!I;itmo0!!%bNDD?o;KNHJ)6a9a8S@rN-9EsQ_-oJ|9N@Hvl${TJvZ&iI3V{0rj`dh6eui^u-=NSVu`m)EyC zo*wMB|2@)KKV*AG&W?dU#M*f=KdU|=XT-oCeER3WAFfF+3;2W2zH<13&mK?sgU@~| z_=9He1N_nPdcO8r)zk#SA7ZJ`fj^94t=#s%%NmlbTfrZE=8)kJn%;fz2hG_l@CVI# zEAWSF(%%OD;5W=R{@`!;jGFB;dd+k>?*RTVX2JGI<&Tb+KIH7bKyU0VzrRrrJS+Ty zT<`}`?$@4v?%7v@T-btWw`pOJn<4kKuVaimD*Ye=8q3`5B-yuhJIoz^GRQUjG{z-0 zjdZg*2f1anV%+k~X!pqbLGF*Aqg~2g=_mMgkn{LNyVRHBT+o6bH>gFFE4nE2(QAU- z%!!fiN$C+kb90ajy%pj5Nu6bzEkUl^2N5poPKtYDV~`tCJ;E(rQQl2i8{~YVBixaD zX)b(KkbACfgnRezDlYA(Aa{JO_(!U{O5yU|%{Tt=T)&Lq9jcCgKkPeT{{?=2b=}{j z+UkMX{~jst-QLO{#!#nc``;s7ejM*m<#qg5Qa=NK^!k18D}T@oyF=*&A5``;s_UaqwAhgeSuwbRvg4D&Pa2miUxuPT4gyf?ugVn5tpuZSJzW2Q9GDm!sKlne^VBMen?~#&U`6z$zm;Fh-Vxr8& z2K>vPdZVT8YKZX%f5CR+54umX@dustrtt@TWr^{J*aKaSKlqb=HU8i~f4`yf2S1^O z@dv%{YvT`k;+gvLZ_!=vCv$&Q&3}k3tYrLQ%rAY7KlnZJjX(I+!i_)Z3$lli{0F@| z!1#k6-`4m;Y@6xEAN;5y*3fs#+Fi8!^D*NO{ugpSDf~fm)(reXbM6EDLI0Rw`46$( zyBmM-EC0qC*3Wv))6yFX{@~NI3;v-0EB$le51L*U@CVJla`?kF+2aX+@Y!z#fAHD+ zK>mYI9WwkubG|nGK~tXtf6%Oz!yjTRT{KGNEAFj!H2k-~K)4XtZ;@%z4%Uw&kp+yny;3gk8Mx|Z`x zyUUW>x4g8A`bK&h-2>%{Y_JQeAp0(Yw4uHP>tQTSx75b@iDChCf_$LST{dhgjxk;17Ddr%?HW=Di92pvUz;ulymF zdrmy;6dW=8#wufto#?qgM_b+_*s>2_y$-XV#zwoVwd5dc6!z2CX#b<2` z{-BxX;r)wP&eVfH`0USuKloO|W6wz4An#v{;b({Z2W{t7{j8ear0|DW-m~BjV>pWn z{@`=|6#T(wZU_FL4|FyDpjpF$KWO@;!yjTtpJWbsgZe`=jX(ID6$O77Pk%r7gXT;q z_=9HMiu?y{bI8F`&n7+5Wj+V~;9GC=F!kwm1Ap+FrWt?G^tXXOXn*M~%=;Ibo;L7@ zYhIFd-c!%YKJutgw{>v1+wqCFyV)ezmHj2c`Mw|MHeD<2UP_B{*JU4O+0wyokg#a? zv2a)G$zbok;)}#>k?eTC|XK|t{m=fYvRtU3r(}{flR8F(^{` zgQl(q{-7U?ictRW>?I{K|1SK&KR5n?tWhQF_qnUeedQ0n)zXyLF*93IOOvXaed)Y^ zG3Hb}>rjm~_CQzqfHhTr+niF$A3kf%b=LixslUVpDSwEaGlJUb>gr#*bV>PxzfbCt zdH*6dKklOP2Y?~3V(>L*OPVs zPWri>-!75Z7uC=8A;(LUb-DO|`9m$$ivx{6=ucM}f6$!g4u8-GTNred7=Q?A68}^zH!T5BmPo#vgQ*@x~uw(?2r);J03D{K5aAl<^1uhnANAptnyj z{-AFis;vA$w-{vnA-4ZIY6!RJ{ZA=v`42wlmBSy#b9ONNL6?!aFZhGz{Bih$&JDHv zhuC-87=Q35$+-{k2cI77hOnH&ijTx_-Br1X#RsA zQN{R!&$>DMLD%nK{6W9^9dpR^UoS0OVh(w$Ui0@1;}8CcUevb1X{jZYwQ~4_&$<=) z58CFCLsic|MQ`&k)rYDYe~9((P0i#P{VbRRfADL{o(cHFbvm96Q~scbW`@Z<`No)xUprU-Piw%biQ*!T;eOy&Rgo0 zf6EAU)dQnlpU-05+rNdn{3oJZ>br67k?b({t}vl=XuNyrvoP1}R=C?FYhM1-!<^rS zFjrWZ;P#CRbNvs6x(w+}JYr~=yWBO@-G8F28$B@0Eg2B%&h4n+9_bq9M&*RLa|6=d z&DLS=4e7_eYhtF0-WTo~jG-Qw-pKJXA8Y*Kxh4;gcQ?s@@Yk&jSN`B%@?-BtqJD2j zj<60T^Y7x7LvYgqShruVZnC{X!>|M#=hPFGidL+^{qAN-^T%uUwP*tbU(D1Y!* z$DLFDpkrp7QT}j0uhl%Q{J{^X@2&j7uQkL=`Gf!4=ge7k)N2MNK9G6uPO4w{;hyq` zF>|x-Du3wh`cMAD-_mjYjX(HTmKcBV>GKSK@HtPA{0Ge$g5*Ew336^A{6W)OgZzhB z&Ics_!Dr5y{0Bdxitz`(*Bizk^bakKKWM*k#vgRIJ=F6I)L84oJVdWaJu~?a*Q7rW z`48inXD0tavu_Ljpsj{^n`-KL;198^ZNVSLaCR{K!H@4@{K0>BE^FxajC+b$L!Y7J zIXe&jFviZy`&nb@!47}$ITsK9a81s_BmcqAmilD)gQo8>{6QDLZ2UpDnGSC`V^L~W zWIh@G;Gf;X8rBB&bLICB{@~Nc82+F+pN{+o&6#xY2Tgqr{Nb9cmBSx=)~(2Y@B`}` zfAIhFA^j*Kbj-Sy)GVFRYm(={AI88O_(SaP8O9%c`rE)C{Qh&ua5 z`Xj_`x*X-kJ&1I1((io6<1wz)@)(y;66#{)Y>0)g%Da`UK^>4j5C3f&?@kX1cO9OI za_OVvUGNJLZi(z2XjCQMjgTBzb4gWq{ffZTI4jm`U$dEn-%lVa$hQC&5A zL3#fow)4Pq${%9OJUFBL!QVghwDJf4tH4vrA9S0~rKgO{|Da#lT;k#V3tj%%2Oi$P zh&{UNp7IBOa)-OhAN-DoZ!3TBnlq8%4|>cR;}1H`+xSE55@-CuuTa7GgTJ_o@dy8@ zsm32P>s-t~qj~3oKj?r?#vfwWTz^#ggWvv9;}5>|0o$hI2hFF3aHnc|f59Kdb6z?8 zLDL6={D;^dS{i@w>&gBs_=CSq`c1(fe9oF7|3P!^1N=d=o&|r=M=s%w%?}_wIWL-2=-e-+J`1GTIKltQ1@CO|)%;EhD zJ$rVD+_OC+`={U!vAbmbm;Q&0p?B8e;|VTngsk)YEqyyg?|LlUt&(;266r(X7Zc%j z#>BYO`x4zenU4-$80D78nWLYdi*gO5SI4o(<6WrqFZ^2S>*9~axRza_-R)7qF5|@* z_tW!HZp(7%L)Jgmg-1t8otV6rmPv3uXGFP=1_!wb`6=%7V^SZzj(3?FdOw5avmc87 z^GT9>upc2y{U2+DD}V6oOFuFA!~I(=U$*LQ=jkDqsCtt07lA*F$&b6G{2{hr{0-#~ zex$BL(SJV4<&0(>DpkjK3BIcQVNB0yvUf=GAGG%|`hYc6Jt2j4s9cTB=*&7)Gxb+| znv{&1bC#ix}&=#9NkDSyzHF8!_iAvUhZ3FQyIr{I|K2mkl7 z_mw~R$0pxZ{-A>r?_&at_`hU{@5P$tF z;}1S(o5CM7=b4iKpgF^o{0GgsrSOMX&MGDU!Jqjb;}1T2OUZxm+1thZ51Kk3=6}%4 z`LOzJ|A})n{%8{@^!S5GUW;2K7r7(ra|HYR<}pKU{~N z#_$KtnV9g0SkA$OKlq$|34ic8?-Kst(+>y!pg$;Q{6ROCemmqp=#%o!0)L3*-3tET zzbknT{K1Dg@CQGzqVWg4^QF?tA2j|XgQ&W#->`^J{ZoYxeod!8BUy2{wU&c?ZovZfVqINY^; zE!xF?5#Vmf^;Q=}xzf(x{d7LUeSA2^buDHuLzq5$!}7dS)X;mVDf=$r5BGEP3VoQf zRIjccru@MlDQi;jhi80F=90*N@RN_wLo8AK_ujjy{J}3(cwPB}p4_ci`Gd~f&pK3j zja~T+>rkn7O{uG4{)aK&44{WkWA$HINFT7K>Q}!c>sZ1c##~Ql9jck?Rj;rP)m-)P zDb!9^*VtBfPAPvFf1=k(rLYiy5{%BpHn$y<@+)I z;8zPb{@_>5HU8kYK4APow~R3Upr3it_=9dS$oNBS^F_uV{3kEgQ~uy5Z#4ekCp}VL<{-A3OG5!!6(1~8k-|Be3amF8fpUu<|&QPCoJmC+qoT*3tgXVlI_=8UKHvSNs znq&OIFW1ZXgP-zay7C9VjO2K%f1wj&j6dkha&`dxK^Ims{t$biv+)PNU_9sCZPoAO ztn49zKlrD;jX&s6ISUN_po67;0REs$Nv|RJ!!-lz8-MWqd(*o$LVe#^Das%G{X;{Q zKj^HS=65aUM2C%G$Q6J49j`9tinOEnybI^6`r@c>hzEPR{n6!v8|imPZ$s*z@!98P z{SW!wrRP-}^}W34;oMO*b%xYGGroKGs**d+Q@!STjxc1QUh_tJj(qMC^)ouxmCvRB zVR^adY+=X>^;zel{+a9W&PDw*dYjaWQvZzRY-09b5Nmx1$Ex4GJAJ^$t55Gi>YpvP zynOCH)$|+eE%nd%oQFmIGnzga)IW1g&JL#j8K3=G)IZ~MrXKar_|{9%p3%+%UZ_6n zS=2u>X6shgu$F2p?^*1>u-JI{Tw9|ZvxZ(4^d{tanM3wgeLbBubZXi7H)0Ko{u$ge z`ykjGz`rjw1H1K_^tPe?8Q;#{J)l0dXw*O3=W;H?an<~evi|~q(xg!NTsyOh{(jUy z+vn03ogQBN8`0A*PJQc3oS>RKhyFi|hdJ~=M8gdF9}-);cA)%!dq(;?bN)O2H`3pR z^WPc2RnC6r{CA7x_py@d&SR*$E@KUs?oz(KY3pIAC{NzoOP&*>X($9)%s_yNiRa` zpY5J`hq7m^E&o>3KU?ex;Xn%=^W5(bJk&qq+dI^=>X-Y3cc@mXKfZ8V7}8qxh1R@7 zwRsrJ9`cNhq-}& z_=8@z()g1iYd)Emj6e7jQj9+ky2>9k{h8qpdO&;Q53wgcG5+8;Uu68jA3ogpgMVcSHO!xD zY{#?I5RO%yA7}hwOx0ZD53%F=8-MUQj}QLfkE&(-!7qN<_=Bcy8UCQ@pA3J{oZ|_9 zh~+#8_Fv%dDPj$a{)efKei!fu|A&^wA9UzodiE|?zyI7gyyb>5%!^o!H`Nt2%Q^dDmk?^f3TPvYL8sHCpk9>X~?HTtJ`O1Czso$_XwY8P>vurOzW%aWUF^7|`dTMFo z57!B(Pfwd_>eF8W{_u?Zz9x5yP(O1&>)`Z1OqHCLIUIY&?GtV)f4I)n;_J#EbT64J z=5GeN(SobWA7ba9VjZfU`iU`t${+lpjRTZFj6dIpT0W1Cd2TxIP>odQ{Yej>G}Xn; z&nkb2T{r8r@`u<7GCvG|@Vj^aTls^Zy`Fa{d&a{-Ezn;vMQ)js4>m z?@+DuvnF@o9g6;k@^ibGcc?b%KNia#c4{o8*IOQY1#(o6O4_CT!GCe!PUR1=nftdZ zfAH^TZ&Uu@Z=djo@~7VDw14?SoyhHF#vk;=GsYh@d)~=^(46fBe~9h%hVciVeeUEx z_?*>F{)2Dlv$s*bJkR)pPv3a*AM}kV;}5ayXNN!dFKjUW;NQHGt^C2CkYfBnKhoUz zgWlQC_=9fJ#P~xjXQRU(e9l9MKlrSzlmFl^yGjkuSE{LDCjY_boGkc*&ij)Zo+BFj z{C(EYkE_qw5PES$#AEwD%7JboU^|O+srw9CD%o0aW(FE0;6$O9r zdAEW;#FFR0AAH+OMUTfcsjH-?mOZ1VfZs=7jXfM={9*jSM%30;Qs3%uDr@YKYs}%K ztN(sE=8!YgkC!=W_(SZXciGF3shT+)_=8XF4g5iGs?QvbJ)_?^=5SzPoXl%oQ~q$D z0~#@hW6${8#3JPnW2VU-5BP(Ati)gWgFaN%U-_f4?U}>z=$P1{)bi2)FiqwOd1p*h zzopFEkpB=nvNe6UE2~~N>xA+LzodkBD0{~G9gZr0@cYj_to-4cJ}Yl4fAAZ|-ctUc z2lU__s+C@I!CKy-TB|Nh;vK4u-cNcT_ONHGA0g+S!XK{L;`JTMAFlK1s%^?2^y;{+ z${+OIo?DbZ=?8e@f|KLxWWc0>3HUB}=UljhJf2?8rA=Y||#;M<85c@t7r1ng56zv_9 zs6O*K@P}A>hr%B;c@Fsx8s@+sVk0AsKlmqQKNhK-^G{KSQ(5(}5aSQy z+ds-2a)$cpo!QG!O=Is4V=qId`rGCND}T7=rAs%IKg53NVGhThk@YF~gMajhoKq<8 zUub$tz#n4MKf0v+!RLJn{@`~#@2C91e>BQZ`GaOZ6#PN&@5&rbBh_<8cq@O1ojv<+ ziw5CVB^Z*r~Bhkl&T<${%#;#aop>#Ln~oL-~W>w%ums5B}|$ z85Bk0Lj6dkXlZ`*be!9x|gTKTXfACkmV*J71@R{)ky?u`H2fcR(d$?9h zZCjG;&9ANeAvQ0MGq^{nzgEu4CI7+y!`Jd3#_y_P{6QaVVf;b=E&H~}f6!4ynaUqx zlVXfN_^CO@AAII{$baz3dEgH^XC~)v{GvLp2m2A{sV+N~HS~pgKb3!D4Slitnfu8H z=zmy6`UY@D=W_KMO5bAgAFkPR8vC%kG@t6fjx{WA)gPW?4a-;S5k3wv{xE)2E#nW@ z9N(5TJ8CSGWSsE_J+P7S2R%gUZ{QD_bHK@eh#mV2bIA6L6L*$Y{@`zFm8kq-{EmK{ z@g1x8v+rx>kS*^!wwyU+*q|ML6CWH<{&3CKYxgOC@X2kM|3T*mUsL{||7>$b`GY<-nRU0;_HT5uQ2B%ZpxQ;{ z57*4g`$PGIzu9+-@&|pe#U|ws`rP;p${+O2L+g}3#0FMetNa;#GW}ovmz_*KRmfAC*jX#7FH_nz?w{o6$25BkayYM96B zeP-_GePq1U!X-=37HSCTf0*umlD>TK2R~$j@dw>}5jBKI)cdG$N$<>-HyF7G?6VI9`{ zJSywR@P{!;52U}C@CV(YtnmlE;+q8J53#pp4IKX9XCI=cDDN@p^7o6n>jd?GEo1y) z4C_|#2kqr${6RCH1AmC+-3tETljp!6e3%1&@Lzs{+WtzaC!|mZSXuR-kI_>rU3J(? z^wi4G*cOA>%TP`I&!(`KAyfTzE9s$1jb*a@9j6Y5y`jl6H%L#LXw@@5y{!DfPu^Il z{Na8k1YT7B;72q&ul&L9IgNGjdKx=>wU6?LF=vi@D}T^w-mLq3bj-`C)Dkz+`>8jK zUhZk?cL`=4oc@RD@;iQ5`9o}*&krhp(A&1|SN@=LL-#3v(5s%=tNbB$RPI&f55C`L zMam!iK^w{0TIpxq3}oG{wd!}8T~Pio{`~L)*paO_Du48vFo@E&~}F4)2cbEo%v^c*1VX1CYCy9=6~?xdl-N0v+C;n4}O}r@dwSE5A)Ax>!Gni zHT${9e~6{FkoPafu+ByPW1nUG!M8nJV|9$3le;CsvzpV0ySoUr4{)KNf z%=ACxvy4CZoyQn|(CpPB|3SM=^u7N@we?b-r?GctQp27ELER5 zJMtf{lP@*E;vWeG(L+pbZ@CWt16$x8ajPAQnYRd{@|y{9$5H;KOx2VgJy1r z`5$zvJJib^c=%byA7X3EdNurE40ZGH2S2VyDb0WI>2J*Y7dp+`_=C2d#&PO%&J_G1 zc0hZ22T_}sBHtl>DsJmF>FGfJga1QIANgE+M*91~AAHVSfIn#ZSiv8zxqs+=G8;C6)J!5 zm*-tj{-CEwT`})p=wX@Xls{gtx6kob{@}Y!UdkVQt0nemEPJEi4`Y}shCk>$ zIky=8pr;mdR+~NJP&rSX{0E;kDdvB;=2KJmD1Y!X_wQ2vpkLX1S^0y`^|_?{L04@+ z&elp}L;Iaq{@`Ev<(%?|YwkVGnP=G#KWl^XhcV5ku2cS?YwTa6{6R-V<|}`QEpEO_ z`GdcI=nCZzzjOb*e=$$vJInZkKYO+D2i^LB@dthL3TG&PBei7Zqz>HpLu~R!;}8DY zW1M07wA7wem%M^AU)t#S$VlT4V}8#t{-9re!uW%(xy1NG?A{&hVPB%LAD&|m`!c;| znz!XYjNg)I{6Y7A#Q1~0e5r!`+>X%LuL6xfT(e<$%YPViGRN{C{E@AVKloX18h_B< z@+|NNJ?kblJV#Wwj4=KXdp+Iw!+4Im^^^GYv!@aNuQHwefH47thamV_}?b7SK3=Y zYjGF$a@sTcjk~Y>;X2Q)y{r5|4`@#vU}cRhC(i zLu}rktouvNqv$@#)Zs*`UiA$7!KLqz_@RR@D1W$Sr+Ed+AN*M-sJWp3VRd&i>WuOS zzr`T-W7gByt6zC3fAF(jF7dGbjvhRgT4ImJZp~*Mypj54uCeY$|HJCS`~%7##=rXA zKIIR3!S=n%AGDVj>)`f`&t&bASbN6F-F7N}7}MbCLgf$F9RAS-+vul|RH@9kN{cgKo57 znevCdP5wlOkb9Bsy(El)1-Y=*j{7PeQL>YhZ*{cqJ zxF-9y;19mlFdtVvW=)2^f8oEij~YVyAEruOC4FCi(O7aG>wlOkzrWNF(*LlA{QStC zbIE@gKl&u^BTH3tUOD{1=j>qeA9RaB>;v_ZdbS$!?pa=bm+60)Dt|jT7nuHsHDs>7 ztnvpx@6QzF4|?JmdA}9@pr4w`J}mklrb^F{VENnwdOtp!ODliyk4nEy_`@}qU6p;^ zlKo0aIm8hP_nPRKKu6&OQKKw!R>rYtQ(^2L;L> z#@v~CR{4XTzn#4d_Ka`dI;s32mObF`hcVUtN<7s6;GfF8ul&LPR`yB3A9S1lyRG~| zhsIvl!I#O~Q>whR`Mb}@Y{K5afS69gA z+B4>i&Qt#27cE(;{Nb9jPArk}^gpa6Id*ON&dW;;SemR^Tm3V-T|29PMtARS_0MR| zR%ZVNvBQT`4@3XMG^vGasQWMQ+2_vw3w-*?v;PZyBb_rW=zo|dc``km>3=Bexh-}}g$fDsx#v~WZ;<^L_&ujplFuzt&3ZcfFSwsEYtrPN z>3=9^UdsL~>Ywr1htB>B{7LdVLH#p&_H5SB>3^6e`8j*8>3^6ebGfWxZPi%bv#5W@ zzkG@J5#BLs$((r^;Q;*)(`3z&H7wbODVj5XseeXuo;dq2&^_gh2-GW)-Xr6!R57x>iYQ2&fi zzjW%K@iS!Iiuz|XJ<_RvMl+wo`aRm}0PPuv4`&Y9o{?VY)IW30ty_!a_kz9GX|m46 znvOkVL}a1-KGGYIpJ(cD`2FB#gE{0ZjXf359CB^-uctGITt|J|4^IC>ex9|zjcV4! zsei_=P~oVsi#<>Lt{oP3*)w+U&K!eP?+5zm zk@fPqSvtO?WUbt@J!6FmYb5qjjcw9owR|r952e@qeJq!^gm2<_qrXB z&+VwX>?h27)BiBdHTr3<#J;Gy+veTMpH_FMr!@YgNWY(fjf_9|tDZ6b;M4Pm{a^S` zzi#|NbG8@!LDT1l{a@%OFLH*(45?eol6ii5IMe^IqWn7=fAEuHj6eAFaE3o<`uV^g zwC(NctGZO7tT9g-sMl;M|IPXzR+PWR#viVEIL7!xY>Pq0AM_Waj6djoUmJhW)b_w1 zVqaO9srf6)JX&iI3-h6nx-OTQiXgWsX7@dy9AYQ`UY_GG~ybk$tr5Bi-p#ve3w zJMf3tN?TaNqW@t<$=_JRqW@u*&h5Y-{F_%;!=g5?qSUdFv(f*sqU62)y8i-Atq%Ml zmUF4te}SL5pLHvGJZ8DRr|CO-Lw)u>z#qnBNF6f#K~ob5f6&zDz#n2+D~CV$tXsh! z{NXZ(41e%BUy534^xmcHGor_1Mag@Mls{;g1AmBpzf_^}2S2bP?;|zT?|YXzoLU;Y zG>AFmEY&5k%puoSO|KjHL+q$p?A_pO;w(4g1MP34{*fc>WuX6ImV4vYA>|L_Z$uqb z{-A9RhyI5ZU05^baO@c;ciW@-Fyj{>avAl|T4#J@S=5_|rdKrTjtH{CO53!YhhM67pvlgt~qx`}59Nne-Vf-Jrb}D~3i{>BxpyxI;{-CSo8h_9~ zv^4(I8(mxXoRa_GPwr;?!Edz5_=BJKr|}2PK2!LE=G;>9A9Us=ddUAzYR_tGoiqHw zXKyL|!S6qpyQgjahB^4vjzf_n$WY z;Bzh>`49dUU*iutH`Mrp&W|(xpxNUIe~4wj75u@czcKv5rw$qZ;8PO_f6&{dJ_r7w zSu2M>Xx6RZ53#nF)1I-yg(Bq-e$oT_qSND1o>%f5_=64*=8*rOA7mFOf6!^(#vfv* zlx7Z@-hh>5FCIBtZT+kXDa;|$|FE+5pnyN<_^#~TpvF>u7i8WT{-Eb?KcM{KnzK&q zQ~uyjEoKgf{)e^Qmx0XT*fV}Eb;aaAjM;PglJW<=<<>>z4>~^>X69<_?`4_8X{O`n zW-*6D|HInuhbE_$Ka77$=8EaRfp!blD1Xp(*RPh(wP(!Szf$=_Y}$q8${)rgJy@pv z!SA+tpYjL)`NMmaKj>DMcPoF;xjxK$chb*l7`s#XLu~Ez?R-B{V^-&1{)~`5?k97M zKlopIj6e8Inizl3oO1zx(CoP&|3MF$Z~P&)#uDQXKD`a$5B``n#vgpAXIT7CV~e)c zm7mG(syVj;{xF6!k>L-qoK->ogU{Xy@*jNaFX0bMH{iye2HO%xs zOqbt~f^_=Be33j9I$NjClv%X=325B}X@tfABYu#WV~V-1V`hty`Uh90ImWCCkg^gm3O zHTM|#_d283Y|_N|Lu_$#YLe-H$j^q4=0EuD+OckK&&W9r@P{!y@*l{22)zN*iuwD1N>pkwB5`hr>f5x4e$rw`xxgkP-B^{>sI7H=y!Au*`AU49Qeci zJW`vUq9Hnl{(kVs?*FXvhuGZ#)B)DgF~dTbL(WqDXcWw(|6#h+={=A+oH`ntA!}9e z2Y*y9dp8o*pCt2Y@CX0)%zerq^b7O$Du2+nm%*N~%*H>JKitnpyLKpl7*q4Bi^?DT zvES1NmHvn6u1MCW;19a>@63DC|1e$Zd`>BU(9t`nU97J6!}}Ec!5^BrTKU5@Pv)#t z{@^!mvRwItp4oDl@(1nT>38K1`uDPXl|RHLRNbxo!5>)XPvsB(fkr!&Klt^Z-lqIP zPww!C@`p9>fASx6LLK7|`a!nwr%!TSxi{kv{^t6|AN;uujX(G+zA^rwr+;hwK@Xo| z{6Y7eX8a+x&2-Cu@N;GwfAEW&8-MT*wlMynS3P6=LI2Rw_=6tV+W154J8g_V_=Dyf zfAC*fX#Bx%zKDC?CN*zWWnPp$T=YMzD)a5^p`bRes?@QtPB%$v;p)nol<^0DayRyH zO;i8>UN!#UckgceK|lREHO%xstSakh#vioXR8jfEH7iNZ#{3U{>8;!|{SWKPJip9| zOa6nucSm{U4?6Ep);6fItSWOX;mRL$=YiDlY|z*zKA?t&{)bhC+pM8)RX=nv`_Szf zuj&~qLGt}omET$RVbTAvs>}nkhDHCwsPo)K8W#NztIFIpYgiHLe|Roh z`GcP`+E?=*blI^!${)1fIB(?-x?nu(=Jt%=R-^Cn4ZY9TYu;D>@L6lFvzMH;_o|W) zGlyJO^?z^E)0p0XRpsvpbI7TxpTEyuPR=Hl8jX@bs69l$=8R*DKyr{-7U8 zXD?N@`VXpUe=XJTzDFHS8I67XgT2Zh#)k~vt^DDd`-ifZ!JcvYr|f00XMB6)HsufF zN9LYa{-E1Ebx!$1Z24!;D1Y!Tv_7T$!C&0&Z{-jE|8=BxvAW*RotdkYKltlrtx*1; z$NrM1{2}&*c}tZ)_?3QJqWr-xTCzy_gCE*&m+}X_@4cPMAM}h5wkvV;--}kdk${%WT{^8H)lR458!1#mzdQIaGnx13K|DeCCX8b|_o?-kUmOf+F|4`Nn zhZ=wIYYj2}Fuuhg;}4p%+Ijy%+qqrcRZ|~H{zEMNe8_(o^HYNH2R}c~_=C@!5BU%J zhV;?0{)g3Ne$x1Z-}Wuz53#-8F#h0=e9icSKl4AvAAHW9fIsMY{>C5lAHK#P^l8~s zN&Z7D>mKAk`0U$)Kls!zGyj7>P|iRn|3Qy$Yy3eo&jWwZvd+E0Wf6yJzmR9}{+wU~zlGFdNy5wNSAN*a98GrCE z%DH~<2Tk1${6VK`?=ouhq=q5e_(LpnJG_74H~Wj4WcnZG$b5^J@(2IUOxDfq8Ebq` z-(&h8R+n|;yUHK*^>pJ8v34#My#cGcYL$#X_)XJ{KloizjX&u3%Nc*r)aSq-bcn2# z!yjTOWkJO}=urwDW44|;d?Iv^x7i-!MD9s z^gqmTeIwbsLI1<*lKbsd{-8&;-mUyWuX^TBabKQwj>qXxIn}0?R%QXJXnO$GjAB{iw6)G5i@cSeifAI6;j6Z13*0KJF zneuyW{J}ra)%ZhfMrY#>{($zzAN)zm3^1I ze-X?1IPeGmqg|=WAN(8X#vlBqX~rM4or6RF!%SW0BL6}2&PD!1?8hO-AN<+UuZ{U1 z{5x`%3;7Q|XWYOa^rT7g${#f66vH2Mz0t-WVmZqO{@{Ddeh~5>eEPb>AN*;%%PW7- z^c&>;3+*S_2@thq){(~OSo--ZFs@~L!doHg!p#{AxWF1&yUu()gJ!K9{-7sKVm?Ir&5O<%&0bD>#{EN2D1Y#Iw}L-hlRO9h;KLm9 zAM{V5x0FBVT%Q{fOKo1JJ9C5D=|qjSeiUWY-&N&LKb?wS6F^=1C~nDPgI<-jA#AM}fFQ@cq2!%P{s zO!XBfQ$B4}P61>y$tEdrq(6`;l5NdUF_mILqSq4C4>FVR_>ZIzP_%gU$^#{t)|z zuki17RhBbHVe^^uIIgLN~^wwbhhgjyV;151?&hQ7n|6Jn_ z{+*e|A2j>f;Sbtxobd_}#AY924=Mc*Ys$L}d${O-*ih!o*~3L|z?#}O1OA{n zZ;Si~&E6IGgRUz5KH(3s%rnCue9lQH|G{UkI{d+B-xm1~ntsdh2i@xp;}4p(E%-z1 zK$+(u|G_8cfj{^|8ykP{Sx<*Q=x%$c;i3OwO__(MhKK%#HRU^`hG(nB7A+~I{K0>B zF6SfA|FEIfD#IWASvTqB6|6e*lJw&c{@~l0dh|c6Dc>RI0!L^pXU)JLeCm_o57(UB zjXe?cKddP=W)D2@2mRDk>UimYSX0iNqVM_*)tv|4QvMK2O)~sp%!yCvgIZQUi~j2H z2mgE@dRb6+!*>{<{6QDL?63SmPt`hPdq!#k;Sc@-sn3Bwd{$oGN#zed`^VuAdi#W9 z${#ef$M6STTi&hU53!HQo^kkt|D-U7{0G0~W%g3h|FEWe;V`w+iK^Kr&ifaB(u3{F zA9TeFTa`b=X71mj{K02$IQ+qHv|xks2Y+%0>TnwCb$)1aLivL~H;a3w|DpW;%9=Ry zKg6yHKBWA?|Krwvy$tEwbR!qf6$M`GS^N2L)QC^Kc{j$(ofI$ zga1>4@dv+au<-{!=|K(oIj^U&dt`4W^UwH8obdcJoM`*OY&{6PmV_EP?!N4929#6^Af2ifEA{FLpfvE`?m52zvI~( z${+NYHKmk4=;n(!(}DhnSyETYnGWTpzRn|g8oey&4VWdhj`Xsi|Di|T@%@xP_(Nsy z1Njg7y3`@VA2c%ZHt{6W_n_LuSp-D%z; (Vec, Vec) { + let mut img = Vec::with_capacity(W * H * 3); + let mut hole = Vec::with_capacity(W * H); + for y in 0..H { + for x in 0..W { + let (fx, fy) = (x as f32 / W as f32, y as f32 / H as f32); + let stripe = if (x / 6 + y / 9) % 2 == 0 { 0.12 } else { 0.0 }; + let weave = if (x * 3 + y * 5) % 7 < 2 { 0.05 } else { 0.0 }; + img.extend([0.15 + 0.6 * fx + stripe, 0.2 + 0.5 * fy + weave, 0.7 - 0.4 * fx * fy + stripe * 0.5]); + let (dx, dy) = (x as i32 - 60, y as i32 - 44); + hole.push((20..38).contains(&x) && (14..30).contains(&y) || dx * dx + dy * dy <= 81); + } + } + (img, hole) +} + +fn fixture(bytes: &[u8]) -> Vec { + bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect() +} + +fn assert_parity(expected: &[u8], actual: &[f32]) { + let expected = fixture(expected); + let report = compare(&Image::new(W as u32, H as u32, &expected).unwrap(), &Image::new(W as u32, H as u32, actual).unwrap()).unwrap(); + assert!(report.within(&Tolerance::BASELINE), "{report}: {:?}", report.exceeded(&Tolerance::BASELINE)); +} + +#[test] +fn completion_matches_lightcraft() { + let (img, hole) = scene(); + let filled = complete(W, H, 3, &img, &hole, &CompleteParams::default()).expect("a completion"); + assert_ne!(filled, img, "the holes were filled"); + assert_parity(include_bytes!("fixtures/inpaint-complete.f32le"), &filled); +} + +#[test] +fn membrane_fill_matches_lightcraft() { + let (img, hole) = scene(); + assert_parity(include_bytes!("fixtures/inpaint-membrane.f32le"), &membrane_fill(W, H, 3, &img, &hole)); +} + +/// The comparison can fail: the unfilled scene is not within tolerance of the filled one. +#[test] +fn the_unfilled_scene_is_not_at_parity() { + let (img, _) = scene(); + let expected = fixture(include_bytes!("fixtures/inpaint-complete.f32le")); + let report = compare(&Image::new(W as u32, H as u32, &expected).unwrap(), &Image::new(W as u32, H as u32, &img).unwrap()).unwrap(); + assert!(!report.within(&Tolerance::BASELINE)); +} From dcb3fcf603d7221007169f6eeea720414dc92374 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 18 Nov 2026 09:33:47 -0500 Subject: [PATCH 06/79] craft-develop: inpaint rejects an impossible patch radius, and one cancelled poll cancels the call Review fixes. A patch radius near usize::MAX overflowed in 2 * r + 1; an image with no pixels and a huge height walked every empty row; a cancellation seen only by a worker's poll was dropped, so a half-finished pass could come back as a result. --- crates/develop/README.md | 6 ++++ crates/develop/src/inpaint.rs | 44 ++++++++++++++++++++++++ crates/develop/src/inpaint/membrane.rs | 2 +- crates/develop/src/inpaint/patchmatch.rs | 20 +++++++++++ 4 files changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/develop/README.md b/crates/develop/README.md index 4b85d3305e..99f3829985 100644 --- a/crates/develop/README.md +++ b/crates/develop/README.md @@ -20,6 +20,12 @@ Each module comes with a test that its output is LightCraft's at the base commit [`craft-render-parity`](../render-parity/README.md) at `Tolerance::BASELINE`. The expected pictures in `tests/fixtures/` were written by LightCraft's own crate at that commit, on the scene the test builds. +Where the code differs from LightCraft's, the output for every input LightCraft handled is the same: + +- `inpaint::complete_with` returns `None` for a patch radius wider than the image before computing with it (LightCraft + reaches the same `None`, or overflows on a huge radius), returns an image with no pixels at once, and reports + `Cancelled` when any one poll said so, including a poll made on a worker thread. + ## Not here yet The rest of the pipeline: colour, raster, the sensor stage, raw loading and the render stages. No app uses this crate diff --git a/crates/develop/src/inpaint.rs b/crates/develop/src/inpaint.rs index 460dfa3073..853eaa51be 100644 --- a/crates/develop/src/inpaint.rs +++ b/crates/develop/src/inpaint.rs @@ -49,6 +49,50 @@ mod tests { let _ = complete(2, 2, 1, &[0.5; 4], &[true, false, false, false], &CompleteParams::default()); } + #[test] + fn a_patch_radius_no_image_could_hold_finds_nothing_to_copy() { + let mut hole = vec![false; 32 * 32]; + hole[16 * 32 + 16] = true; + for patch_radius in [16, usize::MAX / 2, usize::MAX] { + let p = CompleteParams { patch_radius, ..CompleteParams::default() }; + assert_eq!(complete(32, 32, 1, &[0.5; 32 * 32], &hole, &p), None, "radius {patch_radius}"); + } + // A radius the image has room for still fills. + let p = CompleteParams { patch_radius: 5, ..CompleteParams::default() }; + assert!(complete(32, 32, 1, &[0.5; 32 * 32], &hole, &p).is_some()); + } + + #[test] + fn an_image_with_no_pixels_is_returned_without_walking_its_rows() { + let p = CompleteParams::default(); + assert_eq!(complete_with(0, usize::MAX, 1, &[], &[], &p, &|| false), Ok(Some(Vec::new()))); + assert_eq!(complete_with(usize::MAX, 0, 3, &[], &[], &p, &|| false), Ok(Some(Vec::new()))); + } + + /// Whichever poll says "cancelled", and only that one, the call ends in `Err`: also when it was a + /// worker's poll, which can stop the worker but not return. + #[test] + fn one_cancelled_poll_anywhere_cancels_the_call() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let (w, h) = (48usize, 48usize); + let img: Vec = (0..w * h).map(|i| ((i % w) as f32 * 0.37).sin() * 0.5 + 0.5).collect(); + let hole: Vec = (0..w * h).map(|i| (i % w).abs_diff(24) < 5 && (i / w).abs_diff(24) < 5).collect(); + let p = CompleteParams::default(); + let polls = AtomicUsize::new(0); + let count = || { + polls.fetch_add(1, Ordering::Relaxed); + false + }; + assert!(matches!(complete_with(w, h, 1, &img, &hole, &p, &count), Ok(Some(_)))); + let total = polls.load(Ordering::Relaxed); + assert!(total > 8, "the scene polls in the workers too: {total}"); + for nth in 0..total { + let polls = AtomicUsize::new(0); + let once = || polls.fetch_add(1, Ordering::Relaxed) == nth; + assert_eq!(complete_with(w, h, 1, &img, &hole, &p, &once), Err(Cancelled), "poll {nth} of {total}"); + } + } + #[test] fn cancellation_stops() { let img = vec![0.5f32; 64 * 64]; diff --git a/crates/develop/src/inpaint/membrane.rs b/crates/develop/src/inpaint/membrane.rs index 4589d23479..6c517a285f 100644 --- a/crates/develop/src/inpaint/membrane.rs +++ b/crates/develop/src/inpaint/membrane.rs @@ -190,7 +190,7 @@ mod tests { #[test] fn a_zero_area_image_comes_back_unchanged_whatever_its_channel_count() { assert!(membrane_fill(0, 5, usize::MAX, &[], &[]).is_empty()); - assert!(membrane_fill(3, 0, 1 << 40, &[], &[]).is_empty()); + assert!(membrane_fill(3, 0, usize::MAX / 2, &[], &[]).is_empty()); } #[test] diff --git a/crates/develop/src/inpaint/patchmatch.rs b/crates/develop/src/inpaint/patchmatch.rs index 5e9c73cb58..175a5f69d6 100644 --- a/crates/develop/src/inpaint/patchmatch.rs +++ b/crates/develop/src/inpaint/patchmatch.rs @@ -23,6 +23,7 @@ use crate::inpaint::Cancelled; use crate::inpaint::membrane::membrane_fill; +use std::sync::atomic::{AtomicBool, Ordering}; /// Below this many grid cells a level runs single-threaded (thread hand-off costs more than it saves). #[cfg(not(target_arch = "wasm32"))] @@ -377,12 +378,31 @@ pub fn complete_with( p: &CompleteParams, cancelled: &(dyn Fn() -> bool + Sync), ) -> Result>, Cancelled> { + // The workers poll `cancelled` too and can only stop early, not return an error. One `true` from it, + // wherever it was seen, is kept, so the next check out here ends the call and a half-finished pass + // is never returned as a result. + let seen = AtomicBool::new(false); + let cancelled: &(dyn Fn() -> bool + Sync) = &|| { + if !seen.load(Ordering::Relaxed) && cancelled() { + seen.store(true, Ordering::Relaxed); + } + seen.load(Ordering::Relaxed) + }; let check = || if cancelled() { Err(Cancelled) } else { Ok(()) }; if ch == 0 || Some(hole.len()) != w.checked_mul(h) || Some(img.len()) != hole.len().checked_mul(ch) { return Ok(None); } + // No pixels (a zero width or height, whatever the other is): nothing to scan and nothing to fill. + if hole.is_empty() { + return Ok(Some(img.to_vec())); + } let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return Ok(Some(img.to_vec())) }; let r = p.patch_radius.max(1); + // A patch wider than the image has no place to be copied from, which is the `None` the search below + // would reach anyway. Said here, before `2 * r + 1` and `r as i32` can overflow on an absurd radius. + if r > (w.min(h) - 1) / 2 { + return Ok(None); + } let psz = 2 * r + 1; // Pyramid: shrink until the hole is a few patches across. let mut levels = vec![Level { w, h, img: img.to_vec(), hole: hole.to_vec() }]; From aa3dc9e2b0bf97f75926457582e022db6f8b3166 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 13:27:31 -0500 Subject: [PATCH 07/79] Keep inpaint boundary arithmetic and allocation sizes representable --- crates/develop/README.md | 10 +++- crates/develop/src/inpaint.rs | 27 +++++++++ crates/develop/src/inpaint/membrane.rs | 72 ++++++++++++++++++++---- crates/develop/src/inpaint/patchmatch.rs | 52 +++++++++++++++-- 4 files changed, 143 insertions(+), 18 deletions(-) diff --git a/crates/develop/README.md b/crates/develop/README.md index 99f3829985..f37b813472 100644 --- a/crates/develop/README.md +++ b/crates/develop/README.md @@ -20,12 +20,20 @@ Each module comes with a test that its output is LightCraft's at the base commit [`craft-render-parity`](../render-parity/README.md) at `Tolerance::BASELINE`. The expected pictures in `tests/fixtures/` were written by LightCraft's own crate at that commit, on the scene the test builds. -Where the code differs from LightCraft's, the output for every input LightCraft handled is the same: +Differences from LightCraft (ordinary-range output is covered by the baseline fixtures): - `inpaint::complete_with` returns `None` for a patch radius wider than the image before computing with it (LightCraft reaches the same `None`, or overflows on a huge radius), returns an image with no pixels at once, and reports `Cancelled` when any one poll said so, including a poll made on a worker thread. +- `membrane_fill` scales extreme finite boundaries for the harmonic solve and bounds the result by those + boundaries, avoiding overflow in means and neighbour sums. Known pixels remain unchanged; ordinary + values take the original arithmetic path. This does not promise arbitrary extreme-value safety for + PatchMatch completion, which also computes squared costs and downsamples its input. +- Membrane cell indices retain `usize` width. PatchMatch rejects grids whose signed search offsets, + summed-area counts or padded table cannot be represented; patch-area arithmetic no longer overflows + `i32`. An already-cancelled oversized-patch request returns `Cancelled`, not an unavailable-patch result. + ## Not here yet The rest of the pipeline: colour, raster, the sensor stage, raw loading and the render stages. No app uses this crate diff --git a/crates/develop/src/inpaint.rs b/crates/develop/src/inpaint.rs index 853eaa51be..5468d3c259 100644 --- a/crates/develop/src/inpaint.rs +++ b/crates/develop/src/inpaint.rs @@ -37,6 +37,33 @@ impl std::error::Error for Cancelled {} mod tests { use super::*; + #[test] + fn finite_extreme_membrane_boundaries_stay_finite() { + let img = [f32::MAX, 0.0, f32::MAX]; + let out = membrane_fill(3, 1, 1, &img, &[false, true, false]); + assert_eq!(out, vec![f32::MAX; 3]); + assert_eq!(membrane_fill(3, 1, 1, &[-f32::MAX, 0.0, f32::MAX], &[false, true, false]), vec![-f32::MAX, 0.0, f32::MAX]); + // Also exercise the multigrid restriction and prolongation at extreme scale. + let hole: Vec = (0..256).map(|i| i % 16 > 0 && i % 16 < 15 && i / 16 > 0 && i / 16 < 15).collect(); + assert_eq!(membrane_fill(16, 16, 1, &[f32::MAX; 256], &hole), vec![f32::MAX; 256]); + let img: Vec = (0..256).map(|i| if i % 16 < 8 { -f32::MAX } else { f32::MAX }).collect(); + let out = membrane_fill(16, 16, 1, &img, &hole); + for ((&actual, &original), &unknown) in out.iter().zip(&img).zip(&hole) { + assert!(actual.is_finite() && actual >= -f32::MAX && actual <= f32::MAX); + if !unknown { + assert_eq!(actual.to_bits(), original.to_bits()); + } + } + } + + #[test] + fn cancellation_precedes_an_oversized_patch_result() { + let mut hole = vec![false; 32 * 32]; + hole[16 * 32 + 16] = true; + let p = CompleteParams { patch_radius: 16, ..CompleteParams::default() }; + assert_eq!(complete_with(32, 32, 1, &[0.5; 32 * 32], &hole, &p, &|| true), Err(Cancelled)); + } + #[test] fn hostile_sizes_do_not_panic() { assert_eq!(complete(4, 4, 3, &[0.0; 5], &[true; 16], &CompleteParams::default()), None); diff --git a/crates/develop/src/inpaint/membrane.rs b/crates/develop/src/inpaint/membrane.rs index 6c517a285f..83f5d2882f 100644 --- a/crates/develop/src/inpaint/membrane.rs +++ b/crates/develop/src/inpaint/membrane.rs @@ -6,6 +6,10 @@ //! cascadically (solve on a half-resolution grid, prolong bilinearly, a few SOR sweeps per level). //! Ported from PhotoCraft's `algo::poisson` (MIT OR Apache-2.0). +fn allocation_fits(len: usize) -> bool { + len.checked_mul(std::mem::size_of::()).is_some_and(|bytes| bytes <= isize::MAX as usize) +} + /// Convergence threshold (max per-sweep update) for the SOR sweeps. const TOL: f32 = 2e-5; /// SOR sweeps (cap) and relaxation factor on every level above the coarsest: tuned so a 96×72 disc @@ -17,10 +21,41 @@ const FINE_OMEGA: f32 = 1.7; /// (out-of-grid neighbours are ignored, i.e. a Neumann boundary). `v` holds the known values on /// entry and the solution on exit. Cascadic multigrid + SOR. pub(crate) fn solve_membrane(w: usize, h: usize, unknown: &[bool], v: &mut [f32]) { - if unknown.len() != w * h || v.len() != w * h { + if Some(unknown.len()) != w.checked_mul(h) || v.len() != unknown.len() { return; } - solve_rec(w, h, unknown, v, 0, &|| false); + if !allocation_fits::<(usize, u8)>(unknown.iter().filter(|&&hole| hole).count()) { + return; + } + // Keep the ordinary path bit-for-bit unchanged. Extremely large finite boundaries can + // overflow even their mean or a four-neighbour sum; harmonic interpolation is linear, + // so solve those channels at unit scale instead. The final clamp enforces the harmonic + // maximum principle if the finite-iteration relaxation overshoots a boundary extremum. + let mut low = f32::INFINITY; + let mut high = f32::NEG_INFINITY; + for (&value, &hole) in v.iter().zip(unknown) { + if !hole { + if !value.is_finite() { + solve_rec(w, h, unknown, v, 0, &|| false); + return; + } + low = low.min(value); + high = high.max(value); + } + } + let scale = low.abs().max(high.abs()); + let needs_scale = scale.is_finite() && f64::from(scale) > f64::from(f32::MAX) / v.len().max(16) as f64; + if needs_scale { + let mut normalized: Vec = v.iter().map(|&value| value / scale).collect(); + solve_rec(w, h, unknown, &mut normalized, 0, &|| false); + for ((value, solved), &hole) in v.iter_mut().zip(normalized).zip(unknown) { + if hole { + *value = (f64::from(solved) * f64::from(scale)).clamp(f64::from(low), f64::from(high)) as f32; + } + } + } else { + solve_rec(w, h, unknown, v, 0, &|| false); + } } fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize, stop: &(dyn Fn() -> bool + Sync)) { @@ -31,7 +66,9 @@ fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize, if n_unknown == 0 { return; } - let known: Vec = v.iter().zip(unknown).filter(|(_, u)| !**u).map(|(x, _)| *x).collect(); + // Like the cell list below, this filtered collection must not grow geometrically. + let mut known = Vec::with_capacity(v.len() - n_unknown); + known.extend(v.iter().zip(unknown).filter(|(_, u)| !**u).map(|(x, _)| *x)); if known.is_empty() { return; // nothing to interpolate from } @@ -91,21 +128,20 @@ fn solve_rec(w: usize, h: usize, unknown: &[bool], v: &mut [f32], depth: usize, /// SOR sweeps over the unknown pixels until the largest update drops below [`TOL`]. fn sor(w: usize, h: usize, unknown: &[bool], v: &mut [f32], max_iter: usize, omega: f32, stop: &(dyn Fn() -> bool + Sync)) { // Precompute the unknown pixels and which neighbours exist. - let cells: Vec<(u32, u8)> = (0..w * h) - .filter(|&i| unknown[i]) - .map(|i| { - let (x, y) = (i % w, i / w); - let m = u8::from(x > 0) | (u8::from(x + 1 < w) << 1) | (u8::from(y > 0) << 2) | (u8::from(y + 1 < h) << 3); - (i as u32, m) - }) - .collect(); + // The caller validated this exact count; reserve it before extend so geometric growth + // cannot round the allocation above the target's capacity limit. + let mut cells = Vec::with_capacity(unknown.iter().filter(|&&hole| hole).count()); + cells.extend((0..w * h).filter(|&i| unknown[i]).map(|i| { + let (x, y) = (i % w, i / w); + let m = u8::from(x > 0) | (u8::from(x + 1 < w) << 1) | (u8::from(y > 0) << 2) | (u8::from(y + 1 < h) << 3); + (i, m) + })); for _ in 0..max_iter { if stop() { return; } let mut max_d = 0.0f32; for &(i, m) in &cells { - let i = i as usize; let (s, n) = if m == 0b1111 { (v[i - 1] + v[i + 1] + v[i - w] + v[i + w], 4.0) } else { @@ -173,6 +209,10 @@ pub fn membrane_fill(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool]) if hole.is_empty() { return img.to_vec(); } + // A valid input slice does not prove the wider index/plane vectors fit the target. + if !allocation_fits::>(ch) || !allocation_fits::<(usize, u8)>(hole.iter().filter(|&&hole| hole).count()) { + return img.to_vec(); + } per_channel(w, h, ch, |c| { let mut v: Vec = (0..w * h).map(|i| if hole[i] { 0.0 } else { img[i * ch + c] }).collect(); solve_membrane(w, h, hole, &mut v); @@ -187,6 +227,14 @@ mod tests { (0..w * h).map(|i| ((i % w) as f32 - cx).hypot((i / w) as f32 - cy) < r).collect() } + #[test] + fn auxiliary_vector_limits_are_checked_without_allocating() { + let max_cells = isize::MAX as usize / std::mem::size_of::<(usize, u8)>(); + assert!(allocation_fits::<(usize, u8)>(max_cells)); + assert!(!allocation_fits::<(usize, u8)>(max_cells + 1)); + assert!(!allocation_fits::>(usize::MAX)); + } + #[test] fn a_zero_area_image_comes_back_unchanged_whatever_its_channel_count() { assert!(membrane_fill(0, 5, usize::MAX, &[], &[]).is_empty()); diff --git a/crates/develop/src/inpaint/patchmatch.rs b/crates/develop/src/inpaint/patchmatch.rs index 175a5f69d6..af7c3fecda 100644 --- a/crates/develop/src/inpaint/patchmatch.rs +++ b/crates/develop/src/inpaint/patchmatch.rs @@ -117,6 +117,21 @@ fn downsample(l: &Level, ch: usize) -> Level { Level { w, h, img, hole } } +// Search offsets add/subtract a full image dimension in i32. Summed-area queries +// add two u32 entries before subtracting. Both the padded table and the larger +// per-pixel nearest-neighbour/valid-coordinate arrays must fit a Vec. +fn supported_grid(w: usize, h: usize) -> bool { + let max_dimension = (i32::MAX / 2) as usize; + w <= max_dimension + && h <= max_dimension + && w.checked_mul(h).is_some_and(|n| n <= (u32::MAX / 2) as usize) + && w.checked_mul(h).and_then(|n| n.checked_mul(std::mem::size_of::<(i32, i32)>())).is_some_and(|bytes| bytes <= isize::MAX as usize) + && w.checked_add(1) + .and_then(|pw| h.checked_add(1).and_then(|ph| pw.checked_mul(ph))) + .and_then(|n| n.checked_mul(std::mem::size_of::())) + .is_some_and(|bytes| bytes <= isize::MAX as usize) +} + /// Summed-area table of a boolean grid (`(w+1) × (h+1)`). fn integral(w: usize, h: usize, m: &[bool]) -> Vec { let mut s = vec![0u32; (w + 1) * (h + 1)]; @@ -182,7 +197,8 @@ impl Solver<'_> { /// SSD between the (clipped) target patch at `t` and the source patch at `s`, per sample. fn dist(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 { let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r); - let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32; + let diameter = f64::from(2 * r + 1); + let full = (diameter * diameter) as f32 * ch as f32; let mut sum = 0.0f32; let mut n = 0usize; for dy in -r..=r { @@ -396,11 +412,16 @@ pub fn complete_with( if hole.is_empty() { return Ok(Some(img.to_vec())); } + if !supported_grid(w, h) { + check()?; + return Ok(None); + } let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return Ok(Some(img.to_vec())) }; let r = p.patch_radius.max(1); // A patch wider than the image has no place to be copied from, which is the `None` the search below // would reach anyway. Said here, before `2 * r + 1` and `r as i32` can overflow on an absurd radius. if r > (w.min(h) - 1) / 2 { + check()?; return Ok(None); } let psz = 2 * r + 1; @@ -442,7 +463,7 @@ pub fn complete_with( let ri = r as i32; let hs = integral(lw, lh, &lhole); let mut valid = vec![false; lw * lh]; - let mut valid_list = Vec::new(); + let mut valid_count = 0; let mut targets = vec![false; lw * lh]; for y in 0..lh as i32 { if y % 32 == 0 { @@ -454,12 +475,12 @@ pub fn complete_with( let i = y as usize * lw + x as usize; if inside && cnt == 0 { valid[i] = true; - valid_list.push((x, y)); + valid_count += 1; } targets[i] = cnt > 0; } } - if valid_list.is_empty() { + if valid_count == 0 { if li == 0 { return Ok(None); } @@ -467,6 +488,17 @@ pub fn complete_with( nnf.clear(); continue; } + // Count first and reserve exactly, avoiding both geometric capacity overflow and + // allocating coordinates for pixels that cannot be source centres. + let mut valid_list = Vec::with_capacity(valid_count); + for (i, &is_valid) in valid.iter().enumerate() { + if i % (lw * 32) == 0 { + check()?; + } + if is_valid { + valid_list.push(((i % lw) as i32, (i / lw) as i32)); + } + } let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, hole: &lhole, valid, valid_list, targets, ctl: cancelled }; // NNF init: upsampled from the coarser level where possible, random otherwise. let mut rng = Rng::new(p.seed ^ (li as u64) << 20); @@ -522,7 +554,7 @@ pub fn complete_with( } else if li + 1 == nlev || it == 0 { full_search } else { - (4 * psz as i32).min(full_search) + (4 * psz).min(full_search as usize) as i32 }; for pass in 0..pm_iters { check()?; @@ -572,6 +604,16 @@ mod tests { (e / n as f32).sqrt() } + #[test] + fn grid_limits_reject_narrowing_and_integral_overflow_without_allocating() { + assert!(supported_grid(32, 32)); + assert!(supported_grid(16_384, 8_192)); + assert_eq!(supported_grid(20_000, 20_000), usize::BITS > 32); + assert!(!supported_grid(i32::MAX as usize, 1)); + assert!(!supported_grid(65_536, 65_536)); + assert!(!supported_grid(usize::MAX, usize::MAX)); + } + #[test] fn completion_fills_blemish_from_texture() { let (w, h, ch) = (96, 96, 3); From 669c8392512fbd61a65ede9dda31d795d1536850 Mon Sep 17 00:00:00 2001 From: el-j Date: Wed, 18 Nov 2026 19:45:16 +0100 Subject: [PATCH 08/79] audio: DSD review fixes (DSDIFF text and padding, channel layouts, ID3 decoding, factor-64 decimation) --- crates/audio/Cargo.toml | 4 + crates/audio/src/dsd/dsdiff.rs | 56 ++++++++--- crates/audio/src/dsd/dsf.rs | 72 ++++++++++---- crates/audio/src/dsd/filter.rs | 72 +++++++++++++- crates/audio/src/lib.rs | 2 +- crates/audio/tests/dsd_bounds.rs | 5 + crates/audio/tests/dsd_metadata.rs | 153 +++++++++++++++++++++++++++++ 7 files changed, 325 insertions(+), 39 deletions(-) create mode 100644 crates/audio/tests/dsd_metadata.rs diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index a0e46a7a5c..ae633a05d7 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -183,3 +183,7 @@ required-features = ["lossless-encode", "aac-encode"] [[test]] name = "dsd_bounds" required-features = ["dsd"] + +[[test]] +name = "dsd_metadata" +required-features = ["dsd"] diff --git a/crates/audio/src/dsd/dsdiff.rs b/crates/audio/src/dsd/dsdiff.rs index f1980d1367..01a71b42e1 100644 --- a/crates/audio/src/dsd/dsdiff.rs +++ b/crates/audio/src/dsd/dsdiff.rs @@ -38,6 +38,37 @@ fn channel_id_to_name(id: &[u8; 4]) -> String { } } +/// The text of a `DITI` or `DIAR` chunk: a four-byte big-endian character count, then that many +/// bytes. `None` when the count is missing or longer than the chunk. +fn diin_text(sub_data: &[u8]) -> Option { + let count = usize::try_from(u32::from_be_bytes(sub_data.get(..4)?.try_into().ok()?)).ok()?; + let text = sub_data.get(4..)?.get(..count)?; + Some(String::from_utf8_lossy(text).trim().to_string()) +} + +/// The channel identifiers DSDIFF 1.5 defines for a channel count (stereo, 5 and 5.1 channels); +/// other counts use the generic `C001`, `C002`, ... identifiers. +fn channel_ids(num_channels: usize) -> Vec<[u8; 4]> { + let named: &[&[u8; 4]] = match num_channels { + 1 => &[b"SLFT"], + 2 => &[b"SLFT", b"SRGT"], + 5 => &[b"MLFT", b"MRGT", b"C ", b"LS ", b"RS "], + 6 => &[b"MLFT", b"MRGT", b"C ", b"LFE ", b"LS ", b"RS "], + _ => &[], + }; + if !named.is_empty() { + return named.iter().map(|id| **id).collect(); + } + (1..=num_channels) + .map(|n| { + let s = format!("C{n:03}"); + let mut id = [b' '; 4]; + id.copy_from_slice(&s.as_bytes()[..4]); + id + }) + .collect() +} + /// Parses the metadata from a DSDIFF file. pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Error> { if bytes.len() < 16 { @@ -163,9 +194,9 @@ pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Err diin_pos = diin_pos.saturating_add(sub_size).saturating_add(sub_pad); if sub_id == b"DITI" && title.is_none() { - title = Some(String::from_utf8_lossy(sub_data).trim().to_string()); + title = diin_text(sub_data); } else if sub_id == b"DIAR" && artist.is_none() { - artist = Some(String::from_utf8_lossy(sub_data).trim().to_string()); + artist = diin_text(sub_data); } } } @@ -252,7 +283,9 @@ pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> let bytes_per_ch = usize::try_from(sample_count.div_ceil(8)).map_err(|_| Error::MemoryLimitExceeded)?; let data_size = bytes_per_ch.checked_mul(num_channels).ok_or(Error::MemoryLimitExceeded)?; // Fixed headers plus four bytes for each channel identifier. - let file_size = super::encoded_size(data_size, 110 + 4 * num_channels)?; + // An odd-sized chunk payload is followed by a pad byte that its size field does not count. + let data_pad = data_size & 1; + let file_size = super::encoded_size(data_size + data_pad, 110 + 4 * num_channels)?; // Build PROP subchunks: // 1. 'FS ' (4 bytes + 12 chunk header) @@ -267,18 +300,8 @@ pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> chnl_chunk.extend_from_slice(b"CHNL"); chnl_chunk.extend_from_slice(&(chnl_data_len as u64).to_be_bytes()); chnl_chunk.extend_from_slice(&(num_channels as u16).to_be_bytes()); - for c in 0..num_channels { - let code = match (num_channels, c) { - (1, 0) => b"SLFT", - (2, 0) => b"SLFT", - (2, 1) => b"SRGT", - (_, 0) => b"MLFT", - (_, 1) => b"MRGT", - (_, 2) => b"C ", - (_, 3) => b"LFE ", - _ => b"C ", - }; - chnl_chunk.extend_from_slice(code); + for id in channel_ids(num_channels) { + chnl_chunk.extend_from_slice(&id); } if !chnl_data_len.is_multiple_of(2) { chnl_chunk.push(0); @@ -330,6 +353,9 @@ pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> out.push(byte); } } + if data_pad == 1 { + out.push(0); + } Ok(out) } diff --git a/crates/audio/src/dsd/dsf.rs b/crates/audio/src/dsd/dsf.rs index 34472001ea..3a09466645 100644 --- a/crates/audio/src/dsd/dsf.rs +++ b/crates/audio/src/dsd/dsf.rs @@ -15,7 +15,7 @@ fn dsf_channel_names(channel_type: u32, channel_count: u16) -> Vec { 2 => vec!["Left".to_string(), "Right".to_string()], 3 => vec!["Left".to_string(), "Right".to_string(), "Center".to_string()], 4 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "BackLeft".to_string(), "BackRight".to_string()], - 5 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "Surround".to_string()], + 5 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "LFE".to_string()], 6 => vec!["FrontLeft".to_string(), "FrontRight".to_string(), "Center".to_string(), "BackLeft".to_string(), "BackRight".to_string()], 7 => vec![ "FrontLeft".to_string(), @@ -53,7 +53,16 @@ fn parse_id3v2(bytes: &[u8], offset: usize) -> (Option, Option) if frame_id[0] == 0 { break; } - let frame_size = u32::from_be_bytes([id3[pos + 4], id3[pos + 5], id3[pos + 6], id3[pos + 7]]) as usize; + let raw = [id3[pos + 4], id3[pos + 5], id3[pos + 6], id3[pos + 7]]; + // ID3v2.4 frame sizes are synchsafe; v2.3 ones are plain big-endian. + let frame_size = if id3[3] >= 4 { + if raw.iter().any(|b| b & 0x80 != 0) { + break; + } + ((raw[0] as usize) << 21) | ((raw[1] as usize) << 14) | ((raw[2] as usize) << 7) | raw[3] as usize + } else { + u32::from_be_bytes(raw) as usize + }; pos += 10; if frame_size > end.saturating_sub(pos) { break; @@ -78,23 +87,35 @@ fn parse_text_frame(data: &[u8]) -> Option { } let encoding = data[0]; let content = &data[1..]; - match encoding { - 0 | 3 => { - // ISO-8859-1 or UTF-8 - let s = String::from_utf8_lossy(content).trim_end_matches('\0').trim().to_string(); - if s.is_empty() { None } else { Some(s) } + let text = match encoding { + // ISO-8859-1: every byte is the code point of the same value. + 0 => content.iter().map(|&b| char::from(b)).collect::(), + 3 => String::from_utf8_lossy(content).into_owned(), + // UTF-16 with a byte order mark (which is removed); without one, assume big-endian. + 1 => { + let (big_endian, body) = match content { + [0xFE, 0xFF, rest @ ..] => (true, rest), + [0xFF, 0xFE, rest @ ..] => (false, rest), + _ => (true, content), + }; + utf16(body, big_endian) } - 1 | 2 => { - // UTF-16 with BOM or UTF-16BE - if content.len() < 2 { - return None; - } - let u16s: Vec = content.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); - let s = String::from_utf16_lossy(&u16s).trim_end_matches('\0').trim().to_string(); - if s.is_empty() { None } else { Some(s) } - } - _ => None, - } + // UTF-16BE without a byte order mark. + 2 => utf16(content, true), + _ => return None, + }; + let s = text.trim_end_matches('\0').trim().to_string(); + if s.is_empty() { None } else { Some(s) } +} + +fn utf16(bytes: &[u8], big_endian: bool) -> String { + let units: Vec = bytes + .as_chunks::<2>() + .0 + .iter() + .map(|c| if big_endian { u16::from_be_bytes([c[0], c[1]]) } else { u16::from_le_bytes([c[0], c[1]]) }) + .collect(); + String::from_utf16_lossy(&units) } /// Parses DSF file metadata, returning the metadata, audio data offset, and block size per channel. @@ -264,6 +285,10 @@ pub fn parse_dsf(bytes: &[u8]) -> Result { Ok(RawAudio { metadata, bit_order: BitOrder::LsbFirst, channel_bytes }) } +fn unsupported_channel_layout() -> Result { + Err(Error::Unsupported("DSF has no channel type for this channel count (1 to 6 are supported)")) +} + /// Encodes 1-bit planar audio channels into a valid Sony DSF file. pub fn write_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_size: u32) -> Result, Error> { if channels.is_empty() || channels.len() > MAX_CHANNELS { @@ -299,7 +324,16 @@ pub fn write_dsf(sample_rate: u32, channels: &[&[u8]], sample_count: u64, block_ out.extend_from_slice(&52u64.to_le_bytes()); out.extend_from_slice(&1u32.to_le_bytes()); // format_version = 1 out.extend_from_slice(&0u32.to_le_bytes()); // format_id = 0 (raw DSD) - let channel_type = if num_channels == 1 { 1u32 } else { 2u32 }; + // DSF channel types: 1 mono, 2 stereo, 3 L R C, 4 quad, 6 five channels, 7 5.1. + let channel_type = match num_channels { + 1 => 1u32, + 2 => 2, + 3 => 3, + 4 => 4, + 5 => 6, + 6 => 7, + _ => unsupported_channel_layout()?, + }; out.extend_from_slice(&channel_type.to_le_bytes()); out.extend_from_slice(&(num_channels as u32).to_le_bytes()); out.extend_from_slice(&sample_rate.to_le_bytes()); diff --git a/crates/audio/src/dsd/filter.rs b/crates/audio/src/dsd/filter.rs index f7d934d3ec..ec815afd1c 100644 --- a/crates/audio/src/dsd/filter.rs +++ b/crates/audio/src/dsd/filter.rs @@ -156,6 +156,27 @@ pub(super) fn allocation_sizes(len: usize, factor: u32) -> Result<(usize, usize) Ok((working, output)) } +/// Unity-DC-gain low-pass taps for decimating by `ratio` (cutoff 0.45 / ratio cycles per sample). +fn decimation_taps(ratio: usize) -> Vec { + let n = 24 * ratio + 1; + let mid = (n / 2) as f64; + let fc = 0.45 / ratio as f64; + let mut taps: Vec = (0..n) + .map(|k| { + let x = k as f64 - mid; + let sinc = if x == 0.0 { 2.0 * fc } else { (2.0 * std::f64::consts::PI * fc * x).sin() / (std::f64::consts::PI * x) }; + let t = k as f64 / (n - 1) as f64; + let window = 0.42 - 0.5 * (2.0 * std::f64::consts::PI * t).cos() + 0.08 * (4.0 * std::f64::consts::PI * t).cos(); + sinc * window + }) + .collect(); + let sum: f64 = taps.iter().sum(); + for t in &mut taps { + *t /= sum; + } + taps.into_iter().map(|t| t as f32).collect() +} + /// Decimates 1-bit DSD audio bytes for a single channel to `f32` PCM. /// /// The default decimation factor is 8 (1 output float per input byte). @@ -209,16 +230,59 @@ pub fn decimate_channel(channel_bytes: &[u8], bit_order: BitOrder, factor: u32) return Ok(stage1); } - // Secondary downsampling by ratio = factor / 8 (2, 4, or 8). + // Secondary decimation by ratio = factor / 8 (2, 4, or 8). A plain average attenuates the band + // between the new Nyquist rate and the stage-1 rate too little (about -7.6 dB at 29.4 kHz for + // factor 64), so low-pass first: a Blackman-windowed sinc with its cutoff at 90% of the new + // Nyquist frequency, evaluated only at the kept samples. let ratio = (factor / 8) as usize; let out_len = stage1.len() / ratio; let mut out = Vec::new(); out.try_reserve_exact(out_len).map_err(|_| Error::MemoryLimitExceeded)?; - for chunk in stage1.chunks_exact(ratio) { - let sum: f32 = chunk.iter().sum(); - out.push(sum / ratio as f32); + let taps = decimation_taps(ratio); + let half = (taps.len() / 2) as isize; + let last = stage1.len() as isize - 1; + for i in 0..out_len { + let center = (i * ratio + ratio / 2) as isize; + let mut acc = 0.0_f32; + for (k, &w) in taps.iter().enumerate() { + let idx = (center + k as isize - half).clamp(0, last); + if let Some(&x) = stage1.get(idx as usize) { + acc += w * x; + } + } + out.push(acc); } Ok(out) } + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod decimation_tests { + use super::*; + + /// A full-scale 29.4 kHz square wave in DSD64 (six bytes of ones, six of zeros) lies between + /// the output Nyquist frequency and the sampling rate of a 44.1 kHz result: it must be + /// attenuated well, not folded down at 0.42 of its amplitude. + #[test] + fn factor_64_attenuates_29_4_khz() { + let mut bytes = Vec::new(); + for _ in 0..2000 { + bytes.extend_from_slice(&[0xFF; 6]); + bytes.extend_from_slice(&[0x00; 6]); + } + let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap(); + let mid = &out[out.len() / 4..out.len() * 3 / 4]; + let peak = mid.iter().fold(0.0_f32, |m, v| m.max(v.abs())); + assert!(peak < 0.05, "peak {peak}"); + } + + #[test] + fn decimation_keeps_dc_level() { + let bytes = vec![0xFF; 4096]; + let out = decimate_channel(&bytes, BitOrder::MsbFirst, 64).unwrap(); + let mid = out[out.len() / 2]; + assert!((mid - 1.0).abs() < 0.05, "{mid}"); + } +} diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 5ab2b8089e..fcaf2897e1 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -2,7 +2,7 @@ #![warn(missing_docs)] // The docs link items of every feature; built with fewer features, those links have no target. // CI and docs.rs build the docs with all features, where every link must resolve. -#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks")), allow(rustdoc::broken_intra_doc_links))] +#![cfg_attr(not(all(feature = "decode", feature = "encode", feature = "peaks", feature = "dsd")), allow(rustdoc::broken_intra_doc_links))] //! Audio file I/O and codecs for the Craft apps. Input and output are byte slices or a //! [`craft_media::ByteSource`] (no filesystem access of its own); builds for //! `wasm32-unknown-unknown`. diff --git a/crates/audio/tests/dsd_bounds.rs b/crates/audio/tests/dsd_bounds.rs index c335c5d636..52f18730b3 100644 --- a/crates/audio/tests/dsd_bounds.rs +++ b/crates/audio/tests/dsd_bounds.rs @@ -81,6 +81,11 @@ fn encoded_sizes_match_actual_bytes_for_odd_and_even_payloads() { let data = vec![0x69; len]; let planes = vec![data.as_slice(); channels]; for block in [0, 1, 3, 8] { + // DSF has channel types for 1 to 6 channels only. + if channels > 6 { + assert!(matches!(encode_dsf(2_822_400, &planes, len as u64 * 8, block), Err(Error::Unsupported(_)))); + continue; + } let dsf = encode_dsf(2_822_400, &planes, len as u64 * 8, block).unwrap(); assert_eq!(u64::from_le_bytes(dsf[12..20].try_into().unwrap()), dsf.len() as u64); assert_eq!(read_raw(&dsf).unwrap().channel_bytes, vec![data.clone(); channels]); diff --git a/crates/audio/tests/dsd_metadata.rs b/crates/audio/tests/dsd_metadata.rs new file mode 100644 index 0000000000..6b076a0e7f --- /dev/null +++ b/crates/audio/tests/dsd_metadata.rs @@ -0,0 +1,153 @@ +//! Channel labels, text metadata and padding in the DSF and DSDIFF readers and writers. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use craft_audio::dsd::{encode_dsdiff, encode_dsf, read_metadata, read_raw}; + +const RATE: u32 = 2_822_400; + +fn planes(channels: usize, len: usize) -> Vec> { + vec![vec![0x69; len]; channels] +} + +fn refs(p: &[Vec]) -> Vec<&[u8]> { + p.iter().map(Vec::as_slice).collect() +} + +#[test] +fn dsdiff_names_surround_channels_by_layout() { + for (n, names) in [ + (5, vec!["Mono/Left", "Right", "Center", "LeftSurround", "RightSurround"]), + (6, vec!["Mono/Left", "Right", "Center", "LFE", "LeftSurround", "RightSurround"]), + ] { + let p = planes(n, 4); + let bytes = encode_dsdiff(RATE, &refs(&p), 32).unwrap(); + assert_eq!(read_metadata(&bytes).unwrap().channel_names, names, "{n} channels"); + } +} + +#[test] +fn dsdiff_odd_audio_is_padded_and_counted_in_the_file_size() { + let p = planes(1, 1); + let bytes = encode_dsdiff(RATE, &refs(&p), 8).unwrap(); + assert_eq!(bytes.len() % 2, 0); + assert_eq!(u64::from_be_bytes(bytes[4..12].try_into().unwrap()) + 12, bytes.len() as u64); + assert_eq!(*bytes.last().unwrap(), 0, "pad byte"); + assert_eq!(read_raw(&bytes).unwrap().channel_bytes, vec![vec![0x69]]); +} + +fn with_diin(mut bytes: Vec, sub: &[u8; 4], payload: &[u8]) -> Vec { + let mut sub_chunk = Vec::new(); + sub_chunk.extend_from_slice(sub); + sub_chunk.extend_from_slice(&(payload.len() as u64).to_be_bytes()); + sub_chunk.extend_from_slice(payload); + if payload.len() % 2 == 1 { + sub_chunk.push(0); + } + bytes.extend_from_slice(b"DIIN"); + bytes.extend_from_slice(&(sub_chunk.len() as u64).to_be_bytes()); + bytes.extend_from_slice(&sub_chunk); + let size = (bytes.len() - 12) as u64; + bytes[4..12].copy_from_slice(&size.to_be_bytes()); + bytes +} + +#[test] +fn dsdiff_title_and_artist_skip_the_character_count() { + let p = planes(2, 4); + let base = encode_dsdiff(RATE, &refs(&p), 32).unwrap(); + let mut payload = 4u32.to_be_bytes().to_vec(); + payload.extend_from_slice(b"Test"); + let bytes = with_diin(base.clone(), b"DITI", &payload); + assert_eq!(read_metadata(&bytes).unwrap().title.as_deref(), Some("Test")); + let bytes = with_diin(base.clone(), b"DIAR", &payload); + assert_eq!(read_metadata(&bytes).unwrap().artist.as_deref(), Some("Test")); + // A count longer than the chunk is not text. + let mut bad = 99u32.to_be_bytes().to_vec(); + bad.extend_from_slice(b"Test"); + assert_eq!(read_metadata(&with_diin(base, b"DITI", &bad)).unwrap().title, None); +} + +#[test] +fn dsf_channel_types_match_the_channel_count() { + for (n, expect) in [(1, 1), (2, 2), (3, 3), (4, 4), (5, 6), (6, 7)] { + let p = planes(n, 4); + let bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + assert_eq!(u32::from_le_bytes(bytes[48..52].try_into().unwrap()), expect, "{n} channels"); + assert_eq!(read_metadata(&bytes).unwrap().channel_names.len(), n); + } + let p = planes(7, 4); + assert!(encode_dsf(RATE, &refs(&p), 32, 4096).is_err()); +} + +#[test] +fn dsf_type_5_names_the_fourth_channel_lfe() { + let p = planes(4, 4); + let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + bytes[48..52].copy_from_slice(&5u32.to_le_bytes()); + assert_eq!(read_metadata(&bytes).unwrap().channel_names, ["FrontLeft", "FrontRight", "Center", "LFE"]); +} + +fn id3(version: u8, frames: &[u8]) -> Vec { + let n = frames.len(); + let mut tag = vec![b'I', b'D', b'3', version, 0, 0]; + tag.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]); + tag.extend_from_slice(frames); + tag +} + +fn frame(version: u8, id: &[u8; 4], body: &[u8]) -> Vec { + let n = body.len(); + let mut f = id.to_vec(); + if version >= 4 { + f.extend_from_slice(&[(n >> 21) as u8 & 0x7F, (n >> 14) as u8 & 0x7F, (n >> 7) as u8 & 0x7F, n as u8 & 0x7F]); + } else { + f.extend_from_slice(&(n as u32).to_be_bytes()); + } + f.extend_from_slice(&[0, 0]); + f.extend_from_slice(body); + f +} + +fn dsf_with_tag(tag: &[u8]) -> Vec { + let p = planes(2, 4); + let mut bytes = encode_dsf(RATE, &refs(&p), 32, 4096).unwrap(); + let offset = bytes.len() as u64; + bytes[20..28].copy_from_slice(&offset.to_le_bytes()); + bytes.extend_from_slice(tag); + bytes +} + +#[test] +fn id3v24_frame_sizes_are_synchsafe() { + // A 128-byte frame has the synchsafe size 00 00 01 00; read as plain big-endian it is 256. + let mut frames = frame(4, b"APIC", &[0u8; 128]); + let mut title = vec![3]; + title.extend_from_slice(b"After art"); + frames.extend(frame(4, b"TIT2", &title)); + let m = read_metadata(&dsf_with_tag(&id3(4, &frames))).unwrap(); + assert_eq!(m.title.as_deref(), Some("After art")); +} + +#[test] +fn id3v23_frame_sizes_stay_big_endian() { + let mut frames = frame(3, b"APIC", &[0u8; 128]); + let mut title = vec![3]; + title.extend_from_slice(b"Three"); + frames.extend(frame(3, b"TIT2", &title)); + let m = read_metadata(&dsf_with_tag(&id3(3, &frames))).unwrap(); + assert_eq!(m.title.as_deref(), Some("Three")); +} + +#[test] +fn id3_text_encodings() { + let cases: [(&[u8], &str); 5] = [ + (b"\x00Caf\xe9", "Café"), + (b"\x03Caf\xc3\xa9", "Café"), + (b"\x02\x00A\x00B", "AB"), + (b"\x01\xFF\xFEA\x00B\x00", "AB"), + (b"\x01\xFE\xFF\x00A\x00B", "AB"), + ]; + for (body, expect) in cases { + let m = read_metadata(&dsf_with_tag(&id3(4, &frame(4, b"TIT2", body)))).unwrap(); + assert_eq!(m.title.as_deref(), Some(expect), "{body:?}"); + } +} From 7ba969d1bce71c0618198faf9047d40bf76f8a51 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 14:54:05 -0500 Subject: [PATCH 09/79] Separate inpaint source-centre collection from completion --- crates/develop/src/inpaint.rs | 2 +- crates/develop/src/inpaint/patchmatch.rs | 26 ++++++++++++++---------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/crates/develop/src/inpaint.rs b/crates/develop/src/inpaint.rs index 5468d3c259..fece30cada 100644 --- a/crates/develop/src/inpaint.rs +++ b/crates/develop/src/inpaint.rs @@ -49,7 +49,7 @@ mod tests { let img: Vec = (0..256).map(|i| if i % 16 < 8 { -f32::MAX } else { f32::MAX }).collect(); let out = membrane_fill(16, 16, 1, &img, &hole); for ((&actual, &original), &unknown) in out.iter().zip(&img).zip(&hole) { - assert!(actual.is_finite() && actual >= -f32::MAX && actual <= f32::MAX); + assert!(actual.is_finite() && (-f32::MAX..=f32::MAX).contains(&actual)); if !unknown { assert_eq!(actual.to_bits(), original.to_bits()); } diff --git a/crates/develop/src/inpaint/patchmatch.rs b/crates/develop/src/inpaint/patchmatch.rs index af7c3fecda..54c49a267d 100644 --- a/crates/develop/src/inpaint/patchmatch.rs +++ b/crates/develop/src/inpaint/patchmatch.rs @@ -132,6 +132,20 @@ fn supported_grid(w: usize, h: usize) -> bool { .is_some_and(|bytes| bytes <= isize::MAX as usize) } +/// Reserve the already counted source centres exactly, then retain row-major order. +fn source_centres(w: usize, valid: &[bool], count: usize, check: &impl Fn() -> Result<(), Cancelled>) -> Result, Cancelled> { + let mut centres = Vec::with_capacity(count); + for (i, &is_valid) in valid.iter().enumerate() { + if i % (w * 32) == 0 { + check()?; + } + if is_valid { + centres.push(((i % w) as i32, (i / w) as i32)); + } + } + Ok(centres) +} + /// Summed-area table of a boolean grid (`(w+1) × (h+1)`). fn integral(w: usize, h: usize, m: &[bool]) -> Vec { let mut s = vec![0u32; (w + 1) * (h + 1)]; @@ -488,17 +502,7 @@ pub fn complete_with( nnf.clear(); continue; } - // Count first and reserve exactly, avoiding both geometric capacity overflow and - // allocating coordinates for pixels that cannot be source centres. - let mut valid_list = Vec::with_capacity(valid_count); - for (i, &is_valid) in valid.iter().enumerate() { - if i % (lw * 32) == 0 { - check()?; - } - if is_valid { - valid_list.push(((i % lw) as i32, (i / lw) as i32)); - } - } + let valid_list = source_centres(lw, &valid, valid_count, &check)?; let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, hole: &lhole, valid, valid_list, targets, ctl: cancelled }; // NNF init: upsampled from the coarser level where possible, random otherwise. let mut rng = Rng::new(p.seed ^ (li as u64) << 20); From e20290fb439ff63db47fbbc0f1643e469b4f3a21 Mon Sep 17 00:00:00 2001 From: el-j Date: Wed, 18 Nov 2026 21:23:33 +0100 Subject: [PATCH 10/79] Check padding addition for DSDIFF size calculation --- crates/audio/src/dsd/dsdiff.rs | 3 ++- crates/audio/tests/dsd_bounds.rs | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/audio/src/dsd/dsdiff.rs b/crates/audio/src/dsd/dsdiff.rs index 01a71b42e1..0d818f53a6 100644 --- a/crates/audio/src/dsd/dsdiff.rs +++ b/crates/audio/src/dsd/dsdiff.rs @@ -285,7 +285,8 @@ pub fn write_dsdiff(sample_rate: u32, channels: &[&[u8]], sample_count: u64) -> // Fixed headers plus four bytes for each channel identifier. // An odd-sized chunk payload is followed by a pad byte that its size field does not count. let data_pad = data_size & 1; - let file_size = super::encoded_size(data_size + data_pad, 110 + 4 * num_channels)?; + let padded_size = data_size.checked_add(data_pad).ok_or(Error::MemoryLimitExceeded)?; + let file_size = super::encoded_size(padded_size, 110 + 4 * num_channels)?; // Build PROP subchunks: // 1. 'FS ' (4 bytes + 12 chunk header) diff --git a/crates/audio/tests/dsd_bounds.rs b/crates/audio/tests/dsd_bounds.rs index 52f18730b3..13f6608e19 100644 --- a/crates/audio/tests/dsd_bounds.rs +++ b/crates/audio/tests/dsd_bounds.rs @@ -118,3 +118,19 @@ fn dsf_audio_stops_at_the_declared_data_chunk() { assert_eq!(read_raw(&bytes).unwrap().channel_bytes, expected.channel_bytes); } } + +#[test] +fn dsdiff_odd_payload_receives_pad_byte() { + let input = [&[0xaau8; 3][..]]; + let bytes = encode_dsdiff(2_822_400, &input, 24).unwrap(); + let raw = read_raw(&bytes).unwrap(); + assert_eq!(raw.channel_bytes[0].len(), 3); +} + +#[test] +#[cfg(target_pointer_width = "32")] +fn dsdiff_32bit_padding_overflow_is_rejected() { + let dummy = [&[][..]]; + let result = encode_dsdiff(2_822_400, &dummy, 34_359_738_360); + assert_eq!(result, Err(Error::MemoryLimitExceeded)); +} From bf655268d7eb5c920a1ad7b26acc275cb42624f2 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 18 Nov 2026 16:09:33 -0500 Subject: [PATCH 11/79] craft-develop: a cancelled inpaint with an impossible patch radius is still cancelled --- crates/develop/src/inpaint.rs | 3 +++ crates/develop/src/inpaint/patchmatch.rs | 1 + 2 files changed, 4 insertions(+) diff --git a/crates/develop/src/inpaint.rs b/crates/develop/src/inpaint.rs index 853eaa51be..e33347901a 100644 --- a/crates/develop/src/inpaint.rs +++ b/crates/develop/src/inpaint.rs @@ -57,6 +57,9 @@ mod tests { let p = CompleteParams { patch_radius, ..CompleteParams::default() }; assert_eq!(complete(32, 32, 1, &[0.5; 32 * 32], &hole, &p), None, "radius {patch_radius}"); } + // Cancelled is still cancelled, not "nothing to copy from". + let p = CompleteParams { patch_radius: 16, ..CompleteParams::default() }; + assert_eq!(complete_with(32, 32, 1, &[0.5; 32 * 32], &hole, &p, &|| true), Err(Cancelled)); // A radius the image has room for still fills. let p = CompleteParams { patch_radius: 5, ..CompleteParams::default() }; assert!(complete(32, 32, 1, &[0.5; 32 * 32], &hole, &p).is_some()); diff --git a/crates/develop/src/inpaint/patchmatch.rs b/crates/develop/src/inpaint/patchmatch.rs index 175a5f69d6..aa9ff28733 100644 --- a/crates/develop/src/inpaint/patchmatch.rs +++ b/crates/develop/src/inpaint/patchmatch.rs @@ -401,6 +401,7 @@ pub fn complete_with( // A patch wider than the image has no place to be copied from, which is the `None` the search below // would reach anyway. Said here, before `2 * r + 1` and `r as i32` can overflow on an absurd radius. if r > (w.min(h) - 1) / 2 { + check()?; return Ok(None); } let psz = 2 * r + 1; From fa4741d0bbba8da303dd1bb1a93cbcb78e7747a0 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 00:59:54 +0100 Subject: [PATCH 12/79] psd: share raw hue and levels block writers --- crates/psd/src/adjust.rs | 51 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/crates/psd/src/adjust.rs b/crates/psd/src/adjust.rs index bf5a7a6846..7da9b5f035 100644 --- a/crates/psd/src/adjust.rs +++ b/crates/psd/src/adjust.rs @@ -37,6 +37,36 @@ pub fn exposure_block(exposure: f32, offset: f32, gamma: f32) -> crate::tagged:: crate::tagged::TaggedBlock::new(*b"expA", data) } +/// Write a version-2 hue2 master adjustment from raw signed values. +/// +/// Colorize is off, its three values are zero, and all six unused 24-byte +/// color-range records are zero. The payload is exactly 160 bytes, without padding. +pub fn hue_saturation_block(hue: i16, saturation: i16, lightness: i16) -> crate::tagged::TaggedBlock { + let mut data = vec![0, 2, 0, 0]; + for value in [0i16, 0, 0, hue, saturation, lightness] { + data.extend_from_slice(&value.to_be_bytes()); + } + data.resize(160, 0); + crate::tagged::TaggedBlock::new(*b"hue2", data) +} + +/// Write a version-2 levl composite record followed by 28 default records. +/// +/// All fields are raw signed values; gamma_hundredths is already converted by +/// the caller. No clamping or normalization is applied. The payload is 292 bytes. +pub fn levels_block(in_black: i16, in_white: i16, out_black: i16, out_white: i16, gamma_hundredths: i16) -> crate::tagged::TaggedBlock { + let mut data = vec![0, 2]; + for value in [in_black, in_white, out_black, out_white, gamma_hundredths] { + data.extend_from_slice(&value.to_be_bytes()); + } + for _ in 0..28 { + for value in [0i16, 255, 0, 255, 100] { + data.extend_from_slice(&value.to_be_bytes()); + } + } + crate::tagged::TaggedBlock::new(*b"levl", data) +} + /// The adjustment a layer applies. #[derive(Clone, Debug, PartialEq)] pub enum Adjustment { @@ -224,6 +254,27 @@ mod tests { assert_eq!(exposure_block(1.0, -2.5, 0.125).data, [0, 1, 0x3f, 0x80, 0, 0, 0xc0, 0x20, 0, 0, 0x3e, 0, 0, 0]); } + #[test] + fn hue_and_levels_writers_preserve_complete_raw_records() { + let hue = hue_saturation_block(i16::MIN, i16::MAX, -1); + let mut expected = vec![0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0x7f, 0xff, 0xff, 0xff]; + expected.extend([0; 144]); + assert_eq!(hue.key, *b"hue2"); + assert_eq!(hue.data, expected); + let mut zero_hue = vec![0; 160]; + zero_hue[1] = 2; + assert_eq!(hue_saturation_block(0, 0, 0).data, zero_hue); + + let levels = levels_block(i16::MIN, i16::MAX, -1, 0, -13); + let mut expected = vec![0, 2, 0x80, 0, 0x7f, 0xff, 0xff, 0xff, 0, 0, 0xff, 0xf3]; + expected.extend([0, 0, 0, 255, 0, 0, 0, 255, 0, 100].repeat(28)); + assert_eq!(levels.key, *b"levl"); + assert_eq!(levels.data, expected); + let mut zeros = vec![0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + zeros.extend([0, 0, 0, 255, 0, 0, 0, 255, 0, 100].repeat(28)); + assert_eq!(levels_block(0, 0, 0, 0, 0).data, zeros); + } + fn layer(blocks: Vec<([u8; 4], Vec)>) -> LayerRecord { LayerRecord { blocks: blocks.into_iter().map(|(k, d)| TaggedBlock::new(k, d)).collect(), ..Default::default() } } From e701f54d0acd70a7f04100f9eb4f77d04dd8af87 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 02:22:51 +0000 Subject: [PATCH 13/79] workspace: own cache entries for the WASM and 1.95 calls, stripped test binaries, no examples in the test build Needs craft-common-actions gate.yml with the cache-name and dev-strip inputs. --- .github/workflows/workspace.yml | 20 +++++++++++++++----- scripts/test-workspace-tests.py | 10 ++++++---- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 5a9e4989d6..ff1d7ff5a6 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -39,6 +39,9 @@ jobs: packages: mesa-vulkan-drivers libvulkan1 craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan + # Test binaries without debug info or symbols: about a third of the size, and a panic still + # names its file and line. + dev-strip: true # No debuginfo on Windows: writing PDBs for every test binary is a large part of its link # time. A panic still names its file and line; only backtrace frames lose theirs, and the # Linux and macOS legs keep line tables. @@ -74,22 +77,28 @@ jobs: cargo clippy --workspace --all-targets --all-features --locked -- -D warnings command: | # The tests run once, with every feature, in parallel across test binaries; nextest skips - # doctests, so `cargo test --doc` runs them. The default-feature compile is the lint leg's + # doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose + # tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's # first clippy run; the last command runs the crates whose tests check behaviour with a # feature off, which an all-features build cannot reach. - cargo nextest run --workspace --all-features --locked --profile ci + cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests + cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench cargo test --workspace --doc --all-features --locked - cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci + cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests windows-command: | powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' - cargo nextest run --workspace --all-features --locked --profile ci + cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests + cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench cargo test --workspace --doc --all-features --locked - cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci + cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests msrv: name: Rust 1.95 uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: + # Its own dependency-cache entry: the calls in this file share one job id, so without a name + # they would write the same key. + cache-name: msrv os: '["ubuntu-latest"]' toolchain: 1.95.0 targets: "" @@ -104,6 +113,7 @@ jobs: name: UI and settings WASM uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: + cache-name: wasm os: '["ubuntu-latest"]' targets: wasm32-unknown-unknown tools: "" diff --git a/scripts/test-workspace-tests.py b/scripts/test-workspace-tests.py index ac65da9c15..a50d2370cf 100644 --- a/scripts/test-workspace-tests.py +++ b/scripts/test-workspace-tests.py @@ -32,9 +32,10 @@ cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings """ TEST_SOURCE = """ -cargo nextest run --workspace --all-features --locked --profile ci +cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests +cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench cargo test --workspace --doc --all-features --locked -cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci +cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests """ WINDOWS_SETUP = """powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'""" EXPECTED_SOURCE = { @@ -90,9 +91,10 @@ COMMON = [ "clippy --workspace --all-targets --all-features --locked -- -D warnings", ] TESTS = [ - "nextest run --workspace --all-features --locked --profile ci", + "nextest run --workspace --all-features --locked --profile ci --lib --bins --tests", + "nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench", "test --workspace --doc --all-features --locked", - "nextest run -p craft-image-codecs -p craft-text --locked --profile ci", + "nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests", ] From bd3fd7cc704b95b104d3b88f6dd6403349541a3d Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 03:28:39 +0100 Subject: [PATCH 14/79] formats: add borrowed iterative PSD descriptor writer --- crates/psd/src/descriptor.rs | 1 + crates/psd/src/descriptor/borrowed.rs | 449 ++++++++++++++++++++++++++ 2 files changed, 450 insertions(+) create mode 100644 crates/psd/src/descriptor/borrowed.rs diff --git a/crates/psd/src/descriptor.rs b/crates/psd/src/descriptor.rs index a9b0148ec8..7d9b900427 100644 --- a/crates/psd/src/descriptor.rs +++ b/crates/psd/src/descriptor.rs @@ -7,6 +7,7 @@ use crate::error::{PsdError, Result}; use crate::io::{Reader, WriteExt, read_unicode_units, write_unicode_units}; +pub mod borrowed; mod lookup; /// Maximum nesting depth accepted when parsing (fuzz safety). diff --git a/crates/psd/src/descriptor/borrowed.rs b/crates/psd/src/descriptor/borrowed.rs new file mode 100644 index 0000000000..cb718028f3 --- /dev/null +++ b/crates/psd/src/descriptor/borrowed.rs @@ -0,0 +1,449 @@ +//! Borrowed, iterative descriptor serialization into an existing output buffer. +//! +//! Views must be finite, stable and acyclic for the duration of serialization. +//! The first absent indexed item ends a container. Counts are derived from emitted +//! items (wrapping u32, like the owned writer), never supplied by a view. +//! Output growth plus O(depth) heap frames are the only proportional allocations. + +/// An identifier with its explicit wire encoding. +#[derive(Clone, Copy)] +pub enum IdRef<'a> { + /// Length zero followed by four bytes. + Code([u8; 4]), + /// Explicit byte length, even when four. + String(&'a [u8]), +} +/// A Unicode string without interpretation or normalization. +#[derive(Clone, Copy)] +pub enum UnicodeRef<'a> { + /// Encode UTF-8 and optionally append exactly one NUL. + Text(&'a str, bool), + /// Preserve UTF-16 units, including unpaired surrogates. + Units(&'a [u16]), +} +/// A borrowed class. +#[derive(Clone, Copy)] +pub struct ClassRef<'a> { + /// Display name. + pub name: UnicodeRef<'a>, + /// Class identifier. + pub id: IdRef<'a>, +} +/// A finite, stable, acyclic descriptor view. +pub trait DescriptorView { + /// Class metadata. + fn class(&self) -> ClassRef<'_>; + /// Indexed item; the first None terminates the container. + fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)>; +} +/// A finite, stable, acyclic value sequence. +pub trait ValuesView { + /// Indexed value; the first None terminates the container. + fn value(&self, index: usize) -> Option>; +} +/// A finite, stable reference sequence. +pub trait ReferencesView { + /// Indexed reference; the first None terminates the container. + fn reference(&self, index: usize) -> Option>; +} +/// A borrowed value. No variant owns a child model or payload. +pub enum ValueRef<'a> { + /// Objc. + Descriptor(&'a dyn DescriptorView), + /// VlLs. + List(&'a dyn ValuesView), + /// ObAr prefix and body. + ObjectArray(u32, &'a dyn DescriptorView), + /// doub. + Double(f64), + /// UntF. + UnitFloat([u8; 4], f64), + /// UnFl. + UnitFloats([u8; 4], &'a [f64]), + /// TEXT. + Text(UnicodeRef<'a>), + /// enum. + Enumerated(IdRef<'a>, IdRef<'a>), + /// long. + Integer(i32), + /// comp. + LargeInteger(i64), + /// bool. + Boolean(bool), + /// type. + Class(ClassRef<'a>), + /// tdta. + RawData(&'a [u8]), + /// obj reference. + Reference(&'a dyn ReferencesView), +} +/// A borrowed reference item. +#[derive(Clone, Copy)] +pub enum ReferenceRef<'a> { + /// prop. + Property(ClassRef<'a>, IdRef<'a>), + /// Clss. + Class(ClassRef<'a>), + /// Enmr. + Enumerated(ClassRef<'a>, IdRef<'a>, IdRef<'a>), + /// rele. + Offset(ClassRef<'a>, i32), + /// Idnt. + Identifier(ClassRef<'a>, i32), + /// indx. + Index(ClassRef<'a>, i32), + /// name. + Name(ClassRef<'a>, UnicodeRef<'a>), +} + +fn u32_bytes(out: &mut Vec, n: u32) { + out.extend_from_slice(&n.to_be_bytes()); +} +fn id(out: &mut Vec, value: IdRef<'_>) { + match value { + IdRef::Code(bytes) => { + u32_bytes(out, 0); + out.extend_from_slice(&bytes); + } + IdRef::String(bytes) => { + u32_bytes(out, bytes.len() as u32); + out.extend_from_slice(bytes); + } + } +} +fn unicode(out: &mut Vec, value: UnicodeRef<'_>) { + match value { + UnicodeRef::Text(text, nul) => { + let count = text.encode_utf16().fold(0u32, |n, _| n.wrapping_add(1)).wrapping_add(u32::from(nul)); + u32_bytes(out, count); + for unit in text.encode_utf16().chain(nul.then_some(0)) { + out.extend_from_slice(&unit.to_be_bytes()); + } + } + UnicodeRef::Units(units) => { + u32_bytes(out, units.len() as u32); + for unit in units { + out.extend_from_slice(&unit.to_be_bytes()); + } + } + } +} +fn class(out: &mut Vec, value: ClassRef<'_>) { + unicode(out, value.name); + id(out, value.id); +} +#[derive(Clone, Copy)] +enum Container<'a> { + Descriptor(&'a dyn DescriptorView), + List(&'a dyn ValuesView), + References(&'a dyn ReferencesView), +} +struct Frame<'a> { + container: Container<'a>, + index: usize, + count: u32, + offset: usize, +} +fn begin<'a>(out: &mut Vec, container: Container<'a>) -> Frame<'a> { + if let Container::Descriptor(d) = &container { + class(out, d.class()); + } + let offset = out.len(); + u32_bytes(out, 0); + Frame { container, index: 0, count: 0, offset } +} +fn finish(out: &mut [u8], frame: Frame<'_>) { + // This offset denotes the four-byte placeholder emitted by begin, never input data. + if let Some(slot) = out.get_mut(frame.offset..).and_then(|tail| tail.get_mut(..4)) { + slot.copy_from_slice(&frame.count.to_be_bytes()); + } +} +fn reference(out: &mut Vec, value: ReferenceRef<'_>) { + match value { + ReferenceRef::Property(c, k) => { + out.extend_from_slice(b"prop"); + class(out, c); + id(out, k); + } + ReferenceRef::Class(c) => { + out.extend_from_slice(b"Clss"); + class(out, c); + } + ReferenceRef::Enumerated(c, t, v) => { + out.extend_from_slice(b"Enmr"); + class(out, c); + id(out, t); + id(out, v); + } + ReferenceRef::Offset(c, n) | ReferenceRef::Identifier(c, n) | ReferenceRef::Index(c, n) => { + let tag = match value { + ReferenceRef::Offset(..) => b"rele", + ReferenceRef::Identifier(..) => b"Idnt", + _ => b"indx", + }; + out.extend_from_slice(tag); + class(out, c); + out.extend_from_slice(&n.to_be_bytes()); + } + ReferenceRef::Name(c, n) => { + out.extend_from_slice(b"name"); + class(out, c); + unicode(out, n); + } + } +} +fn value<'a>(out: &mut Vec, v: ValueRef<'a>) -> Option> { + match v { + ValueRef::Descriptor(d) => { + out.extend_from_slice(b"Objc"); + return Some(Container::Descriptor(d)); + } + ValueRef::List(v) => { + out.extend_from_slice(b"VlLs"); + return Some(Container::List(v)); + } + ValueRef::ObjectArray(n, d) => { + out.extend_from_slice(b"ObAr"); + u32_bytes(out, n); + return Some(Container::Descriptor(d)); + } + ValueRef::Reference(v) => { + out.extend_from_slice(b"obj "); + return Some(Container::References(v)); + } + ValueRef::Double(n) => { + out.extend_from_slice(b"doub"); + out.extend_from_slice(&n.to_be_bytes()); + } + ValueRef::UnitFloat(u, n) => { + out.extend_from_slice(b"UntF"); + out.extend_from_slice(&u); + out.extend_from_slice(&n.to_be_bytes()); + } + ValueRef::UnitFloats(u, ns) => { + out.extend_from_slice(b"UnFl"); + out.extend_from_slice(&u); + u32_bytes(out, ns.len() as u32); + for n in ns { + out.extend_from_slice(&n.to_be_bytes()); + } + } + ValueRef::Text(s) => { + out.extend_from_slice(b"TEXT"); + unicode(out, s); + } + ValueRef::Enumerated(t, v) => { + out.extend_from_slice(b"enum"); + id(out, t); + id(out, v); + } + ValueRef::Integer(n) => { + out.extend_from_slice(b"long"); + out.extend_from_slice(&n.to_be_bytes()); + } + ValueRef::LargeInteger(n) => { + out.extend_from_slice(b"comp"); + out.extend_from_slice(&n.to_be_bytes()); + } + ValueRef::Boolean(b) => { + out.extend_from_slice(b"bool"); + out.push(u8::from(b)); + } + ValueRef::Class(c) => { + out.extend_from_slice(b"type"); + class(out, c); + } + ValueRef::RawData(b) => { + out.extend_from_slice(b"tdta"); + u32_bytes(out, b.len() as u32); + out.extend_from_slice(b); + } + } + None +} +/// Append without cloning the model or staging serialized output. +/// +/// Traversal uses constant call-stack depth and O(nesting depth) heap frames. +/// Views must terminate, remain stable and contain no cycles. Existing bytes in +/// out are untouched; only count placeholders in newly appended data are patched. +pub fn append_descriptor(out: &mut Vec, descriptor: &dyn DescriptorView) { + let mut frames = vec![begin(out, Container::Descriptor(descriptor))]; + while let Some(mut frame) = frames.pop() { + let child = match frame.container { + Container::Descriptor(d) => match d.item(frame.index) { + Some((key, v)) => { + id(out, key); + Some(value(out, v)) + } + None => None, + }, + Container::List(list) => list.value(frame.index).map(|v| value(out, v)), + Container::References(refs) => refs.reference(frame.index).map(|v| { + reference(out, v); + None + }), + }; + let Some(child) = child else { + finish(out, frame); + continue; + }; + frame.count = frame.count.wrapping_add(1); + if let Some(index) = frame.index.checked_add(1) { + frame.index = index; + frames.push(frame); + } else { + // No further index is representable; patch the items actually emitted. + finish(out, frame); + } + if let Some(container) = child { + frames.push(begin(out, container)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + struct Node { + next: Option>, + kind: u8, + } + impl DescriptorView for Node { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, i: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + if i != 0 { + return None; + } + self.next.as_deref().map(|n| { + ( + IdRef::Code(*b"next"), + match self.kind % 3 { + 0 => ValueRef::Descriptor(n), + 1 => ValueRef::List(n), + _ => ValueRef::ObjectArray(7, n), + }, + ) + }) + } + } + impl ValuesView for Node { + fn value(&self, i: usize) -> Option> { + if i != 0 { + return None; + } + self.next.as_deref().map(|n| ValueRef::Descriptor(n)) + } + } + #[test] + fn deeply_mixed_views_use_heap_frames_not_recursive_calls() { + let mut node = Box::new(Node { next: None, kind: 0 }); + for kind in 0..12000 { + node = Box::new(Node { next: Some(node), kind: (kind % 3) as u8 }); + } + let mut out = vec![0xaa]; + append_descriptor(&mut out, node.as_ref()); + assert_eq!(out[0], 0xaa); + assert!(out.len() > 12000 * 8); + // Tear down the test model iteratively too; serializer never owns or drops it. + while let Some(next) = node.next.take() { + node = next; + } + } + struct Custom; + impl DescriptorView for Custom { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + match index { + 0 => Some((IdRef::Code(*b"one "), ValueRef::Integer(-1))), + 1 => Some((IdRef::Code(*b"list"), ValueRef::List(self))), + 2 => Some((IdRef::Code(*b"tail"), ValueRef::Boolean(true))), + _ => None, + } + } + } + impl ValuesView for Custom { + fn value(&self, _index: usize) -> Option> { + None + } + } + #[test] + fn counts_patch_emitted_items_and_empty_children_without_touching_prefix() { + let mut out = vec![9, 8]; + append_descriptor(&mut out, &Custom); + let mut expected = vec![9, 8, 0, 0, 0, 0, 0, 0, 0, 0]; + expected.extend(b"null"); + expected.extend([0, 0, 0, 3, 0, 0, 0, 0]); + expected.extend(b"one long"); + expected.extend([255, 255, 255, 255, 0, 0, 0, 0]); + expected.extend(b"listVlLs"); + expected.extend([0, 0, 0, 0, 0, 0, 0, 0]); + expected.extend(b"tailbool"); + expected.push(1); + assert_eq!(out, expected); + } + struct Raw<'a>(&'a [u8]); + impl DescriptorView for Raw<'_> { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, i: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + (i == 0).then_some((IdRef::Code(*b"data"), ValueRef::RawData(self.0))) + } + } + #[test] + fn large_payload_is_borrowed_and_appended_without_model_conversion() { + let bytes = vec![0xa5; 1024 * 1024]; + let view = Raw(&bytes); + let Some((_, ValueRef::RawData(slice))) = view.item(0) else { + panic!("raw view"); + }; + assert_eq!(slice.as_ptr(), bytes.as_ptr()); + let mut out = Vec::with_capacity(bytes.len() + 32); + append_descriptor(&mut out, &view); + assert_eq!(&out[32..], bytes); + } + + struct Gapped; + impl DescriptorView for Gapped { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + match index { + 0 => Some((IdRef::Code(*b"list"), ValueRef::List(self))), + 1 => Some((IdRef::Code(*b"refs"), ValueRef::Reference(self))), + 3 => panic!("descriptor must stop at first None"), + _ => None, + } + } + } + impl ValuesView for Gapped { + fn value(&self, index: usize) -> Option> { + match index { + 0 => Some(ValueRef::Integer(9)), + 2 => panic!("list must stop at first None"), + _ => None, + } + } + } + impl ReferencesView for Gapped { + fn reference(&self, index: usize) -> Option> { + match index { + 1 => panic!("reference must stop at first None"), + _ => None, + } + } + } + #[test] + fn first_absent_item_terminates_each_custom_container() { + let mut out = Vec::new(); + append_descriptor(&mut out, &Gapped); + let expected: Vec = + [&b"\0\0\0\0\0\0\0\0null\0\0\0\x02"[..], b"\0\0\0\0listVlLs\0\0\0\x01long\0\0\0\x09", b"\0\0\0\0refsobj \0\0\0\0"].concat(); + assert_eq!(out, expected); + } +} From adb9e769cab985991c125f3ef13f9d2ea97fb1b7 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 21:57:49 -0500 Subject: [PATCH 15/79] Add bounded borrowed certificate inspection views MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep wire evidence separate from existing verification and trust APIs. Inspection semantics acknowledge Afloat’s original Craft Anything raw-field and non-minimal-length contributions. --- crates/pkcs7/README.md | 9 ++ crates/pkcs7/src/inspection.rs | 184 ++++++++++++++++++++++++++++ crates/pkcs7/src/lib.rs | 1 + crates/pkcs7/tests/it/inspection.rs | 119 ++++++++++++++++++ crates/pkcs7/tests/it/main.rs | 1 + 5 files changed, 314 insertions(+) create mode 100644 crates/pkcs7/src/inspection.rs create mode 100644 crates/pkcs7/tests/it/inspection.rs diff --git a/crates/pkcs7/README.md b/crates/pkcs7/README.md index fc715c3b9d..b0339a848e 100644 --- a/crates/pkcs7/README.md +++ b/crates/pkcs7/README.md @@ -7,6 +7,11 @@ message or a digital ID file is made of. keeps its exact encoding, so a signed structure is verified over the bytes that were signed. Reading is strict DER; `parse_ber` also takes indefinite lengths and segmented strings, which PKCS #12 files from Windows use. Nesting is bounded. +- **`inspection`**: borrowed definite-length cursors without child-list allocations and borrowed X.509 wire fields. + Each sibling list is bounded to 4,096 elements and child cursors to depth 32; callers must + separately bound whole-document traversal. Redundant lengths are flagged. Optional and + trailing fields remain explicitly uninspected until their cursors are consumed. This is + evidence extraction, not a complete certificate validator or a signature/trust verdict. - **`x509`**: certificates (RFC 5280): names, validity, key, the extensions that matter for signing (basic constraints, key usage, extended key usage, key identifiers, OCSP and CRL locations), `build_chain` / `build_chain_noted` (issuers that may issue, path length, validity, @@ -42,3 +47,7 @@ Weak algorithms are read, not refused, because old signed documents use them: `DigestAlg::weakness` and `PublicKey::weakness` say when one is weak, and the caller decides. Moved from PdfCraft's `pdfcraft-sign`. + +The inspection profile follows Craft Anything’s bounded reader and Afloat’s raw-certificate +and non-minimal-length contributions (craft-anything #1131, #1514, #1646). Existing verification +and trust APIs are unchanged; high-level CMS/metadata adapters remain separate work. diff --git a/crates/pkcs7/src/inspection.rs b/crates/pkcs7/src/inspection.rs new file mode 100644 index 0000000000..93b9eed39c --- /dev/null +++ b/crates/pkcs7/src/inspection.rs @@ -0,0 +1,184 @@ +//! Bounded, borrowed inspection of definite-length ASN.1 and X.509 wire fields. +//! +//! These views are evidence, not validated certificates or signature/trust verdicts. They do +//! not replace [`crate::x509::Certificate`]. Unknown algorithms and original encodings are kept. +//! The profile follows Craft Anything's inspection reader (including Afloat's raw-field and +//! non-minimal-length work); callers retain their existing semantic and verification checks. + +use crate::der::{Tlv, tag}; + +/// Maximum siblings read by one cursor, matching the inspection consumer's bound. +pub const MAX_CHILDREN: usize = 4096; +/// Maximum nesting accepted when obtaining child cursors. Root elements have depth zero. +pub const MAX_DEPTH: usize = 32; + +/// An inspection stopped without establishing that the remaining bytes are complete. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum InspectionError { + #[error("malformed or unsupported definite-length element")] + Malformed, + #[error("inspection child limit reached")] + ChildLimit, + #[error("inspection depth limit reached")] + DepthLimit, + #[error("missing or unexpected certificate field")] + Field, +} + +/// One borrowed wire element. Redundant definite lengths are readable but explicitly noted. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Element<'a> { + tlv: Tlv<'a>, + depth: usize, + non_minimal_length: bool, +} + +impl<'a> Element<'a> { + pub fn tag(&self) -> u8 { + self.tlv.tag + } + pub fn raw(&self) -> &'a [u8] { + self.tlv.raw + } + pub fn value(&self) -> &'a [u8] { + self.tlv.value + } + pub fn non_minimal_length(&self) -> bool { + self.non_minimal_length + } + + /// Inspect children without allocating a child list. Primitive values are not interpreted as children. + pub fn children(&self) -> Result, InspectionError> { + if self.tlv.tag & 0x20 == 0 { + return Err(InspectionError::Field); + } + // Prevent callers following nested wire fields from silently exceeding the profile. + if self.depth >= MAX_DEPTH { + return Err(InspectionError::DepthLimit); + } + Ok(Cursor::at_depth(self.tlv.value, self.depth + 1)) + } +} + +/// A non-recursive sibling cursor with a hard per-list work bound and no child-list allocation. +/// +/// Successful reads allocate no memory; the underlying parser may allocate an error message. +/// `Ok(None)` means complete input, never a malformed/limited prefix. Errors are sticky and +/// leave the offending remainder available. Separate cursors have separate sibling budgets; +/// this does not impose a global budget on an application's traversal of many lists. +#[derive(Clone, Debug)] +pub struct Cursor<'a> { + remaining: &'a [u8], + count: usize, + depth: usize, + stopped: Option, +} + +impl<'a> Cursor<'a> { + pub fn new(input: &'a [u8]) -> Self { + Self::at_depth(input, 0) + } + fn at_depth(input: &'a [u8], depth: usize) -> Self { + Self { remaining: input, count: 0, depth, stopped: None } + } + /// Bytes not yet inspected. An empty remainder alone is not a recursive DER validation. + pub fn remaining(&self) -> &'a [u8] { + self.remaining + } + pub fn next_element(&mut self) -> Result>, InspectionError> { + if let Some(error) = self.stopped { + return Err(error); + } + if self.remaining.is_empty() { + return Ok(None); + } + if self.count == MAX_CHILDREN { + self.stopped = Some(InspectionError::ChildLimit); + return Err(InspectionError::ChildLimit); + } + let input = self.remaining; + let (tlv, rest) = match Tlv::parse(input) { + Ok(value) => value, + Err(_) => { + self.stopped = Some(InspectionError::Malformed); + return Err(InspectionError::Malformed); + } + }; + let non_minimal_length = input.get(1).is_some_and(|b| b & 0x80 != 0) && (input.get(2) == Some(&0) || tlv.value.len() < 128); + self.remaining = rest; + self.count += 1; + Ok(Some(Element { tlv, depth: self.depth, non_minimal_length })) + } + fn required(&mut self, expected: u8) -> Result, InspectionError> { + self.next_element()?.filter(|e| e.tag() == expected).ok_or(InspectionError::Field) + } +} + +/// Borrowed required X.509 wire fields, without algorithm, signature, key or trust validation. +/// +/// The BIT STRING is retained whole, including its unused-bit count. Both AlgorithmIdentifier +/// encodings are retained independently: their equality and parameter policy are the verifier's +/// responsibility. Optional/trailing fields remain in bounded cursors rather than being silently +/// reported as complete. Parsing this view does not walk nested names, keys or extensions. +#[derive(Clone, Debug)] +pub struct CertificateView<'a> { + pub certificate: Element<'a>, + pub tbs: Element<'a>, + pub version: Option>, + pub serial: Element<'a>, + pub signed_algorithm: Element<'a>, + pub issuer: Element<'a>, + pub validity: Element<'a>, + pub subject: Element<'a>, + pub spki: Element<'a>, + pub signature_algorithm: Element<'a>, + pub signature_bits: Element<'a>, + pub remaining_certificate_fields: Cursor<'a>, + pub remaining_tbs_fields: Cursor<'a>, +} + +impl<'a> CertificateView<'a> { + /// Inspect required fields of the first certificate; return bytes following its outer TLV. + /// Readable prefixes do not imply complete optional fields. Inspect the returned cursors to + /// distinguish complete, malformed, and limited tails. Existing strict verification stays separate. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> { + let mut roots = Cursor::new(input); + let certificate = roots.required(tag::SEQUENCE)?; + let mut outer = certificate.children()?; + let tbs = outer.required(tag::SEQUENCE)?; + let signature_algorithm = outer.required(tag::SEQUENCE)?; + let signature_bits = outer.required(tag::BIT_STRING)?; + let mut fields = tbs.children()?; + let first = fields.next_element()?.ok_or(InspectionError::Field)?; + let (version, serial) = if first.tag() == tag::ctx(0) { + (Some(first), fields.required(tag::INTEGER)?) + } else if first.tag() == tag::INTEGER { + (None, first) + } else { + return Err(InspectionError::Field); + }; + let signed_algorithm = fields.required(tag::SEQUENCE)?; + let issuer = fields.required(tag::SEQUENCE)?; + let validity = fields.required(tag::SEQUENCE)?; + let subject = fields.required(tag::SEQUENCE)?; + let spki = fields.required(tag::SEQUENCE)?; + Ok(( + Self { + certificate, + tbs, + version, + serial, + signed_algorithm, + issuer, + validity, + subject, + spki, + signature_algorithm, + signature_bits, + remaining_certificate_fields: outer, + remaining_tbs_fields: fields, + }, + roots.remaining(), + )) + } +} diff --git a/crates/pkcs7/src/lib.rs b/crates/pkcs7/src/lib.rs index 776be2749e..0b501515d5 100644 --- a/crates/pkcs7/src/lib.rs +++ b/crates/pkcs7/src/lib.rs @@ -29,6 +29,7 @@ pub mod cms; pub mod der; mod ec512; +pub mod inspection; pub mod keys; pub mod pkcs12; pub mod revocation; diff --git a/crates/pkcs7/tests/it/inspection.rs b/crates/pkcs7/tests/it/inspection.rs new file mode 100644 index 0000000000..e079a19f51 --- /dev/null +++ b/crates/pkcs7/tests/it/inspection.rs @@ -0,0 +1,119 @@ +//! Benign wire parity and boundary tests; no signature/trust decisions are made by these views. +use craft_pkcs7::der::{self, tag}; +use craft_pkcs7::inspection::{CertificateView, Cursor, InspectionError, MAX_CHILDREN, MAX_DEPTH}; + +#[test] +fn cursor_keeps_exact_bytes_and_length_notes() { + for (encoded, note) in [(vec![4, 3, 1, 2, 3], false), (vec![4, 0x81, 3, 1, 2, 3], true), (vec![4, 0x82, 0, 3, 1, 2, 3], true)] { + let mut cursor = Cursor::new(&encoded); + let element = cursor.next_element().unwrap().unwrap(); + assert_eq!(element.raw(), encoded); + assert_eq!(element.raw().as_ptr(), encoded.as_ptr()); + assert_eq!(element.value(), &[1, 2, 3]); + assert_eq!(element.non_minimal_length(), note); + assert_eq!(cursor.next_element(), Ok(None)); + } + let canonical = der::octets(&[7; 128]); + assert!(!Cursor::new(&canonical).next_element().unwrap().unwrap().non_minimal_length()); +} + +#[test] +fn cursor_distinguishes_completion_and_sticky_partial_results() { + let bytes = [5, 0, 4]; // One complete NULL followed by an incomplete header. + let mut cursor = Cursor::new(&bytes); + assert_eq!(cursor.next_element().unwrap().unwrap().tag(), tag::NULL); + assert_eq!(cursor.next_element(), Err(InspectionError::Malformed)); + assert_eq!(cursor.next_element(), Err(InspectionError::Malformed)); + assert_eq!(cursor.remaining(), &[4]); + assert_eq!(Cursor::new(&[0x30, 0x80, 0, 0]).next_element(), Err(InspectionError::Malformed)); + assert_eq!(Cursor::new(&[0x30, 0]).next_element().unwrap().unwrap().raw(), &[0x30, 0]); +} + +#[test] +fn sibling_limit_allows_exact_completion_without_allocating_a_child_list() { + let mut bytes = [5, 0].repeat(MAX_CHILDREN); + let mut cursor = Cursor::new(&bytes); + for _ in 0..MAX_CHILDREN { + assert!(cursor.next_element().unwrap().is_some()); + } + assert_eq!(cursor.next_element(), Ok(None)); + bytes.extend_from_slice(&[5, 0]); + let mut cursor = Cursor::new(&bytes); + for _ in 0..MAX_CHILDREN { + cursor.next_element().unwrap(); + } + assert_eq!(cursor.next_element(), Err(InspectionError::ChildLimit)); + assert_eq!(cursor.next_element(), Err(InspectionError::ChildLimit)); + assert_eq!(cursor.remaining(), &[5, 0]); +} + +#[test] +fn nested_cursor_depth_is_explicitly_bounded() { + let mut bytes = der::seq(&[]); + for _ in 0..MAX_DEPTH { + bytes = der::seq(&[&bytes]); + } + let mut element = Cursor::new(&bytes).next_element().unwrap().unwrap(); + for _ in 0..MAX_DEPTH { + element = element.children().unwrap().next_element().unwrap().unwrap(); + } + assert!(matches!(element.children(), Err(InspectionError::DepthLimit))); +} + +fn certificate(version: bool, tail: &[u8]) -> (Vec, Vec, Vec, Vec) { + // Unknown algorithms are still inspectable. These are wire fixtures, not signed certificates. + let algorithm = der::seq(&[&der::oid("1.2.3.4"), &der::tlv(tag::NULL, &[])]); + let name = der::seq(&[]); + let spki = der::seq(&[&algorithm, &der::bit_string(&[1, 2, 3])]); + let version_field = if version { der::explicit(0, &der::int(2)) } else { vec![] }; + let tbs = der::seq(&[&version_field, &der::int(7), &algorithm, &name, &der::seq(&[]), &name, &spki, tail]); + let cert = der::seq(&[&tbs, &algorithm, &der::bit_string(&[9, 8, 7])]); + (cert, tbs, algorithm, spki) +} + +#[test] +fn certificate_fields_are_borrowed_exact_and_do_not_consume_trailing_input() { + for version in [false, true] { + let (mut bytes, tbs, algorithm, spki) = certificate(version, &[]); + let len = bytes.len(); + bytes.extend_from_slice(&[5, 0]); + let (mut view, rest) = CertificateView::parse(&bytes).unwrap(); + assert_eq!(view.certificate.raw(), &bytes[..len]); + assert_eq!(view.certificate.raw().as_ptr(), bytes.as_ptr()); + assert_eq!(view.tbs.raw(), tbs); + assert_eq!(view.signed_algorithm.raw(), algorithm); + assert_eq!(view.signature_algorithm.raw(), algorithm); + assert_eq!(view.spki.raw(), spki); + assert_eq!(view.serial.value(), &[7]); + assert_eq!(view.signature_bits.value(), &[0, 9, 8, 7]); + assert_eq!(view.version.is_some(), version); + assert_eq!(rest, &[5, 0]); + assert_eq!(view.remaining_tbs_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_certificate_fields.next_element(), Ok(None)); + } +} + +#[test] +fn required_fields_do_not_hide_optional_tail_diagnostics() { + let (bytes, _, _, _) = certificate(false, &[0xa3]); + let (mut view, _) = CertificateView::parse(&bytes).unwrap(); + assert_eq!(view.remaining_tbs_fields.remaining(), &[0xa3]); + assert_eq!(view.remaining_tbs_fields.next_element(), Err(InspectionError::Malformed)); + // This partial wire view is deliberately not accepted as a validated certificate. + assert!(craft_pkcs7::Certificate::parse(&bytes).is_err()); +} + +#[test] +fn existing_certificate_fixture_retains_signed_components() { + let cert = craft_pkcs7::x509::load_certificates(include_bytes!("../data/ca.crt.pem")).unwrap().remove(0); + let (view, rest) = CertificateView::parse(&cert.raw).unwrap(); + assert!(rest.is_empty()); + let parts = cert.clone().into_parts(); + assert_eq!(view.tbs.raw(), parts.tbs); + assert_eq!(view.signature_algorithm.raw(), parts.sig_alg); + assert_eq!(view.signature_bits.value().first(), Some(&0)); + assert_eq!(&view.signature_bits.value()[1..], parts.signature); + assert_eq!(view.issuer.raw(), parts.issuer.raw); + assert_eq!(view.subject.raw(), parts.subject.raw); + assert_eq!(view.spki.raw(), parts.public_key.spki()); +} diff --git a/crates/pkcs7/tests/it/main.rs b/crates/pkcs7/tests/it/main.rs index 4a10ec7935..c4a2f0fbae 100644 --- a/crates/pkcs7/tests/it/main.rs +++ b/crates/pkcs7/tests/it/main.rs @@ -5,4 +5,5 @@ mod ber; mod chain; mod cms; mod crypto; +mod inspection; mod store_keys; From c24d572c8fa6ac80a1967da050121ad19b8cbe6e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 22:03:03 -0500 Subject: [PATCH 16/79] Add private bounded CMS wire prefix views --- crates/pkcs7/src/inspection.rs | 2 + crates/pkcs7/src/inspection/cms.rs | 98 +++++++++++++++++++++++++ crates/pkcs7/tests/it/inspection_cms.rs | 56 ++++++++++++++ crates/pkcs7/tests/it/main.rs | 2 + 4 files changed, 158 insertions(+) create mode 100644 crates/pkcs7/src/inspection/cms.rs create mode 100644 crates/pkcs7/tests/it/inspection_cms.rs diff --git a/crates/pkcs7/src/inspection.rs b/crates/pkcs7/src/inspection.rs index 93b9eed39c..aacc6aa94b 100644 --- a/crates/pkcs7/src/inspection.rs +++ b/crates/pkcs7/src/inspection.rs @@ -7,6 +7,8 @@ use crate::der::{Tlv, tag}; +pub mod cms; + /// Maximum siblings read by one cursor, matching the inspection consumer's bound. pub const MAX_CHILDREN: usize = 4096; /// Maximum nesting accepted when obtaining child cursors. Root elements have depth zero. diff --git a/crates/pkcs7/src/inspection/cms.rs b/crates/pkcs7/src/inspection/cms.rs new file mode 100644 index 0000000000..0d63c64add --- /dev/null +++ b/crates/pkcs7/src/inspection/cms.rs @@ -0,0 +1,98 @@ +//! Borrowed CMS wire prefixes. These do not validate signed attributes or authenticate signers. +//! Optional/remaining fields are explicit cursors, governed by the parent inspection bounds. + +use super::{Cursor, Element, InspectionError}; +use crate::der::tag; + +/// Required SignedData fields inside ContentInfo, without copying certificates or content. +/// All optional certificate/CRL/signer sets remain in `remaining_fields` for bounded inspection. +#[derive(Clone, Debug)] +pub struct SignedDataView<'a> { + pub content_info: Element<'a>, + pub signed_data: Element<'a>, + pub version: Element<'a>, + pub digest_algorithms: Element<'a>, + pub encapsulated_content: Element<'a>, + pub remaining_fields: Cursor<'a>, + pub remaining_explicit_fields: Cursor<'a>, + pub remaining_content_info_fields: Cursor<'a>, +} + +impl<'a> SignedDataView<'a> { + /// Read the required prefix and retain every tail. Matching the ContentInfo OID is not a + /// signature check. Encapsulated content, certificates, attributes and identities are unvalidated. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> { + let mut roots = Cursor::new(input); + let content_info = roots.required(tag::SEQUENCE)?; + let mut fields = content_info.children()?; + let kind = fields.required(tag::OID)?; + if kind.value() != [0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 1, 7, 2] { + return Err(InspectionError::Field); + } + let explicit = fields.required(tag::ctx(0))?; + let mut wrapped = explicit.children()?; + let signed_data = wrapped.required(tag::SEQUENCE)?; + let mut inner = signed_data.children()?; + let version = inner.required(tag::INTEGER)?; + let digest_algorithms = inner.required(tag::SET)?; + let encapsulated_content = inner.required(tag::SEQUENCE)?; + Ok(( + Self { + content_info, + signed_data, + version, + digest_algorithms, + encapsulated_content, + remaining_fields: inner, + remaining_explicit_fields: wrapped, + remaining_content_info_fields: fields, + }, + roots.remaining(), + )) + } +} + +/// One SignerInfo's raw required fields, not an authentication or identity-match result. +/// The identity remains its original issuer/serial SEQUENCE or context-specific key identifier. +/// Version consistency, algorithm policy, signed-attribute validation and re-encoding remain the +/// caller's responsibility; this view never substitutes an encapsulated content type or digest. +#[derive(Clone, Debug)] +pub struct SignerInfoView<'a> { + pub signer_info: Element<'a>, + pub version: Element<'a>, + pub identifier: Element<'a>, + pub digest_algorithm: Element<'a>, + pub signed_attributes: Option>, + pub signature_algorithm: Element<'a>, + pub signature: Element<'a>, + pub remaining_fields: Cursor<'a>, +} + +impl<'a> SignerInfoView<'a> { + /// Read one signer's required wire fields, retaining any optional tail and subsequent signers. + /// An absent signature field is an error, not an implicitly empty authenticated signature. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> { + let mut roots = Cursor::new(input); + let signer_info = roots.required(tag::SEQUENCE)?; + let mut fields = signer_info.children()?; + let version = fields.required(tag::INTEGER)?; + let identifier = fields.next_element()?.ok_or(InspectionError::Field)?; + if identifier.tag() != tag::SEQUENCE && identifier.tag() != tag::ctx_prim(0) { + return Err(InspectionError::Field); + } + let digest_algorithm = fields.required(tag::SEQUENCE)?; + let next = fields.next_element()?.ok_or(InspectionError::Field)?; + let (signed_attributes, signature_algorithm) = if next.tag() == tag::ctx(0) { + (Some(next), fields.required(tag::SEQUENCE)?) + } else if next.tag() == tag::SEQUENCE { + (None, next) + } else { + return Err(InspectionError::Field); + }; + let signature = fields.required(tag::OCTET_STRING)?; + Ok(( + Self { signer_info, version, identifier, digest_algorithm, signed_attributes, signature_algorithm, signature, remaining_fields: fields }, + roots.remaining(), + )) + } +} diff --git a/crates/pkcs7/tests/it/inspection_cms.rs b/crates/pkcs7/tests/it/inspection_cms.rs new file mode 100644 index 0000000000..4e7609f768 --- /dev/null +++ b/crates/pkcs7/tests/it/inspection_cms.rs @@ -0,0 +1,56 @@ +use craft_pkcs7::der::{self, tag}; +use craft_pkcs7::inspection::InspectionError; +use craft_pkcs7::inspection::cms::{SignedDataView, SignerInfoView}; + +fn fixture(key_id: bool, attrs: bool) -> (Vec, Vec) { + let digest = der::seq(&[&der::oid("2.16.840.1.101.3.4.2.1")]); + let sig_alg = der::seq(&[&der::oid("1.2.840.113549.1.1.1"), &der::tlv(tag::NULL, &[])]); + let identifier = if key_id { der::tlv(tag::ctx_prim(0), &[7, 8]) } else { der::seq(&[&der::seq(&[]), &der::int(7)]) }; + let attributes = if attrs { + let content = der::seq(&[&der::oid("1.2.840.113549.1.9.3"), &der::set_of(&[&der::oid("1.2.840.113549.1.7.1")])]); + let digest_attr = der::seq(&[&der::oid("1.2.840.113549.1.9.4"), &der::set_of(&[&der::octets(&[6; 32])])]); + der::tlv(tag::ctx(0), &[content, digest_attr].concat()) + } else { + vec![] + }; + let signer = der::seq(&[&der::int(if key_id { 3 } else { 1 }), &identifier, &digest, &attributes, &sig_alg, &der::octets(&[1, 2, 3])]); + let content = der::seq(&[&der::oid("1.2.840.113549.1.7.1"), &der::explicit(0, &der::octets(b"hello"))]); + let signed_data = der::seq(&[&der::int(1), &der::set_of(&[&digest]), &content, &der::set_of(&[&signer])]); + (der::seq(&[&der::oid("1.2.840.113549.1.7.2"), &der::explicit(0, &signed_data)]), signer) +} + +#[test] +fn cms_fields_retain_encodings_and_both_identifier_forms() { + for key_id in [false, true] { + for attrs in [false, true] { + let (cms, signer) = fixture(key_id, attrs); + let (mut view, rest) = SignedDataView::parse(&cms).unwrap(); + assert!(rest.is_empty()); + assert_eq!(view.content_info.raw().as_ptr(), cms.as_ptr()); + assert_eq!(view.version.value(), &[1]); + let signer_set = view.remaining_fields.next_element().unwrap().unwrap(); + let (mut si, rest) = SignerInfoView::parse(signer_set.value()).unwrap(); + assert_eq!(si.signer_info.raw(), signer); + assert!(rest.is_empty()); + assert_eq!(si.identifier.tag(), if key_id { 0x80 } else { 0x30 }); + assert_eq!(si.signed_attributes.is_some(), attrs); + assert_eq!(si.signature.value(), &[1, 2, 3]); + assert_eq!(si.remaining_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_explicit_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_content_info_fields.next_element(), Ok(None)); + } + } +} + +#[test] +fn signer_prefix_does_not_hide_optional_tail_or_consume_next_signer() { + let (_, signer) = fixture(false, true); + let parsed = der::Tlv::parse_all(&signer).unwrap(); + let with_tail = der::seq(&[parsed.value, &[0xa1]]); + let joined = [with_tail, signer.clone()].concat(); + let (mut view, rest) = SignerInfoView::parse(&joined).unwrap(); + assert_eq!(rest, signer); + assert_eq!(view.remaining_fields.next_element(), Err(InspectionError::Malformed)); + assert_eq!(view.remaining_fields.remaining(), &[0xa1]); +} diff --git a/crates/pkcs7/tests/it/main.rs b/crates/pkcs7/tests/it/main.rs index c4a2f0fbae..1c6616b398 100644 --- a/crates/pkcs7/tests/it/main.rs +++ b/crates/pkcs7/tests/it/main.rs @@ -7,3 +7,5 @@ mod cms; mod crypto; mod inspection; mod store_keys; + +mod inspection_cms; From a51b0f81db0a53558364a80b5e5957d4809b37f2 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 04:25:01 +0100 Subject: [PATCH 17/79] psd: share borrowed layer effects and solid color framing --- crates/psd/src/tagged.rs | 51 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs index 3bfc210d11..d433c2527e 100644 --- a/crates/psd/src/tagged.rs +++ b/crates/psd/src/tagged.rs @@ -686,6 +686,26 @@ pub(crate) fn write_blocks_to( Ok(()) } +/// Append the data of an lfx2 block: fixed version words 0 and 16, then a descriptor. +/// +/// No outer signature, key, length or padding is written. Existing output is preserved. +/// Descriptor semantics are the caller's responsibility; no values are normalized. +/// Views inherit the borrowed writer's finite, stable, acyclic contract and O(depth) +/// heap traversal. No owned model conversion or serialized temporary is created. +pub fn append_layer_effects_data(out: &mut Vec, descriptor: &dyn crate::descriptor::borrowed::DescriptorView) { + out.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 16]); + crate::descriptor::borrowed::append_descriptor(out, descriptor); +} + +/// Append the data of a SoCo block: fixed descriptor version 16, then a descriptor. +/// +/// This is data-only, with the same append and borrowed-view contract as +/// [append_layer_effects_data]. The caller supplies the color descriptor unchanged. +pub fn append_solid_color_data(out: &mut Vec, descriptor: &dyn crate::descriptor::borrowed::DescriptorView) { + out.extend_from_slice(&[0, 0, 0, 16]); + crate::descriptor::borrowed::append_descriptor(out, descriptor); +} + #[cfg(test)] mod tests { use super::*; @@ -938,4 +958,35 @@ mod tests { versioned.extend(raw); assert!(VersionedDescriptor::parse_prefix(&versioned).is_err()); } + + #[test] + fn borrowed_block_headers_append_literal_empty_and_nonempty_data() { + use crate::descriptor::borrowed::{ClassRef, DescriptorView, IdRef, UnicodeRef, ValueRef}; + struct View(bool); + impl DescriptorView for View { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + (self.0 && index == 0).then_some((IdRef::Code(*b"enab"), ValueRef::Boolean(true))) + } + } + for populated in [false, true] { + let mut descriptor = b"\0\0\0\0\0\0\0\0null\0\0\0".to_vec(); + descriptor.push(u8::from(populated)); + if populated { + descriptor.extend_from_slice(b"\0\0\0\0enabbool\x01"); + } + let mut effects = vec![0xa5, 0x5a]; + append_layer_effects_data(&mut effects, &View(populated)); + let mut expected = vec![0xa5, 0x5a, 0, 0, 0, 0, 0, 0, 0, 16]; + expected.extend_from_slice(&descriptor); + assert_eq!(effects, expected); + let mut color = vec![0xa5, 0x5a]; + append_solid_color_data(&mut color, &View(populated)); + let mut expected = vec![0xa5, 0x5a, 0, 0, 0, 16]; + expected.extend_from_slice(&descriptor); + assert_eq!(color, expected); + } + } } From 4e0c880f58d745befcf53ee6618414a0b1038544 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Wed, 18 Nov 2026 20:20:42 -0800 Subject: [PATCH 18/79] craft-csv: delimiter detection samples 65,536 characters, not 64 KiB (#2326) sniff_delimiter read the first 64 KiB of the text. A first field of three-byte characters longer than about 21,800 characters filled that sample before its delimiter, so a semicolon or tab file opened as comma-separated. The sample is now the first 65,536 characters, the amount detection read before it moved into craft-csv. The new test fails without the change: a first field of 65,535 three-byte characters followed by a semicolon is detected as comma. --- crates/csv/README.md | 2 +- crates/csv/src/lib.rs | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/crates/csv/README.md b/crates/csv/README.md index 8fd264d4c8..7df204e104 100644 --- a/crates/csv/README.md +++ b/crates/csv/README.md @@ -11,7 +11,7 @@ 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 64 KiB sample; 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; 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 | | `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 395ad21523..f4a82f393f 100644 --- a/crates/csv/src/lib.rs +++ b/crates/csv/src/lib.rs @@ -37,7 +37,7 @@ pub use decode::{decode_text, decode_utf8}; /// the same rules pick among the candidates whose records hold only their delimiters and /// whitespace, such as an exported row of empty cells; a candidate that finds a record with /// other text is left out of that pick. Comma is the fallback when neither pick finds one. -/// Only the first 64 KiB are read. A record cut off at the end of that sample is left out, +/// Only the first 65,536 characters are read. A record cut off at the end of that sample is left out, /// except when no candidate finds coherent complete records with a delimiter in each. Then a candidate /// that finds no complete record with other text counts the delimiters read so far in the first /// such record, unless it found rows of its empty cells and that record has none of its @@ -45,11 +45,8 @@ 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 { - const SAMPLE_BYTES: usize = 64 * 1024; - let mut sample_end = text.len().min(SAMPLE_BYTES); - while !text.is_char_boundary(sample_end) { - sample_end -= 1; - } + 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)); @@ -441,6 +438,15 @@ mod tests { assert_eq!(sniff_delimiter(&format!("a,b,c;\"hello,\";d\n{}", "x;y;z\n".repeat(12_000)), '"'), b';'); } + #[test] + fn delimiter_sniffing_samples_characters_not_bytes() { + // 30,000 three-byte characters are 90,000 bytes, more than 64 KiB. + assert_eq!(sniff_delimiter(&format!("{};b;c\n1;2;3\n", "€".repeat(30_000)), '"'), b';'); + // The 65,536th character is in the sample and the 65,537th is not. + assert_eq!(sniff_delimiter(&format!("{};x\n1;2\n", "€".repeat(65_535)), '"'), b';'); + assert_eq!(sniff_delimiter(&format!("{};x\n1;2\n", "€".repeat(65_536)), '"'), b','); + } + // A sheet whose only value is far down exports rows of empty cells that fill the whole sample. #[test] fn delimiter_sniffing_reads_a_sparse_semicolon_export() { From d2a7d88d2ea655a8618189cd27c06fbb007ba1b8 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:20:45 +0800 Subject: [PATCH 19/79] hayro-postscript: a `\ddd` escape above `\377` keeps its low eight bits (#2321) (#2324) A literal string's octal escape was converted with `u8::from_str_radix`, which fails above 0o377, so the byte was dropped. Read one to three octal digits into a u16 (at most 0o777) and push the low byte, as ISO 32000-2 7.3.4.2 and the PostScript Language Reference (third edition, 3.2.2) specify: "high-order overflow shall be ignored". Escapes up to `\377` decode as before. Record the patch in SOURCE.json and vendor/README.craft-reader.md. Fixes #2321 --- vendor/README.craft-reader.md | 9 ++- vendor/hayro-postscript/SOURCE.json | 7 ++- vendor/hayro-postscript/src/string.rs | 15 +++++ vendor/hayro-postscript/src/string/literal.rs | 57 ++++++++----------- 4 files changed, 50 insertions(+), 38 deletions(-) diff --git a/vendor/README.craft-reader.md b/vendor/README.craft-reader.md index 6487d1a59c..405799ceb6 100644 --- a/vendor/README.craft-reader.md +++ b/vendor/README.craft-reader.md @@ -42,12 +42,17 @@ Consuming workspaces need a `hayro-cmap` patch entry beside the other Hayro entr `hayro-postscript` 0.1.0 is the crates.io package (upstream revision a2354aebaf86f5ab13e5fd6b6b0521306488bf9d), the PostScript token scanner `hayro-cmap` uses -to parse the CMap streams PDFs embed. One local patch: the scanner, which does not parse +to parse the CMap streams PDFs embed. Two local patches. The scanner, which does not parse dictionaries yet, skips runs of `<<` and `>>` in a loop and returns the next object, instead of recursing once per delimiter, so a long run of `<` or `>` bytes no longer overflows the stack. Tests: `object::tests::long_open_dict_run_does_not_overflow`, `object::tests::long_close_dict_run_does_not_overflow`, `object::tests::dict_delimiters_are_skipped` -and `object::tests::nested_dict_delimiters_are_skipped`. Its `SOURCE.json` records the +and `object::tests::nested_dict_delimiters_are_skipped`. A literal string's `\ddd` escape keeps +the low eight bits of its value, as ISO 32000-2 §7.3.4.2 asks ("high-order overflow shall be +ignored"), so `\737` decodes to `0xDF` instead of being dropped; code comments label it +`Craft patch (octal overflow, craft-libs #2321)`. Tests: +`string::tests::literal_octal_overflow_keeps_the_low_eight_bits` and +`string::tests::literal_octal_short_escape_stops_at_a_non_octal_byte`. Its `SOURCE.json` records the registry hashes. Consuming workspaces need a `hayro-postscript` patch entry beside the other Hayro entries. diff --git a/vendor/hayro-postscript/SOURCE.json b/vendor/hayro-postscript/SOURCE.json index 2e4cc5a700..06e922bccd 100644 --- a/vendor/hayro-postscript/SOURCE.json +++ b/vendor/hayro-postscript/SOURCE.json @@ -8,7 +8,8 @@ "upstream_revision": "a2354aebaf86f5ab13e5fd6b6b0521306488bf9d", "upstream_directory": "hayro-postscript", "local_patches": [ - "Skip runs of `<<` and `>>` in a loop in `object::read` instead of recursing once per delimiter, so a long run cannot overflow the stack." + "Skip runs of `<<` and `>>` in a loop in `object::read` instead of recursing once per delimiter, so a long run cannot overflow the stack.", + "Keep the low eight bits of a literal string's `\\ddd` escape in `string::literal::decode_into` (ISO 32000-2 §7.3.4.2), instead of dropping an escape above `\\377`." ], "files": [ { @@ -99,7 +100,7 @@ "path": "src/string.rs", "source_sha256": "1c47947beb5ce7c56036d5b115a47e703a5a276cb9f3faf5e9b2a4304e4a518f", "source_git_blob": null, - "sha256": "1c47947beb5ce7c56036d5b115a47e703a5a276cb9f3faf5e9b2a4304e4a518f" + "sha256": "42bb4c6a7291165f3841333032f582c74145109443f9161065afc6881d2e9f2b" }, { "path": "src/string/ascii_85.rs", @@ -117,7 +118,7 @@ "path": "src/string/literal.rs", "source_sha256": "8633efbb282227512ef506d020ea69d4ef47c549ae9248e7b0d4fcefd2aaf933", "source_git_blob": null, - "sha256": "8633efbb282227512ef506d020ea69d4ef47c549ae9248e7b0d4fcefd2aaf933" + "sha256": "0feae923df7807fe671bc3d320bdcf5e1a65cb7b652aa9245b0b918376c1daf9" } ] } diff --git a/vendor/hayro-postscript/src/string.rs b/vendor/hayro-postscript/src/string.rs index ed39d57c73..26a8998478 100644 --- a/vendor/hayro-postscript/src/string.rs +++ b/vendor/hayro-postscript/src/string.rs @@ -187,6 +187,21 @@ mod tests { assert_eq!(decode_literal(b"(\\3)").unwrap(), b"\x03"); } + #[test] + fn literal_octal_overflow_keeps_the_low_eight_bits() { + assert_eq!(decode_literal(b"(\\737)").unwrap(), b"\xDF"); + assert_eq!(decode_literal(b"(\\400\\777)").unwrap(), b"\x00\xFF"); + assert_eq!(decode_literal(b"(\\1234)").unwrap(), b"S4"); + } + + #[test] + fn literal_octal_short_escape_stops_at_a_non_octal_byte() { + assert_eq!( + decode_literal(b"(\\36a\\3z\\0089)").unwrap(), + b"\x1ea\x03z\x0089" + ); + } + #[test] fn literal_line_continuation_lf() { assert_eq!(decode_literal(b"(Hi \\\nthere)").unwrap(), b"Hi there"); diff --git a/vendor/hayro-postscript/src/string/literal.rs b/vendor/hayro-postscript/src/string/literal.rs index 37a15934ff..be994f9f3a 100644 --- a/vendor/hayro-postscript/src/string/literal.rs +++ b/vendor/hayro-postscript/src/string/literal.rs @@ -12,38 +12,26 @@ pub(crate) fn decode_into(data: &[u8], out: &mut Vec) -> Option<()> { b'\\' => { let next = r.read_byte()?; - if is_octal_digit(next) { - let second = r.read_byte(); - let third = r.read_byte(); - - let bytes = match (second, third) { - (Some(n1), Some(n2)) => match (is_octal_digit(n1), is_octal_digit(n2)) { - (true, true) => [next, n1, n2], - (true, _) => { - r.jump(r.offset() - 1); - [b'0', next, n1] - } - _ => { - r.jump(r.offset() - 2); - [b'0', b'0', next] - } - }, - (Some(n1), None) => { - if is_octal_digit(n1) { - [b'0', next, n1] - } else { - r.jump(r.offset() - 1); - [b'0', b'0', next] - } - } - _ => [b'0', b'0', next], - }; - - let str = core::str::from_utf8(&bytes).unwrap(); - - if let Ok(num) = u8::from_str_radix(str, 8) { - out.push(num); + if let Some(first) = octal_digit(next) { + // Craft patch (octal overflow, craft-libs #2321): read one + // to three octal digits and keep the low eight bits of + // the value. "The number ddd may consist of one, two, or + // three octal digits; high-order overflow shall be + // ignored" (ISO 32000-2 §7.3.4.2; PostScript Language + // Reference, third edition, §3.2.2), so `\737` is 0xDF. + // Previously an escape above `\377` was dropped. + let mut value = first; + for _ in 0..2 { + let Some(digit) = r.peek_byte().and_then(octal_digit) else { + break; + }; + r.forward(); + // At most 0o777 after three digits, so no overflow. + value = value * 8 + digit; } + + // Truncation to the low byte is the overflow rule above. + out.push((value & 0xFF) as u8); } else { match next { b'n' => out.push(0xA), @@ -80,6 +68,9 @@ pub(crate) fn decode_into(data: &[u8], out: &mut Vec) -> Option<()> { Some(()) } -fn is_octal_digit(byte: u8) -> bool { - matches!(byte, b'0'..=b'7') +fn octal_digit(byte: u8) -> Option { + match byte { + b'0'..=b'7' => Some(u16::from(byte - b'0')), + _ => None, + } } From c39072d321c216f88f733369eb5514260f9a8e5e Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Wed, 18 Nov 2026 20:20:49 -0800 Subject: [PATCH 20/79] image-codecs: keep PrefixDetector tests within the prefix contract (#2277) PrefixDetector::detect requires each call's bytes to start with the previous call's bytes. Two integration tests passed a buffer that broke that rule, so a detector that rechecks the SOI before resuming would have failed them while still honoring the contract. The tests now pass longer prefixes of one file and compare each answer with detect_prefix on the same bytes. The check that a walk resumes at the marker it stopped at stays in the jpegls unit tests, and a new unit test checks that a walk that found a non-JPEG-LS frame header stays at that marker. --- crates/image-codecs/src/codecs/jpegls.rs | 11 +++++++++++ crates/image-codecs/tests/it/detect_caps.rs | 21 +++++++-------------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/crates/image-codecs/src/codecs/jpegls.rs b/crates/image-codecs/src/codecs/jpegls.rs index aa65793495..3c7d5920a4 100644 --- a/crates/image-codecs/src/codecs/jpegls.rs +++ b/crates/image-codecs/src/codecs/jpegls.rs @@ -924,6 +924,17 @@ mod tests { assert_eq!(jpeg_frame(&file), Some(JpegFrame::Ls)); } + #[test] + fn a_walk_that_found_another_frame_header_stays_at_it() { + // SOI, a comment with two bytes of text, then a baseline frame header. + let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xC0, 0, 11]; + let mut pos = 0; + assert_eq!(jpeg_frame_from(&file, &mut pos), Some(JpegFrame::Other)); + assert_eq!(pos, 8); + assert_eq!(jpeg_frame_from(&file, &mut pos), Some(JpegFrame::Other)); + assert_eq!(pos, 8); + } + #[test] fn interleaved_scans_and_tables_are_unsupported() { let img = image(8, 4, ChannelLayout::Rgb, false, 2); diff --git a/crates/image-codecs/tests/it/detect_caps.rs b/crates/image-codecs/tests/it/detect_caps.rs index 76e8bc5847..ee9ccda515 100644 --- a/crates/image-codecs/tests/it/detect_caps.rs +++ b/crates/image-codecs/tests/it/detect_caps.rs @@ -422,17 +422,13 @@ fn a_stuffed_zero_where_a_marker_should_be_is_jpeg() { } #[test] -fn a_detector_that_found_a_jpeg_frame_does_not_walk_again() { +fn a_detector_that_found_a_jpeg_frame_keeps_answering_jpeg() { // SOI, a comment with two bytes of text, then a baseline frame header. let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xC0, 0, 11]; let mut detector = PrefixDetector::new(); + assert_eq!(detector.detect(&file[..10]), Detection::Format(Format::Jpeg)); + assert_eq!(detector.detect(&file), detect_prefix(&file)); assert_eq!(detector.detect(&file), Detection::Format(Format::Jpeg)); - // With an SOF55 marker where the comment marker was, a walk from the SOI finds JPEG-LS. The - // detector starts at the baseline frame header it stopped at and still answers JPEG. - let mut changed = file; - changed[3] = 0xF7; - assert_eq!(detect_prefix(&changed), Detection::Format(Format::JpegLs)); - assert_eq!(detector.detect(&changed), Detection::Format(Format::Jpeg)); } #[test] @@ -440,14 +436,11 @@ fn a_detector_keeps_its_place_between_calls() { // SOI, a comment with two bytes of text, then an SOF55 frame header. let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xF7, 0, 11]; let mut detector = PrefixDetector::new(); + assert_eq!(detector.detect(&file[..5]), Detection::NeedBytes(6)); assert_eq!(detector.detect(&file[..9]), Detection::NeedBytes(10)); - // The next call starts at the frame header's marker and does not read the bytes before it - // again: with them cleared, the detector still finds JPEG-LS, while a walk from the start - // finds no SOI. - let mut cleared = file; - cleared[..8].fill(0); - assert_ne!(detect_prefix(&cleared), Detection::Format(Format::JpegLs)); - assert_eq!(detector.detect(&cleared), Detection::Format(Format::JpegLs)); + // Each call extends the previous prefix, and the answer matches a walk from the SOI. + assert_eq!(detector.detect(&file), detect_prefix(&file)); + assert_eq!(detect_prefix(&file), Detection::Format(Format::JpegLs)); } #[cfg(feature = "sunraster")] From cbf6840b1047e984202891b31fe794cd3fc5bacf Mon Sep 17 00:00:00 2001 From: keithcsqueensu <92232107+keithcsqueensu@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:23:02 -0500 Subject: [PATCH 21/79] Add craft-ppt-binary: DeckCraft's PowerPoint 97-2003 reader on craft-cfb and craft-pptx (#2316) * ppt-binary: open PowerPoint 97-2003 .ppt/.pot/.pps files New crate deckcraft-ppt (L3), written from the public [MS-CFB], [MS-PPT] and [MS-ODRAW] Open Specifications: a compound-file reader (ported from FilmCraft's clean-room reader), the edit chain and persist directory, and the OfficeArt drawings. Main masters become masters (colours, fonts, text styles, background, decorations), title masters become layouts; slides keep their shapes (presets, freeforms, groups, rotation, flips), fills, lines, shadows, pictures (PNG, JPEG, DIB, TIFF, EMF, WMF), text with the master styles resolved into it, fields, notes and hidden flags. Import only: an opened .ppt has no save path, so Save asks for a new name. A .pps from the system starts the slide show. File dialogs, drag and drop, the web shell and the macOS, Windows and Linux file associations offer the three extensions. Tests build .ppt files from records and sweep hostile input. From storytold/deckcraft@0aef89cb1a (storytold/deckcraft#1137). * ppt-binary: address review: budget picture decoding, read each persist directory once, macOS .pot/.pps types - Pictures decode lazily, when a shape first uses them, each at most once and all within a shared 4 GiB budget: many store entries pointing at one deflated blob can no longer ask for unbounded memory. - A persist directory named by many edits is read once. - Info.plist declares com.microsoft.powerpoint.pot and .pps alongside .ppt. From storytold/deckcraft@9e575ccecc (storytold/deckcraft#1137). * ppt-binary: address review: check the picture budget before copying bitmap data From storytold/deckcraft@470a429392 (storytold/deckcraft#1137). * ppt-binary: build against current main - convert.rs: set `flip: None` on imported gradients. `Gradient` gained the field in ad97533a; None is what an unflipped gradient was before. - tests.rs: split `imports_a_presentation` into one check per section (title, picture, group, text box, master) for the workspace `cognitive_complexity` lint (6ddd2fb8). The assertions are unchanged. - Cargo.lock: deckcraft-ppt takes the workspace version, 0.15.0. From storytold/deckcraft@a0ececefeb (storytold/deckcraft#1137). * ppt-binary: keep the picture budget on 32-bit targets `MAX_TOTAL` was `4 << 30` as a `usize`. On wasm32 that is 2^32, which wraps to 0 without any error, so the web build's picture budget was zero and every .ppt picture was dropped. Use the address space as the limit there. A compile-time assertion that the budget holds at least one picture keeps it from happening again on any target: the CI wasm step (`cargo check`) now fails if it does. From storytold/deckcraft@4fd930ce1a (storytold/deckcraft#1137). * ppt-binary: read past the character fields PowerPoint 2002 and later add A TextCFException can end with pp10runid (mask bit 20), newEAFontRef (24), csFontRef (25) and pp11ext (26), after `position`. read_cf stopped at `position`, so in a StyleTextPropAtom the next run's count and mask were read from the leftover bytes, and every later run got garbage formatting or the walk ended. Master text styles go through the same reader. The fields are read past and not used. The test has a run carrying all four followed by a bold 18 pt run, which now reads as written. From storytold/deckcraft@773af639c9 (storytold/deckcraft#1137). * ppt-binary: convert each listed object once and index notes pages Nothing stopped a slide list from naming one persist object many times, and each listing converted its whole drawing again: a 100k-shape slide listed 180k times fits in about 10 MB and makes 1.8e10 shapes. An object is now listed once across the slide, master and notes lists (PowerPoint never lists one twice), and a repeat is logged and skipped. Notes pages are looked up through a map built once, instead of a scan per slide (slides x notes). The first matching page still wins. From storytold/deckcraft@b3aa0983bd (storytold/deckcraft#1137). * ppt-binary: find formatting runs by binary search paragraphs() found the run at a position (rposition) and the next run start (find) by scanning the run starts for every run, break and field, so text cost grew with chars x runs. The starts are a running sum and never decrease, so both lookups are now partition_point. Measured in a debug build, 640k one-character runs (about 6 MB of file): 75 s before, about 2 s after. The test uses a 20 s bound, like render's pathgrad budget test. From storytold/deckcraft@b70b022362 (storytold/deckcraft#1137). * ppt-binary: cap decoded pictures at the .pptx package total The picture budget was 4 GiB, so a few MB of small deflated metafiles, each inflating to 64 MiB, could make the import hold 4 GiB. A .pptx package may inflate to 2 GiB in total (deckcraft-pptx opc MAX_TOTAL), and pictures are the only part of a .ppt this crate inflates, so use the same 2 GiB. That also fits a 32-bit usize, which replaces the wasm32 special case. This is a limit change, so there is no new test: the budget test (the_store_decodes_lazily_within_a_budget) and the compile-time check that the budget holds a picture still cover it. From storytold/deckcraft@a9cefff8b8 (storytold/deckcraft#1137). * ppt-binary: fall back to the first main master the same way every time A slide naming a master that doesn't exist fell back to the lowest index in the masters HashMap. A title master is stored with its main master's index, so the two tied and the HashMap's random order picked one: the same file got the "Title Master" layout on some opens and the main master's on others. The fallback now considers main masters only. The test opens such a deck 30 times; before the fix it took the title master's layout within those opens. From storytold/deckcraft@60942d5950 (storytold/deckcraft#1137). * ppt-binary: try the edit scan before calling a file too old Any Current User token other than the plain or encrypted one, including none at all from a truncated record, returned TooOld at once. A PowerPoint 97 file with a damaged Current User stream was reported as "made by PowerPoint 95 or earlier", and the UserEditAtom scan meant for a missing stream never ran. [MS-PPT] allows only those two tokens, so an unknown one can't tell a damaged file from an older format. The scan now runs, and TooOld is returned only when it finds no edit record behind an unknown token. From storytold/deckcraft@3869c3dc51 (storytold/deckcraft#1137). * ppt-binary: read persist directories within one stream's worth of words dirs_seen only skips a directory named at the same offset again. Directories nested inside one another, each named by its own UserEditAtom, were each read to the end of the stream: MAX_EDITS x the stream. In a debug build, 4095 such edits over a 64 MiB stream took about 48 s. All directories now share a budget of stream.len() / 4 words. Real directories are separate records inside the stream, so they always fit. The hostile case stops in milliseconds and is reported as damaged. From storytold/deckcraft@5799048d88 (storytold/deckcraft#1137). * ppt-binary: check two additions on input-derived sizes - cfb.rs: the mini sector end `at + MINI_SECTOR_SIZE` was unchecked. On a 32-bit target (wasm32), a sector number near 0x03FF_FFFF puts `at` at the top of usize, so the add panics in a debug build and wraps in release. - text.rs: the style-run total `chars.len() as u32 + 1` truncated and could overflow past u32::MAX characters. It now saturates. Neither case can be reached in a native test (one needs a 32-bit target, the other more than 4 GiB of text), so there is no new test. The `+ 1`s in convert.rs paragraphs() that the review also named are bounded by the text length and can't overflow, so they are unchanged. From storytold/deckcraft@b58c354246 (storytold/deckcraft#1137). * ppt-binary: a sector chain that revisits a sector is an error read_chain stopped at the stream's size, so a FAT loop shorter than the stream returned the looped sectors again as the stream's bytes. It now tracks visited sectors and fails on a revisit, and reserves the stream's size (capped at the file length) up front. a_looping_chain_stops expected the repeated bytes; it now expects the error (eliets2's review). From storytold/deckcraft@2b0940bff5 (storytold/deckcraft#1137). * ppt-binary: slide shapes inherit from their own master's shapes Master shape properties were remembered by shape id alone, so a later master (a title master, or a second main master) that reused a shape id replaced the first master's entry, and slides inherited fill and line from the wrong master. They are now keyed by master slide id and shape id, and a shape's hspMaster is looked up in its slide's master, then a title master's main master. Notes pages have no imported master, so they inherit nothing. PowerPoint gives shapes file-unique ids, so this takes a damaged or generated file (eliets2's review). From storytold/deckcraft@7ad2f5152b (storytold/deckcraft#1137). * ppt-binary: drop the unused fBackground field RawShape.background was set from the FSP flag but never read: the background shape is the drawing container's own shape (OfficeArtDgContainer.shape, [MS-ODRAW] 2.2.13), which drawing() already takes. The comment there now says so (eliets2's review). From storytold/deckcraft@afd57f47e0 (storytold/deckcraft#1137). * ppt-binary: shadowed text keeps its shadow TextCFException's shadow bit was read and merged but never reached the run. A shadowed run now gets a shadow in the colour scheme's shadow colour, at the distance and direction of the app's own Text Shadow command, with no blur (the record has none). Emboss has no counterpart in the model, so its field is gone and the loss is listed in the docs (eliets2's review). From storytold/deckcraft@ab5cf618e1 (storytold/deckcraft#1137). * ppt-binary: the .pps show-on-open test opens a real 97-2003 file a_ppsx_from_the_system_starts_the_show saved a .pptx under the name "Old talk.pps", so it went through the PPTX path and never reached the legacy importer. crates/ppt/tests/fixtures/old-talk.pps is a one-slide .pps built from records by the ppt tests (rebuilt with DECKCRAFT_WRITE_PPT_FIXTURE=1, checked on every run), attributed CC0 like the other generated fixtures, and the UI test opens it (eliets2's review). From storytold/deckcraft@f511a2a66b (storytold/deckcraft#1137). * ppt-binary: test mini streams, 4096-byte sectors and the DIFAT chain The compound-file test builder only made version-3 files with 512-byte sectors, no mini stream and every FAT sector in the header, so read_mini_chain, 4096-byte sectors and the DIFAT chain never ran. build_with takes the sector shift and the mini stream cutoff, and lists FAT sectors past the header's 109 in DIFAT sectors; build is build_with(streams, 9, 0), so existing tests see the same layout. Three tests read streams back through each path (eliets2's review). From storytold/deckcraft@212788b693 (storytold/deckcraft#1137). * ppt-binary: test every picture kind, two-UID blips and blips inside the FBSE The blip tests covered PNG, deflated WMF and DIB only. New tests decode JPEG (RGB and CMYK), TIFF and PNG with one and two UIDs, an uncompressed EMF with each UID count, a metafile over the budget (compressed or not), and a blip held inside its FBSE rather than in the Pictures stream. All passed as written (eliets2's review). From storytold/deckcraft@fe8023b9c2 (storytold/deckcraft#1137). * ppt-binary: placeholder text held only in the slide list is imported A shape's client text box may hold just an OutlineTextRefAtom, with no TextHeaderAtom ([MS-PPT] OfficeArtClientTextbox): the text lives in the slide list, and that is the usual form for slide placeholders. read_block returned None without a header, so text_block never reached its outline fallback and the placeholder came in empty. A block with a reference and no header is now returned for the caller to follow. placeholder_text_can_come_from_the_slide_list covers the reference alone (it failed before this change) and a header with a reference; the test document builder can put outline blocks in the slide list (streams_with_outline). Found writing the test eliets2's review asked for. From storytold/deckcraft@bf8ec603f3 (storytold/deckcraft#1137). * ppt-binary: test newer edits and the two other encryption signs doc::read had tests for one edit and the Current User token only. a_later_edit_replaces_a_slide adds an edit whose persist directory gives the slide a new object; the newer slide is imported and the master from the older directory is kept. encryption_is_found_in_the_edit_and_the_persist_directory covers an edit record long enough for encryptSessionPersistIdRef and a CryptSession object named by a later edit. Both passed as written (eliets2's review). From storytold/deckcraft@f0b8525cc6 (storytold/deckcraft#1137). * ppt-binary: test title masters and slides that follow nothing No test made a slide of a title master or a slide with the follow-master flags off. The new test checks that a title master becomes a "Title Master" layout with its own background and shapes and without the master's shapes, that its slide uses that layout and follows its background, and that a slide with all three flags off keeps its own background and colour scheme and hides the master's shapes. It passed as written (eliets2's review). From storytold/deckcraft@a41bf545e7 (storytold/deckcraft#1137). * ppt-binary: merge boolean properties flag by flag A boolean property word holds sixteen flags, each with its own fUse bit. Props::inherit and add_table kept the whole word from the most specific set, so a placeholder or text box that set only fNoFillHitTest lost the inherited "not filled" and "no line" and was drawn with a fill and an outline. Merge those words per flag instead (storytold/deckcraft#1137 review, issue 1). From storytold/deckcraft@79ae833152 (storytold/deckcraft#1137). * ppt-binary: recover a broken edit chain and report lost slides An edit whose previous-edit offset points back at itself (or anywhere that isn't an edit) cut the older edits off, and with them the persist directories holding the slides: such a file opened as an empty deck with no warning. When the chain doesn't end at offset 0, read every edit's persist directory in the stream, newest first, filling only what the chain left unset. Slides the slide list names but whose objects are still missing are now returned by deckcraft_ppt::import_checked and reported like a damaged .pptx: lostSlides, a "(Repaired)" copy and the CLI warning (storytold/deckcraft#1137 review, issue 3). From storytold/deckcraft@135674101f (storytold/deckcraft#1137). * ppt-binary: picture frames, inline picture fills, gradients, footers, numbering The remaining differences from LibreOffice in the storytold/deckcraft#1137 stress test: - Picture frames (and OLE frames) that say nothing about fill or line start with neither, as placeholders and text boxes do, instead of the drawing defaults' fill. - A pib or fillBlip held in the property's own complex bytes (fBid) is decoded within the picture budget: table cells with a picture fill showed a plain colour. - Shaded fills put the back colour at fillFocus ([MS-ODRAW]), and the linear angle follows how LibreOffice writes and reads it (0 degrees from the top): the linear gradient was reversed, the radial inside out. - HeadersFooters (the slide's, else the document's) add the date, footer and slide number placeholders; the master's footer placement, alignment, size and colour reach every layout. - Numbering from the document's ___PPT9 tag (OutlineTextProps9, pp9rt in the runs' fontStyle) turns bulleted paragraphs into numbered ones. - Wingdings diamonds draw as a diamond, not a dot. From storytold/deckcraft@24437bd075 (storytold/deckcraft#1137). * ppt-binary: read CString records up to their first NUL Header/footer text and the ___PPT9 tag name were decoded from the whole CString body. A writer that ends the string with a NUL would put the NUL into the footer text and make the tag name fail to match, losing the numbering. Stop at the first NUL, as the font names already do. From storytold/deckcraft@110e1420fd (storytold/deckcraft#1137). * ppt-binary: on craft-cfb and craft-pptx (the move from DeckCraft) What the move from storytold/deckcraft#1137 changes; the commits before this one are that PR's crates/ppt as it is on its branch, without its manifest. - craft-cfb replaces the crate's own compound-file reader (cfb.rs, 552 lines). Streams are read capped at the file's length, as before. Its six tests (looping chains, mini streams, version 4 sectors, the DIFAT) are covered by craft-cfb's own. The byte helpers move to record.rs. Test files are written by craft-cfb's writer. - deckcraft-model, deckcraft-color and deckcraft-geom become craft-pptx and craft-drawingml, the same types (storytold/deckcraft#2179, storytold/deckcraft#2180 and #792's plan). A gradient now states its shape and rotate-with-shape explicitly, as craft-drawingml's are optional. - DeckCraft's default master (defaults::build_master and blank_presentation) becomes the caller's craft_pptx::Defaults: import(bytes, &defaults), as craft_pptx::import takes. The file's masters take the default master's layouts and placeholders, then the file's theme, placeholder boxes and styles. The tests use a default master with title, body and footer placeholders and the seven layouts .ppt layout types map to; a new test reads with craft_pptx::Plain. - The two tests that drive DeckCraft's engine (open and save, lost slides in the app) stay in DeckCraft. - The fixture's rebuild variable is CRAFT_WRITE_PPT_FIXTURE; old-talk.pps is unchanged and gets its ATTRIBUTION row. Bare #1137 references in comments name storytold/deckcraft#1137. - README, crate README (doctested) and the workspace entry. * ppt-binary: bound text, strings, paths and repeated work from hostile files Tab stops keep the first 64 entries while still reading past the rest, string properties stop at 4096 units, and a freeform path uses at most 8192 vertices, since each of these is copied into every paragraph or inheriting shape. An outline block in the slide list is the text of one shape only; a second reference keeps the shape's own text. The fallback master and each master's layout per type are found once before the slides are converted, a shape's primary property tables are collected without inserting at the front, and a compressed metafile that fails to inflate is charged to the picture budget. * ppt-binary: review fixes for footers, rulers, title masters, paths and numbering A slide's own headers and footers record (instance 0) now wins over the document's, and a text box that points at an outline block keeps the margins and indents of its own ruler. A slide list entry whose object is not a slide is reported as lost. Title masters place their layout's placeholders from their own placeholder boxes, adding any the title layout lacks, and copy only placeholders from an earlier title layout. Slides that don't name a title master no longer pick its layout. Freeform paths skip the points of escape segments, and without segments follow shapePath (closed lines by default, open lines or curves). DIB colour tables are sized by bit depth and refused when they run past the bitmap. Numbering schemes 0x10 to 0x28 map to their DrawingML names, master style levels go to the level they name, and a broken edit chain reads the newest edits rather than the oldest. The nested persist directory test now checks the file is reported damaged, the footer test fails when a layout has no slide number, and the README says tables come in as groups of shapes. * ppt-binary: second review round: failed pictures, title layouts, notes, arcs and property tables Inflating a compressed metafile is now charged its compressed bytes as well as its output, and is refused when those bytes alone pass the remaining budget, so many entries pointing at one stream that inflates to nothing can't each read it again for free. A title master's layout starts only from the defaults' own title layout, not one made for an earlier title master. A notes page shared by two slide records with the same slide id goes to the first only. After elliptical quadrants or a quadratic Bezier escape a path goes on from their last point; after an arc or angle ellipse, whose end isn't one of its vertices, the path stops rather than draw from the wrong place. A property set keeps at most 1024 distinct properties, so copying the drawing defaults into each shape costs a bounded amount. * ppt-binary: take each main master's title-layout base once; test outline notes A title master's layout starts from the placeholders of the defaults' title layout. They are now taken once, when the main master is made, instead of rebuilding the set of title-master layouts and rescanning the master's layouts for every title master, which was quadratic in title masters. A notes page whose body text is in the notes list's outline block also goes to one slide only. --------- Co-authored-by: Oliwier Kulczycki Co-authored-by: kiwi4boy --- ATTRIBUTION.md | 1 + Cargo.lock | 13 + Cargo.toml | 1 + README.md | 2 + crates/ppt-binary/Cargo.toml | 23 + crates/ppt-binary/README.md | 40 + crates/ppt-binary/src/blip.rs | 404 ++++++ crates/ppt-binary/src/convert.rs | 1181 ++++++++++++++++ crates/ppt-binary/src/doc.rs | 390 ++++++ crates/ppt-binary/src/draw.rs | 522 +++++++ crates/ppt-binary/src/geom.rs | 454 ++++++ crates/ppt-binary/src/lib.rs | 76 + crates/ppt-binary/src/record.rs | 186 +++ crates/ppt-binary/src/tests.rs | 1245 +++++++++++++++++ crates/ppt-binary/src/text.rs | 755 ++++++++++ crates/ppt-binary/tests/fixtures/old-talk.pps | Bin 0 -> 4096 bytes 16 files changed, 5293 insertions(+) create mode 100644 crates/ppt-binary/Cargo.toml create mode 100644 crates/ppt-binary/README.md create mode 100644 crates/ppt-binary/src/blip.rs create mode 100644 crates/ppt-binary/src/convert.rs create mode 100644 crates/ppt-binary/src/doc.rs create mode 100644 crates/ppt-binary/src/draw.rs create mode 100644 crates/ppt-binary/src/geom.rs create mode 100644 crates/ppt-binary/src/lib.rs create mode 100644 crates/ppt-binary/src/record.rs create mode 100644 crates/ppt-binary/src/tests.rs create mode 100644 crates/ppt-binary/src/text.rs create mode 100644 crates/ppt-binary/tests/fixtures/old-talk.pps diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 1b6105f242..5805271e03 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -11,6 +11,7 @@ author, source and license. Library code and original assets are under the repos | `licenses/dwg/acadrust-MPL-2.0.txt`, `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | `acadrust` contributors; ACadSharp authors for the noted ported routines | [acadrust 0.6.6](https://github.com/hakanaktt/acadrust), used unmodified as `craft-dwg`'s optional native dependency | MPL-2.0; embedded ACadSharp notice is MIT; see both retained files | | `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 | | `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 | +| `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 | | `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | | `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | | `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 | diff --git a/Cargo.lock b/Cargo.lock index a91d9773a8..0d65079709 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2969,6 +2969,19 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-ppt-binary" +version = "0.1.0" +dependencies = [ + "craft-cfb", + "craft-drawingml", + "craft-pptx", + "image", + "log", + "miniz_oxide 0.8.9", + "thiserror 2.0.21", +] + [[package]] name = "craft-pptx" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c36973b4a4..a278beb414 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -161,6 +161,7 @@ craft-opc = { path = "crates/opc" } craft-openpgp = { path = "crates/openpgp" } craft-ora = { path = "crates/ora" } craft-pptx = { path = "crates/pptx" } +craft-ppt-binary = { path = "crates/ppt-binary" } craft-penpot = { path = "crates/penpot" } craft-pcraft-format = { path = "crates/pcraft-format" } craft-pcraft-bundle = { path = "crates/pcraft-bundle" } diff --git a/README.md b/README.md index c4dabafb67..9512980917 100644 --- a/README.md +++ b/README.md @@ -324,6 +324,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-plotter`](crates/plotter/README.md): cutter and pen-plotter command languages: HP-GL, DMPL and GP-GL (plain and the Silhouette dialect, three generations, registration marks) from a job in millimetres, plus the Silhouette device queries and reply parsers. No I/O. +- [`craft-ppt-binary`](crates/ppt-binary/README.md): the PowerPoint 97-2003 binary format (`.ppt`, `.pot`, `.pps`; + [MS-PPT], [MS-ODRAW]) read into `craft-pptx`, on `craft-cfb`. Import only. DeckCraft's reader. - [`craft-pptx`](crates/pptx/README.md): PresentationML, the model of a `.pptx` presentation: masters, layouts, slides, shapes, placeholders and their inheritance, transitions and animations, comments, sections, media and kept parts. From DeckCraft. DrawingML comes from `craft-drawingml`. diff --git a/crates/ppt-binary/Cargo.toml b/crates/ppt-binary/Cargo.toml new file mode 100644 index 0000000000..897aad8a4a --- /dev/null +++ b/crates/ppt-binary/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "craft-ppt-binary" +description = "Reader for the PowerPoint 97-2003 binary file format (.ppt, .pot, .pps; [MS-PPT], [MS-ODRAW]) into the craft-pptx presentation model, on craft-cfb." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-cfb = { workspace = true } +craft-drawingml = { workspace = true } +craft-pptx = { workspace = true } +log = { workspace = true } +miniz_oxide = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +# Pictures in the tests: a PNG to embed, and the BMP a DIB blip becomes. +image = { version = "0.25", default-features = false, features = ["png", "bmp"] } diff --git a/crates/ppt-binary/README.md b/crates/ppt-binary/README.md new file mode 100644 index 0000000000..d1bbdd24e3 --- /dev/null +++ b/crates/ppt-binary/README.md @@ -0,0 +1,40 @@ +# craft-ppt-binary + +Reader for the PowerPoint 97-2003 binary file format (`.ppt`, `.pot` and `.pps`) into the +`craft-pptx` presentation model. It is DeckCraft's reader, on `craft-cfb` for the compound file. +Import only: there is no `.ppt` writer. + +| Document | Used for | +|---|---| +| [MS-PPT] PowerPoint (.ppt) Binary File Format (Microsoft Open Specifications) | the Current User stream, the edit chain and persist directories, documents, masters, slides, notes, text and its styles, headers and footers | +| [MS-ODRAW] Office Drawing Binary File Formats | shapes, their property tables and geometry, the BLIP store and its pictures | +| [MS-CFB] Compound File Binary File Format | through `craft-cfb` | + +```rust +// Not a compound file: an error, never a panic. +assert!(!craft_ppt_binary::sniff(b"not a .ppt")); +assert!(craft_ppt_binary::import(b"not a .ppt", &craft_pptx::Plain).is_err()); +``` + +- `sniff(bytes)`, `import(bytes, &defaults)` and `import_checked(bytes, &defaults)`, which also + names the slides the file lists but whose objects are gone. +- Main masters become masters, with their colour scheme, fonts, text styles, background and + decorative shapes. Title masters become layouts of their main master. +- Slides keep their shapes (preset and freeform geometry, groups, rotation and flips), fills, + lines, shadows, pictures (PNG, JPEG, DIB, TIFF, EMF and WMF), tables (as groups of shapes, the + way the file stores them), and text with the master's styles resolved into it, along with + fields, numbering, headers and footers, notes, and hidden slides. +- Damaged files read as far as they can: a broken edit chain falls back to a scan of the edits, + and unknown or damaged records are skipped. Sizes, counts, nesting and picture decoding are + bounded. +- Password-protected files are refused (`PptError::Encrypted`), as are PowerPoint 95 and earlier + files (`PptError::TooOld`). + +The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from: +its layouts and placeholders. The file's masters then place and style the placeholders that +master has. With `craft_pptx::Plain` (one blank layout, no placeholders), the slides still read +with their own boxes. + +The reader was written for DeckCraft (storytold/deckcraft#1137); the history of +`crates/ppt-binary` names its authors. Its tests build `.ppt` files from records; no file made +by PowerPoint is used. diff --git a/crates/ppt-binary/src/blip.rs b/crates/ppt-binary/src/blip.rs new file mode 100644 index 0000000000..56b6abaeca --- /dev/null +++ b/crates/ppt-binary/src/blip.rs @@ -0,0 +1,404 @@ +//! Pictures ([MS-ODRAW] §2.2.32–2.2.45): the drawing group's blip store lists every picture +//! (`FBSE`), either holding its blip or pointing into the `Pictures` stream. Shapes name a picture +//! by its 1-based index in the store. + +use crate::doc::rt; +use crate::record::Rec; + +/// Largest picture inflated from a compressed metafile. +const MAX_INFLATED: usize = 64 << 20; +/// Most bytes all of a file's pictures may decode to together: 2 GiB, the total a `.pptx` package +/// may inflate to (`craft_pptx::MAX_TOTAL`). Pictures are the only part of a `.ppt` +/// that inflates, so a small hostile file can't make the import hold more than a `.pptx` could. +/// It also fits a 32-bit `usize` (wasm32), where a 4 GiB constant wraps to 0. +const MAX_TOTAL: usize = 2 << 30; +// A zero or tiny budget would drop every picture without a word, and the shift above can wrap on +// a 32-bit target (wasm32) without any error, so the build checks it on every target. +const _: () = assert!(MAX_TOTAL >= MAX_INFLATED); + +/// A decoded picture: file extension, content type and bytes as a file of that type. +#[derive(Clone, Debug, PartialEq)] +pub struct Picture { + pub ext: &'static str, + pub content_type: &'static str, + pub data: Vec, +} + +/// The blip store: each entry's blip record, decoded only when a shape first asks for it, every +/// entry at most once, and all of them together within [`MAX_TOTAL`] bytes. +pub struct Store<'a> { + entries: Vec>>, + budget: usize, +} + +impl<'a> Store<'a> { + pub fn new(dgg: Option>, pictures_stream: &'a [u8]) -> Self { + let entries = match dgg.and_then(|d| d.child(rt::BSTORE)) { + Some(bstore) => bstore.children().map(|r| if r.kind == rt::FBSE { fbse(&r, pictures_stream) } else { None }).collect(), + None => vec![], + }; + Store { entries, budget: MAX_TOTAL } + } + + /// The picture at `index` (0-based; shapes use 1-based ids), taken out of the store. `None` + /// for an entry that is empty, can't be read, was taken already, or would pass the budget. + pub fn take(&mut self, index: usize) -> Option { + let blip = self.entries.get_mut(index)?.take()?; + self.decode_charged(&blip) + } + + /// A blip held in a shape's own property ([MS-ODRAW] §2.2.37: a complex `fillBlip` or `pib` + /// whose extra bytes are the blip record itself), decoded within the same budget. + pub fn decode_inline(&mut self, bytes: &[u8]) -> Option { + let blip = Rec::at(bytes, 0).filter(|r| (0xF018..=0xF117).contains(&r.kind))?; + self.decode_charged(&blip) + } + + /// Decode `blip` and take its size from the budget. A compressed metafile is also charged + /// its compressed bytes, which inflating reads whatever it produces, and one that fails to + /// inflate is charged what the inflate may have produced before failing: many entries pointing + /// at one damaged stream (or one that inflates to nothing) would otherwise each inflate it again + /// for free. + fn decode_charged(&mut self, blip: &Rec) -> Option { + let bounds = inflate_bounds(blip, self.budget); + let pic = decode(blip, self.budget); + let cost = match (&pic, bounds) { + (Some(p), Some((input, _))) => input.saturating_add(p.data.len()), + (Some(p), None) => p.data.len(), + (None, Some((input, output))) => input.saturating_add(output), + (None, None) => 0, + }; + self.budget = self.budget.saturating_sub(cost); + pic + } +} + +/// For a compressed metafile (EMF or WMF, with one UID or, for instances 0x3D5 and 0x217, two): +/// the compressed bytes inflating it reads, and the most bytes it may produce so that both +/// together stay within `limit`. `None` for any other blip, or when the compressed bytes alone +/// pass `limit`. +fn inflate_bounds(b: &Rec, limit: usize) -> Option<(usize, usize)> { + if !matches!(b.kind, 0xF01A | 0xF01B) { + return None; + } + let uids = if matches!(b.instance, 0x3D5 | 0x217) { 32 } else { 16 }; + let h = b.data.get(uids..uids + 34)?; + let size = crate::record::u32_at(h, 0)? as usize; + if *h.get(32)? != 0 { + return None; + } + let input = b.data.get(uids + 34..)?.len(); + let output = limit.checked_sub(input)?; + Some((input, size.min(MAX_INFLATED).min(output))) +} + +fn fbse<'a>(r: &Rec<'a>, pictures: &'a [u8]) -> Option> { + // btWin32, btMacOS, rgbUid[16], tag, size, cRef, foDelay, unused, cbName, unused, unused. + let size = r.u32(20)? as usize; + let offset = r.u32(28)? as usize; + let name_len = usize::from(r.u8(33)?); + if size == 0 { + return None; + } + let embedded_at = 36usize.checked_add(name_len)?; + if r.data.len() > embedded_at { Rec::at(r.data, embedded_at) } else { Rec::at(pictures, offset) } +} + +/// Decode one blip record into at most `limit` bytes. +pub fn decode(b: &Rec, limit: usize) -> Option { + // The instance says whether a second UID follows the first. + let (kind, two_uids): (u16, bool) = match b.instance { + 0x3D4 | 0x216 | 0x542 | 0x46A | 0x6E2 | 0x6E0 | 0x7A8 | 0x6E4 => (b.kind, false), + 0x3D5 | 0x217 | 0x543 | 0x46B | 0x6E3 | 0x6E1 | 0x7A9 | 0x6E5 => (b.kind, true), + _ => (b.kind, false), + }; + let uids = if two_uids { 32 } else { 16 }; + // The bytes a picture is copied from, refused before copying when they (plus `extra` bytes of + // header to add) would pass the budget. + let within = |bytes: &'_ [u8], extra: usize| bytes.len().checked_add(extra).is_some_and(|n| n <= limit); + let bitmap = || b.data.get(uids + 1..).filter(|d| within(d, 0)).map(<[u8]>::to_vec); + match kind { + // EMF, WMF: a metafile header then (usually deflated) data. + 0xF01A | 0xF01B => { + let h = b.data.get(uids..uids + 34)?; + let size = crate::record::u32_at(h, 0)? as usize; + let compressed = *h.get(32)? == 0; + let body = b.data.get(uids + 34..)?; + let data = if compressed { + miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(body, inflate_bounds(b, limit)?.1).ok()? + } else { + body.get(..size.min(body.len())).filter(|d| within(d, 0))?.to_vec() + }; + let (ext, content_type) = if kind == 0xF01A { ("emf", "image/x-emf") } else { ("wmf", "image/x-wmf") }; + Some(Picture { ext, content_type, data }) + } + // Bitmaps: a one-byte tag then the file. + 0xF01D | 0xF02A => Some(Picture { ext: "jpg", content_type: "image/jpeg", data: bitmap()? }), + 0xF01E => Some(Picture { ext: "png", content_type: "image/png", data: bitmap()? }), + 0xF029 => Some(Picture { ext: "tif", content_type: "image/tiff", data: bitmap()? }), + 0xF01F => Some(Picture { ext: "bmp", content_type: "image/bmp", data: dib_to_bmp(b.data.get(uids + 1..).filter(|d| within(d, 14))?)? }), + // PICT (Macintosh) has no decoder here. + _ => None, + } + .filter(|p| p.data.len() <= limit) +} + +/// A device-independent bitmap with the 14-byte file header a `.bmp` needs in front. +fn dib_to_bmp(dib: &[u8]) -> Option> { + let header = crate::record::u32_at(dib, 0)? as usize; + let (bits, compression, used) = if header == 12 { + (usize::from(crate::record::u16_at(dib, 10)?), 0, 0) + } else { + (usize::from(crate::record::u16_at(dib, 14)?), crate::record::u32_at(dib, 16)?, crate::record::u32_at(dib, 32)? as usize) + }; + let entry = if header == 12 { 3 } else { 4 }; + // The colour table: up to 2^bits entries (all of them when biClrUsed is 0) for 8 bits or + // fewer; biClrUsed entries, an optional table, for more. + let colors = match bits { + 0..=8 if used > 0 => used.min(1 << bits), + 0..=8 => 1 << bits, + _ => used, + }; + // BI_BITFIELDS with the 40-byte header: three masks follow it. + let masks = if compression == 3 && header == 40 { 12 } else { 0 }; + let offset = 14usize.checked_add(header)?.checked_add(colors.checked_mul(entry)?)?.checked_add(masks)?; + let file_len = 14usize.checked_add(dib.len())?; + // Pixels starting past the end are no bitmap. + if offset > file_len { + return None; + } + let total = u32::try_from(file_len).ok()?; + let mut out = Vec::with_capacity(dib.len() + 14); + out.extend_from_slice(b"BM"); + out.extend_from_slice(&total.to_le_bytes()); + out.extend_from_slice(&[0; 4]); + out.extend_from_slice(&u32::try_from(offset).ok()?.to_le_bytes()); + out.extend_from_slice(dib); + Some(out) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::build::*; + + fn decode_all(b: &Rec) -> Option { + decode(b, usize::MAX) + } + + /// Many entries pointing at one deflated metafile decode within the shared budget, each + /// at most once. + #[test] + fn the_store_decodes_lazily_within_a_budget() { + let wmf = vec![7u8; 1000]; + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + let pictures = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat()); + let mut fbse = vec![0u8; 36]; + fbse[20..24].copy_from_slice(&(pictures.len() as u32).to_le_bytes()); + let entries: Vec> = (0..5).map(|_| atom(rt::FBSE, 3, &fbse)).collect(); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 5, &entries)]); + let mut store = Store::new(Rec::at(&dgg, 0), &pictures); + store.budget = 2500; + assert_eq!(store.take(0).map(|p| p.data.len()), Some(1000)); + assert!(store.take(0).is_none(), "taken already"); + assert!(store.take(1).is_some()); + assert!(store.take(2).is_none(), "past the budget"); + assert!(store.take(99).is_none()); + } + + /// A compressed metafile that fails to inflate still costs the budget what it may have + /// inflated, so entries pointing at one damaged stream can't each inflate it again for free. + #[test] + fn a_failed_inflate_is_charged_to_the_budget() { + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&1000u32.to_le_bytes()); + let damaged = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &[0x78, 0x9C, 0xFF, 0xFF]].concat()); + let mut fbse = vec![0u8; 36]; + fbse[20..24].copy_from_slice(&(damaged.len() as u32).to_le_bytes()); + let entries: Vec> = (0..3).map(|_| atom(rt::FBSE, 3, &fbse)).collect(); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 3, &entries)]); + let mut store = Store::new(Rec::at(&dgg, 0), &damaged); + store.budget = 2500; + assert!(store.take(0).is_none()); + assert_eq!(store.budget, 1496, "1000 bytes it may have inflated and the 4 it read"); + assert!(store.take(1).is_none()); + assert!(store.take(2).is_none()); + assert_eq!(store.budget, 0, "the last attempt is charged what was left"); + // A picture that isn't a compressed metafile costs nothing when it can't be read. + let mut store = Store::new(None, &[]); + store.budget = 10; + assert!(store.decode_inline(&atom(0xF01E, 0x6E0, &[0; 4])).is_none()); + assert_eq!(store.budget, 10); + } + + /// A compressed metafile that inflates to nothing (a declared size of 0 and a run of empty + /// stored blocks, here with a bad checksum) still costs the bytes it makes the inflate read, so + /// many entries pointing at it run out of budget instead of each reading it again for free. + #[test] + fn inflating_is_charged_the_compressed_bytes() { + let mut z = vec![0x78, 0x01]; + for _ in 0..200 { + z.extend_from_slice(&[0x00, 0x00, 0x00, 0xFF, 0xFF]); + } + z.extend_from_slice(&[0x01, 0x00, 0x00, 0xFF, 0xFF, 1, 2, 3, 4]); + let empty = atom(0xF01B, 0x216, &[&[0u8; 16][..], &[0u8; 34], &z].concat()); + let mut fbse = vec![0u8; 36]; + fbse[20..24].copy_from_slice(&(empty.len() as u32).to_le_bytes()); + let entries: Vec> = (0..5).map(|_| atom(rt::FBSE, 3, &fbse)).collect(); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 5, &entries)]); + let mut store = Store::new(Rec::at(&dgg, 0), &empty); + store.budget = 2 * z.len() + 10; + assert!(store.take(0).is_none()); + assert_eq!(store.budget, z.len() + 10); + assert!(store.take(1).is_none()); + assert_eq!(store.budget, 10); + // Too little left for its compressed bytes: not inflated, and nothing charged. + assert!(store.take(2).is_none()); + assert_eq!(store.budget, 10); + // One that inflates is charged its compressed bytes as well as what they inflate to. + let wmf = vec![7u8; 100]; + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + let blip = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat()); + let mut store = Store::new(None, &[]); + store.budget = 1000; + assert_eq!(store.decode_inline(&blip).map(|p| p.data.len()), Some(100)); + assert_eq!(store.budget, 1000 - 100 - z.len()); + } + + #[test] + fn decodes_png_and_deflated_metafiles() { + let png = [&[0u8; 17][..], b"\x89PNG..."].concat(); + let p = decode_all(&Rec::at(&atom(0xF01E, 0x6E0, &png), 0).unwrap()).unwrap(); + assert_eq!((p.ext, &p.data[..4]), ("png", &b"\x89PNG"[..])); + // Over the remaining budget: refused before it is copied. + assert!(decode(&Rec::at(&atom(0xF01E, 0x6E0, &png), 0).unwrap(), 6).is_none()); + + let wmf = b"\x01\x00\x09\x00\x00\x03 a tiny metafile".to_vec(); + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + header[28..32].copy_from_slice(&(z.len() as u32).to_le_bytes()); + let body = [&[0u8; 16][..], &header, &z].concat(); + let p = decode_all(&Rec::at(&atom(0xF01B, 0x216, &body), 0).unwrap()).unwrap(); + assert_eq!((p.ext, p.data), ("wmf", wmf)); + // Damaged deflate data is no picture rather than a panic. + let bad = [&[0u8; 16][..], &header, &[1, 2, 3]].concat(); + assert!(decode_all(&Rec::at(&atom(0xF01A, 0x3D4, &bad), 0).unwrap()).is_none()); + } + + #[test] + fn a_dib_becomes_a_bmp_the_image_crate_reads() { + // 1×1, 24-bit. + let mut dib = vec![0u8; 40]; + dib[0] = 40; + dib[4] = 1; + dib[8] = 1; + dib[12] = 1; + dib[14] = 24; + dib.extend_from_slice(&[0, 0, 255, 0]); + let body = [&[0u8; 17][..], &dib].concat(); + let p = decode_all(&Rec::at(&atom(0xF01F, 0x7A8, &body), 0).unwrap()).unwrap(); + assert_eq!(&p.data[..2], b"BM"); + assert_eq!(u32::from_le_bytes(p.data[10..14].try_into().unwrap()), 54); + let img = image::load_from_memory_with_format(&p.data, image::ImageFormat::Bmp).unwrap().to_rgba8(); + assert_eq!(img.dimensions(), (1, 1)); + assert_eq!(img.get_pixel(0, 0).0, [255, 0, 0, 255]); + } + + /// The pixels start after the colour table: biClrUsed entries for more than 8 bits (none when + /// it is 0), at most 2^bits for fewer, and a table running past the DIB is no picture. + #[test] + fn a_dib_colour_table_is_sized_by_its_bit_depth() { + let dib = |bits: u16, used: u32, extra: usize| { + let mut d = vec![0u8; 40]; + d[0] = 40; + d[14..16].copy_from_slice(&bits.to_le_bytes()); + d[32..36].copy_from_slice(&used.to_le_bytes()); + d.resize(40 + extra, 0); + d + }; + let offset = |b: &[u8]| dib_to_bmp(b).map(|bmp| u32::from_le_bytes(bmp[10..14].try_into().unwrap())); + assert_eq!(offset(&dib(24, 0, 4)), Some(54)); + assert_eq!(offset(&dib(24, 300, 1204)), Some(54 + 1200), "more than 256 entries for 24 bits"); + assert_eq!(offset(&dib(8, 300, 1028)), Some(54 + 1024), "8 bits: at most 256"); + assert_eq!(offset(&dib(4, 0, 68)), Some(54 + 64)); + assert_eq!(offset(&dib(24, 300, 100)), None, "the table runs past the DIB"); + assert_eq!(offset(&dib(32, u32::MAX, 0)), None); + } + + /// JPEG (RGB and CMYK), TIFF and a PNG with a second UID: the instance says how many UIDs come + /// before the tag byte, and the bytes after it are the file. + #[test] + fn decodes_each_bitmap_kind() { + let file = b"the picture file"; + for (kind, instance, uids, ext) in [ + (0xF01D, 0x46A, 16, "jpg"), + (0xF01D, 0x46B, 32, "jpg"), + (0xF02A, 0x6E2, 16, "jpg"), + (0xF029, 0x6E4, 16, "tif"), + (0xF029, 0x6E5, 32, "tif"), + (0xF01E, 0x6E1, 32, "png"), + ] { + let body = [&vec![0xAAu8; uids][..], &[0xFF], file].concat(); + let p = decode_all(&Rec::at(&atom(kind, instance, &body), 0).unwrap()).unwrap(); + assert_eq!((p.ext, p.data.as_slice()), (ext, &file[..]), "{kind:#x}/{instance:#x}"); + } + } + + /// A metafile stored without compression (compression byte 0xFE) is copied as it is, up to its + /// stated size; with two UIDs the header starts 32 bytes in. + #[test] + fn decodes_an_uncompressed_metafile() { + let emf = b"\x01\x00\x00\x00 an enhanced metafile".to_vec(); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(emf.len() as u32).to_le_bytes()); + header[28..32].copy_from_slice(&(emf.len() as u32).to_le_bytes()); + header[32] = 0xFE; + for (instance, uids) in [(0x3D4, 16), (0x3D5, 32)] { + let body = [&vec![0u8; uids][..], &header, &emf, b"trailing"].concat(); + let p = decode_all(&Rec::at(&atom(0xF01A, instance, &body), 0).unwrap()).unwrap(); + assert_eq!((p.ext, &p.data), ("emf", &emf)); + } + } + + /// A metafile whose inflated size (with its compressed bytes) would pass the remaining budget is refused, compressed or not. + #[test] + fn a_metafile_over_the_budget_is_refused() { + let wmf = vec![9u8; 4000]; + let z = miniz_oxide::deflate::compress_to_vec_zlib(&wmf, 6); + let mut header = vec![0u8; 34]; + header[..4].copy_from_slice(&(wmf.len() as u32).to_le_bytes()); + let deflated = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &z].concat()); + // The budget covers the compressed bytes read as well as the bytes they inflate to. + assert!(decode(&Rec::at(&deflated, 0).unwrap(), 3999 + z.len()).is_none()); + assert_eq!(decode(&Rec::at(&deflated, 0).unwrap(), 4000 + z.len()).map(|p| p.data.len()), Some(4000)); + header[32] = 0xFE; + let raw = atom(0xF01B, 0x216, &[&[0u8; 16][..], &header, &wmf].concat()); + assert!(decode(&Rec::at(&raw, 0).unwrap(), 3999).is_none()); + assert!(decode(&Rec::at(&raw, 0).unwrap(), 4000).is_some()); + } + + /// An FBSE may hold its blip itself, after its name, instead of pointing into the Pictures + /// stream. + #[test] + fn a_blip_inside_its_fbse_is_read() { + let png = [&[0u8; 17][..], b"\x89PNG inside"].concat(); + let blip = atom(0xF01E, 0x6E0, &png); + let name = "p".encode_utf16().flat_map(u16::to_le_bytes).collect::>(); + let mut fbse = [0u8; 36]; + fbse[20..24].copy_from_slice(&(blip.len() as u32).to_le_bytes()); + fbse[33] = name.len() as u8; + let entry = atom(rt::FBSE, 6, &[&fbse[..], &name, &blip].concat()); + let dgg = container(rt::DGG_CONTAINER, 0, &[container(rt::BSTORE, 1, &[entry])]); + // The Pictures stream is empty: the blip can only come from the FBSE. + let mut store = Store::new(Rec::at(&dgg, 0), &[]); + let p = store.take(0).unwrap(); + assert_eq!((p.ext, &p.data[..]), ("png", &b"\x89PNG inside"[..])); + } +} diff --git a/crates/ppt-binary/src/convert.rs b/crates/ppt-binary/src/convert.rs new file mode 100644 index 0000000000..f7897cdbb6 --- /dev/null +++ b/crates/ppt-binary/src/convert.rs @@ -0,0 +1,1181 @@ +//! Building a `craft_pptx` presentation from the parsed `.ppt` structure. +//! +//! Each main master becomes a master: the caller's default master (its layouts and placeholders), +//! with the file's colours, fonts, text styles, background and decorative shapes, and the file's +//! placeholder boxes on the placeholders the default master has. A title master becomes a layout +//! of its main master. Slide shapes keep their own boxes, and their text carries its formatting +//! resolved against the master's text styles, so it draws the same whatever the layouts hold. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use craft_pptx::style::{Dash, LineCap, LineEnd, LineJoin, PictureFill, PictureMode, Shadow}; +use craft_pptx::text::{Align, Anchor as TextAnchor, AutoFit, BodyProps, Bullet, LevelStyle, ListStyle, ParaProps, RunKind, Spacing, TabStop}; +use craft_pptx::{ + Background, ColorRef, Defaults, Effects, Fill, Layout, LayoutId, LayoutType, Line, Master, MediaId, Paragraph, PhType, Placeholder, Presentation, + Run, RunProps, Shape, ShapeId, ShapeKind, Size, Slide, SlideId, TextBody, Theme, Xfrm, +}; +use craft_pptx::{ColorTransform, Rgba, SchemeSlot}; + +use crate::doc::{self, Doc, Listed, rt}; +use crate::draw::{self, Props, RawShape, prop}; +use crate::geom; +use crate::record::{MAX_DEPTH, Rec}; +use crate::text::{self, Cf, FieldKind, Pf, StyleSheet, TextBlock, TextColor, ty}; + +/// Master units (576 per inch) per point. +const MU: f64 = 8.0; +/// EMUs per point. +const EMU: f64 = 12700.0; + +/// The eight colours of a `.ppt` colour scheme: background, text, shadow, title text, fill, +/// accent, accent and hyperlink, accent and followed hyperlink. +type Scheme = [Rgba; 8]; + +const DEFAULT_SCHEME: Scheme = [ + Rgba::rgb(0xFF, 0xFF, 0xFF), + Rgba::rgb(0, 0, 0), + Rgba::rgb(0x80, 0x80, 0x80), + Rgba::rgb(0, 0, 0), + Rgba::rgb(0xBB, 0xE0, 0xE3), + Rgba::rgb(0x33, 0x33, 0x99), + Rgba::rgb(0, 0x99, 0x99), + Rgba::rgb(0x99, 0xCC, 0x00), +]; + +fn scheme_of(container: &Rec) -> Option { + let r = container.children_of(rt::COLOR_SCHEME).find(|r| r.instance == 1)?; + let mut s = DEFAULT_SCHEME; + for (i, c) in s.iter_mut().enumerate() { + *c = Rgba::rgb(r.u8(i * 4)?, r.u8(i * 4 + 1)?, r.u8(i * 4 + 2)?); + } + Some(s) +} + +/// What converting one drawing needs besides the shapes. +struct Scope<'s, 'a> { + scheme: Scheme, + styles: &'s StyleSheet, + /// The slide list's outline text, for placeholders that point at it. + outline: &'s [crate::record::Records<'a>], + /// Each outline block's numbering (`StyleTextProp9Atom` entries), by outline index. + numbering: &'s [Option>], + /// The outline blocks a shape has taken already. Each block is one shape's text: a second + /// shape pointing at it keeps its own, so a big block can't be copied into every shape. + used_outline: RefCell>, + master: bool, + /// Where `hspMaster` shape ids are looked up: the slide's master, then a title master's main + /// master. + masters: Chain, +} + +/// Master slide ids, nearest first. +type Chain = [Option; 2]; + +struct Ctx<'a> { + p: Presentation, + fonts: Vec, + blips: crate::blip::Store<'a>, + media: HashMap>, + /// Pictures held in a shape's own property, by where their bytes start, so a master shape's + /// picture inherited by many slides is added once. + inline_media: HashMap>, + /// The slides' outline numbering, by slide id and text type ([`doc::outline_numbering`]). + numbering: HashMap<(u32, u32), Vec>>, + defaults: Props<'a>, + /// Master shapes by master slide id and shape id, for slide shapes that inherit from one + /// (`hspMaster`). Keyed by master too, so a shape id repeated in another master can't replace + /// this master's shape. + master_props: HashMap<(u32, u32), Props<'a>>, + /// The caller's defaults: the master each of the file's masters starts from. + app: &'a dyn Defaults, + /// Notes pages converted already. Distinct slides can share a slide id, and so a notes page: + /// it goes to the first of them only, so its text isn't copied into every one. + used_notes: HashSet, +} + +pub fn convert<'a>(d: &Doc<'a>, pictures: &'a [u8], app: &'a dyn Defaults) -> Presentation { + let atom = d.document_atom(); + let side = + |v: Option, fallback: f64| v.map(|v| f64::from(v) / MU).filter(|v| v.is_finite() && *v >= 1.0 && *v <= 56.0 * 72.0).unwrap_or(fallback); + let size = Size::new(side(atom.as_ref().map(|a| a.slide_w), 720.0), side(atom.as_ref().map(|a| a.slide_h), 540.0)); + // Ids above 256, as a new presentation's are. + let mut p = Presentation { slide_size: size, default_text_style: app.default_text_style(), next_id: 256, ..Default::default() }; + p.notes_size = Size::new(side(atom.as_ref().map(|a| a.notes_w), 540.0), side(atom.as_ref().map(|a| a.notes_h), 720.0)); + p.first_slide_number = atom.as_ref().map_or(1, |a| u32::from(a.first_slide_number)); + let dgg = d.document.child(rt::DRAWING_GROUP).and_then(|g| g.child(rt::DGG_CONTAINER)); + let mut cx = Ctx { + p, + fonts: doc::fonts(d), + blips: crate::blip::Store::new(dgg, pictures), + media: HashMap::new(), + inline_media: HashMap::new(), + numbering: doc::outline_numbering(&d.document), + defaults: draw::default_props(dgg), + master_props: HashMap::new(), + app, + used_notes: HashSet::new(), + }; + let environment = d.document.child(rt::ENVIRONMENT); + if let Some(hf) = doc::headers_footers(&d.document, 3) { + cx.p.header_footer = craft_pptx::HeaderFooter { + date: hf.date, + slide_number: hf.slide_number, + footer: hf.footer, + footer_text: hf.footer_text, + date_text: if hf.user_date { hf.date_text } else { String::new() }, + date_format: format!("datetime{}", hf.format.min(12) + 1), + ..Default::default() + }; + } + + // Main masters first, then title masters as layouts of theirs. + let mut masters: HashMap = HashMap::new(); + for m in d.masters.iter().filter(|m| m.rec.kind == rt::MAIN_MASTER) { + if let Some(info) = cx.main_master(m, environment, size) { + masters.insert(m.slide_id, info); + } + } + if cx.p.masters.is_empty() { + let m = cx.default_master(size, None); + cx.p.masters.push(Arc::new(m)); + } + for m in d.masters.iter().filter(|m| m.rec.kind == rt::SLIDE) { + cx.title_master(m, &mut masters); + } + + // Each slide's notes page, by the slide id its NotesAtom names (the first one wins), built once: + // a scan per slide would be slides × notes pages. + let mut notes_of: HashMap = HashMap::new(); + for (i, n) in d.notes.iter().enumerate() { + if n.rec.kind == rt::NOTES + && let Some(id) = n.rec.child(rt::NOTES_ATOM).and_then(|a| a.u32(0)) + { + notes_of.entry(id).or_insert(i); + } + } + // An unknown master falls back to the first main master. Title masters share their main + // master's index, so including them would tie, and HashMap order would pick the winner. Found + // once, as is each master's layout for each layout type: a search per slide would be slides × + // masters (or layouts). A title master's layout is only for the slides that name it. + let first_main = masters.values().filter(|m| m.layout.is_none()).min_by_key(|m| m.index).cloned(); + let title_layouts: HashSet = masters.values().filter_map(|m| m.layout).collect(); + let layouts: Vec = cx.p.masters.iter().map(|m| layout_table(m, &title_layouts)).collect(); + let find = Find { masters: &masters, first_main: first_main.as_ref(), layouts: &layouts, notes_of: ¬es_of }; + for s in &d.slides { + if s.rec.kind != rt::SLIDE { + continue; + } + if let Some(slide) = cx.slide(d, s, &find) { + cx.p.slides.push(Arc::new(slide)); + } + } + cx.p +} + +/// A master's first layout of each layout type, and its first layout. +type LayoutTable = (Vec<(LayoutType, LayoutId)>, Option); + +fn layout_table(m: &Master, skip: &HashSet) -> LayoutTable { + let mut kinds: Vec<(LayoutType, LayoutId)> = vec![]; + let layouts = m.layouts.iter().filter(|l| !skip.contains(&l.id)); + let first = layouts.clone().next().map(|l| l.id); + for l in layouts { + // Layout types are few, so the list stays short. + if !kinds.iter().any(|(k, _)| *k == l.kind) { + kinds.push((l.kind, l.id)); + } + } + (kinds, first) +} + +/// What a slide's master, layout and notes page are looked up in. +struct Find<'f> { + masters: &'f HashMap, + first_main: Option<&'f MasterInfo>, + layouts: &'f [LayoutTable], + notes_of: &'f HashMap, +} + +/// A converted master: where it went and what its slides inherit. +#[derive(Clone)] +struct MasterInfo { + index: usize, + scheme: Scheme, + styles: Arc, + /// A layout made for a title master; slides of that title master use it. + layout: Option, + /// This master's slide id, then its main master's for a title master. + ids: Chain, + /// The placeholders of the defaults' title layout, taken before any title master adds layouts + /// of its own: what each title master's layout starts from. Empty when there is none. + title_base: Arc>, +} + +impl<'a> Ctx<'a> { + fn alloc(&mut self) -> Option { + self.p.alloc_id() + } + + /// The caller's default master for slides of `size`, with ids above every id handed out so + /// far. With `theme`, the master wears it and is named after it. + fn default_master(&mut self, size: Size, theme: Option) -> Master { + let (mut master, last) = self.app.master(size, self.p.next_id); + self.p.next_id = self.p.next_id.max(last); + if let Some(theme) = theme { + master.name = theme.name.clone(); + master.theme = theme; + } + master + } + + fn main_master(&mut self, m: &Listed<'a>, environment: Option>, size: Size) -> Option { + let scheme = scheme_of(&m.rec).unwrap_or(DEFAULT_SCHEME); + let styles = Arc::new(StyleSheet::new(environment, Some(&m.rec))); + let theme = self.theme(&scheme, &styles); + let mut master = self.default_master(size, Some(theme)); + let drawing = draw::drawing(&m.rec); + self.remember_master_props(m.slide_id, &drawing.shapes, 0); + let ids = [Some(m.slide_id), None]; + let scope = + Scope { scheme, styles: &styles, outline: &m.outline, numbering: &[], used_outline: Default::default(), master: true, masters: ids }; + master.background = drawing.background.as_ref().and_then(|b| self.background(b, &scope)); + for raw in &drawing.shapes { + if let Some(ph) = raw.placeholder.filter(|p| p.kind != 0) { + // The master's placeholders set where new slides' placeholders go. + if let (Some(kind), Some(x)) = (ph_type(ph.kind), raw.anchor.map(|a| xfrm(&a, TOP, 0.0, false, false))) + && let Some(s) = master.shapes.iter_mut().find(|s| s.ph_type().is_some_and(|t| same_family(t, kind))) + { + s.xfrm = Some(x); + // The footer row sits in the same place on every layout, with the master's look: + // its first paragraph's alignment and its first run's size and colour. + if matches!(kind, PhType::Date | PhType::Footer | PhType::SlideNum) { + let look = self.shape(raw, &scope, 0, TOP).and_then(|c| c.text).and_then(|t| t.paragraphs.into_iter().next()); + let style = |t: &mut TextBody| { + if let Some(p) = &look { + let mut level = t.list_style.level(0).cloned().unwrap_or_default(); + level.para.align = p.props.align.or(level.para.align); + if let Some(run) = p.runs.first() { + level.run.size = run.props.size.or(level.run.size); + level.run.fill = run.props.fill.clone().or(level.run.fill.take()); + } + t.list_style.set(0, level); + } + }; + if let Some(t) = s.text.as_mut() { + style(t); + } + for l in &mut master.layouts { + for ls in l.shapes.iter_mut().filter(|ls| ls.ph_type() == Some(kind)) { + ls.xfrm = Some(x); + if let Some(t) = ls.text.as_mut() { + style(t); + } + } + } + } + } + continue; + } + if let Some(s) = self.shape(raw, &scope, 0, TOP) { + master.shapes.push(s); + } + } + master.title_style = self.list_style(&styles, ty::TITLE, &scheme); + master.body_style = self.list_style(&styles, ty::BODY, &scheme); + master.other_style = self.list_style(&styles, ty::OTHER, &scheme); + let title_base = master + .layouts + .iter() + .find(|l| l.kind == LayoutType::Title) + .map(|l| l.shapes.iter().filter(|s| s.ph.is_some()).cloned().collect()) + .unwrap_or_default(); + let index = self.p.masters.len(); + self.p.masters.push(Arc::new(master)); + Some(MasterInfo { index, scheme, styles, layout: None, ids, title_base: Arc::new(title_base) }) + } + + /// A title master: a layout of its main master holding its background and shapes. + fn title_master(&mut self, m: &Listed<'a>, masters: &mut HashMap) { + let atom = doc::slide_atom(&m.rec); + let Some(parent) = masters.get(&atom.master_id).cloned() else { return }; + let scheme = if atom.follow_master_scheme { parent.scheme } else { scheme_of(&m.rec).unwrap_or(parent.scheme) }; + let Some(id) = self.alloc() else { return }; + let drawing = draw::drawing(&m.rec); + self.remember_master_props(m.slide_id, &drawing.shapes, 0); + let ids = [Some(m.slide_id), parent.ids[0]]; + let scope = Scope { + scheme, + styles: &parent.styles, + outline: &m.outline, + numbering: &[], + used_outline: Default::default(), + master: true, + masters: ids, + }; + let background = if atom.follow_master_background { None } else { drawing.background.as_ref().and_then(|b| self.background(b, &scope)) }; + let shapes: Vec = + drawing.shapes.iter().filter(|r| r.placeholder.is_none_or(|p| p.kind == 0)).filter_map(|r| self.shape(r, &scope, 0, TOP)).collect(); + // Its placeholders follow the main master's own title layout (from the defaults, taken once + // when the main master was made), with ids of their own. A layout made for an earlier title + // master holds that one's shapes and placeholder boxes, so it is never the base. + let mut placeholders = Vec::with_capacity(parent.title_base.len()); + for mut s in parent.title_base.iter().cloned() { + let Some(id) = self.alloc() else { break }; + s.id = ShapeId(id); + placeholders.push(s); + } + // The title master's own placeholders say where its slides' placeholders go, as a main + // master's do; one the title layout lacks is added. + for raw in &drawing.shapes { + let Some(ph) = raw.placeholder.filter(|p| p.kind != 0) else { continue }; + let (Some(kind), Some(x)) = (ph_type(ph.kind), raw.anchor.map(|a| xfrm(&a, TOP, 0.0, false, false))) else { continue }; + if let Some(s) = placeholders.iter_mut().find(|s| s.ph_type().is_some_and(|t| same_family(t, kind))) { + s.xfrm = Some(x); + continue; + } + let Some(id) = self.alloc() else { break }; + placeholders.push(Shape { + id: ShapeId(id), + name: raw.props.string(prop::NAME).unwrap_or_else(|| default_name(raw)), + xfrm: Some(x), + ph: Some(Placeholder { kind, idx: ph.position, ..Default::default() }), + text: Some(TextBody::default()), + ..Default::default() + }); + } + let Some(master) = self.p.masters.get_mut(parent.index) else { return }; + Arc::make_mut(master).layouts.push(Layout { + id: LayoutId(id), + name: "Title Master".into(), + kind: LayoutType::Title, + shapes: shapes.into_iter().chain(placeholders).collect(), + background, + show_master_shapes: atom.follow_master_objects, + ..Default::default() + }); + masters.insert(m.slide_id, MasterInfo { layout: Some(LayoutId(id)), scheme, ids, ..parent }); + } + + fn remember_master_props(&mut self, master: u32, shapes: &[RawShape<'a>], depth: usize) { + if depth > MAX_DEPTH { + return; + } + for s in shapes { + self.master_props.insert((master, s.spid), s.props.clone()); + self.remember_master_props(master, &s.children, depth + 1); + } + } + + /// A theme carrying the master's colours and fonts, so shapes added later match the deck. + fn theme(&self, scheme: &Scheme, styles: &StyleSheet) -> Theme { + let mut t = Theme { name: "Imported".into(), ..Default::default() }; + for (slot, i) in [ + (SchemeSlot::Lt1, 0), + (SchemeSlot::Dk1, 1), + (SchemeSlot::Lt2, 2), + (SchemeSlot::Dk2, 3), + (SchemeSlot::Accent1, 4), + (SchemeSlot::Accent2, 5), + (SchemeSlot::Hlink, 6), + (SchemeSlot::FolHlink, 7), + ] { + if let Some(c) = scheme.get(i) { + t.colors.set(slot, *c); + } + } + if let Some(f) = styles.resolve(ty::TITLE, 0).1.font.and_then(|i| self.fonts.get(usize::from(i))) { + t.fonts.major.latin = f.clone(); + } + if let Some(f) = styles.resolve(ty::BODY, 0).1.font.and_then(|i| self.fonts.get(usize::from(i))) { + t.fonts.minor.latin = f.clone(); + } + t + } + + fn list_style(&self, styles: &StyleSheet, text_type: u32, scheme: &Scheme) -> ListStyle { + let mut ls = ListStyle::default(); + for level in 0..5u8 { + let (pf, cf) = styles.resolve(text_type, level); + let run = self.run_props(&cf, scheme); + let para = self.para_props(&pf, scheme, run.size.unwrap_or(18.0)); + ls.set(level, LevelStyle { para, run }); + } + ls + } + + fn slide(&mut self, d: &Doc<'a>, s: &Listed<'a>, find: &Find) -> Option { + let atom = doc::slide_atom(&s.rec); + let info = find.masters.get(&atom.master_id).or(find.first_main).cloned(); + let (index, master_scheme, styles, title_layout, ids) = match &info { + Some(m) => (m.index, m.scheme, m.styles.clone(), m.layout, m.ids), + None => (0, DEFAULT_SCHEME, Arc::new(StyleSheet::new(d.document.child(rt::ENVIRONMENT), None)), None, [None; 2]), + }; + let scheme = if atom.follow_master_scheme { master_scheme } else { scheme_of(&s.rec).unwrap_or(master_scheme) }; + let layout = title_layout.or_else(|| { + let kind = layout_kind(atom.geom); + let (kinds, first) = find.layouts.get(index)?; + kinds.iter().find(|(k, _)| *k == kind).map(|(_, id)| *id).or(*first) + })?; + let id = SlideId(self.alloc()?); + let drawing = draw::drawing(&s.rec); + // The n-th outline block of a text type takes the n-th numbering entry for that type. + let mut seen: HashMap = HashMap::new(); + let numbering: Vec>> = s + .outline + .iter() + .map(|block| { + let tt = block.clone().next().filter(|h| h.kind == rt::TEXT_HEADER).and_then(|h| h.u32(0))?; + let k = seen.entry(tt).or_insert(0); + let n = *k; + *k += 1; + self.numbering.get(&(s.slide_id, tt)).and_then(|v| v.get(n)).cloned() + }) + .collect(); + let scope = Scope { + scheme, + styles: &styles, + outline: &s.outline, + numbering: &numbering, + used_outline: Default::default(), + master: false, + masters: ids, + }; + let background = if atom.follow_master_background { None } else { drawing.background.as_ref().and_then(|b| self.background(b, &scope)) }; + let mut shapes: Vec = drawing.shapes.iter().filter_map(|r| self.shape(r, &scope, 0, TOP)).collect(); + // The slide's own headers and footers, else the document's for every slide. + if let Some(hf) = doc::headers_footers(&s.rec, 0).or_else(|| doc::headers_footers(&d.document, 3)) { + self.footers(&mut shapes, &hf); + } + let hidden = s.rec.child(rt::SLIDE_SHOW_SLIDE_INFO).and_then(|i| i.u16(10)).is_some_and(|f| f & 0x4 != 0); + let notes = find + .notes_of + .get(&s.slide_id) + .filter(|&&i| self.used_notes.insert(i)) + .and_then(|&i| d.notes.get(i)) + .map(|n| self.notes(n, &styles, scheme)) + .unwrap_or_default(); + Some(Slide { id, layout, shapes, background, hidden, show_master_shapes: atom.follow_master_objects, notes, ..Default::default() }) + } + + /// The date, footer and slide number placeholders `hf` turns on, for those the slide doesn't + /// hold itself. They take their place and look from the layout and master. + fn footers(&mut self, shapes: &mut Vec, hf: &doc::HeadersFooters) { + let field = |text: &str, field: String| TextBody { + paragraphs: vec![Paragraph { + runs: vec![Run { text: text.into(), props: Default::default(), kind: RunKind::Field { field } }], + ..Default::default() + }], + ..Default::default() + }; + let wanted = [ + (PhType::Date, hf.date, "Date Placeholder"), + (PhType::Footer, hf.footer && !hf.footer_text.is_empty(), "Footer Placeholder"), + (PhType::SlideNum, hf.slide_number, "Slide Number Placeholder"), + ]; + for (kind, on, name) in wanted { + if !on || shapes.iter().any(|s| s.ph_type() == Some(kind)) { + continue; + } + let text = match kind { + PhType::SlideNum => field("‹#›", "slidenum".into()), + PhType::Date if hf.user_date => TextBody::from_text(&hf.date_text), + // formatId 0–12 are the thirteen date formats, in DrawingML's order. + PhType::Date => field("", format!("datetime{}", hf.format.min(12) + 1)), + _ => TextBody::from_text(&hf.footer_text), + }; + let Some(id) = self.alloc() else { return }; + shapes.push(Shape { + id: ShapeId(id), + name: name.into(), + ph: Some(Placeholder { kind, ..Default::default() }), + text: Some(text), + ..Default::default() + }); + } + } + + /// The text of a notes page's notes placeholder. + fn notes(&mut self, n: &Listed<'a>, styles: &StyleSheet, scheme: Scheme) -> TextBody { + let drawing = draw::drawing(&n.rec); + // Notes masters aren't imported, so there are no master shapes to inherit from. + let scope = + Scope { scheme, styles, outline: &n.outline, numbering: &[], used_outline: Default::default(), master: false, masters: [None; 2] }; + for raw in &drawing.shapes { + let Some(block) = self.text_block(raw, &scope) else { continue }; + // The notes body placeholder; a slide number or header placeholder on the page isn't notes. + let is_notes = match raw.placeholder.filter(|p| p.kind != 0) { + Some(p) => matches!(p.kind, 0x06 | 0x0C), + None => block.text_type == ty::NOTES, + }; + if is_notes { + let mut body = self.text_body(&block, &scope, &raw.props); + body.body = BodyProps::default(); + return body; + } + } + TextBody::default() + } + + fn background(&mut self, raw: &RawShape<'a>, scope: &Scope) -> Option { + let props = self.props_of(raw, scope, false); + let fill = self.fill(&props, scope, true)?; + Some(Background::Fill { fill }) + } + + /// The shape's properties with what it inherits: its master shape's, then (for placeholders, + /// text boxes and picture frames) no fill and no line, then the drawing defaults. + fn props_of(&self, raw: &RawShape<'a>, scope: &Scope, unfilled: bool) -> Props<'a> { + let mut props = raw.props.clone(); + let inherited = + props.get(prop::HSP_MASTER).and_then(|spid| scope.masters.iter().flatten().find_map(|&master| self.master_props.get(&(master, spid)))); + if let Some(m) = inherited { + props.inherit(m); + } + if unfilled { + props.inherit(&no_fill_no_line()); + } + props.inherit(&self.defaults); + props + } + + fn shape(&mut self, raw: &RawShape<'a>, scope: &Scope, depth: usize, map: Map) -> Option { + if raw.deleted || depth > MAX_DEPTH { + return None; + } + let ph = raw.placeholder.filter(|p| p.kind != 0); + let text_box = raw.shape_type == 202; + // A picture frame (also an OLE object's frame) shows its picture with no fill or line of + // its own unless it says so; the drawing defaults' fill would cover a transparent picture. + let picture_frame = raw.shape_type == PICTURE_FRAME; + let props = self.props_of(raw, scope, ph.is_some() || text_box || picture_frame); + let rot = props.fixed(prop::ROTATION).unwrap_or(0.0); + let anchor = raw.anchor?; + let mut s = Shape { + id: ShapeId(self.alloc()?), + name: props.string(prop::NAME).unwrap_or_else(|| default_name(raw)), + xfrm: Some(xfrm(&anchor, map, rot, raw.flip_h, raw.flip_v)), + descr: props.string(prop::DESCRIPTION).unwrap_or_default(), + hidden: props.flag(prop::GROUP_BOOLS, 1).unwrap_or(false), + ..Default::default() + }; + if raw.is_group { + // Children are placed in slide points; the group's child space is its own box. + let at = s.xfrm.unwrap_or_default(); + let inner = Map::into_group(&at, &raw.group_rect.unwrap_or(anchor)); + let children = raw.children.iter().filter_map(|c| self.shape(c, scope, depth + 1, inner)).collect(); + let child = Xfrm::new(at.x, at.y, at.w, at.h); + s.kind = ShapeKind::Group { children, child }; + return Some(s); + } + if !scope.master + && let Some(ph) = ph + && let Some(kind) = ph_type(ph.kind) + { + s.ph = Some(Placeholder { kind, idx: ph.position, ..Default::default() }); + } + s.geom = geom::geometry(raw.shape_type, &props); + if geom::is_connector(raw.shape_type) { + s.kind = ShapeKind::Connector { start: None, end: None }; + } + // A picture: a picture frame, or any shape showing a picture (an OLE object's preview). + if let Some(media) = self.picture(&props, prop::PIB) { + let crop = |id| props.fixed(id).unwrap_or(0.0).clamp(-1.0, 1.0); + s.kind = ShapeKind::Picture { + fill: PictureFill { + media, + crop: [crop(prop::CROP_LEFT), crop(prop::CROP_TOP), crop(prop::CROP_RIGHT), crop(prop::CROP_BOTTOM)], + ..Default::default() + }, + }; + } + s.fill = Some(self.fill(&props, scope, false).unwrap_or(Fill::None)); + s.line = Some(self.line(&props, scope)); + if let Some(shadow) = self.shadow(&props, scope) { + s.effects = Some(Effects { outer_shadow: Some(shadow), ..Default::default() }); + } + if let Some(block) = self.text_block(raw, scope) { + s.text = Some(self.text_body(&block, scope, &props)); + } else if ph.is_some() { + // An empty placeholder draws nothing (its prompt shows only while editing). + s.text = Some(TextBody::default()); + } + Some(s) + } + + /// The picture a `pib` or `fillBlip` property names: a blip store entry (1-based), or a blip + /// held in the property's own complex bytes. + fn picture(&mut self, props: &Props<'a>, id: u16) -> Option { + let Some(bytes) = props.complex(id) else { + return props.get(id).filter(|&i| i > 0).and_then(|i| self.media(i as usize)); + }; + let key = bytes.as_ptr() as usize; + if let Some(m) = self.inline_media.get(&key) { + return *m; + } + let n = self.inline_media.len() + 1; + let id = self.blips.decode_inline(bytes).and_then(|pic| self.p.add_media(&format!("inline{n}.{}", pic.ext), pic.content_type, pic.data)); + self.inline_media.insert(key, id); + id + } + + fn media(&mut self, pib: usize) -> Option { + if let Some(m) = self.media.get(&pib) { + return *m; + } + let id = + self.blips.take(pib.wrapping_sub(1)).and_then(|pic| self.p.add_media(&format!("image{pib}.{}", pic.ext), pic.content_type, pic.data)); + self.media.insert(pib, id); + id + } + + fn color(&self, v: u32, props: &Props, scope: &Scope, depth: u8) -> Rgba { + let [r, g, b, flags] = v.to_le_bytes(); + if flags & 0x08 != 0 { + return scope.scheme.get(usize::from(r)).copied().unwrap_or(Rgba::BLACK); + } + if flags & 0x10 != 0 { + // A system colour index; the high ones stand for the shape's own fill and line colours. + let other = match r { + 0xF0 => Some(prop::FILL_COLOR), + 0xF1 => Some(prop::LINE_COLOR), + 0xF3 => Some(prop::FILL_BACK_COLOR), + _ => None, + }; + return match other.and_then(|id| props.get(id)) { + Some(o) if depth < 2 => self.color(o, props, scope, depth + 1), + _ => Rgba::BLACK, + }; + } + if flags & 0x01 != 0 { + return Rgba::BLACK; + } + Rgba::rgb(r, g, b) + } + + fn color_ref(&self, id: u16, fallback: u32, opacity: Option, props: &Props, scope: &Scope) -> ColorRef { + let c = ColorRef::rgb(self.color(props.get(id).unwrap_or(fallback), props, scope, 0)); + match opacity.and_then(|o| props.fixed(o)).filter(|a| *a < 1.0) { + Some(a) => c.with(ColorTransform::Alpha((a.clamp(0.0, 1.0) * 100_000.0) as i32)), + None => c, + } + } + + fn fill(&mut self, props: &Props<'a>, scope: &Scope, background: bool) -> Option { + if !background && !props.flag(prop::FILL_BOOLS, 4).unwrap_or(true) { + return None; + } + let fg = self.color_ref(prop::FILL_COLOR, 0x00FF_FFFF, Some(prop::FILL_OPACITY), props, scope); + let bg = self.color_ref(prop::FILL_BACK_COLOR, 0x00FF_FFFF, Some(prop::FILL_BACK_OPACITY), props, scope); + Some(match props.get(prop::FILL_TYPE).unwrap_or(0) { + // Texture (tiled) and picture (stretched). + t @ (2 | 3) => match self.picture(props, prop::FILL_BLIP) { + Some(media) => { + let mode = if t == 2 { + PictureMode::Tile { tx: 0.0, ty: 0.0, sx: 1.0, sy: 1.0, flip: String::new(), align: "tl".into() } + } else { + PictureMode::default() + }; + Fill::Picture(PictureFill { media, mode, ..Default::default() }) + } + None => Fill::solid(fg), + }, + // Gradients. + t @ 4..=8 => { + use craft_pptx::style::{Gradient, GradientShape}; + let focus = props.get(prop::FILL_FOCUS).map_or(0, |v| v as i32).clamp(-100, 100); + let stops = gradient_stops(focus, &fg, &bg); + let shape = if matches!(t, 5 | 6) { + // Position 0 is the centre (the focus rectangle), 1 the shape's edge. + GradientShape::Path { path: if t == 5 { "rect".into() } else { "shape".into() }, focus: [0.5, 0.5, 0.5, 0.5] } + } else { + GradientShape::Linear { angle: linear_angle(props.fixed(prop::FILL_ANGLE).unwrap_or(0.0)), scaled: false } + }; + Fill::Gradient(Gradient { stops, shape: Some(shape), flip: None, rotate_with_shape: Some(true), tile: [0.0; 4] }) + } + 9 => Fill::Background, + _ => Fill::solid(fg), + }) + } + + fn line(&self, props: &Props, scope: &Scope) -> Line { + if !props.flag(prop::LINE_BOOLS, 3).unwrap_or(true) { + return Line::none(); + } + let width = props.get(prop::LINE_WIDTH).map_or(9525.0, f64::from) / EMU; + let mut l = Line::solid(self.color_ref(prop::LINE_COLOR, 0, Some(prop::LINE_OPACITY), props, scope), width); + l.dash = Some(Dash::Preset { + name: match props.get(prop::LINE_DASHING).unwrap_or(0) { + 1 => "sysDash", + 2 => "sysDot", + 3 => "sysDashDot", + 4 => "sysDashDotDot", + 5 => "dot", + 6 => "dash", + 7 => "lgDash", + 8 => "dashDot", + 9 => "lgDashDot", + 10 => "lgDashDotDot", + _ => "solid", + } + .into(), + }); + l.compound = props.get(prop::LINE_STYLE).map(|v| match v { + 1 => craft_pptx::style::Compound::Double, + 2 => craft_pptx::style::Compound::ThickThin, + 3 => craft_pptx::style::Compound::ThinThick, + 4 => craft_pptx::style::Compound::Triple, + _ => craft_pptx::style::Compound::Single, + }); + l.join = props.get(prop::LINE_JOIN).map(|v| match v { + 0 => LineJoin::Bevel, + 1 => LineJoin::Miter, + _ => LineJoin::Round, + }); + l.cap = props.get(prop::LINE_CAP).map(|v| match v { + 0 => LineCap::Round, + 1 => LineCap::Square, + _ => LineCap::Flat, + }); + let end = |kind: u16, w: u16, len: u16| { + let k = match props.get(kind).unwrap_or(0) { + 1 => "triangle", + 2 => "stealth", + 3 => "diamond", + 4 => "oval", + 5 => "arrow", + _ => return None, + }; + let size = |v: Option| match v { + Some(0) => "sm", + Some(2) => "lg", + _ => "med", + }; + Some(LineEnd { kind: k.into(), w: size(props.get(w)).into(), len: size(props.get(len)).into() }) + }; + l.head = end(prop::LINE_START_ARROW, prop::LINE_START_ARROW_WIDTH, prop::LINE_START_ARROW_LENGTH); + l.tail = end(prop::LINE_END_ARROW, prop::LINE_END_ARROW_WIDTH, prop::LINE_END_ARROW_LENGTH); + l + } + + fn shadow(&self, props: &Props, scope: &Scope) -> Option { + if !props.flag(prop::SHADOW_BOOLS, 1).unwrap_or(false) { + return None; + } + let dx = props.get(prop::SHADOW_OFFSET_X).map_or(25400.0, |v| f64::from(v as i32)) / EMU; + let dy = props.get(prop::SHADOW_OFFSET_Y).map_or(25400.0, |v| f64::from(v as i32)) / EMU; + Some(Shadow { + color: self.color_ref(prop::SHADOW_COLOR, 0x0080_8080, Some(prop::SHADOW_OPACITY), props, scope), + blur: 0.0, + dist: dx.hypot(dy), + dir: dy.atan2(dx).to_degrees().rem_euclid(360.0), + inner: false, + sx: 1.0, + sy: 1.0, + kx: 0.0, + ky: 0.0, + align: String::new(), + rotate_with_shape: false, + }) + } + + /// The text block of a shape: its own, or the slide list's outline block it points at. A text + /// box holding the reference may also hold its own ruler ([MS-PPT] OfficeArtClientTextbox: + /// `OutlineTextRefAtom` then an optional `TextRulerAtom`); the margins and indents it sets + /// win over the block's. + fn text_block(&self, raw: &RawShape<'a>, scope: &Scope) -> Option { + let tb = raw.text?; + let own = text::read_block(tb.children())?; + let own_ruler = own.ruler; + match own.outline_ref { + Some(i) if own.chars.is_empty() && scope.used_outline.borrow_mut().insert(i as usize) => scope + .outline + .get(i as usize) + .and_then(|r| text::read_block(r.clone())) + .map(|mut b| { + b.outline_index = Some(i as usize); + for ((lm, ind), (own_lm, own_ind)) in b.ruler.iter_mut().zip(own_ruler) { + *lm = own_lm.or(*lm); + *ind = own_ind.or(*ind); + } + b + }) + .or(Some(own)), + _ => Some(own), + } + } + + fn text_body(&self, block: &TextBlock, scope: &Scope, props: &Props) -> TextBody { + let inset = |id, d: f64| props.get(id).map_or(d, |v| f64::from(v as i32) / EMU).max(0.0); + let body = BodyProps { + inset_l: Some(inset(prop::TEXT_LEFT, 7.2)), + inset_t: Some(inset(prop::TEXT_TOP, 3.6)), + inset_r: Some(inset(prop::TEXT_RIGHT, 7.2)), + inset_b: Some(inset(prop::TEXT_BOTTOM, 3.6)), + anchor: Some(match props.get(prop::ANCHOR_TEXT).unwrap_or(0) { + // middle, middle centred + 1 | 4 => TextAnchor::Middle, + // bottom, bottom centred, and their baseline forms + 2 | 5 | 7 | 9 => TextAnchor::Bottom, + _ => TextAnchor::Top, + }), + anchor_ctr: Some(matches!(props.get(prop::ANCHOR_TEXT), Some(3 | 4 | 5 | 8 | 9))), + wrap: Some(props.get(prop::WRAP_TEXT) != Some(2)), + autofit: Some(AutoFit::None), + ..Default::default() + }; + TextBody { body, paragraphs: self.paragraphs(block, scope), ..Default::default() } + } + + fn paragraphs(&self, block: &TextBlock, scope: &Scope) -> Vec { + let chars = &block.chars; + let total = chars.len(); + let fields: HashMap = block.fields.iter().map(|(p, k)| (*p as usize, *k)).collect(); + // Where each formatting run starts. + let starts = |counts: &mut dyn Iterator| -> Vec { + let mut at = 0usize; + counts + .map(|n| { + let s = at; + at = at.saturating_add(n as usize); + s + }) + .collect() + }; + let para_starts = starts(&mut block.para_runs.iter().map(|r| r.0)); + let char_starts = starts(&mut block.char_runs.iter().map(|r| r.0)); + // The starts never decrease (a running sum), so both lookups are binary searches. A scan per + // run, break and field made text with many runs quadratic: 1M one-character runs, about 10 MB + // of file, took minutes. + let run_at = |starts: &[usize], i: usize| starts.partition_point(|&s| s <= i).checked_sub(1); + let mut out = vec![]; + let mut start = 0usize; + loop { + let end = chars.get(start..).and_then(|rest| rest.iter().position(|&c| c == 0x0D)).map_or(total, |e| start + e); + let (level, pf_exc) = run_at(¶_starts, start).and_then(|i| block.para_runs.get(i)).map_or((0, None), |r| (r.1, Some(&r.2))); + let (mut pf, base_cf) = scope.styles.resolve(block.text_type, level); + if let Some((lm, ind)) = block.ruler.get(usize::from(level)) { + if lm.is_some() { + pf.left_margin = *lm; + } + if ind.is_some() { + pf.indent = *ind; + } + } + if let Some(e) = pf_exc { + pf.apply(e); + } + let cf_at = |i: usize| -> Cf { + let mut cf = base_cf.clone(); + if let Some(e) = run_at(&char_starts, i).and_then(|k| block.char_runs.get(k)) { + cf.apply(&e.1); + } + cf + }; + let first_cf = cf_at(start); + let first = self.run_props(&first_cf, &scope.scheme); + let mut para = Paragraph { level, props: self.para_props(&pf, &scope.scheme, first.size.unwrap_or(18.0)), ..Default::default() }; + // A bulleted paragraph whose PowerPoint 2000 formatting numbers it. + if matches!(para.props.bullet, Some(Bullet::Char { .. })) + && let Some((scheme, start_at)) = block + .outline_index + .and_then(|i| scope.numbering.get(i)) + .and_then(Option::as_ref) + .zip(first_cf.pp9rt) + .and_then(|(entries, i)| entries.get(usize::from(i))) + .and_then(|e| e.auto_number) + { + para.props.bullet = + Some(Bullet::AutoNum { scheme: text::auto_number_scheme(scheme).into(), start_at: u32::try_from(start_at).unwrap_or(1).max(1) }); + } + let mut i = start; + while i < end { + let props = self.run_props(&cf_at(i), &scope.scheme); + let c = chars.get(i).copied().unwrap_or(0); + if let Some(k) = fields.get(&i) { + let field = match k { + FieldKind::SlideNumber => "slidenum", + FieldKind::DateTime => "datetime1", + }; + para.runs.push(Run { + text: if *k == FieldKind::SlideNumber { "‹#›".into() } else { String::new() }, + props, + kind: RunKind::Field { field: field.into() }, + }); + i += 1; + continue; + } + if c == 0x0B { + para.runs.push(Run { text: String::new(), props, kind: RunKind::Break }); + i += 1; + continue; + } + // A text run: up to the next format change, field, break or the paragraph's end. + let next_change = char_starts.get(char_starts.partition_point(|&s| s <= i)).copied().unwrap_or(end).min(end); + let mut j = i; + while j < next_change && !fields.contains_key(&j) && chars.get(j) != Some(&0x0B) { + j += 1; + } + let j = j.max(i + 1); + let units: Vec = chars.get(i..j).unwrap_or(&[]).iter().copied().filter(|&u| u >= 0x20 || u == 0x09).collect(); + para.runs.push(Run::with(String::from_utf16_lossy(&units), props)); + i = j; + } + para.end_props = first; + para.normalize(); + out.push(para); + if end >= total { + break; + } + start = end + 1; + } + out + } + + fn run_props(&self, cf: &Cf, scheme: &Scheme) -> RunProps { + let font = |i: Option| i.and_then(|i| self.fonts.get(usize::from(i))).filter(|f| !f.is_empty()).cloned(); + RunProps { + font: font(cf.font).or_else(|| self.fonts.first().cloned()), + font_ea: font(cf.ea_font), + font_sym: font(cf.symbol_font), + size: cf.size.map(f64::from).filter(|s| (1.0..=4000.0).contains(s)), + bold: Some(cf.bold.unwrap_or(false)), + italic: Some(cf.italic.unwrap_or(false)), + underline: Some(if cf.underline.unwrap_or(false) { "sng" } else { "none" }.into()), + baseline: cf.position.filter(|p| *p != 0).map(|p| f64::from(p) / 100.0), + fill: cf.color.map(|c| Fill::solid(ColorRef::rgb(text_color(c, scheme)))), + shadow: cf.shadow.filter(|&on| on).map(|_| text_shadow(scheme)), + ..Default::default() + } + } + + fn para_props(&self, pf: &Pf, scheme: &Scheme, text_size: f64) -> ParaProps { + let spacing = |v: i16| if v >= 0 { Spacing::Pct(f64::from(v) / 100.0) } else { Spacing::Pts(-f64::from(v) / MU) }; + let margin = f64::from(pf.left_margin.unwrap_or(0)) / MU; + let indent = f64::from(pf.indent.unwrap_or(0)) / MU; + let bullet = if pf.has_bullet == Some(true) { + let c = pf.bullet_char.filter(|&c| c >= 0x20).unwrap_or(0x2022); + Bullet::Char { char: char::from_u32(u32::from(c)).unwrap_or('•').to_string() } + } else { + Bullet::None + }; + let has_bullet = matches!(bullet, Bullet::Char { .. }); + ParaProps { + align: Some(match pf.align.unwrap_or(0) { + 1 => Align::Center, + 2 => Align::Right, + 3 | 5 => Align::Justify, + 4 => Align::Distributed, + 6 => Align::JustLow, + _ => Align::Left, + }), + margin_left: Some(margin), + indent: Some(indent - margin), + line_spacing: Some(spacing(pf.line_spacing.unwrap_or(100))), + space_before: Some(spacing(pf.space_before.unwrap_or(0))), + space_after: Some(spacing(pf.space_after.unwrap_or(0))), + bullet: Some(bullet), + bullet_font: if has_bullet && pf.bullet_has_font == Some(true) { + pf.bullet_font.and_then(|i| self.fonts.get(usize::from(i))).cloned() + } else { + None + }, + bullet_color: if has_bullet && pf.bullet_has_color == Some(true) { + pf.bullet_color.map(|c| ColorRef::rgb(text_color(c, scheme))) + } else { + None + }, + bullet_size: if has_bullet && pf.bullet_has_size == Some(true) { + pf.bullet_size.map(|v| if v > 0 { f64::from(v) / 100.0 } else { -f64::from(v) / text_size.max(1.0) }).map(|v| v.clamp(0.25, 4.0)) + } else { + None + }, + default_tab: pf.default_tab.map(|t| f64::from(t) / MU), + tabs: pf.tabs.as_ref().map(|t| { + t.iter() + .map(|(pos, kind)| TabStop { + pos: f64::from(*pos) / MU, + align: match kind { + 1 => "ctr", + 2 => "r", + 3 => "dec", + _ => "l", + } + .into(), + }) + .collect() + }), + ..Default::default() + } + } +} + +fn text_color(c: TextColor, scheme: &Scheme) -> Rgba { + match c { + TextColor::Rgb(r, g, b) => Rgba::rgb(r, g, b), + TextColor::Scheme(i) => scheme.get(usize::from(i)).copied().unwrap_or(Rgba::BLACK), + } +} + +/// A text shadow in the colour scheme's shadow colour. The record holds only the on/off bit, so +/// the distance and direction are the app's own Text Shadow command's (`format.textShadow`); with +/// no blur in the record, none is added. +fn text_shadow(scheme: &Scheme) -> Shadow { + Shadow { + color: ColorRef::rgb(scheme.get(2).copied().unwrap_or(Rgba::rgb(0x80, 0x80, 0x80))), + blur: 0.0, + dist: 2.0, + dir: 45.0, + inner: false, + sx: 1.0, + sy: 1.0, + kx: 0.0, + ky: 0.0, + align: String::new(), + rotate_with_shape: false, + } +} + +/// A shaded fill's stops ([MS-ODRAW] `fillFocus`: the position of the last colour, the back +/// colour). Focus 0 starts at the back colour and ends at the fill colour, ±100 the other way; in +/// between, the back colour sits at that point with the fill colour at both ends. +fn gradient_stops(focus: i32, fg: &ColorRef, bg: &ColorRef) -> Vec { + use craft_pptx::style::GradientStop; + let stop = |pos: f64, c: &ColorRef| GradientStop { pos, color: c.clone() }; + match focus { + 0 => vec![stop(0.0, bg), stop(1.0, fg)], + 100 | -100 => vec![stop(0.0, fg), stop(1.0, bg)], + f => vec![stop(0.0, fg), stop(f64::from(f.abs()) / 100.0, bg), stop(1.0, fg)], + } +} + +/// The DrawingML angle (0° runs left to right, turning clockwise) of a linear fill's `fillAngle`, +/// for stops from [`gradient_stops`]: the gradient starts on the left at -90°, the top at -180°, +/// the right at -270°, turning clockwise as the angle falls. 0° starts at the top too: that is how +/// LibreOffice reads it, and how it writes a top-to-bottom gradient. +fn linear_angle(a: f64) -> f64 { + if a == 0.0 { 90.0 } else { (270.0 - a).rem_euclid(360.0) } +} + +/// `msosptPictureFrame`. +const PICTURE_FRAME: u16 = 75; + +fn no_fill_no_line<'a>() -> Props<'a> { + let mut p = Props::default(); + p.set(prop::FILL_BOOLS, 0x0010_0000); // fFilled set to false + p.set(prop::LINE_BOOLS, 0x0008_0000); // fLine set to false + p +} + +/// Maps anchor coordinates to slide points: master units at the top level, a group's child units +/// inside it (`x * sx + ox`). +#[derive(Clone, Copy, Debug)] +struct Map { + sx: f64, + sy: f64, + ox: f64, + oy: f64, +} + +const TOP: Map = Map { sx: 1.0 / MU, sy: 1.0 / MU, ox: 0.0, oy: 0.0 }; + +impl Map { + /// The map for the children of a group placed at `at` (points) whose child space is `rect`. + fn into_group(at: &Xfrm, rect: &draw::Anchor) -> Map { + let (w, h) = (rect.right - rect.left, rect.bottom - rect.top); + let sx = if w.abs() > f64::EPSILON { at.w / w } else { 0.0 }; + let sy = if h.abs() > f64::EPSILON { at.h / h } else { 0.0 }; + Map { sx, sy, ox: at.x - rect.left * sx, oy: at.y - rect.top * sy } + } +} + +/// A box in points from an anchor. A shape turned by 45–135° or 225–315° stores the box of its +/// turned outline: swap it back. +fn xfrm(a: &draw::Anchor, m: Map, rot: f64, flip_h: bool, flip_v: bool) -> Xfrm { + let finite = |v: f64| if v.is_finite() { v } else { 0.0 }; + let (l, t, r, b) = (finite(a.left * m.sx + m.ox), finite(a.top * m.sy + m.oy), finite(a.right * m.sx + m.ox), finite(a.bottom * m.sy + m.oy)); + let (mut x, mut y, mut w, mut h) = (l.min(r), t.min(b), (r - l).abs(), (b - t).abs()); + let rot = if rot.is_finite() { rot.rem_euclid(360.0) } else { 0.0 }; + if (45.0..135.0).contains(&rot) || (225.0..315.0).contains(&rot) { + let (cx, cy) = (x + w / 2.0, y + h / 2.0); + std::mem::swap(&mut w, &mut h); + x = cx - w / 2.0; + y = cy - h / 2.0; + } + Xfrm { x, y, w, h, rot, flip_h, flip_v } +} + +fn default_name(raw: &RawShape) -> String { + match raw.shape_type { + 75 => "Picture".into(), + 202 => "Text Box".into(), + 20 => "Line".into(), + _ if raw.is_group => "Group".into(), + _ => format!("Shape {}", raw.spid & 0x3FF), + } +} + +/// `PlaceholderEnum` as a placeholder type. +fn ph_type(kind: u8) -> Option { + Some(match kind { + 0x01 | 0x0D | 0x11 => PhType::Title, + 0x03 | 0x0F => PhType::CtrTitle, + 0x04 | 0x10 => PhType::SubTitle, + 0x02 | 0x06 | 0x0C | 0x0E | 0x12 => PhType::Body, + 0x07 => PhType::Date, + 0x08 => PhType::SlideNum, + 0x09 => PhType::Footer, + 0x0A => PhType::Header, + 0x05 | 0x0B => PhType::SlideImage, + 0x13 | 0x19 => PhType::Obj, + 0x14 => PhType::Chart, + 0x15 => PhType::Table, + 0x16 => PhType::ClipArt, + 0x17 => PhType::Diagram, + 0x18 => PhType::Media, + 0x1A => PhType::Picture, + _ => return None, + }) +} + +fn same_family(a: PhType, b: PhType) -> bool { + let title = |t| matches!(t, PhType::Title | PhType::CtrTitle); + a == b || (title(a) && title(b)) +} + +/// `SlideLayoutType` as a layout type. +fn layout_kind(geom: u32) -> LayoutType { + match geom { + 0 => LayoutType::Title, + 7 => LayoutType::TitleOnly, + 8 | 9 | 10 | 11 | 13 | 14 => LayoutType::TwoContent, + 16 => LayoutType::Blank, + 17 => LayoutType::VerticalTitleAndText, + 18 => LayoutType::TitleAndVerticalText, + _ => LayoutType::TitleAndContent, + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + + /// [MS-ODRAW] `fillFocus` is where the back colour sits; LibreOffice draws 0° from the top + /// (storytold/deckcraft#1137 review: the linear gradient's colours were reversed, the radial one inside out). + #[test] + fn shaded_fills_put_the_back_colour_at_the_focus() { + let (fg, bg) = (ColorRef::rgb(Rgba::rgb(255, 0, 0)), ColorRef::rgb(Rgba::rgb(0, 0, 255))); + let at = |stops: &[craft_pptx::style::GradientStop]| stops.iter().map(|s| (s.pos, s.color == fg)).collect::>(); + assert_eq!(at(&gradient_stops(0, &fg, &bg)), [(0.0, false), (1.0, true)]); + assert_eq!(at(&gradient_stops(100, &fg, &bg)), [(0.0, true), (1.0, false)]); + assert_eq!(at(&gradient_stops(-50, &fg, &bg)), [(0.0, true), (0.5, false), (1.0, true)]); + // 0° and -180° start at the top, -90° on the left, -270° on the right, -315° at the + // bottom right (DrawingML: 90° runs top to bottom, 0° left to right). + for (a, dm) in [(0.0, 90.0), (-90.0, 0.0), (-180.0, 90.0), (-270.0, 180.0), (-315.0, 225.0), (-45.0, 315.0)] { + assert_eq!(linear_angle(a), dm, "{a}"); + } + } +} diff --git a/crates/ppt-binary/src/doc.rs b/crates/ppt-binary/src/doc.rs new file mode 100644 index 0000000000..d0aa46f0ea --- /dev/null +++ b/crates/ppt-binary/src/doc.rs @@ -0,0 +1,390 @@ +//! The document structure of the `PowerPoint Document` stream ([MS-PPT] §2.1–2.4): the current +//! user's pointer to the last edit, the chain of edits with their persist directories (which map +//! object ids to stream offsets, newer edits winning), the document container and the lists of +//! masters, slides and notes. + +use std::collections::{HashMap, HashSet, VecDeque}; + +use crate::PptError; +use crate::record::{Rec, Records}; + +pub mod rt { + //! Record types used here ([MS-PPT] §2.13.24, [MS-ODRAW] §2.1.4). + pub const DOCUMENT: u16 = 0x03E8; + pub const DOCUMENT_ATOM: u16 = 0x03E9; + pub const SLIDE: u16 = 0x03EE; + pub const SLIDE_ATOM: u16 = 0x03EF; + pub const NOTES: u16 = 0x03F0; + pub const NOTES_ATOM: u16 = 0x03F1; + pub const ENVIRONMENT: u16 = 0x03F2; + pub const SLIDE_PERSIST_ATOM: u16 = 0x03F3; + pub const MAIN_MASTER: u16 = 0x03F8; + pub const SLIDE_SHOW_SLIDE_INFO: u16 = 0x03F9; + pub const DRAWING_GROUP: u16 = 0x040B; + pub const DRAWING: u16 = 0x040C; + pub const COLOR_SCHEME: u16 = 0x07F0; + pub const LIST: u16 = 0x07D0; + pub const PROG_TAGS: u16 = 0x1388; + pub const PROG_BINARY_TAG: u16 = 0x138A; + pub const BINARY_TAG_DATA: u16 = 0x138B; + pub const STYLE_TEXT_PROP9: u16 = 0x0FAC; + pub const OUTLINE_TEXT_PROPS9: u16 = 0x0FAE; + pub const OUTLINE_TEXT_PROPS_HEADER: u16 = 0x0FAF; + pub const FONT_COLLECTION: u16 = 0x07D5; + pub const OUTLINE_TEXT_REF: u16 = 0x0F9E; + pub const TEXT_HEADER: u16 = 0x0F9F; + pub const TEXT_CHARS: u16 = 0x0FA0; + pub const STYLE_TEXT_PROP: u16 = 0x0FA1; + pub const TEXT_MASTER_STYLE: u16 = 0x0FA3; + pub const TEXT_CF_EXCEPTION: u16 = 0x0FA4; + pub const TEXT_PF_EXCEPTION: u16 = 0x0FA5; + pub const TEXT_RULER: u16 = 0x0FA6; + pub const TEXT_BYTES: u16 = 0x0FA8; + pub const FONT_ENTITY: u16 = 0x0FB7; + pub const CSTRING: u16 = 0x0FBA; + pub const SLIDE_NUMBER_MC: u16 = 0x0FD8; + pub const HEADERS_FOOTERS: u16 = 0x0FD9; + pub const HEADERS_FOOTERS_ATOM: u16 = 0x0FDA; + pub const SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0; + pub const USER_EDIT: u16 = 0x0FF5; + pub const CURRENT_USER: u16 = 0x0FF6; + pub const DATETIME_MC: u16 = 0x0FF7; + pub const GENERIC_DATE_MC: u16 = 0x0FF8; + pub const PLACEHOLDER_ATOM: u16 = 0x0BC3; + pub const PERSIST_DIRECTORY: u16 = 0x1772; + pub const CRYPT_SESSION: u16 = 0x2F14; + + pub const DGG_CONTAINER: u16 = 0xF000; + pub const BSTORE: u16 = 0xF001; + pub const DG_CONTAINER: u16 = 0xF002; + pub const SPGR_CONTAINER: u16 = 0xF003; + pub const SP_CONTAINER: u16 = 0xF004; + pub const FBSE: u16 = 0xF007; + pub const FSPGR: u16 = 0xF009; + pub const FSP: u16 = 0xF00A; + pub const FOPT: u16 = 0xF00B; + pub const CLIENT_TEXTBOX: u16 = 0xF00D; + pub const CHILD_ANCHOR: u16 = 0xF00F; + pub const CLIENT_ANCHOR: u16 = 0xF010; + pub const CLIENT_DATA: u16 = 0xF011; + pub const SECONDARY_FOPT: u16 = 0xF121; + pub const TERTIARY_FOPT: u16 = 0xF122; +} + +/// `headerToken` of a `CurrentUserAtom` for an encrypted document. +const ENCRYPTED_TOKEN: u32 = 0xF3D1_C4DF; +/// `headerToken` of an unencrypted PowerPoint 97+ document. +const PLAIN_TOKEN: u32 = 0xE391_C05F; +/// Edits followed at most along the `offsetLastEdit` chain. +const MAX_EDITS: usize = 4096; + +/// A master, slide or notes page as listed in a `SlideListWithTextContainer`. +#[derive(Clone, Debug)] +pub struct Listed<'a> { + /// The container (`SlideContainer`, `MainMasterContainer`, `NotesContainer`). + pub rec: Rec<'a>, + /// The id other records use for it (`SlideAtom.masterIdRef`, `NotesAtom.slideIdRef`). + pub slide_id: u32, + /// The outline text stored in the list after its `SlidePersistAtom` (placeholders point at it + /// with an `OutlineTextRefAtom`). + pub outline: Vec>, +} + +/// The parsed structure of a `.ppt`. +pub struct Doc<'a> { + pub document: Rec<'a>, + pub masters: Vec>, + pub slides: Vec>, + pub notes: Vec>, + /// Slides the slide list names but whose objects couldn't be found: what a damaged file lost. + pub lost: Vec, +} + +/// Read the structure from the `Current User` and `PowerPoint Document` streams. +pub fn read<'a>(current_user: &[u8], stream: &'a [u8]) -> Result, PptError> { + let damaged = |s: &str| PptError::Damaged(s.to_string()); + // The current user names the newest edit; without it (some writers omit the stream), scan + // for the last UserEditAtom in the stream. + let mut edit_at = None; + // [MS-PPT] allows only the two tokens. Any other value (or none, in a truncated record) is a + // damaged PowerPoint 97 file or an older format; only the scan below can tell which. + let mut unknown_token = false; + if let Some(cu) = Rec::at(current_user, 0).filter(|r| r.kind == rt::CURRENT_USER) { + match cu.u32(4) { + Some(ENCRYPTED_TOKEN) => return Err(PptError::Encrypted), + Some(PLAIN_TOKEN) => edit_at = cu.u32(8).map(|v| v as usize), + _ => unknown_token = true, + } + } + let edit_at = match edit_at.filter(|&at| Rec::at(stream, at).is_some_and(|r| r.kind == rt::USER_EDIT)) { + Some(at) => at, + None => match Records::new(stream).filter(|r| r.kind == rt::USER_EDIT).last() { + Some(r) => r.offset, + None if unknown_token => return Err(PptError::TooOld), + None => return Err(damaged("no edit record")), + }, + }; + // Walk the edits newest first; the first entry seen for a persist id wins. + let mut persist: HashMap = HashMap::new(); + let mut doc_ref = None; + let mut seen = HashSet::new(); + // Many edits may name one persist directory; it is read once (its first reading wins anyway). + let mut dirs_seen = HashSet::new(); + // All directories together are read within one stream's worth of words. Real directories + // don't overlap, so they fit. Hostile ones nested inside each other would otherwise each be + // read to the end of the stream, once per edit (MAX_EDITS × the stream). + let mut words = stream.len() / 4; + let mut at = edit_at; + // The chain ends at an edit whose previous offset is 0. Ending anywhere else (a loop, an + // offset that isn't an edit, too many edits) means older edits were cut off. + let mut broken = true; + for _ in 0..MAX_EDITS { + if !seen.insert(at) { + break; + } + let Some(edit) = Rec::at(stream, at).filter(|r| r.kind == rt::USER_EDIT) else { break }; + if doc_ref.is_none() { + doc_ref = edit.u32(16); + // An encryptSessionPersistIdRef follows only in encrypted documents. + if edit.data.len() >= 32 { + return Err(PptError::Encrypted); + } + } + if let Some(dir) = + edit.u32(12).filter(|&o| dirs_seen.insert(o)).and_then(|o| Rec::at(stream, o as usize)).filter(|r| r.kind == rt::PERSIST_DIRECTORY) + { + read_persist_directory(dir.data, &mut persist, &mut words); + } + match edit.u32(8) { + Some(0) => { + broken = false; + break; + } + None => break, + Some(prev) => at = prev as usize, + } + } + if broken { + // Recover what the cut-off edits held: every edit in the stream, newest (last written) + // first, fills only the persist ids the chain left unset. Past MAX_EDITS, the newest are + // kept: they are the ones that win. + log::warn!("ppt: the edit history is broken; reading every edit in the stream"); + let mut edits: VecDeque = VecDeque::with_capacity(MAX_EDITS.min(64)); + for edit in Records::new(stream).filter(|r| r.kind == rt::USER_EDIT) { + if edits.len() == MAX_EDITS { + edits.pop_front(); + } + edits.push_back(edit); + } + for edit in edits.into_iter().rev() { + if let Some(dir) = + edit.u32(12).filter(|&o| dirs_seen.insert(o)).and_then(|o| Rec::at(stream, o as usize)).filter(|r| r.kind == rt::PERSIST_DIRECTORY) + { + read_persist_directory(dir.data, &mut persist, &mut words); + } + } + } + let lookup = |id: u32| persist.get(&id).and_then(|&o| Rec::at(stream, o)); + let document = doc_ref.and_then(lookup).filter(|r| r.kind == rt::DOCUMENT).ok_or_else(|| damaged("no document container"))?; + if lookup_kind(&persist, stream, rt::CRYPT_SESSION) { + return Err(PptError::Encrypted); + } + let mut doc = Doc { document, masters: vec![], slides: vec![], notes: vec![], lost: vec![] }; + // Each object is listed once. PowerPoint never lists one twice, and a hostile file that lists a + // big drawing many times would otherwise have it converted again for every listing (shapes × + // listings, from linear input). + let mut listed = HashSet::new(); + for list in document.children_of(rt::SLIDE_LIST_WITH_TEXT) { + let out = match list.instance { + 0 => &mut doc.slides, + 1 => &mut doc.masters, + 2 => &mut doc.notes, + _ => continue, + }; + let mut current: Option = None; + for r in list.children() { + if r.kind == rt::SLIDE_PERSIST_ATOM { + if let Some(l) = current.take() { + out.push(l); + } + let (Some(pid), Some(slide_id)) = (r.u32(0), r.u32(12)) else { continue }; + match lookup(pid) { + // The slide list names slides; anything else there is a slide the file lost. + Some(rec) if list.instance == 0 && rec.kind != rt::SLIDE => { + log::warn!("ppt: slide persist id {pid} is not a slide"); + doc.lost.push(format!("slide {slide_id}")); + } + Some(rec) if !listed.insert(rec.offset) => log::warn!("ppt: persist id {pid} is listed again; skipped"), + Some(rec) => current = Some(Listed { rec, slide_id, outline: vec![] }), + None => { + log::warn!("ppt: slide persist id {pid} has no object"); + if list.instance == 0 { + doc.lost.push(format!("slide {slide_id}")); + } + } + } + } else if r.kind == rt::TEXT_HEADER + && let Some(l) = current.as_mut() + { + // An outline text block starts at its header and runs to the next header or persist atom. + let rest = list.data.get(r.offset..).unwrap_or(&[]); + l.outline.push(Records::new(rest)); + } + } + if let Some(l) = current.take() { + out.push(l); + } + } + Ok(doc) +} + +/// Read one persist directory into `persist`, taking each word read from `words`. +fn read_persist_directory(b: &[u8], persist: &mut HashMap, words: &mut usize) { + let mut c = crate::record::Cursor::new(b); + let mut next = |c: &mut crate::record::Cursor| { + *words = words.checked_sub(1)?; + c.u32() + }; + while let Some(head) = next(&mut c) { + let first = head & 0x000F_FFFF; + let count = head >> 20; + for k in 0..count { + let Some(off) = next(&mut c) else { return }; + persist.entry(first.saturating_add(k)).or_insert(off as usize); + } + } +} + +fn lookup_kind(persist: &HashMap, stream: &[u8], kind: u16) -> bool { + persist.values().any(|&o| Rec::at(stream, o).is_some_and(|r| r.kind == kind)) +} + +/// The `DocumentAtom`: slide and notes sizes in master units (576 per inch), first slide number. +pub struct DocumentAtom { + pub slide_w: i32, + pub slide_h: i32, + pub notes_w: i32, + pub notes_h: i32, + pub first_slide_number: u16, +} + +impl Doc<'_> { + pub fn document_atom(&self) -> Option { + let a = self.document.child(rt::DOCUMENT_ATOM)?; + Some(DocumentAtom { + slide_w: a.i32(0)?, + slide_h: a.i32(4)?, + notes_w: a.i32(8)?, + notes_h: a.i32(12)?, + first_slide_number: a.u16(32).unwrap_or(1), + }) + } +} + +/// The `SlideAtom` of a slide or master. +#[derive(Clone, Copy, Debug, Default)] +pub struct SlideAtom { + /// `SlideLayoutType`. + pub geom: u32, + pub master_id: u32, + pub follow_master_objects: bool, + pub follow_master_scheme: bool, + pub follow_master_background: bool, +} + +pub fn slide_atom(container: &Rec) -> SlideAtom { + let Some(a) = container.child(rt::SLIDE_ATOM) else { + return SlideAtom { follow_master_objects: true, follow_master_scheme: true, follow_master_background: true, ..Default::default() }; + }; + let flags = a.u16(20).unwrap_or(0x7); + SlideAtom { + geom: a.u32(0).unwrap_or(0), + master_id: a.u32(12).unwrap_or(0), + follow_master_objects: flags & 0x1 != 0, + follow_master_scheme: flags & 0x2 != 0, + follow_master_background: flags & 0x4 != 0, + } +} + +/// Font names by index (`FontCollectionContainer` in the environment). +pub fn fonts(doc: &Doc) -> Vec { + let Some(coll) = doc.document.child(rt::ENVIRONMENT).and_then(|e| e.child(rt::FONT_COLLECTION)) else { return vec![] }; + coll.children_of(rt::FONT_ENTITY) + .map(|f| { + let units: Vec = (0..32).filter_map(|i| f.u16(i * 2)).take_while(|&u| u != 0).collect(); + String::from_utf16_lossy(&units) + }) + .collect() +} + +/// What a `HeadersFootersContainer` ([MS-PPT] §2.4.15.1 and §2.5.16) says the footer row +/// shows: the date (today's in a format, or fixed text), the slide number and the footer text. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct HeadersFooters { + /// `formatId`: 0–12, the date format. + pub format: u16, + pub date: bool, + /// The date is fixed text (`fHasUserDate`) rather than today's. + pub user_date: bool, + pub slide_number: bool, + pub footer: bool, + pub date_text: String, + pub footer_text: String, +} + +/// The UTF-16 units of a `CString` body, up to its first NUL: the record has no terminator, but a +/// writer that adds one would otherwise put a NUL into the text, or make a tag name fail to match. +fn cstring_units(b: &[u8]) -> impl Iterator + '_ { + b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|&u| u != 0) +} + +/// The slides' headers and footers in `container`, from its `HeadersFootersContainer` of +/// `instance`: 3 in the document (`SlideHeadersFootersContainer`, for every slide), 0 in a slide or +/// main master (`PerSlideHeadersFootersContainer`, its own). +pub fn headers_footers(container: &Rec, instance: u16) -> Option { + let hf = container.children().find(|r| r.kind == rt::HEADERS_FOOTERS && r.instance == instance)?; + let atom = hf.child(rt::HEADERS_FOOTERS_ATOM)?; + let flags = atom.u16(2)?; + let text = |instance: u16| { + hf.children() + .find(|r| r.kind == rt::CSTRING && r.instance == instance) + .map(|r| String::from_utf16_lossy(&cstring_units(r.data).collect::>())) + .unwrap_or_default() + }; + Some(HeadersFooters { + format: atom.u16(0).unwrap_or(0), + date: flags & 0x01 != 0, + user_date: flags & 0x04 != 0, + slide_number: flags & 0x08 != 0, + footer: flags & 0x20 != 0, + date_text: text(0), + footer_text: text(2), + }) +} + +/// The PowerPoint 2000 paragraph formatting of the slides' outline text ([MS-PPT] §2.4.22.10, +/// the document's `___PPT9` tag): by slide id and text type, one `StyleTextProp9Atom` for each of +/// the slide's outline blocks of that type, in order. +pub fn outline_numbering(document: &Rec) -> HashMap<(u32, u32), Vec>> { + let mut out: HashMap<(u32, u32), Vec>> = HashMap::new(); + let tags = document.child(rt::LIST).and_then(|l| l.child(rt::PROG_TAGS)); + let Some(tags) = tags else { return out }; + let ppt9 = tags + .children_of(rt::PROG_BINARY_TAG) + .find(|tag| tag.child(rt::CSTRING).is_some_and(|name| cstring_units(name.data).eq("___PPT9".encode_utf16()))); + let Some(data) = ppt9.and_then(|t| t.child(rt::BINARY_TAG_DATA)) else { return out }; + // The tag's data is an atom whose body holds records. + for props in Records::new(data.data).filter(|r| r.kind == rt::OUTLINE_TEXT_PROPS9) { + let mut header = None; + for r in props.children() { + if r.kind == rt::OUTLINE_TEXT_PROPS_HEADER { + header = r.u32(0).zip(r.u32(4)); + } else if r.kind == rt::STYLE_TEXT_PROP9 + && let Some(key) = header.take() + { + out.entry(key).or_default().push(crate::text::read_style9(r.data)); + } + } + } + out +} diff --git a/crates/ppt-binary/src/draw.rs b/crates/ppt-binary/src/draw.rs new file mode 100644 index 0000000000..2b1e8ec796 --- /dev/null +++ b/crates/ppt-binary/src/draw.rs @@ -0,0 +1,522 @@ +//! OfficeArt drawings ([MS-ODRAW]) as `.ppt` stores them: a tree of shape group containers and +//! shape containers, each shape with its `FSP` (type, id, flags), property tables (`FOPT`), +//! anchor and client records (placeholder, text). + +use std::collections::HashMap; + +use crate::doc::rt; +use crate::record::{MAX_DEPTH, Rec}; + +/// Property ids ([MS-ODRAW] §2.3). +pub mod prop { + pub const ROTATION: u16 = 0x0004; + pub const TEXT_LEFT: u16 = 0x0081; + pub const TEXT_TOP: u16 = 0x0082; + pub const TEXT_RIGHT: u16 = 0x0083; + pub const TEXT_BOTTOM: u16 = 0x0084; + pub const WRAP_TEXT: u16 = 0x0085; + pub const ANCHOR_TEXT: u16 = 0x0087; + pub const CROP_TOP: u16 = 0x0100; + pub const CROP_BOTTOM: u16 = 0x0101; + pub const CROP_LEFT: u16 = 0x0102; + pub const CROP_RIGHT: u16 = 0x0103; + pub const PIB: u16 = 0x0104; + pub const GEO_LEFT: u16 = 0x0140; + pub const GEO_TOP: u16 = 0x0141; + pub const GEO_RIGHT: u16 = 0x0142; + pub const GEO_BOTTOM: u16 = 0x0143; + pub const SHAPE_PATH: u16 = 0x0144; + pub const VERTICES: u16 = 0x0145; + pub const SEGMENT_INFO: u16 = 0x0146; + pub const ADJUST_VALUE: u16 = 0x0147; + pub const FILL_TYPE: u16 = 0x0180; + pub const FILL_COLOR: u16 = 0x0181; + pub const FILL_OPACITY: u16 = 0x0182; + pub const FILL_BACK_COLOR: u16 = 0x0183; + pub const FILL_BACK_OPACITY: u16 = 0x0184; + pub const FILL_BLIP: u16 = 0x0186; + pub const FILL_ANGLE: u16 = 0x018B; + pub const FILL_FOCUS: u16 = 0x018C; + pub const FILL_BOOLS: u16 = 0x01BF; + pub const LINE_COLOR: u16 = 0x01C0; + pub const LINE_OPACITY: u16 = 0x01C1; + pub const LINE_WIDTH: u16 = 0x01CB; + pub const LINE_STYLE: u16 = 0x01CD; + pub const LINE_DASHING: u16 = 0x01CE; + pub const LINE_START_ARROW: u16 = 0x01D0; + pub const LINE_END_ARROW: u16 = 0x01D1; + pub const LINE_START_ARROW_WIDTH: u16 = 0x01D2; + pub const LINE_START_ARROW_LENGTH: u16 = 0x01D3; + pub const LINE_END_ARROW_WIDTH: u16 = 0x01D4; + pub const LINE_END_ARROW_LENGTH: u16 = 0x01D5; + pub const LINE_JOIN: u16 = 0x01D6; + pub const LINE_CAP: u16 = 0x01D7; + pub const LINE_BOOLS: u16 = 0x01FF; + pub const SHADOW_COLOR: u16 = 0x0201; + pub const SHADOW_OPACITY: u16 = 0x0204; + pub const SHADOW_OFFSET_X: u16 = 0x0205; + pub const SHADOW_OFFSET_Y: u16 = 0x0206; + pub const SHADOW_BOOLS: u16 = 0x023F; + pub const HSP_MASTER: u16 = 0x0301; + pub const NAME: u16 = 0x0380; + pub const DESCRIPTION: u16 = 0x0381; + pub const GROUP_BOOLS: u16 = 0x03BF; +} + +/// UTF-16 units kept of a string property. +pub const MAX_STRING: usize = 4096; + +/// Distinct properties one set keeps. Ids are 14 bits, so a file's tables could name about 16K of +/// them, and every shape copies the drawing defaults' and its master shape's sets into its own: +/// unbounded, that is shapes × 16K. [MS-ODRAW] defines a few hundred properties and a real shape +/// or the drawing defaults set tens of them. Entries past the limit are still read (their complex +/// data keeps its place) but not kept. +pub const MAX_PROPS: usize = 1024; + +/// One property value: the 32-bit operand and, for complex properties, the extra bytes. +#[derive(Clone, Copy, Debug)] +pub struct PropVal<'a> { + pub op: u32, + pub complex: Option<&'a [u8]>, +} + +/// A shape's merged property tables (primary first; secondary and tertiary fill gaps). +#[derive(Clone, Debug, Default)] +pub struct Props<'a> { + map: HashMap>, +} + +impl<'a> Props<'a> { + /// Read one `FOPT` body: `count` 6-byte entries then the complex data in entry order. Entries + /// already present are kept (the caller adds the most specific table first). + pub fn add_table(&mut self, r: &Rec<'a>) { + let count = usize::from(r.instance); + let mut complex_at = count.saturating_mul(6); + for i in 0..count { + let (Some(id), Some(op)) = (r.u16(i * 6), r.u32(i * 6 + 2)) else { break }; + let is_complex = id & 0x8000 != 0; + let pid = id & 0x3FFF; + let complex = if is_complex { + let len = op as usize; + let data = r.data.get(complex_at..complex_at.saturating_add(len).min(r.data.len())); + complex_at = complex_at.saturating_add(len); + data + } else { + None + }; + self.fill_gap(pid, PropVal { op, complex }); + } + } + + /// Fill gaps from another set (a master shape's or the drawing defaults). + pub fn inherit(&mut self, other: &Props<'a>) { + for (k, v) in &other.map { + self.fill_gap(*k, *v); + } + } + + /// Add `v` for `id` where this set doesn't say it already. A boolean property word ([MS-ODRAW]: + /// the last id of each 64-id group) holds sixteen flags, each with its own `fUse` bit 16 + /// places up, so it is merged flag by flag: a shape that sets only `fNoFillHitTest` still + /// inherits `fFilled` from its master or the defaults. + fn fill_gap(&mut self, id: u16, v: PropVal<'a>) { + let full = self.map.len() >= MAX_PROPS; + match self.map.get_mut(&id) { + None if full => {} + None => { + self.map.insert(id, v); + } + Some(have) if id & 0x3F == 0x3F => { + let unset = !(have.op >> 16) & 0xFFFF; + let take = (v.op >> 16) & unset; + have.op |= take << 16; + have.op = (have.op & !take) | (v.op & take); + } + Some(_) => {} + } + } + + /// Set a simple (non-complex) property. + pub fn set(&mut self, id: u16, op: u32) { + self.map.insert(id, PropVal { op, complex: None }); + } + + pub fn get(&self, id: u16) -> Option { + self.map.get(&id).map(|v| v.op) + } + + pub fn complex(&self, id: u16) -> Option<&'a [u8]> { + self.map.get(&id).and_then(|v| v.complex) + } + + /// A 16.16 fixed-point value. + pub fn fixed(&self, id: u16) -> Option { + self.get(id).map(|v| f64::from(v as i32) / 65536.0) + } + + /// A boolean from a bool-property word: bit `bit` holds the value, bit `bit + 16` says it is set. + pub fn flag(&self, id: u16, bit: u32) -> Option { + let v = self.get(id)?; + (v & (1 << (bit + 16)) != 0).then_some(v & (1 << bit) != 0) + } + + /// A UTF-16 string property (names, alt text), at most [`MAX_STRING`] units: a master shape's + /// name is copied into every shape that inherits it. + pub fn string(&self, id: u16) -> Option { + let b = self.complex(id)?; + let units: Vec = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take(MAX_STRING).take_while(|&u| u != 0).collect(); + Some(String::from_utf16_lossy(&units)).filter(|s| !s.is_empty()) + } + + /// An `IMsoArray` property: element size and the elements' bytes. + pub fn array(&self, id: u16) -> Option<(usize, &'a [u8])> { + let b = self.complex(id)?; + let n = usize::from(crate::record::u16_at(b, 0)?); + let size = crate::record::u16_at(b, 4)?; + // 0xFFF0 marks 4-byte elements stored as two 2-byte halves. + let size = if size == 0xFFF0 { 4 } else { usize::from(size) }; + if size == 0 { + return None; + } + let body = b.get(6..)?; + let len = n.saturating_mul(size).min(body.len() / size * size); + Some((size, body.get(..len)?)) + } +} + +/// An anchor rectangle in its own coordinate units: master units for a client anchor, the parent +/// group's units for a child anchor. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Anchor { + pub left: f64, + pub top: f64, + pub right: f64, + pub bottom: f64, +} + +/// The placeholder a shape stands for (`OEPlaceholderAtom`). +#[derive(Clone, Copy, Debug)] +pub struct Placeholder { + pub position: u32, + /// `PlaceholderEnum`. + pub kind: u8, +} + +/// One shape of a drawing, before conversion. +#[derive(Clone, Debug)] +pub struct RawShape<'a> { + /// `MSOSPT` shape type. + pub shape_type: u16, + pub spid: u32, + pub flip_h: bool, + pub flip_v: bool, + pub patriarch: bool, + pub deleted: bool, + pub props: Props<'a>, + pub anchor: Option, + /// For a group: the child coordinate rectangle (`FSPGR`). + pub group_rect: Option, + pub children: Vec>, + pub is_group: bool, + pub placeholder: Option, + /// The records of the shape's text box (`OfficeArtClientTextbox`). + pub text: Option>, +} + +/// The top-level shapes and the background shape of a `DrawingContainer`. +pub struct Drawing<'a> { + pub shapes: Vec>, + pub background: Option>, +} + +/// Read the drawing of a slide, master or notes container. +pub fn drawing<'a>(container: &Rec<'a>) -> Drawing<'a> { + let mut out = Drawing { shapes: vec![], background: None }; + let Some(dg) = container.child(rt::DRAWING).and_then(|d| d.child(rt::DG_CONTAINER)) else { return out }; + // The background is the container's own shape (`OfficeArtDgContainer.shape`, [MS-ODRAW] + // 2.2.13), not one found by its fBackground flag. + if let Some(bg) = dg.child(rt::SP_CONTAINER) { + out.background = Some(shape(&bg)); + } + if let Some(top) = dg.child(rt::SPGR_CONTAINER) { + // The first shape of the top group is the patriarch, standing for the drawing itself. + out.shapes = group_children(&top, 0).into_iter().filter(|s| !s.patriarch).collect(); + } + out +} + +fn group_children<'a>(gr: &Rec<'a>, depth: usize) -> Vec> { + if depth > MAX_DEPTH { + return vec![]; + } + let mut out = vec![]; + for r in gr.children() { + match r.kind { + rt::SP_CONTAINER => out.push(shape(&r)), + rt::SPGR_CONTAINER => { + let mut kids = r.children(); + // A group container's first shape describes the group itself. + let Some(head) = kids.next().filter(|h| h.kind == rt::SP_CONTAINER) else { continue }; + let mut g = shape(&head); + g.is_group = true; + g.children = group_children(&r, depth + 1).into_iter().skip(1).collect(); + out.push(g); + } + _ => {} + } + } + out +} + +fn rect_i32(r: &Rec) -> Option { + Some(Anchor { left: f64::from(r.i32(0)?), top: f64::from(r.i32(4)?), right: f64::from(r.i32(8)?), bottom: f64::from(r.i32(12)?) }) +} + +fn shape<'a>(sp: &Rec<'a>) -> RawShape<'a> { + let mut s = RawShape { + shape_type: 0, + spid: 0, + flip_h: false, + flip_v: false, + patriarch: false, + deleted: false, + props: Props::default(), + anchor: None, + group_rect: None, + children: vec![], + is_group: false, + placeholder: None, + text: None, + }; + // Tables in specificity order: primary (the last one first), then secondary and tertiary. + let mut primary: Vec = vec![]; + let mut tables: Vec = vec![]; + for r in sp.children() { + match r.kind { + rt::FSP => { + s.shape_type = r.instance; + s.spid = r.u32(0).unwrap_or(0); + let f = r.u32(4).unwrap_or(0); + s.patriarch = f & 0x4 != 0; + s.deleted = f & 0x8 != 0; + s.flip_h = f & 0x40 != 0; + s.flip_v = f & 0x80 != 0; + } + rt::FOPT => primary.push(r), + rt::SECONDARY_FOPT | rt::TERTIARY_FOPT => tables.push(r), + rt::FSPGR => s.group_rect = rect_i32(&r), + rt::CHILD_ANCHOR => s.anchor = rect_i32(&r), + rt::CLIENT_ANCHOR => { + s.anchor = if r.data.len() >= 16 { + // RectStruct: top, left, right, bottom. + (|| { + Some(Anchor { + top: f64::from(r.i32(0)?), + left: f64::from(r.i32(4)?), + right: f64::from(r.i32(8)?), + bottom: f64::from(r.i32(12)?), + }) + })() + } else { + // SmallRectStruct: top, left, right, bottom. + (|| { + Some(Anchor { + top: f64::from(r.i16(0)?), + left: f64::from(r.i16(2)?), + right: f64::from(r.i16(4)?), + bottom: f64::from(r.i16(6)?), + }) + })() + }; + } + rt::CLIENT_DATA => { + if let Some(p) = r.child(rt::PLACEHOLDER_ATOM) { + s.placeholder = Some(Placeholder { position: p.u32(0).unwrap_or(0), kind: p.u8(4).unwrap_or(0) }); + } + } + rt::CLIENT_TEXTBOX => s.text = Some(r), + _ => {} + } + } + for t in primary.iter().rev().chain(&tables) { + s.props.add_table(t); + } + s +} + +/// The drawing-wide default properties (`OfficeArtDggContainer`'s `FOPT`). +pub fn default_props<'a>(dgg: Option>) -> Props<'a> { + let mut p = Props::default(); + if let Some(dgg) = dgg { + for t in dgg.children().filter(|r| matches!(r.kind, rt::FOPT | rt::SECONDARY_FOPT | rt::TERTIARY_FOPT)) { + p.add_table(&t); + } + } + p +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::build::*; + + pub fn fopt(entries: &[(u16, u32)], complex: &[u8]) -> Vec { + let mut b = vec![]; + for (id, op) in entries { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + b.extend_from_slice(complex); + atom(rt::FOPT, entries.len() as u16, &b) + } + + #[test] + fn reads_properties_and_complex_strings() { + let name: Vec = "Logo\0".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let t = fopt(&[(prop::FILL_COLOR, 0x0011_2233), (0x8000 | prop::NAME, name.len() as u32), (prop::FILL_BOOLS, 0x0010_0000)], &name); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(p.get(prop::FILL_COLOR), Some(0x0011_2233)); + assert_eq!(p.string(prop::NAME).as_deref(), Some("Logo")); + assert_eq!(p.flag(prop::FILL_BOOLS, 4), Some(false)); + assert_eq!(p.flag(prop::LINE_BOOLS, 3), None); + } + + /// A boolean word inherits the flags it doesn't set (storytold/deckcraft#1137 review): a text box that sets only + /// `fNoFillHitTest` (bit 4 is `fFilled`, bit 0 `fNoFillHitTest`) still gets "not filled" + /// from below, and its own flags win over the inherited ones. + #[test] + fn boolean_properties_merge_flag_by_flag() { + let mut p = Props::default(); + p.set(prop::FILL_BOOLS, 0x0001_0001); // fNoFillHitTest = true; fFilled not said + p.set(prop::LINE_BOOLS, 0x0008_0008); // fLine = true + let mut below = Props::default(); + below.set(prop::FILL_BOOLS, 0x0011_0000); // fFilled = false, fNoFillHitTest = false + below.set(prop::LINE_BOOLS, 0x0008_0000); // fLine = false + p.inherit(&below); + assert_eq!(p.flag(prop::FILL_BOOLS, 4), Some(false)); + assert_eq!(p.flag(prop::FILL_BOOLS, 0), Some(true)); + assert_eq!(p.flag(prop::LINE_BOOLS, 3), Some(true)); + // The same merge applies between a shape's own tables. + let t = fopt(&[(prop::FILL_BOOLS, 0x0001_0001)], &[]); + let t2 = fopt(&[(prop::FILL_BOOLS, 0x0010_0010)], &[]); + let mut q = Props::default(); + q.add_table(&Rec::at(&t, 0).unwrap()); + q.add_table(&Rec::at(&t2, 0).unwrap()); + assert_eq!(q.flag(prop::FILL_BOOLS, 4), Some(true)); + assert_eq!(q.flag(prop::FILL_BOOLS, 0), Some(true)); + // Non-boolean properties still keep the first value. + let mut r = Props::default(); + r.set(prop::FILL_COLOR, 1); + let mut s = Props::default(); + s.set(prop::FILL_COLOR, 2); + r.inherit(&s); + assert_eq!(r.get(prop::FILL_COLOR), Some(1)); + } + + /// A string property longer than [`MAX_STRING`] units is cut there. + #[test] + fn a_long_string_property_is_capped() { + let name: Vec = "x".repeat(10_000).encode_utf16().flat_map(u16::to_le_bytes).collect(); + let t = fopt(&[(0x8000 | prop::NAME, name.len() as u32)], &name); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(p.string(prop::NAME).map(|s| s.len()), Some(MAX_STRING)); + } + + /// A table naming more than [`MAX_PROPS`] properties keeps that many, and still reads the + /// complex data after them and the records after it. + #[test] + fn a_property_set_keeps_at_most_max_props() { + let mut entries: Vec<(u16, u32)> = (0..MAX_PROPS as u16 + 100).map(|i| (0x1000 + i, u32::from(i))).collect(); + let name: Vec = "Kept\0".encode_utf16().flat_map(u16::to_le_bytes).collect(); + entries.insert(0, (0x8000 | prop::NAME, name.len() as u32)); + let fsp = atom(rt::FSP, 1, &[1025u32.to_le_bytes(), 0u32.to_le_bytes()].concat()); + let anchor = atom(rt::CHILD_ANCHOR, 0, &[1i32, 2, 3, 4].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let sp = container(rt::SP_CONTAINER, 0, &[fsp, fopt(&entries, &name), anchor]); + let s = shape(&Rec::at(&sp, 0).unwrap()); + assert_eq!(s.props.map.len(), MAX_PROPS); + assert_eq!(s.props.string(prop::NAME).as_deref(), Some("Kept")); + assert_eq!(s.props.get(0x1000), Some(0)); + assert_eq!(s.props.get(0x1000 + MAX_PROPS as u16), None, "past the limit"); + assert_eq!(s.anchor, Some(Anchor { left: 1.0, top: 2.0, right: 3.0, bottom: 4.0 })); + // Inheriting can't pass the limit either. + let mut p = Props::default(); + p.set(prop::FILL_COLOR, 1); + p.inherit(&s.props); + assert_eq!(p.map.len(), MAX_PROPS); + } + + /// A shape's later primary property table wins over its earlier one, and both over its + /// secondary table. + #[test] + fn the_last_primary_table_wins() { + let fsp = atom(rt::FSP, 1, &[1025u32.to_le_bytes(), 0u32.to_le_bytes()].concat()); + let secondary = { + let mut b = vec![]; + for (id, op) in [(prop::FILL_COLOR, 3u32), (prop::LINE_COLOR, 3)] { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + atom(rt::SECONDARY_FOPT, 2, &b) + }; + let sp = container( + rt::SP_CONTAINER, + 0, + &[fsp, secondary, fopt(&[(prop::FILL_COLOR, 1), (prop::LINE_WIDTH, 1)], &[]), fopt(&[(prop::FILL_COLOR, 2)], &[])], + ); + let s = shape(&Rec::at(&sp, 0).unwrap()); + assert_eq!((s.props.get(prop::FILL_COLOR), s.props.get(prop::LINE_WIDTH), s.props.get(prop::LINE_COLOR)), (Some(2), Some(1), Some(3))); + } + + #[test] + fn a_complex_length_past_the_record_is_clipped() { + let t = fopt(&[(0x8000 | prop::NAME, 0xFFFF_FFFF), (0x8000 | prop::DESCRIPTION, 10)], b"A\0"); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(p.string(prop::NAME).as_deref(), Some("A")); + assert_eq!(p.complex(prop::DESCRIPTION), None); + } + + #[test] + fn reads_groups_anchors_and_placeholders() { + let fsp = |t: u16, id: u32, flags: u32| atom(rt::FSP, t, &[id.to_le_bytes(), flags.to_le_bytes()].concat()); + let small = + |t: i16, l: i16, r: i16, b: i16| atom(rt::CLIENT_ANCHOR, 0, &[t, l, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let child = + |l: i32, t: i32, r: i32, b: i32| atom(rt::CHILD_ANCHOR, 0, &[l, t, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::>()); + let ph = container(rt::CLIENT_DATA, 0, &[atom(rt::PLACEHOLDER_ATOM, 0, &[0, 0, 0, 0, 0x0D, 0, 0, 0])]); + let patriarch = container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &[0; 16]), fsp(0, 1024, 0x5)]); + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 1025, 0xA00), small(10, 20, 300, 80), ph]); + let group = container( + rt::SPGR_CONTAINER, + 0, + &[ + container( + rt::SP_CONTAINER, + 0, + &[ + atom(rt::FSPGR, 1, &[0i32, 0, 100, 100].iter().flat_map(|v| v.to_le_bytes()).collect::>()), + fsp(0, 1026, 0x201), + small(100, 100, 200, 200), + ], + ), + container(rt::SP_CONTAINER, 0, &[fsp(3, 1027, 0x40), child(0, 0, 50, 50)]), + ], + ); + let drawing = container(rt::DRAWING, 0, &[container(rt::DG_CONTAINER, 0, &[container(rt::SPGR_CONTAINER, 0, &[patriarch, title, group])])]); + let slide = container(rt::SLIDE, 0, &[drawing]); + let d = super::drawing(&Rec::at(&slide, 0).unwrap()); + assert_eq!(d.shapes.len(), 2); + let t = &d.shapes[0]; + assert_eq!(t.placeholder.unwrap().kind, 0x0D); + assert_eq!(t.anchor, Some(Anchor { left: 20.0, top: 10.0, right: 300.0, bottom: 80.0 })); + let g = &d.shapes[1]; + assert!(g.is_group); + assert_eq!(g.children.len(), 1); + assert!(g.children[0].flip_h); + assert_eq!(g.group_rect.unwrap().right, 100.0); + } +} diff --git a/crates/ppt-binary/src/geom.rs b/crates/ppt-binary/src/geom.rs new file mode 100644 index 0000000000..52206018a9 --- /dev/null +++ b/crates/ppt-binary/src/geom.rs @@ -0,0 +1,454 @@ +//! Shape geometry: OfficeArt shape types (`MSOSPT`, [MS-ODRAW] §2.4.24) as DrawingML preset +//! names, and freeform paths from the vertices and segment properties (§2.3.6). + +use craft_pptx::{CustomPath, Geom}; + +use crate::draw::{Props, prop}; + +/// The preset for a shape type, `None` for a freeform (`msosptNotPrimitive`) or a type with no +/// preset counterpart. +pub fn preset_name(shape_type: u16) -> Option<&'static str> { + Some(match shape_type { + 1 | 75 | 202 | 201 => "rect", + 2 => "roundRect", + 3 => "ellipse", + 4 => "diamond", + 5 => "triangle", + 6 => "rtTriangle", + 7 => "parallelogram", + 8 => "trapezoid", + 9 => "hexagon", + 10 => "octagon", + 11 => "plus", + 12 => "star5", + 13 | 14 => "rightArrow", + 15 => "homePlate", + 16 => "cube", + 17 => "wedgeRoundRectCallout", + 18 => "star16", + 19 => "arc", + 20 => "line", + 21 => "plaque", + 22 => "can", + 23 => "donut", + 32 => "straightConnector1", + 33 => "bentConnector2", + 34 => "bentConnector3", + 35 => "bentConnector4", + 36 => "bentConnector5", + 37 => "curvedConnector2", + 38 => "curvedConnector3", + 39 => "curvedConnector4", + 40 => "curvedConnector5", + 41 | 178 => "callout1", + 42 => "callout2", + 43 => "callout3", + 44 | 179 => "accentCallout1", + 45 => "accentCallout2", + 46 => "accentCallout3", + 47 | 180 => "borderCallout1", + 48 => "borderCallout2", + 49 => "borderCallout3", + 50 | 181 => "accentBorderCallout1", + 51 => "accentBorderCallout2", + 52 => "accentBorderCallout3", + 53 => "ribbon", + 54 => "ribbon2", + 55 => "chevron", + 56 => "pentagon", + 57 => "noSmoking", + 58 => "star8", + 59 => "star16", + 60 => "star32", + 61 => "wedgeRectCallout", + 62 => "wedgeRoundRectCallout", + 63 => "wedgeEllipseCallout", + 64 => "wave", + 65 => "foldedCorner", + 66 => "leftArrow", + 67 => "downArrow", + 68 => "upArrow", + 69 => "leftRightArrow", + 70 => "upDownArrow", + 71 => "irregularSeal1", + 72 => "irregularSeal2", + 73 => "lightningBolt", + 74 => "heart", + 76 => "quadArrow", + 77 => "leftArrowCallout", + 78 => "rightArrowCallout", + 79 => "upArrowCallout", + 80 => "downArrowCallout", + 81 => "leftRightArrowCallout", + 82 => "upDownArrowCallout", + 83 => "quadArrowCallout", + 84 => "bevel", + 85 => "leftBracket", + 86 => "rightBracket", + 87 => "leftBrace", + 88 => "rightBrace", + 89 => "leftUpArrow", + 90 => "bentUpArrow", + 91 => "bentArrow", + 92 => "star24", + 93 => "stripedRightArrow", + 94 => "notchedRightArrow", + 95 => "blockArc", + 96 => "smileyFace", + 97 => "verticalScroll", + 98 => "horizontalScroll", + 99 | 100 => "circularArrow", + 101 => "uturnArrow", + 102 => "curvedRightArrow", + 103 => "curvedLeftArrow", + 104 => "curvedUpArrow", + 105 => "curvedDownArrow", + 106 => "cloudCallout", + 107 => "ellipseRibbon", + 108 => "ellipseRibbon2", + 109 => "flowChartProcess", + 110 => "flowChartDecision", + 111 => "flowChartInputOutput", + 112 => "flowChartPredefinedProcess", + 113 => "flowChartInternalStorage", + 114 => "flowChartDocument", + 115 => "flowChartMultidocument", + 116 => "flowChartTerminator", + 117 => "flowChartPreparation", + 118 => "flowChartManualInput", + 119 => "flowChartManualOperation", + 120 => "flowChartConnector", + 121 => "flowChartPunchedCard", + 122 => "flowChartPunchedTape", + 123 => "flowChartSummingJunction", + 124 => "flowChartOr", + 125 => "flowChartCollate", + 126 => "flowChartSort", + 127 => "flowChartExtract", + 128 => "flowChartMerge", + 129 => "flowChartOfflineStorage", + 130 => "flowChartOnlineStorage", + 131 => "flowChartMagneticTape", + 132 => "flowChartMagneticDisk", + 133 => "flowChartMagneticDrum", + 134 => "flowChartDisplay", + 135 => "flowChartDelay", + 176 => "flowChartAlternateProcess", + 177 => "flowChartOffpageConnector", + 182 => "leftRightUpArrow", + 183 => "sun", + 184 => "moon", + 185 => "bracketPair", + 186 => "bracePair", + 187 => "star4", + 188 => "doubleWave", + 189 => "actionButtonBlank", + 190 => "actionButtonHome", + 191 => "actionButtonHelp", + 192 => "actionButtonInformation", + 193 => "actionButtonForwardNext", + 194 => "actionButtonBackPrevious", + 195 => "actionButtonEnd", + 196 => "actionButtonBeginning", + 197 => "actionButtonReturn", + 198 => "actionButtonDocument", + 199 => "actionButtonSound", + 200 => "actionButtonMovie", + // WordArt text shapes (24–31, 136–175) draw their text as plain text in a rectangle. + 24..=31 | 136..=175 => "rect", + _ => return None, + }) +} + +/// Whether a shape type is a connector. +pub fn is_connector(shape_type: u16) -> bool { + (32..=40).contains(&shape_type) +} + +/// The geometry of a shape: its preset (checked against the presets `craft_drawingml` draws, with a +/// rounded rectangle's corner carried over), else its freeform path, else a rectangle. +pub fn geometry(shape_type: u16, props: &Props) -> Geom { + if let Some(name) = preset_name(shape_type).filter(|n| craft_drawingml::preset::build(n, 100.0, 100.0, &[]).is_some()) { + let mut adj = vec![]; + // A rounded rectangle's corner: a 21600 coordinate in OfficeArt, a 100000 fraction of the + // shorter side in DrawingML. + if shape_type == 2 + && let Some(v) = props.get(prop::ADJUST_VALUE) + { + adj.push(f64::from(v as i32).clamp(0.0, 10800.0) / 21600.0 * 100_000.0); + } + return Geom::Preset { name: name.into(), adj }; + } + custom_path(props).map(|paths| Geom::Custom { paths }).unwrap_or_default() +} + +/// Segments followed at most in one path. +const MAX_SEGMENTS: usize = 1 << 16; +/// Vertices used at most in one path. The path text is copied into every shape that inherits the +/// vertices from a master shape, so it stays a bounded size. +const MAX_POINTS: usize = 8192; + +/// A freeform's path in its geometry box. +fn custom_path(props: &Props) -> Option> { + let (size, verts) = props.array(prop::VERTICES)?; + let points: Vec<(f64, f64)> = match size { + 8 => verts + .as_chunks::<8>() + .0 + .iter() + .take(MAX_POINTS) + .map(|c| (f64::from(i32::from_le_bytes([c[0], c[1], c[2], c[3]])), f64::from(i32::from_le_bytes([c[4], c[5], c[6], c[7]])))) + .collect(), + 4 => verts + .as_chunks::<4>() + .0 + .iter() + .take(MAX_POINTS) + .map(|c| (f64::from(i16::from_le_bytes([c[0], c[1]])), f64::from(i16::from_le_bytes([c[2], c[3]])))) + .collect(), + _ => return None, + }; + if points.is_empty() { + return None; + } + let left = f64::from(props.get(prop::GEO_LEFT).unwrap_or(0) as i32); + let top = f64::from(props.get(prop::GEO_TOP).unwrap_or(0) as i32); + let right = f64::from(props.get(prop::GEO_RIGHT).unwrap_or(21600) as i32); + let bottom = f64::from(props.get(prop::GEO_BOTTOM).unwrap_or(21600) as i32); + let (w, h) = ((right - left).abs().max(1.0), (bottom - top).abs().max(1.0)); + let mut pts = points.iter().map(|(x, y)| (x - left, y - top)); + let mut d = String::new(); + let mut push = |cmd: &str, ps: &[(f64, f64)]| { + d.push_str(cmd); + for (x, y) in ps { + d.push_str(&format!(" {x} {y}")); + } + d.push(' '); + }; + match props.array(prop::SEGMENT_INFO) { + // An empty segment list is no segments ([MS-ODRAW] shapePath: it applies unless the list + // is "neither NULL nor empty"). + Some((2, segs)) if !segs.is_empty() => { + for c in segs.as_chunks::<2>().0.iter().take(MAX_SEGMENTS) { + let v = u16::from_le_bytes(*c); + let count = usize::from(v & 0x1FFF); + match v >> 13 { + // lineTo + 0 => { + for _ in 0..count.max(1) { + let Some(p) = pts.next() else { break }; + push("L", &[p]); + } + } + // curveTo: three points per segment + 1 => { + for _ in 0..count.max(1) { + let ps: Vec<_> = pts.by_ref().take(3).collect(); + if ps.len() < 3 { + break; + } + push("C", &ps); + } + } + 2 => { + let Some(p) = pts.next() else { break }; + push("M", &[p]); + } + 3 => push("Z", &[]), + 4 => break, + // Escapes (MSOPATHESCAPEINFO: escape code in bits 8–12, point count in bits + // 0–7). They aren't drawn as curves, but they use up their points, and the + // segments after them start where they end. + 5 => { + let n = usize::from(v & 0xFF); + let code = (v >> 8) & 0x1F; + let mut last = None; + for _ in 0..n { + last = pts.next().or(last); + } + match code { + // Extension: more points for the escape that follows. Fill and line + // colours: a colour pair, not a place. NoFill, NoLine and the Bézier + // editing hints: no points. + 0x00 | 0x0A..=0x16 => {} + // Elliptical quadrants run from point to point and a quadratic Bézier + // ends on its last point: a line there keeps the path's place. + 0x07..=0x09 => { + if let Some(p) = last { + push("L", &[p]); + } + } + // Angle ellipses and arcs end at a point computed from their angles or + // radial vectors, not at one of their vertices: the path stops rather + // than go on from the wrong place. So does any other escape. + _ => break, + } + } + // Client escapes mean what the writing application says: the path stops + // unless one has no points. + 6 if v & 0xFF != 0 => break, + _ => {} + } + } + } + // No segments: shapePath says how the vertices join (MSOSHAPEPATH), by default + // msoshapeLinesClosed. + _ => { + let shape_path = props.get(prop::SHAPE_PATH).unwrap_or(1); + if let Some(p) = pts.next() { + push("M", &[p]); + } + if matches!(shape_path, 2 | 3) { + loop { + let ps: Vec<_> = pts.by_ref().take(3).collect(); + if ps.len() < 3 { + break; + } + push("C", &ps); + } + } else { + for p in pts { + push("L", &[p]); + } + } + if matches!(shape_path, 1 | 3) { + push("Z", &[]); + } + } + } + let d = d.trim_end().to_string(); + if !d.starts_with('M') { + return None; + } + Some(vec![CustomPath { w, h, d, ..Default::default() }]) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::Rec; + use crate::record::build::atom; + + fn props(entries: &[(u16, u32)], complex: &[u8]) -> Vec { + let mut b = vec![]; + for (id, op) in entries { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + b.extend_from_slice(complex); + atom(crate::doc::rt::FOPT, entries.len() as u16, &b) + } + + fn array(size: u16, elems: &[u8]) -> Vec { + let n = (elems.len() / usize::from(size)) as u16; + [&n.to_le_bytes()[..], &n.to_le_bytes(), &size.to_le_bytes(), elems].concat() + } + + #[test] + fn every_mapped_preset_is_one_craft_drawingml_draws() { + for t in 0..=255u16 { + if let Some(name) = preset_name(t) { + assert!(craft_drawingml::preset::build(name, 100.0, 100.0, &[]).is_some(), "type {t}: {name}"); + } + } + } + + #[test] + fn reads_a_freeform_triangle() { + let verts: Vec = [(0i16, 100i16), (50, 0), (100, 100)].iter().flat_map(|(x, y)| [x.to_le_bytes(), y.to_le_bytes()].concat()).collect(); + // moveTo, lineTo ×2, close, end + let segs: Vec = [0x4000u16, 0x0002, 0x6001, 0x8000].iter().flat_map(|v| v.to_le_bytes()).collect(); + let v = array(4, &verts); + let s = array(2, &segs); + let t = props( + &[ + (prop::GEO_RIGHT, 100), + (prop::GEO_BOTTOM, 100), + (0x8000 | prop::VERTICES, v.len() as u32), + (0x8000 | prop::SEGMENT_INFO, s.len() as u32), + ], + &[v, s].concat(), + ); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + let Geom::Custom { paths } = geometry(0, &p) else { panic!("not custom") }; + assert_eq!(paths[0].d, "M 0 100 L 50 0 L 100 100 Z"); + assert_eq!((paths[0].w, paths[0].h), (100.0, 100.0)); + } + + /// A freeform with more vertices than [`MAX_POINTS`] draws through the first of them only. + #[test] + fn a_path_uses_at_most_max_points() { + let verts: Vec = (0..20_000u32).flat_map(|i| [(i as i16 % 100).to_le_bytes(), 0i16.to_le_bytes()].concat()).collect(); + let v = array(4, &verts); + let t = props(&[(0x8000 | prop::VERTICES, v.len() as u32)], &v); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + let Geom::Custom { paths } = geometry(0, &p) else { panic!("not custom") }; + let d = &paths[0].d; + assert_eq!(d.matches('M').count() + d.matches('L').count(), MAX_POINTS); + } + + fn freeform(verts: &[(i16, i16)], segs: Option<&[u16]>, extra: &[(u16, u32)]) -> Geom { + let verts: Vec = verts.iter().flat_map(|(x, y)| [x.to_le_bytes(), y.to_le_bytes()].concat()).collect(); + let v = array(4, &verts); + let mut entries = vec![(prop::GEO_RIGHT, 100), (prop::GEO_BOTTOM, 100), (0x8000 | prop::VERTICES, v.len() as u32)]; + entries.extend_from_slice(extra); + let mut complex = v; + if let Some(segs) = segs { + let s = array(2, &segs.iter().flat_map(|v| v.to_le_bytes()).collect::>()); + entries.push((0x8000 | prop::SEGMENT_INFO, s.len() as u32)); + complex.extend_from_slice(&s); + } + let t = props(&entries, &complex); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + geometry(0, &p) + } + + fn path_of(g: Geom) -> String { + let Geom::Custom { paths } = g else { panic!("not custom: {g:?}") }; + paths[0].d.clone() + } + + /// An escape segment uses up its points and the path goes on from where it ends: after + /// elliptical quadrants or a quadratic Bézier, from their last point; an arc ends at a point + /// worked out from its radial vectors, so the path stops there rather than draw the next line + /// from the point before the arc. + #[test] + fn path_escapes_end_where_they_end() { + let verts = [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (50, 60)]; + let escape = |code: u16, n: u16| (5u16 << 13) | (code << 8) | n; + // moveTo, escape ArcTo (3) over 4 points, lineTo, end. + assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(3, 4), 0x0001, 0x8000]), &[])), "M 0 0"); + // moveTo, two elliptical quadrants (7), lineTo, end. + let verts = [(0, 0), (10, 10), (20, 0), (50, 60)]; + assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(7, 2), 0x0001, 0x8000]), &[])), "M 0 0 L 20 0 L 50 60"); + // A colour escape uses its point but doesn't move the path. + assert_eq!(path_of(freeform(&verts, Some(&[0x4000, escape(0x15, 1), 0x0001, 0x8000]), &[])), "M 0 0 L 20 0"); + } + + /// Without segments, shapePath says how the vertices join: closed lines by default, open + /// lines, or Bézier curves three points at a time. An empty segment list is no segments. + #[test] + fn shape_path_joins_vertices_without_segments() { + let tri = [(0, 100), (50, 0), (100, 100)]; + assert_eq!(path_of(freeform(&tri, None, &[])), "M 0 100 L 50 0 L 100 100 Z"); + assert_eq!(path_of(freeform(&tri, Some(&[]), &[])), "M 0 100 L 50 0 L 100 100 Z"); + assert_eq!(path_of(freeform(&tri, None, &[(prop::SHAPE_PATH, 0)])), "M 0 100 L 50 0 L 100 100"); + let curve = [(0, 0), (10, 0), (20, 10), (20, 20)]; + assert_eq!(path_of(freeform(&curve, None, &[(prop::SHAPE_PATH, 2)])), "M 0 0 C 10 0 20 10 20 20"); + assert_eq!(path_of(freeform(&curve, None, &[(prop::SHAPE_PATH, 3)])), "M 0 0 C 10 0 20 10 20 20 Z"); + } + + #[test] + fn a_rounded_rectangle_keeps_its_corner() { + let t = props(&[(prop::ADJUST_VALUE, 5400)], &[]); + let mut p = Props::default(); + p.add_table(&Rec::at(&t, 0).unwrap()); + assert_eq!(geometry(2, &p), Geom::Preset { name: "roundRect".into(), adj: vec![25000.0] }); + assert_eq!(geometry(9999, &Props::default()), Geom::default()); + } +} diff --git a/crates/ppt-binary/src/lib.rs b/crates/ppt-binary/src/lib.rs new file mode 100644 index 0000000000..b9b2fa3159 --- /dev/null +++ b/crates/ppt-binary/src/lib.rs @@ -0,0 +1,76 @@ +//! Legacy PowerPoint 97–2003 import (`.ppt`, `.pot`, `.pps`), written from Microsoft's public +//! Open Specifications: [MS-PPT] (the presentation records) and [MS-ODRAW] (the shapes and +//! pictures), on `craft-cfb` for the compound file ([MS-CFB]). +//! +//! [`import`] reads a presentation leniently into a [`craft_pptx::Presentation`]: unknown records +//! are skipped, damaged ones are left out, and every size, count and depth is bounded. The caller's +//! [`Defaults`] supply each master's layouts and placeholders, which the file's masters then +//! place and style. There is no `.ppt` writer. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +#[cfg(doctest)] +#[doc = include_str!("../README.md")] +struct ReadmeExamples; + +mod blip; +mod convert; +mod doc; +mod draw; +mod geom; +mod record; +mod text; + +use craft_cfb::{CompoundFile, Error as CfbError}; +use craft_pptx::{Defaults, Presentation}; + +/// Name of the stream holding the presentation. +const DOCUMENT_STREAM: &str = "PowerPoint Document"; + +#[derive(Debug, thiserror::Error)] +pub enum PptError { + #[error("not a PowerPoint 97-2003 presentation")] + NotPpt, + #[error("the presentation is password-protected")] + Encrypted, + #[error("the presentation was made by PowerPoint 95 or earlier")] + TooOld, + #[error("the presentation is damaged: {0}")] + Damaged(String), +} + +/// Does this look like a PowerPoint 97–2003 file (a compound file with a `PowerPoint Document` +/// stream)? +pub fn sniff(bytes: &[u8]) -> bool { + craft_cfb::sniff(bytes) && CompoundFile::open(bytes).is_ok_and(|f| f.has_stream(DOCUMENT_STREAM)) +} + +/// Read a `.ppt` / `.pot` / `.pps` file. `defaults` gives the master each of the file's masters +/// starts from, and the one used when the file has none it can read. +pub fn import(bytes: &[u8], defaults: &dyn Defaults) -> Result { + import_checked(bytes, defaults).map(|(p, _)| p) +} + +/// [`import`], plus the slides the file lists but whose objects couldn't be found, so they are not +/// in the presentation. +pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec), PptError> { + let file = CompoundFile::open(bytes).map_err(|e| match e { + CfbError::NotCfb => PptError::NotPpt, + other => PptError::Damaged(other.to_string()), + })?; + // No stream is longer than the file holding it: a larger stated size is damage, refused + // before anything is allocated for it. + let cap = bytes.len() as u64; + let stream = file.read_path_capped(DOCUMENT_STREAM, cap).map_err(|e| match e { + CfbError::NotFound(_) => PptError::NotPpt, + other => PptError::Damaged(other.to_string()), + })?; + let current_user = file.read_path_capped("Current User", cap).unwrap_or_default(); + // A damaged or missing picture stream costs the pictures, not the presentation. + let pictures = file.read_path_capped("Pictures", cap).unwrap_or_default(); + let d = doc::read(¤t_user, &stream)?; + Ok((convert::convert(&d, &pictures, defaults), d.lost.clone())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ppt-binary/src/record.rs b/crates/ppt-binary/src/record.rs new file mode 100644 index 0000000000..62655e2be0 --- /dev/null +++ b/crates/ppt-binary/src/record.rs @@ -0,0 +1,186 @@ +//! The record framing shared by [MS-PPT] and [MS-ODRAW]: an 8-byte header (version, instance, +//! type, length) followed by `len` bytes, which for a container (version `0xF`) are more records. + +/// The little-endian `u16` at `at`, if `b` holds it. +pub(crate) fn u16_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(2)?)?; + Some(u16::from_le_bytes([*s.first()?, *s.get(1)?])) +} + +/// The little-endian `u32` at `at`, if `b` holds it. +pub(crate) fn u32_at(b: &[u8], at: usize) -> Option { + let s = b.get(at..at.checked_add(4)?)?; + Some(u32::from_le_bytes([*s.first()?, *s.get(1)?, *s.get(2)?, *s.get(3)?])) +} + +/// Containers nest at most this deep; deeper input is treated as damaged and skipped. +pub const MAX_DEPTH: usize = 32; + +/// One record over borrowed bytes. +#[derive(Clone, Copy, Debug)] +pub struct Rec<'a> { + pub ver: u8, + pub instance: u16, + pub kind: u16, + /// The record's body (after the header), clipped to the input. + pub data: &'a [u8], + /// Offset of the header in the slice it was read from. + pub offset: usize, +} + +impl<'a> Rec<'a> { + /// The record whose header starts at `at`, its body clipped to `bytes` (a truncated last record + /// keeps what is there). + pub fn at(bytes: &'a [u8], at: usize) -> Option> { + let vi = u16_at(bytes, at)?; + let kind = u16_at(bytes, at.checked_add(2)?)?; + let len = u32_at(bytes, at.checked_add(4)?)? as usize; + let start = at.checked_add(8)?; + let end = start.saturating_add(len).min(bytes.len()); + Some(Rec { ver: (vi & 0xF) as u8, instance: vi >> 4, kind, data: bytes.get(start..end)?, offset: at }) + } + + pub fn is_container(&self) -> bool { + self.ver == 0xF + } + + /// The records inside this one; none for an atom. + pub fn children(&self) -> Records<'a> { + Records::new(if self.is_container() { self.data } else { &[] }) + } + + /// The first child of type `kind`. + pub fn child(&self, kind: u16) -> Option> { + self.children().find(|r| r.kind == kind) + } + + /// Every child of type `kind`. + pub fn children_of(&self, kind: u16) -> impl Iterator> { + self.children().filter(move |r| r.kind == kind) + } + + pub fn u8(&self, at: usize) -> Option { + self.data.get(at).copied() + } + pub fn u16(&self, at: usize) -> Option { + u16_at(self.data, at) + } + pub fn i16(&self, at: usize) -> Option { + self.u16(at).map(|v| v as i16) + } + pub fn u32(&self, at: usize) -> Option { + u32_at(self.data, at) + } + pub fn i32(&self, at: usize) -> Option { + self.u32(at).map(|v| v as i32) + } +} + +/// Iterates the records laid end to end in a byte slice. +#[derive(Clone, Debug)] +pub struct Records<'a> { + bytes: &'a [u8], + at: usize, +} + +impl<'a> Records<'a> { + pub fn new(bytes: &'a [u8]) -> Self { + Records { bytes, at: 0 } + } +} + +impl<'a> Iterator for Records<'a> { + type Item = Rec<'a>; + fn next(&mut self) -> Option> { + let r = Rec::at(self.bytes, self.at)?; + // Always advance by at least the header, so a zero-length record can't stall the walk. + self.at = self.at.checked_add(8)?.checked_add(r.data.len())?; + Some(r) + } +} + +/// A little-endian reader over a record body for the variable-length structures (text +/// exceptions, style runs): every read is checked and a short body ends the walk. +pub struct Cursor<'a> { + pub b: &'a [u8], + pub at: usize, +} + +impl<'a> Cursor<'a> { + pub fn new(b: &'a [u8]) -> Self { + Cursor { b, at: 0 } + } + /// Bytes left to read. + pub fn remaining(&self) -> usize { + self.b.len().saturating_sub(self.at) + } + pub fn u8(&mut self) -> Option { + let v = *self.b.get(self.at)?; + self.at += 1; + Some(v) + } + pub fn u16(&mut self) -> Option { + let v = u16_at(self.b, self.at)?; + self.at += 2; + Some(v) + } + pub fn i16(&mut self) -> Option { + self.u16().map(|v| v as i16) + } + pub fn u32(&mut self) -> Option { + let v = u32_at(self.b, self.at)?; + self.at += 4; + Some(v) + } +} + +#[cfg(test)] +pub(crate) mod build { + //! Writing records, for tests that build `.ppt` files. + + pub fn atom(kind: u16, instance: u16, body: &[u8]) -> Vec { + head(0, kind, instance, body) + } + + pub fn container(kind: u16, instance: u16, children: &[Vec]) -> Vec { + head(0xF, kind, instance, &children.concat()) + } + + fn head(ver: u16, kind: u16, instance: u16, body: &[u8]) -> Vec { + let mut v = Vec::with_capacity(body.len() + 8); + v.extend_from_slice(&(ver | (instance << 4)).to_le_bytes()); + v.extend_from_slice(&kind.to_le_bytes()); + v.extend_from_slice(&(body.len() as u32).to_le_bytes()); + v.extend_from_slice(body); + v + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::build::*; + use super::*; + + #[test] + fn walks_nested_records() { + let c = container(0x03E8, 0, &[atom(0x03E9, 0, &[1, 2, 3, 4]), atom(0x0FA0, 2, &[9; 6])]); + let r = Rec::at(&c, 0).unwrap(); + assert!(r.is_container()); + let kids: Vec<_> = r.children().collect(); + assert_eq!(kids.len(), 2); + assert_eq!(kids[1].instance, 2); + assert_eq!(r.child(0x03E9).unwrap().u32(0), Some(0x0403_0201)); + } + + #[test] + fn truncated_and_zero_length_records_end_the_walk() { + let mut c = atom(0x1, 0, &[]).repeat(3); + c.extend_from_slice(&[0xF, 0, 0, 0, 0xFF, 0xFF, 0xFF, 0x7F, 1, 2]); + let all: Vec<_> = Records::new(&c).collect(); + assert_eq!(all.len(), 4); + assert_eq!(all[3].data, &[1, 2]); + assert!(Records::new(&[1, 2, 3]).next().is_none()); + } +} diff --git a/crates/ppt-binary/src/tests.rs b/crates/ppt-binary/src/tests.rs new file mode 100644 index 0000000000..55ed55396c --- /dev/null +++ b/crates/ppt-binary/src/tests.rs @@ -0,0 +1,1245 @@ +//! End-to-end tests over `.ppt` files built here from records (never files made by PowerPoint). +#![allow(clippy::unwrap_used)] + +use craft_pptx::text::{Align, Bullet, RunKind}; +use craft_pptx::{ + Background, Defaults, Fill, Layout, LayoutId, LayoutType, Master, MasterId, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId, ShapeKind, + Size, Slide, TextBody, Xfrm, +}; + +use crate::doc::rt; +use crate::draw::prop; +use crate::record::build::{atom, container}; +use crate::text::tests::{cf_bytes, pf_bytes}; + +/// A default master as an application gives one: title, body and footer placeholders on the +/// master, and the layouts `.ppt` layout types map to, each with its placeholders. The `.ppt` +/// masters place and style these. +struct AppDefaults; + +impl Defaults for AppDefaults { + fn master(&self, size: Size, after: u32) -> (Master, u32) { + let next = std::cell::Cell::new(after); + let id = || { + next.set(next.get() + 1); + next.get() + }; + let (w, h) = (size.width, size.height); + let ph = |kind: PhType, name: &str, x: [f64; 4]| Shape { + id: ShapeId(id()), + name: name.into(), + xfrm: Some(Xfrm::new(x[0] * w, x[1] * h, x[2] * w, x[3] * h)), + ph: Some(Placeholder { kind, ..Default::default() }), + text: Some(TextBody::default()), + ..Default::default() + }; + let title = || ph(PhType::Title, "Title", [0.06, 0.05, 0.88, 0.17]); + let footers = || { + vec![ + ph(PhType::Date, "Date", [0.06, 0.92, 0.22, 0.05]), + ph(PhType::Footer, "Footer", [0.33, 0.92, 0.34, 0.05]), + ph(PhType::SlideNum, "Slide Number", [0.72, 0.92, 0.22, 0.05]), + ] + }; + let mut shapes = vec![title(), ph(PhType::Body, "Text", [0.06, 0.25, 0.88, 0.62])]; + shapes.extend(footers()); + let kinds = [ + (LayoutType::Title, "Title Slide"), + (LayoutType::TitleAndContent, "Title and Content"), + (LayoutType::TitleOnly, "Title Only"), + (LayoutType::TwoContent, "Two Content"), + (LayoutType::VerticalTitleAndText, "Vertical Title and Text"), + (LayoutType::TitleAndVerticalText, "Title and Vertical Text"), + (LayoutType::Blank, "Blank"), + ]; + let layouts = kinds + .into_iter() + .map(|(kind, name)| { + let mut l: Vec = if kind == LayoutType::Blank { vec![] } else { vec![title()] }; + l.extend(footers()); + Layout { id: LayoutId(id()), name: name.into(), kind, shapes: l, show_master_shapes: true, ..Default::default() } + }) + .collect(); + let master = Master { id: MasterId(id()), name: "Default".into(), shapes, layouts, ..Default::default() }; + (master, next.get()) + } +} + +fn import(bytes: &[u8]) -> Result { + crate::import(bytes, &AppDefaults) +} + +fn import_checked(bytes: &[u8]) -> Result<(Presentation, Vec), crate::PptError> { + crate::import_checked(bytes, &AppDefaults) +} + +/// A version 3 compound file holding `streams` at its root. +fn build(streams: &[(&str, &[u8])]) -> Vec { + craft_cfb::write_streams(craft_cfb::Version::V3, streams).unwrap() +} + +/// With no default master of the caller's, a file's masters still read: the plain master has no +/// placeholders for the file's to place, and the slides keep their own. +#[test] +fn plain_defaults_still_read_the_file() { + let p = crate::import(&file(), &craft_pptx::Plain).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().text(), "Hello\nWorld"); + assert!(p.layout(p.slides[0].layout).is_some()); +} + +fn le32(v: &[u32]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +fn utf16(s: &str) -> Vec { + s.encode_utf16().flat_map(u16::to_le_bytes).collect() +} + +fn fopt(entries: &[(u16, u32)]) -> Vec { + let mut b = vec![]; + for (id, op) in entries { + b.extend_from_slice(&id.to_le_bytes()); + b.extend_from_slice(&op.to_le_bytes()); + } + atom(rt::FOPT, entries.len() as u16, &b) +} + +fn fsp(shape_type: u16, spid: u32, flags: u32) -> Vec { + atom(rt::FSP, shape_type, &le32(&[spid, flags])) +} + +/// A client anchor in master units: top, left, right, bottom. +fn anchor(t: i16, l: i16, r: i16, b: i16) -> Vec { + atom(rt::CLIENT_ANCHOR, 0, &[t, l, r, b].iter().flat_map(|v| v.to_le_bytes()).collect::>()) +} + +fn text_box(text_type: u32, text: &str, extra: &[Vec]) -> Vec { + let mut kids = vec![atom(rt::TEXT_HEADER, 0, &text_type.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16(text))]; + kids.extend_from_slice(extra); + container(rt::CLIENT_TEXTBOX, 0, &kids) +} + +fn placeholder(kind: u8) -> Vec { + container(rt::CLIENT_DATA, 0, &[atom(rt::PLACEHOLDER_ATOM, 0, &[0, 0, 0, 0, kind, 0, 0, 0])]) +} + +fn drawing(background: Option>, shapes: &[Vec]) -> Vec { + let patriarch = container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &[0; 16]), fsp(0, 1024, 0x5)]); + let mut tree = vec![patriarch]; + tree.extend_from_slice(shapes); + let mut dg = vec![container(rt::SPGR_CONTAINER, 0, &tree)]; + dg.extend(background); + container(rt::DRAWING, 0, &[container(rt::DG_CONTAINER, 0, &dg)]) +} + +fn solid_background(rgb: u32) -> Vec { + container(rt::SP_CONTAINER, 0, &[fsp(1, 1025, 0x400 | 0x800), fopt(&[(prop::FILL_COLOR, rgb), (prop::FILL_BOOLS, 0x0010_0010)])]) +} + +fn slide_atom(geom: u32, master_id: u32, flags: u16) -> Vec { + let mut b = geom.to_le_bytes().to_vec(); + b.extend_from_slice(&[0; 8]); + b.extend_from_slice(&le32(&[master_id, 0])); + b.extend_from_slice(&flags.to_le_bytes()); + b.extend_from_slice(&[0; 2]); + atom(rt::SLIDE_ATOM, 0, &b) +} + +/// A master text style with one level: a paragraph and a character exception. +fn master_style(instance: u16, pf: &[u8], cf: &[u8]) -> Vec { + atom(rt::TEXT_MASTER_STYLE, instance, &[&1u16.to_le_bytes()[..], pf, cf].concat()) +} + +const MASTER_ID: u32 = 0x8000_0001; +const SLIDE_ID: u32 = 256; +const TITLE_MASTER_ID: u32 = 0x8000_0002; + +fn master() -> Vec { + master_with(&[]) +} + +/// The test master with `shapes` after its decoration. +fn master_with(shapes: &[Vec]) -> Vec { + // Background, text, shadow, title, fill, accent, hyperlink, followed hyperlink. + let scheme: Vec = [0xFFFFFFu32, 0x000000, 0x808080, 0x000099, 0x00CC00, 0x0000FF, 0x00FF00, 0xFF0000] + .iter() + .flat_map(|c| [(c >> 16) as u8, (c >> 8) as u8, *c as u8, 0]) + .collect(); + let decoration = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 1026, 0xA00), + fopt(&[(prop::FILL_COLOR, 0x0800_0004), (prop::FILL_BOOLS, 0x0010_0010), (prop::LINE_BOOLS, 0x0008_0000)]), + anchor(0, 0, 5760, 400), + ], + ); + container( + rt::MAIN_MASTER, + 0, + &[ + slide_atom(1, 0, 0), + atom(rt::COLOR_SCHEME, 1, &scheme), + master_style(0, &pf_bytes(1, false), &cf_bytes(true, 0, 44, [0x11, 0x22, 0x33])), + master_style(1, &pf_bytes(0, true), &cf_bytes(false, 0, 28, [0, 0, 0])), + drawing(Some(solid_background(0x0000_00FF)), &[&[decoration][..], shapes].concat()), + ], + ) +} + +fn slide() -> Vec { + let title = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 2049, 0xA00), fopt(&[(prop::ANCHOR_TEXT, 1)]), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Hello\rWorld", &[])], + ); + let picture = container(rt::SP_CONTAINER, 0, &[fsp(75, 2050, 0xA00), fopt(&[(prop::PIB, 1)]), anchor(1600, 800, 2400, 2400)]); + let group = container( + rt::SPGR_CONTAINER, + 0, + &[ + container(rt::SP_CONTAINER, 0, &[atom(rt::FSPGR, 1, &le32(&[0, 0, 1000, 1000])), fsp(0, 2051, 0x201), anchor(1600, 3000, 4000, 3200)]), + container( + rt::SP_CONTAINER, + 0, + &[ + fsp(3, 2052, 0x2), + fopt(&[(prop::FILL_COLOR, 0x0000_FF00), (prop::LINE_WIDTH, 25400)]), + atom(rt::CHILD_ANCHOR, 0, &le32(&[500, 0, 1000, 500])), + ], + ), + ], + ); + // "Page *": the star is a slide number field. The first four characters are bold. + let mut style = vec![]; + style.extend_from_slice(&7u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(2, false)); + for (n, bold) in [(4u32, true), (3, false)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&cf_bytes(bold, 1, 12, [0xAB, 0xCD, 0xEF])); + } + let footer = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(202, 2053, 0xA00), + anchor(4000, 500, 2000, 4200), + text_box(4, "Page *", &[atom(rt::STYLE_TEXT_PROP, 0, &style), atom(rt::SLIDE_NUMBER_MC, 0, &5u32.to_le_bytes())]), + ], + ); + // A hidden slide (SlideShowSlideInfoAtom fHidden). + let mut info = vec![0u8; 16]; + info[10] = 0x4; + container( + rt::SLIDE, + 0, + &[slide_atom(1, MASTER_ID, 0x7), atom(rt::SLIDE_SHOW_SLIDE_INFO, 0, &info), drawing(None, &[title, picture, group, footer])], + ) +} + +fn notes() -> Vec { + let number = container(rt::SP_CONTAINER, 0, &[fsp(1, 3073, 0xA00), anchor(0, 0, 100, 100), placeholder(0x08), text_box(2, "*", &[])]); + let body = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 3074, 0xA00), anchor(100, 0, 4000, 4000), placeholder(0x0C), text_box(2, "Say hello\rThen wave", &[])], + ); + container(rt::NOTES, 0, &[atom(rt::NOTES_ATOM, 0, &le32(&[SLIDE_ID, 0])), drawing(None, &[number, body])]) +} + +fn png() -> Vec { + let mut buf = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut buf, image::ImageFormat::Png).unwrap(); + buf.into_inner() +} + +/// The streams of a one-slide presentation, with `edit` choosing the current user's header token. +fn streams(token: u32) -> (Vec, Vec, Vec) { + streams_listing(token, 1) +} + +/// The test document with its slide listed `times` times in the slide list. +fn streams_listing(token: u32, times: usize) -> (Vec, Vec, Vec) { + streams_of(token, times, slide(), None) +} + +/// The test document with `slide` as its slide and, when given, a title master (persist id 5, +/// slide id `TITLE_MASTER_ID`) listed after the main master. +fn streams_of(token: u32, times: usize, slide: Vec, title_master: Option>) -> (Vec, Vec, Vec) { + streams_with_outline(token, times, slide, title_master, &[]) +} + +/// As [`streams_of`], with `outline` (text blocks: header, characters, styles) following the +/// slide's persist atom in the slide list. +fn streams_with_outline(token: u32, times: usize, slide: Vec, title_master: Option>, outline: &[Vec]) -> (Vec, Vec, Vec) { + streams_with_document(token, times, master(), slide, title_master, outline, &[]) +} + +/// As [`streams_with_outline`], with `master` as the main master and `extra` records at the end of +/// the document container. +fn streams_with_document( + token: u32, + times: usize, + master: Vec, + slide: Vec, + title_master: Option>, + outline: &[Vec], + extra: &[Vec], +) -> (Vec, Vec, Vec) { + streams_with_title_masters(token, times, master, slide, title_master.into_iter().collect(), outline, extra) +} + +/// As [`streams_with_document`], with any number of title masters: persist ids 5 on, slide ids +/// `TITLE_MASTER_ID` on. +fn streams_with_title_masters( + token: u32, + times: usize, + master: Vec, + slide: Vec, + title_masters: Vec>, + outline: &[Vec], + extra: &[Vec], +) -> (Vec, Vec, Vec) { + streams_with_notes(token, times, master, slide, title_masters, outline, extra, notes(), &[]) +} + +/// As [`streams_with_title_masters`], with `notes` as the notes page (persist id 4) and +/// `notes_outline` following its persist atom in the notes list. +#[allow(clippy::too_many_arguments)] +fn streams_with_notes( + token: u32, + times: usize, + master: Vec, + slide: Vec, + title_masters: Vec>, + outline: &[Vec], + extra: &[Vec], + notes: Vec, + notes_outline: &[Vec], +) -> (Vec, Vec, Vec) { + let pictures = atom(0xF01E, 0x6E0, &[&[0u8; 17][..], &png()].concat()); + let mut fbse = vec![0u8; 36]; + fbse[0] = 6; + fbse[1] = 6; + fbse[20..24].copy_from_slice(&(pictures.len() as u32).to_le_bytes()); + let bstore = container(rt::BSTORE, 1, &[atom(rt::FBSE, 6, &fbse)]); + let mut font = utf16("Arial"); + font.resize(68, 0); + let mut wing = utf16("Wingdings"); + wing.resize(68, 0); + let mut doc_atom = le32(&[5760, 4320, 4320, 5760, 1, 2, 0, 0]); + doc_atom.extend_from_slice(&1u16.to_le_bytes()); + doc_atom.resize(40, 0); + let persist = |id: u32| { + atom( + rt::SLIDE_PERSIST_ATOM, + 0, + &le32(&[ + id, + 0, + 0, + if id == 2 { + MASTER_ID + } else if id >= 5 { + TITLE_MASTER_ID + (id - 5) + } else if id == 3 { + SLIDE_ID + } else { + SLIDE_ID + 1 + }, + 0, + ]), + ) + }; + let parts = [ + atom(rt::DOCUMENT_ATOM, 0, &doc_atom), + container(rt::ENVIRONMENT, 0, &[container(rt::FONT_COLLECTION, 0, &[atom(rt::FONT_ENTITY, 0, &font), atom(rt::FONT_ENTITY, 1, &wing)])]), + container(rt::DRAWING_GROUP, 0, &[container(rt::DGG_CONTAINER, 0, &[bstore])]), + container( + rt::SLIDE_LIST_WITH_TEXT, + 1, + &(0..=title_masters.len() as u32).map(|k| persist(if k == 0 { 2 } else { 4 + k })).collect::>(), + ), + container(rt::SLIDE_LIST_WITH_TEXT, 0, &[vec![persist(3); times], outline.to_vec()].concat()), + container(rt::SLIDE_LIST_WITH_TEXT, 2, &[vec![persist(4)], notes_outline.to_vec()].concat()), + ]; + let document = container(rt::DOCUMENT, 0, &[&parts[..], extra].concat()); + let mut stream = vec![]; + let mut offsets = vec![]; + let parts: Vec> = [document, master, slide, notes].into_iter().chain(title_masters).collect(); + for part in &parts { + offsets.push(stream.len() as u32); + stream.extend_from_slice(part); + } + let dir_at = stream.len() as u32; + let mut dir = vec![1u32 | ((parts.len() as u32) << 20)]; + dir.extend_from_slice(&offsets); + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&dir))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, 0, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let current_user = atom(rt::CURRENT_USER, 0, &le32(&[0x14, token, edit_at, 0, 0])); + (current_user, stream, pictures) +} + +fn file_with(token: u32) -> Vec { + let (cu, doc, pics) = streams(token); + build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]) +} + +fn file() -> Vec { + file_with(0xE391_C05F) +} + +#[test] +fn imports_a_presentation() { + let bytes = file(); + assert!(crate::sniff(&bytes)); + let p = import(&bytes).unwrap(); + assert_eq!((p.slide_size.width, p.slide_size.height), (720.0, 540.0)); + assert_eq!(p.slides.len(), 1); + let s = &p.slides[0]; + assert!(s.hidden); + assert_eq!(s.notes.text(), "Say hello\nThen wave"); + check_title_placeholder(s); + check_picture(&p, s); + check_group(s); + check_text_box(s); + check_master(&p, s); +} + +fn check_title_placeholder(s: &Slide) { + // The title placeholder: its box, its text and the master's title style. + let title = &s.shapes[0]; + assert_eq!(title.ph_type(), Some(PhType::Title)); + let x = title.xfrm.unwrap(); + assert_eq!((x.x, x.y, x.w, x.h), (62.5, 50.0, 595.0, 100.0)); + assert_eq!(title.fill, Some(Fill::None)); + let t = title.text.as_ref().unwrap(); + assert_eq!(t.text(), "Hello\nWorld"); + assert_eq!(t.body.anchor, Some(craft_pptx::text::Anchor::Middle)); + let p0 = &t.paragraphs[0]; + assert_eq!(p0.props.align, Some(Align::Center)); + assert_eq!(p0.props.bullet, Some(Bullet::None)); + let r = &p0.runs[0].props; + assert_eq!((r.size, r.bold, r.font.as_deref()), (Some(44.0), Some(true), Some("Arial"))); + assert_eq!(r.fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0x11, 0x22, 0x33))))); + assert_eq!(s.title(), "Hello\nWorld"); +} + +fn check_picture(p: &Presentation, s: &Slide) { + // The picture. + let ShapeKind::Picture { fill } = &s.shapes[1].kind else { panic!("not a picture: {:?}", s.shapes[1].kind) }; + let media = p.media.iter().find(|m| m.id == fill.media).unwrap(); + assert_eq!(media.content_type, "image/png"); + assert!(media.data.starts_with(b"\x89PNG")); +} + +fn check_group(s: &Slide) { + // The group: children in slide points, the child space the group's own box. + let g = &s.shapes[2]; + let ShapeKind::Group { children, child } = &g.kind else { panic!("not a group") }; + let gx = g.xfrm.unwrap(); + assert_eq!((gx.x, gx.y, gx.w, gx.h), (375.0, 200.0, 125.0, 200.0)); + assert_eq!((child.x, child.y, child.w, child.h), (gx.x, gx.y, gx.w, gx.h)); + let e = children[0].xfrm.unwrap(); + assert_eq!((e.x, e.y, e.w, e.h, e.flip_h), (437.5, 200.0, 62.5, 100.0, false)); + assert_eq!(children[0].geom.preset_name(), Some("ellipse")); + assert_eq!(children[0].fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xFF, 0))))); + assert_eq!(children[0].line.as_ref().and_then(|l| l.width), Some(2.0)); +} + +fn check_text_box(s: &Slide) { + // The text box: runs split at the format change, the star a slide number field. + let tb = s.shapes[3].text.as_ref().unwrap(); + let runs = &tb.paragraphs[0].runs; + assert_eq!(tb.paragraphs[0].props.align, Some(Align::Right)); + assert_eq!(runs.len(), 3, "{runs:?}"); + assert_eq!((runs[0].text.as_str(), runs[0].props.bold), ("Page", Some(true))); + assert_eq!((runs[1].text.as_str(), runs[1].props.bold), (" ", Some(false))); + assert_eq!(runs[2].kind, RunKind::Field { field: "slidenum".into() }); + assert_eq!(runs[0].props.font.as_deref(), Some("Wingdings")); + assert_eq!(s.shapes[3].fill, Some(Fill::None)); +} + +fn check_master(p: &Presentation, s: &Slide) { + // The master: its background, colours and decoration. + let m = &p.masters[0]; + assert_eq!(m.background, Some(Background::Fill { fill: Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0xFF, 0, 0))) })); + assert_eq!(m.theme.colors.get(craft_pptx::SchemeSlot::Accent1), Rgba::rgb(0, 0xCC, 0)); + assert!(m.shapes.iter().any(|sh| sh.ph.is_none() && sh.fill == Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xCC, 0)))))); + assert_eq!(m.title_style.level(0).and_then(|l| l.run.size), Some(44.0)); + assert!(p.layout(s.layout).is_some()); +} + +/// A slide listed many times is one slide: a hostile file can't make the importer convert one +/// big drawing again for every listing (180k listings of a 100k-shape slide fit in ~10 MB). +#[test] +fn a_slide_listed_again_is_imported_once() { + let (cu, doc, pics) = streams_listing(0xE391_C05F, 3); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]); + let p = import(&bytes).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!( + p.slides[0].notes.text(), + "Say hello +Then wave" + ); +} + +/// Two slide records with the same slide id share its notes page, which goes to the first only: +/// converting it again for each would copy its text into every one. +#[test] +fn a_notes_page_goes_to_one_slide() { + let again = container(rt::SLIDE_LIST_WITH_TEXT, 0, &[atom(rt::SLIDE_PERSIST_ATOM, 0, &le32(&[6, 0, 0, SLIDE_ID, 0]))]); + let (_, mut stream, pics) = streams_with_document(0xE391_C05F, 1, master(), slide(), None, &[], &[again]); + let first_edit = stream.len() as u32 - 36; + // Persist id 6: a second copy of the slide. + let copy_at = stream.len() as u32; + stream.extend_from_slice(&slide()); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[6 | (1 << 20), copy_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 7]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 2); + assert_eq!(p.slides[0].notes.text(), "Say hello\nThen wave"); + assert_eq!(p.slides[1].notes.text(), ""); +} + +/// As [`a_notes_page_goes_to_one_slide`], with the notes body's text in the notes list's outline +/// block: that block, too, is copied into the first slide's notes only. +#[test] +fn a_notes_pages_outline_text_goes_to_one_slide() { + let body = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 3074, 0xA00), + anchor(100, 0, 4000, 4000), + placeholder(0x0C), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes())]), + ], + ); + let notes = container(rt::NOTES, 0, &[atom(rt::NOTES_ATOM, 0, &le32(&[SLIDE_ID, 0])), drawing(None, &[body])]); + let outline = [atom(rt::TEXT_HEADER, 0, &2u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("From the outline"))]; + let again = container(rt::SLIDE_LIST_WITH_TEXT, 0, &[atom(rt::SLIDE_PERSIST_ATOM, 0, &le32(&[6, 0, 0, SLIDE_ID, 0]))]); + let (_, mut stream, pics) = streams_with_notes(0xE391_C05F, 1, master(), slide(), vec![], &[], &[again], notes, &outline); + let first_edit = stream.len() as u32 - 36; + let copy_at = stream.len() as u32; + stream.extend_from_slice(&slide()); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[6 | (1 << 20), copy_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 7]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 2); + assert_eq!(p.slides[0].notes.text(), "From the outline"); + assert_eq!(p.slides[1].notes.text(), ""); +} + +/// Text with very many formatting runs is laid into runs in about linear time. Each lookup used to +/// scan the run starts from the beginning, so the cost grew with runs²: in a debug build these 640k +/// one-character runs (about 6 MB of file) took 75 s that way, and take about 2 s with binary search. +#[test] +fn many_character_runs_are_not_quadratic() { + const N: usize = 640_000; + let text: String = (0..N).map(|i| if i % 2 == 0 { 'a' } else { '\u{0B}' }).collect(); + let mut style = vec![]; + style.extend_from_slice(&(N as u32 + 1).to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&0u32.to_le_bytes()); // a paragraph exception with no fields + for _ in 0..=N { + style.extend_from_slice(&1u32.to_le_bytes()); + style.extend_from_slice(&0u32.to_le_bytes()); // a character exception with no fields + } + let shape = container( + rt::SP_CONTAINER, + 0, + &[fsp(202, 2060, 0xA00), anchor(0, 0, 1000, 1000), text_box(1, &text, &[atom(rt::STYLE_TEXT_PROP, 0, &style)])], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[shape])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]); + let t = std::time::Instant::now(); + let p = import(&bytes).unwrap(); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); + let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs; + assert_eq!(runs.iter().filter(|r| r.kind == RunKind::Break).count(), N / 2); +} + +/// A slide naming a master that doesn't exist falls back to the first main master, every time. The +/// fallback used to be the lowest index in a HashMap where a title master ties with its main +/// master, so the slide took the "Title Master" layout on some opens and not on others. +#[test] +fn a_slide_with_an_unknown_master_falls_back_the_same_way_every_time() { + let title_master = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[])]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, 0x8000_0099, 0x7), drawing(None, &[])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, Some(title_master)); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]); + for _ in 0..30 { + let p = import(&bytes).unwrap(); + assert_eq!(p.masters[0].layouts.iter().filter(|l| l.name == "Title Master").count(), 1, "the title master became a layout"); + let (_, layout) = p.layout(p.slides[0].layout).unwrap(); + assert_ne!(layout.name, "Title Master"); + } +} + +/// A damaged Current User record doesn't make a PowerPoint 97 file "too old": the newest edit is +/// found by scanning the document stream instead. A file with no edit record at all, behind a +/// token that isn't PowerPoint 97's, is still reported as too old. +#[test] +fn a_damaged_current_user_falls_back_to_the_scan() { + let (cu, doc, pics) = streams(0xE391_C05F); + let open = |cu: &[u8], doc: &[u8]| import(&build(&[("Current User", cu), ("PowerPoint Document", doc), ("Pictures", &pics)])); + // Truncated after the header and two bytes, so the token can't be read. + let truncated = atom(rt::CURRENT_USER, 0, &[0x14, 0]); + assert_eq!(open(&truncated, &doc).unwrap().slides.len(), 1); + // A corrupted token. + let corrupted = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xDEAD_BEEF, 0, 0, 0])); + assert_eq!(open(&corrupted, &doc).unwrap().slides.len(), 1); + assert!(matches!(open(&corrupted, &atom(rt::DOCUMENT_ATOM, 0, &[0; 40])), Err(crate::PptError::TooOld))); + // An intact token that points at no edit still gets the scan, and a stream without one is damaged. + assert!(matches!(open(&cu, &atom(rt::DOCUMENT_ATOM, 0, &[0; 40])), Err(crate::PptError::Damaged(_)))); +} + +/// Persist directories nested inside one another are not each read to the end of the stream. A chain +/// of edits, each naming a directory header 8 bytes after the last one, made every edit reparse the +/// rest of the stream (4095 edits × the filler): about 48 s for this 64 MiB stream in a debug build. +/// Within the shared budget it takes milliseconds, and the file is reported as damaged. +#[test] +fn nested_persist_directories_are_read_within_the_stream() { + const FILLER: usize = 1 << 26; + const EDITS: u32 = 4095; + let (_, mut stream, _) = streams(0xE391_C05F); + let mut prev = stream.len() as u32 - 36; // the test document's own UserEditAtom (8 + 28 bytes) + let base = stream.len() as u32; + for _ in 0..EDITS { + // A PersistDirectoryAtom header whose length runs past the end (clipped to the stream). + stream.extend_from_slice(&0u16.to_le_bytes()); + stream.extend_from_slice(&rt::PERSIST_DIRECTORY.to_le_bytes()); + stream.extend_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); + } + stream.resize(stream.len() + FILLER, 0); + for k in 0..EDITS { + let at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, prev, base + 8 * k, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + prev = at; + } + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, prev, 0, 0])); + // The streams are read directly: the test file builder can't hold a stream this size. + let t = std::time::Instant::now(); + let r = crate::doc::read(&cu, &stream); + assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed()); + assert!(matches!(r, Err(crate::PptError::Damaged(_)))); +} + +#[test] +fn an_encrypted_presentation_says_so() { + assert!(matches!(import(&file_with(0xF3D1_C4DF)), Err(crate::PptError::Encrypted))); +} + +#[test] +fn other_files_are_not_ppt() { + assert!(!crate::sniff(b"PK\x03\x04")); + assert!(!crate::sniff(&build(&[("WordDocument", b"x")]))); + assert!(matches!(import(b"not a presentation"), Err(crate::PptError::NotPpt))); + assert!(matches!(import(&build(&[("Workbook", b"x")])), Err(crate::PptError::NotPpt))); +} + +/// Damaged input never panics, loops or allocates without bound: every 4-byte word of the +/// document stream set to hostile values, and truncations of it. +#[test] +fn hostile_documents_never_panic() { + let (cu, doc, pics) = streams(0xE391_C05F); + for at in (0..doc.len().saturating_sub(4)).step_by(3) { + for v in [0u32, 1, 0x7FFF_FFFF, 0xFFFF_FFFF, 0x0000_FFFF, 0xF00F_000F] { + let mut d = doc.clone(); + d[at..at + 4].copy_from_slice(&v.to_le_bytes()); + let f = build(&[("Current User", &cu), ("PowerPoint Document", &d), ("Pictures", &pics)]); + let _ = import(&f); + } + } + for cut in (0..doc.len()).step_by(7) { + let f = build(&[("Current User", &cu), ("PowerPoint Document", &doc[..cut]), ("Pictures", &pics[..cut.min(pics.len())])]); + let _ = import(&f); + } +} + +/// A slide shape that inherits from a master shape (`hspMaster`) takes it from its own master. +/// Master shapes used to be remembered by shape id alone, so a title master reusing the main +/// master's shape id (here 1026, red instead of the scheme's green) replaced it for every slide. +#[test] +fn a_master_shape_id_is_looked_up_in_the_slides_own_master() { + let red = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 1026, 0xA00), fopt(&[(prop::FILL_COLOR, 0x0000_00FF), (prop::FILL_BOOLS, 0x0010_0010)]), anchor(0, 0, 100, 100)], + ); + let title_master = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[red])]); + let inheriting = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), fopt(&[(prop::HSP_MASTER, 1026)]), anchor(0, 0, 100, 100)]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[inheriting])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, Some(title_master)); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides[0].shapes[0].fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xCC, 0))))); +} + +/// A run's shadow bit (TextCFException fontStyle bit 4) gives the run a shadow in the colour +/// scheme's shadow colour (grey in the test scheme). It used to be read and then dropped. +#[test] +fn a_shadowed_run_keeps_its_shadow() { + let mut style = vec![]; + style.extend_from_slice(&7u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, false)); + for (n, shadow) in [(3u32, true), (4, false)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&0x10u32.to_le_bytes()); // mask: shadow + style.extend_from_slice(&(if shadow { 0x10u16 } else { 0 }).to_le_bytes()); + } + let tb = container( + rt::SP_CONTAINER, + 0, + &[fsp(202, 2049, 0xA00), anchor(0, 0, 1000, 1000), text_box(4, "Hi you", &[atom(rt::STYLE_TEXT_PROP, 0, &style)])], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[tb])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let runs = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs; + assert_eq!(runs[0].text, "Hi "); + let shadow = runs[0].props.shadow.as_ref().expect("the first run is shadowed"); + assert_eq!(shadow.color, craft_pptx::ColorRef::rgb(Rgba::rgb(0x80, 0x80, 0x80))); + assert!(runs[1].props.shadow.is_none()); +} + +/// `tests/fixtures/old-talk.pps`: a one-slide `.pps` built here from records, for applications' +/// tests that need real 97–2003 bytes (DeckCraft's show-on-open test). Run this test with +/// `CRAFT_WRITE_PPT_FIXTURE=1` to rebuild the file after changing the builders. +#[test] +fn the_pps_fixture_is_a_built_presentation() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/old-talk.pps"); + if std::env::var_os("CRAFT_WRITE_PPT_FIXTURE").is_some() { + let title = + container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Old talk", &[])]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, slide, None); + std::fs::write(path, build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + } + let p = import(&std::fs::read(path).unwrap()).unwrap(); + assert_eq!(p.slides.len(), 1); + assert!(!p.slides[0].hidden); + let title = p.slides[0].shapes[0].text.as_ref().unwrap(); + assert_eq!(title.paragraphs[0].runs[0].text, "Old talk"); +} + +/// A placeholder whose client text box holds only an `OutlineTextRefAtom` takes its text and +/// formatting from that block of the slide list ([MS-PPT] OfficeArtClientTextbox allows the +/// reference alone). A text box that also has a header but no characters falls back the same way. +#[test] +fn placeholder_text_can_come_from_the_slide_list() { + let mut style = vec![]; + style.extend_from_slice(&7u32.to_le_bytes()); // the text and its closing paragraph mark + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(1, false)); + for (n, bold) in [(2u32, true), (5, false)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&cf_bytes(bold, 0, 40, [0x12, 0x34, 0x56])); + } + let outline = [ + atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()), + atom(rt::TEXT_CHARS, 0, &utf16("Hi all")), + atom(rt::STYLE_TEXT_PROP, 0, &style), + atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), + atom(rt::TEXT_CHARS, 0, &utf16("Second block")), + ]; + let reference = |n: u32| atom(rt::OUTLINE_TEXT_REF, 0, &n.to_le_bytes()); + let only_ref = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), container(rt::CLIENT_TEXTBOX, 0, &[reference(0)])], + ); + let header_and_ref = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 2050, 0xA00), + anchor(1300, 500, 5260, 3000), + placeholder(0x0E), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), reference(1)]), + ], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[only_ref, header_and_ref])]); + let (cu, doc, pics) = streams_with_outline(0xE391_C05F, 1, slide, None, &outline); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let shapes = &p.slides[0].shapes; + let title = shapes[0].text.as_ref().expect("the title has the outline text"); + let runs = &title.paragraphs[0].runs; + assert_eq!((runs[0].text.as_str(), runs[0].props.bold), ("Hi", Some(true))); + assert_eq!((runs[1].text.as_str(), runs[1].props.bold), (" all", Some(false))); + assert_eq!(runs[0].props.size, Some(40.0)); + assert_eq!(title.paragraphs[0].props.align, Some(Align::Center)); + let body = shapes[1].text.as_ref().expect("the body has the second block"); + assert_eq!(body.paragraphs[0].runs[0].text, "Second block"); +} + +/// The newest edit wins: a later edit's persist directory that gives the slide's persist id a new +/// slide replaces the old one. +#[test] +fn a_later_edit_replaces_a_slide() { + let (_, mut stream, pics) = streams(0xE391_C05F); + let first_edit = stream.len() as u32 - 36; // the test document's UserEditAtom (8 + 28 bytes) + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Edited", &[])]); + let slide_at = stream.len() as u32; + stream.extend_from_slice(&container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])])); + // Persist id 3 (the slide) only. + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[3 | (1 << 20), slide_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs[0].text, "Edited"); + // The master, from the first edit's directory, is still there. + assert_eq!(p.masters.len(), 1); +} + +/// An edit whose "previous edit" points back at itself cuts the older edits off the chain, and +/// with them the document, master and notes (storytold/deckcraft#1137 review: such a file opened as an empty deck). +/// Every edit in the stream is read instead, the newest still winning. +#[test] +fn a_broken_edit_chain_is_recovered_from_every_edit() { + let (_, mut stream, pics) = streams(0xE391_C05F); + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Edited", &[])]); + let slide_at = stream.len() as u32; + stream.extend_from_slice(&container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])])); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[3 | (1 << 20), slide_at]))); + let edit_at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, edit_at, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at, 0, 0])); + let (p, lost) = import_checked(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides.len(), 1); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs[0].runs[0].text, "Edited"); + assert_eq!(p.masters.len(), 1); + assert!(lost.is_empty(), "{lost:?}"); +} + +/// A slide the list names but whose object is gone is reported as lost, so an application can +/// say so instead of opening a deck that silently misses it. +#[test] +fn a_slide_without_its_object_is_reported_lost() { + let (cu, mut stream, pics) = streams(0xE391_C05F); + // The persist directory (ids 1–4: document, master, slide, notes) ends just before the + // 36-byte edit; point the slide's entry past the end of the stream. + let slide_entry = stream.len() - 36 - 8; + stream[slide_entry..slide_entry + 4].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); + let bytes = build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)]); + let (p, lost) = import_checked(&bytes).unwrap(); + assert!(p.slides.is_empty()); + assert_eq!(lost, vec![format!("slide {SLIDE_ID}")]); +} + +/// Two more signs of an encrypted file besides the Current User token: an edit record long enough +/// to hold `encryptSessionPersistIdRef`, and a `CryptSession` object in the persist directory. +#[test] +fn encryption_is_found_in_the_edit_and_the_persist_directory() { + let open = |doc: &[u8], pics: &[u8]| { + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, doc.len() as u32 - 36, 0, 0])); + import(&build(&[("Current User", &cu), ("PowerPoint Document", doc), ("Pictures", pics)])) + }; + let (_, stream, pics) = streams(0xE391_C05F); + assert!(open(&stream, &pics).is_ok()); + // The edit record with a fifth reference: 28 bytes become 32. The Current User points at the + // new last record, 40 bytes from the end. + let mut long_edit = stream.clone(); + let edit_at = long_edit.len() - 36; + long_edit.truncate(edit_at); + let mut edit = le32(&[0, 0x0300_03F4, 0, 0, 1, 5]); + edit[12..16].copy_from_slice(&stream[edit_at + 8 + 12..edit_at + 8 + 16]); // offsetPersistDirectory + edit.extend_from_slice(&[0; 4]); + edit.extend_from_slice(&6u32.to_le_bytes()); // encryptSessionPersistIdRef + long_edit.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, edit_at as u32, 0, 0])); + let r = import(&build(&[("Current User", &cu), ("PowerPoint Document", &long_edit), ("Pictures", &pics)])); + assert!(matches!(r, Err(crate::PptError::Encrypted)), "{:?}", r.err()); + // A CryptSession container given a persist id by a later edit. + let mut crypt = stream.clone(); + let first_edit = crypt.len() as u32 - 36; + let session_at = crypt.len() as u32; + crypt.extend_from_slice(&container(rt::CRYPT_SESSION, 0, &[atom(0x0FFF, 0, &[0; 8])])); + let dir_at = crypt.len() as u32; + crypt.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[9 | (1 << 20), session_at]))); + let mut edit = le32(&[0, 0x0300_03F4, first_edit, dir_at, 1, 9]); + edit.extend_from_slice(&[0; 4]); + crypt.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + assert!(matches!(open(&crypt, &pics), Err(crate::PptError::Encrypted))); +} + +/// A colour scheme record whose fill colour (index 4) is `fill`, the rest as the test master's. +fn scheme_with_fill(fill: [u8; 3]) -> Vec { + let mut colors: Vec = [0xFFFFFFu32, 0x000000, 0x808080, 0x000099, 0, 0x0000FF, 0x00FF00, 0xFF0000] + .iter() + .flat_map(|c| [(c >> 16) as u8, (c >> 8) as u8, *c as u8, 0]) + .collect(); + colors[16..19].copy_from_slice(&fill); + atom(rt::COLOR_SCHEME, 1, &colors) +} + +/// A shape filled with the scheme's fill colour. +fn scheme_filled(spid: u32) -> Vec { + container( + rt::SP_CONTAINER, + 0, + &[fsp(1, spid, 0xA00), fopt(&[(prop::FILL_COLOR, 0x0800_0004), (prop::FILL_BOOLS, 0x0010_0010)]), anchor(0, 0, 100, 100)], + ) +} + +/// A title master becomes a layout of its main master, with its own background and shapes, and +/// without the master's shapes when it doesn't follow them. A slide of the title master uses that +/// layout. A slide that follows nothing keeps its own background and scheme and hides the +/// master's shapes. +#[test] +fn title_masters_and_slides_that_dont_follow_the_master() { + let title_master = + container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x0), drawing(Some(solid_background(0x0000_FF00)), &[scheme_filled(3000)])]); + let on_title = container(rt::SLIDE, 0, &[slide_atom(0, TITLE_MASTER_ID, 0x7), drawing(None, &[])]); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, on_title, Some(title_master)); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let (_, layout) = p.layout(p.slides[0].layout).unwrap(); + assert_eq!(layout.name, "Title Master"); + assert_eq!(layout.background, Some(Background::Fill { fill: Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0, 0xFF, 0))) })); + assert!(!layout.show_master_shapes); + assert!(layout.shapes.iter().any(|sh| sh.ph.is_none()), "the title master's own shape"); + assert_eq!(p.slides[0].background, None, "the slide follows its master's background"); + + let alone = container( + rt::SLIDE, + 0, + &[slide_atom(1, MASTER_ID, 0x0), scheme_with_fill([0x11, 0x22, 0xCC]), drawing(Some(solid_background(0x0000_00FF)), &[scheme_filled(2049)])], + ); + let (cu, doc, pics) = streams_of(0xE391_C05F, 1, alone, None); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap(); + let s = &p.slides[0]; + assert_eq!(s.background, Some(Background::Fill { fill: Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0xFF, 0, 0))) })); + assert!(!s.show_master_shapes); + assert_eq!(s.shapes[0].fill, Some(Fill::solid(craft_pptx::ColorRef::rgb(Rgba::rgb(0x11, 0x22, 0xCC)))), "the slide's own scheme"); +} + +fn open_streams((cu, doc, pics): (Vec, Vec, Vec)) -> Presentation { + import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)])).unwrap() +} + +/// A picture frame that says nothing about its fill or line draws neither (storytold/deckcraft#1137 review): the +/// drawing defaults' fill would cover a picture's transparent parts, or an OLE chart's preview. +#[test] +fn a_picture_frame_has_no_fill_or_line_of_its_own() { + let p = import(&file()).unwrap(); + let picture = &p.slides[0].shapes[1]; + assert!(matches!(picture.kind, ShapeKind::Picture { .. })); + assert_eq!(picture.fill, Some(Fill::None)); + assert_eq!(picture.line.as_ref().map(|l| l.fill.clone()), Some(Some(Fill::None))); +} + +/// A picture fill whose blip is held in the shape's own `fillBlip` property (complex, with fBid), +/// as table cells with a picture have it (storytold/deckcraft#1137 review), shows that picture. +#[test] +fn a_picture_held_in_the_fill_property_is_read() { + let blip = atom(0xF01E, 0x6E0, &[&[0u8; 17][..], &png()].concat()); + let mut entries = vec![]; + for (id, op) in [(prop::FILL_TYPE, 3u32), (0xC000 | prop::FILL_BLIP, blip.len() as u32), (prop::FILL_BOOLS, 0x0010_0010)] { + entries.extend_from_slice(&id.to_le_bytes()); + entries.extend_from_slice(&op.to_le_bytes()); + } + entries.extend_from_slice(&blip); + let cell = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), atom(rt::FOPT, 3, &entries), anchor(400, 500, 2000, 1200)]); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[cell])]); + let p = open_streams(streams_of(0xE391_C05F, 1, slide, None)); + let Some(Fill::Picture(fill)) = &p.slides[0].shapes[0].fill else { panic!("{:?}", p.slides[0].shapes[0].fill) }; + let media = p.media.iter().find(|m| m.id == fill.media).unwrap(); + assert!(media.data.starts_with(b"\x89PNG")); +} + +/// The headers and footers the document sets for its slides (storytold/deckcraft#1137 review: the date, footer and +/// slide number were missing) become the slide's footer placeholders, placed and styled as the +/// master's are on every layout. +#[test] +fn headers_and_footers_become_footer_placeholders() { + let cstring = |instance: u16, s: &str| atom(rt::CSTRING, instance, &utf16(s)); + // fHasDate | fHasUserDate | fHasSlideNumber | fHasFooter. The footer string ends in a NUL, as + // some writers add one: the text stops there. + let flags: u16 = 0x01 | 0x04 | 0x08 | 0x20; + let hf = container( + rt::HEADERS_FOOTERS, + 3, + &[ + atom(rt::HEADERS_FOOTERS_ATOM, 0, &[&0u16.to_le_bytes()[..], &flags.to_le_bytes()].concat()), + cstring(0, "26 May 2004"), + cstring(2, "Workshop\0"), + ], + ); + // The master's slide number placeholder: bottom right, right-aligned 10 pt text. + let mut style = vec![]; + style.extend_from_slice(&2u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(2, false)); + style.extend_from_slice(&2u32.to_le_bytes()); + style.extend_from_slice(&cf_bytes(false, 0, 10, [1, 2, 3])); + let number = container( + rt::SP_CONTAINER, + 0, + &[fsp(1, 1030, 0xA00), anchor(4000, 5000, 5700, 4300), placeholder(0x08), text_box(4, "*", &[atom(rt::STYLE_TEXT_PROP, 0, &style)])], + ); + let p = open_streams(streams_with_document(0xE391_C05F, 1, master_with(&[number]), slide(), None, &[], &[hf])); + let shapes = &p.slides[0].shapes; + let of = |k: PhType| shapes.iter().find(|s| s.ph_type() == Some(k)).unwrap_or_else(|| panic!("no {k:?}")); + assert_eq!(of(PhType::Date).text.as_ref().unwrap().text(), "26 May 2004"); + assert_eq!(of(PhType::Footer).text.as_ref().unwrap().text(), "Workshop"); + let runs = &of(PhType::SlideNum).text.as_ref().unwrap().paragraphs[0].runs; + assert!(matches!(&runs[0].kind, RunKind::Field { field } if field == "slidenum")); + assert!(p.header_footer.slide_number && p.header_footer.footer && p.header_footer.date); + // Every layout's slide number sits where the master's does, with its look. + let master = &p.masters[0]; + for l in &master.layouts { + let n = l.shapes.iter().find(|s| s.ph_type() == Some(PhType::SlideNum)).unwrap_or_else(|| panic!("no slide number on {}", l.name)); + let x = n.xfrm.unwrap(); + assert_eq!((x.x, x.y), (5000.0 / 8.0, 4000.0 / 8.0), "{}", l.name); + let level = n.text.as_ref().unwrap().list_style.level(0).unwrap(); + assert_eq!((level.para.align, level.run.size), (Some(Align::Right), Some(10.0))); + } +} + +/// Numbered paragraphs (storytold/deckcraft#1137 review: drawn with the bullet character) take their numbering from +/// the document's `___PPT9` tag: the slide's outline block of that text type, and the entry the +/// run's `pp9rt` names. The tag's name ends in a NUL here, as some writers add one. +#[test] +fn outline_numbering_from_the_ppt9_tag() { + // Entry 0: nothing. Entry 1: numbered, "1." (scheme 3), from 4. + let mut prop9 = vec![0u8; 12]; + prop9.extend_from_slice(&0x0300_0000u32.to_le_bytes()); + prop9.extend_from_slice(&1u16.to_le_bytes()); + prop9.extend_from_slice(&3u16.to_le_bytes()); + prop9.extend_from_slice(&4i16.to_le_bytes()); + prop9.extend_from_slice(&[0; 8]); + let tag_data = [atom(rt::OUTLINE_TEXT_PROPS_HEADER, 1, &le32(&[SLIDE_ID, 1])), atom(rt::STYLE_TEXT_PROP9, 0, &prop9)]; + let tag = container( + rt::PROG_BINARY_TAG, + 0, + &[atom(rt::CSTRING, 0, &utf16("___PPT9\0")), atom(rt::BINARY_TAG_DATA, 0, &container(rt::OUTLINE_TEXT_PROPS9, 0, &tag_data))], + ); + let list = container(rt::LIST, 0, &[container(rt::PROG_TAGS, 0, &[tag])]); + // Two bulleted paragraphs: the second's run names entry 1 (pp9rt in fontStyle bits 10–13). + let pp9rt = |i: u16| [&0x0000_0400u32.to_le_bytes()[..], &(i << 10).to_le_bytes()].concat(); + let mut style = vec![]; + style.extend_from_slice(&8u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, true)); + for (n, i) in [(4u32, 0u16), (4, 1)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&pp9rt(i)); + } + let outline = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("One\rTwo")), atom(rt::STYLE_TEXT_PROP, 0, &style)]; + let body = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 2049, 0xA00), + anchor(1300, 500, 5260, 3000), + placeholder(0x0E), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes())]), + ], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[body])]); + let p = open_streams(streams_with_document(0xE391_C05F, 1, master(), slide, None, &outline, &[list])); + let paras = &p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs; + assert!(matches!(paras[0].props.bullet, Some(Bullet::Char { .. })), "{:?}", paras[0].props.bullet); + assert_eq!(paras[1].props.bullet, Some(Bullet::AutoNum { scheme: "arabicPeriod".into(), start_at: 4 })); +} + +/// An outline block is one shape's text. A second shape pointing at the same block keeps its own +/// (here none), so a hostile file can't copy one big block into every shape of the slide. +#[test] +fn an_outline_block_is_used_by_one_shape() { + let outline = [atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("Shared"))]; + let referring = |spid: u32| { + container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, spid, 0xA00), + anchor(400, 500, 5260, 1200), + placeholder(0x0D), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes())]), + ], + ) + }; + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[referring(2049), referring(2050)])]); + let p = open_streams(streams_with_outline(0xE391_C05F, 1, slide, None, &outline)); + let texts: Vec = p.slides[0].shapes.iter().map(|s| s.text.as_ref().unwrap().text()).collect(); + assert_eq!(texts, ["Shared", ""]); +} + +fn open_plain((cu, doc, pics): (Vec, Vec, Vec)) -> Presentation { + crate::import(&build(&[("Current User", &cu), ("PowerPoint Document", &doc), ("Pictures", &pics)]), &craft_pptx::Plain).unwrap() +} + +/// A footer-only `HeadersFootersContainer` of `instance` with `footer` as its text. +fn footer_record(instance: u16, footer: &str) -> Vec { + container( + rt::HEADERS_FOOTERS, + instance, + &[atom(rt::HEADERS_FOOTERS_ATOM, 0, &[&0u16.to_le_bytes()[..], &0x20u16.to_le_bytes()].concat()), atom(rt::CSTRING, 2, &utf16(footer))], + ) +} + +/// A slide's own headers and footers (`PerSlideHeadersFootersContainer`, instance 0) win over the +/// document's for every slide (instance 3). Only the document's used to be looked for. +#[test] +fn a_slides_own_footer_wins_over_the_documents() { + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[]), footer_record(0, "This slide")]); + let p = open_streams(streams_with_document(0xE391_C05F, 1, master(), slide, None, &[], &[footer_record(3, "Every slide")])); + let footer = p.slides[0].shapes.iter().find(|s| s.ph_type() == Some(PhType::Footer)).expect("a footer"); + assert_eq!(footer.text.as_ref().unwrap().text(), "This slide"); + assert_eq!(p.header_footer.footer_text, "Every slide"); +} + +/// A text box that points at an outline block keeps its own `TextRulerAtom`: the margin it sets +/// (one inch at level 1) wins over the block's. It used to be dropped with the reference. +#[test] +fn a_text_boxs_own_ruler_applies_to_its_outline_text() { + let outline = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &utf16("Indented"))]; + let ruler = atom(rt::TEXT_RULER, 0, &[&(1u32 << 3).to_le_bytes()[..], &576u16.to_le_bytes()].concat()); + let body = container( + rt::SP_CONTAINER, + 0, + &[ + fsp(1, 2049, 0xA00), + anchor(1300, 500, 5260, 3000), + placeholder(0x0E), + container(rt::CLIENT_TEXTBOX, 0, &[atom(rt::OUTLINE_TEXT_REF, 0, &0u32.to_le_bytes()), ruler]), + ], + ); + let slide = container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[body])]); + let p = open_streams(streams_with_outline(0xE391_C05F, 1, slide, None, &outline)); + let t = p.slides[0].shapes[0].text.as_ref().unwrap(); + assert_eq!(t.text(), "Indented"); + assert_eq!(t.paragraphs[0].props.margin_left, Some(72.0)); +} + +/// A slide list entry whose object isn't a slide (here the notes page) is a lost slide, not a +/// slide silently left out. +#[test] +fn a_slide_entry_naming_another_object_is_reported_lost() { + let (cu, mut stream, pics) = streams(0xE391_C05F); + // The persist directory's last two entries (the slide's, then the notes page's) end just + // before the 36-byte edit: point the slide's at the notes page. + let end = stream.len() - 36; + let notes_at: [u8; 4] = stream[end - 4..end].try_into().unwrap(); + stream[end - 8..end - 4].copy_from_slice(¬es_at); + let (p, lost) = import_checked(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert!(p.slides.is_empty()); + assert_eq!(lost, vec![format!("slide {SLIDE_ID}")]); +} + +/// A title master with a centred title and a subtitle placeholder, `extra` shapes after them. +fn title_master_with(extra: &[Vec]) -> Vec { + let ph = + |spid: u32, kind: u8, a: [i16; 4]| container(rt::SP_CONTAINER, 0, &[fsp(1, spid, 0xA00), anchor(a[0], a[1], a[2], a[3]), placeholder(kind)]); + let shapes = [vec![ph(3001, 0x0F, [1000, 600, 5160, 2000]), ph(3002, 0x10, [2200, 1200, 4540, 3200])], extra.to_vec()].concat(); + container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &shapes)]) +} + +/// The first "Title Master" layout of `p`'s first master. +fn title_layout(p: &Presentation) -> &Layout { + p.masters[0].layouts.iter().find(|l| l.name == "Title Master").expect("the title master's layout") +} + +/// A title master's placeholders place its layout's, as a main master's place the master's: the +/// title takes its box, and the subtitle the default title layout lacks is added. With the plain +/// defaults (no placeholders at all) both are added. +#[test] +fn a_title_masters_placeholders_place_its_layouts() { + let boxes = |l: &Layout| { + let at = |f: &dyn Fn(PhType) -> bool| { + let x = l.shapes.iter().find(|s| s.ph_type().is_some_and(f)).and_then(|s| s.xfrm).unwrap_or_else(|| panic!("{:?}", l.shapes)); + (x.x, x.y, x.w, x.h) + }; + (at(&|t| matches!(t, PhType::Title | PhType::CtrTitle)), at(&|t| t == PhType::SubTitle)) + }; + let expected = ((75.0, 125.0, 570.0, 125.0), (150.0, 275.0, 417.5, 125.0)); + let p = open_streams(streams_of(0xE391_C05F, 1, slide(), Some(title_master_with(&[])))); + assert_eq!(boxes(title_layout(&p)), expected); + let p = open_plain(streams_of(0xE391_C05F, 1, slide(), Some(title_master_with(&[])))); + assert_eq!(boxes(title_layout(&p)), expected); +} + +/// A second title master's layout takes nothing from the first title master's layout: not its own +/// shapes, and not its placeholders or their boxes. With the plain defaults (no title layout of +/// theirs) it holds only its own placeholder, where it puts it. +#[test] +fn a_second_title_master_doesnt_copy_the_firsts_shapes() { + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 4001, 0xA00), anchor(200, 400, 2000, 800), placeholder(0x0F)]); + let second = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[title])]); + let p = + open_plain(streams_with_title_masters(0xE391_C05F, 1, master(), slide(), vec![title_master_with(&[scheme_filled(3003)]), second], &[], &[])); + let layouts: Vec<&Layout> = p.masters[0].layouts.iter().filter(|l| l.name == "Title Master").collect(); + assert_eq!(layouts.len(), 2); + assert_eq!(layouts[0].shapes.iter().filter(|s| s.ph.is_none()).count(), 1); + assert_eq!(layouts[1].shapes.len(), 1, "only its own placeholder: {:?}", layouts[1].shapes); + let x = layouts[1].shapes[0].xfrm.unwrap(); + assert_eq!((layouts[1].shapes[0].ph_type(), x.x, x.y, x.w, x.h), (Some(PhType::CtrTitle), 50.0, 25.0, 200.0, 75.0)); +} + +/// A title slide of the main master takes an ordinary layout, not the one made for a title +/// master: that one is for the slides that name the title master. +#[test] +fn a_title_masters_layout_is_only_for_its_own_slides() { + let on_main = container(rt::SLIDE, 0, &[slide_atom(0, MASTER_ID, 0x7), drawing(None, &[])]); + let p = open_plain(streams_of(0xE391_C05F, 1, on_main, Some(title_master_with(&[])))); + let (_, layout) = p.layout(p.slides[0].layout).unwrap(); + assert_eq!(layout.name, "Blank"); +} + +/// When the edit chain is broken and the stream holds more edits than are read, the newest are the +/// ones read: here the newest edit replaces the slide, behind 4095 edits with no directory. +#[test] +fn a_broken_chain_reads_the_newest_edits() { + let (_, mut stream, pics) = streams(0xE391_C05F); + let first_edit = stream.len() - 36; + let offsets: Vec = + (0..4).map(|i| u32::from_le_bytes(stream[first_edit - 16 + 4 * i..first_edit - 12 + 4 * i].try_into().unwrap())).collect(); + // Edits that point at themselves and name the document as their directory. + let junk_at = stream.len() as u32; + for _ in 0..4095 { + let at = stream.len() as u32; + let mut edit = le32(&[0, 0x0300_03F4, at, 0, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + } + let title = container(rt::SP_CONTAINER, 0, &[fsp(1, 2049, 0xA00), anchor(400, 500, 5260, 1200), placeholder(0x0D), text_box(0, "Newest", &[])]); + let slide_at = stream.len() as u32; + stream.extend_from_slice(&container(rt::SLIDE, 0, &[slide_atom(1, MASTER_ID, 0x7), drawing(None, &[title])])); + let dir_at = stream.len() as u32; + stream.extend_from_slice(&atom(rt::PERSIST_DIRECTORY, 0, &le32(&[1 | (4 << 20), offsets[0], offsets[1], slide_at, offsets[3]]))); + let mut edit = le32(&[0, 0x0300_03F4, first_edit as u32, dir_at, 1, 5]); + edit.extend_from_slice(&[0; 4]); + stream.extend_from_slice(&atom(rt::USER_EDIT, 0, &edit)); + let cu = atom(rt::CURRENT_USER, 0, &le32(&[0x14, 0xE391_C05F, junk_at, 0, 0])); + let p = import(&build(&[("Current User", &cu), ("PowerPoint Document", &stream), ("Pictures", &pics)])).unwrap(); + assert_eq!(p.slides[0].shapes[0].text.as_ref().unwrap().text(), "Newest"); +} diff --git a/crates/ppt-binary/src/text.rs b/crates/ppt-binary/src/text.rs new file mode 100644 index 0000000000..5c2be1e31b --- /dev/null +++ b/crates/ppt-binary/src/text.rs @@ -0,0 +1,755 @@ +//! Text in `.ppt` ([MS-PPT] §2.9): characters in a `TextCharsAtom` (UTF-16) or `TextBytesAtom` +//! (Latin-1), formatting as runs of paragraph exceptions (`TextPFException`) and character +//! exceptions (`TextCFException`) over the master's per-level text styles. + +use crate::doc::rt; +use crate::record::{Cursor, Rec}; + +/// A colour as text formatting stores it: an RGB value or an index into the colour scheme. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TextColor { + Rgb(u8, u8, u8), + Scheme(u8), +} + +fn color_index(c: &mut Cursor) -> Option> { + let (r, g, b, i) = (c.u8()?, c.u8()?, c.u8()?, c.u8()?); + Some(match i { + 0xFE => Some(TextColor::Rgb(r, g, b)), + 0..=7 => Some(TextColor::Scheme(i)), + _ => None, + }) +} + +/// Paragraph formatting; `None` fields are not set at this level. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Pf { + pub has_bullet: Option, + pub bullet_has_font: Option, + pub bullet_has_color: Option, + pub bullet_has_size: Option, + pub bullet_char: Option, + pub bullet_font: Option, + /// Positive: percent of the text size; negative: absolute size in points. + pub bullet_size: Option, + pub bullet_color: Option, + /// 0 left, 1 centre, 2 right, 3 justify, 4 distributed, 5 Thai distributed, 6 justify low. + pub align: Option, + /// Positive: percent of a line; negative: master units (−8 per point). + pub line_spacing: Option, + pub space_before: Option, + pub space_after: Option, + /// Master units from the text box's left edge. + pub left_margin: Option, + pub indent: Option, + pub default_tab: Option, + pub tabs: Option>, +} + +impl Pf { + /// Overlay `o`'s set fields on this one. + pub fn apply(&mut self, o: &Pf) { + macro_rules! over { + ($($f:ident),*) => { $( if o.$f.is_some() { self.$f.clone_from(&o.$f); } )* }; + } + over!( + has_bullet, + bullet_has_font, + bullet_has_color, + bullet_has_size, + bullet_char, + bullet_font, + bullet_size, + bullet_color, + align, + line_spacing, + space_before, + space_after, + left_margin, + indent, + default_tab, + tabs + ); + } +} + +/// Character formatting; `None` fields are not set at this level. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Cf { + pub bold: Option, + pub italic: Option, + pub underline: Option, + pub shadow: Option, + pub font: Option, + pub ea_font: Option, + pub symbol_font: Option, + /// Points. + pub size: Option, + pub color: Option, + /// Superscript (positive) or subscript (negative) offset, percent of the size. + pub position: Option, + /// `pp9rt`: the index of the paragraph's PowerPoint 2000 formatting (numbering) in the text's + /// `StyleTextProp9Atom`. + pub pp9rt: Option, +} + +impl Cf { + pub fn apply(&mut self, o: &Cf) { + macro_rules! over { + ($($f:ident),*) => { $( if o.$f.is_some() { self.$f = o.$f; } )* }; + } + over!(bold, italic, underline, shadow, font, ea_font, symbol_font, size, color, position, pp9rt); + } +} + +fn bit(m: u32, b: u32) -> bool { + m & (1 << b) != 0 +} + +/// A `TextPFException`. +pub fn read_pf(c: &mut Cursor) -> Option { + let m = c.u32()?; + let mut pf = Pf::default(); + if m & 0xF != 0 { + let flags = c.u16()?; + for (b, slot) in [(0, &mut pf.has_bullet), (1, &mut pf.bullet_has_font), (2, &mut pf.bullet_has_color), (3, &mut pf.bullet_has_size)] { + if bit(m, b) { + *slot = Some(flags & (1 << b) != 0); + } + } + } + if bit(m, 7) { + pf.bullet_char = Some(c.u16()?); + } + if bit(m, 4) { + pf.bullet_font = Some(c.u16()?); + } + if bit(m, 6) { + pf.bullet_size = Some(c.i16()?); + } + if bit(m, 5) { + pf.bullet_color = color_index(c)?; + } + if bit(m, 11) { + pf.align = Some(c.u16()?); + } + if bit(m, 12) { + pf.line_spacing = Some(c.i16()?); + } + if bit(m, 13) { + pf.space_before = Some(c.i16()?); + } + if bit(m, 14) { + pf.space_after = Some(c.i16()?); + } + if bit(m, 8) { + pf.left_margin = Some(c.u16()?); + } + if bit(m, 10) { + pf.indent = Some(c.u16()?); + } + if bit(m, 15) { + pf.default_tab = Some(c.u16()?); + } + if bit(m, 20) { + pf.tabs = Some(read_tabs(c)?); + } + if bit(m, 16) { + c.u16()?; // fontAlign + } + if m & (0x7 << 17) != 0 { + c.u16()?; // wrapFlags + } + if bit(m, 21) { + c.u16()?; // textDirection + } + Some(pf) +} + +/// Tab stops kept per paragraph exception or ruler. Every entry is still read past, so the fields +/// after the list stay aligned; the rest are dropped, since each paragraph copies the list. +const MAX_TABS: usize = 64; + +fn read_tabs(c: &mut Cursor) -> Option> { + let n = c.u16()?; + let mut v = Vec::with_capacity(usize::from(n).min(MAX_TABS)); + for _ in 0..n { + let tab = (c.i16()?, c.u16()?); + if v.len() < MAX_TABS { + v.push(tab); + } + } + Some(v) +} + +/// A `TextCFException`. +pub fn read_cf(c: &mut Cursor) -> Option { + let m = c.u32()?; + let mut cf = Cf::default(); + // fontStyle is present when any of bold, italic, underline, shadow, fehint, kumi, emboss or + // fHasStyle is in the mask. + if m & 0x3EB7 != 0 { + let s = c.u16()?; + // Emboss (bit 9) has no counterpart in the model; docs/gaps.md lists it. + for (b, slot) in [(0, &mut cf.bold), (1, &mut cf.italic), (2, &mut cf.underline), (4, &mut cf.shadow)] { + if bit(m, b) { + *slot = Some(s & (1 << b) != 0); + } + } + // fHasStyle (bits 10–13) says pp9rt, the same four bits of fontStyle, is given. + if m & 0x3C00 != 0 { + cf.pp9rt = Some(((s >> 10) & 0xF) as u8); + } + } + if bit(m, 16) { + cf.font = Some(c.u16()?); + } + if bit(m, 21) { + cf.ea_font = Some(c.u16()?); + } + if bit(m, 22) { + c.u16()?; // ansiFontRef + } + if bit(m, 23) { + cf.symbol_font = Some(c.u16()?); + } + if bit(m, 17) { + cf.size = Some(c.u16()?); + } + if bit(m, 18) { + cf.color = color_index(c)?; + } + if bit(m, 19) { + cf.position = Some(c.i16()?); + } + // The fields PowerPoint 2002 and later add are not used, but they must be read past: the next + // run's count and mask follow them, so stopping short garbles every later run's formatting. + if bit(m, 20) { + c.u32()?; // pp10runid (4 bits) and unused (28 bits) + } + if bit(m, 24) { + c.u16()?; // newEAFontRef + } + if bit(m, 25) { + c.u16()?; // csFontRef + } + if bit(m, 26) { + c.u32()?; // pp11ext + } + Some(cf) +} + +/// A paragraph's PowerPoint 2000 formatting (`TextPFException9`): its automatic numbering. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Pf9 { + /// `fBulletHasAutoNumber` with `bulletAutoNumberScheme`: the scheme and the first number. + pub auto_number: Option<(u16, i16)>, +} + +/// The entries of a `StyleTextProp9Atom` ([MS-PPT] §2.9.33): each a `TextPFException9`, a +/// `TextCFException9` and a `TextSIException`, indexed by the runs' `pp9rt`. Reading stops at an +/// entry with a field this reader can't size, keeping the entries before it. +pub fn read_style9(b: &[u8]) -> Vec { + let mut c = Cursor::new(b); + let mut out = vec![]; + // pp9rt has four bits, so sixteen entries are all a run can name. + while out.len() < 16 && c.remaining() > 0 { + let Some(pf9) = read_pf9(&mut c) else { break }; + out.push(pf9); + // TextCFException9: the extension fields of a character mask. + let Some(m) = c.u32() else { break }; + if m & !((1 << 20) | (1 << 24) | (1 << 25) | (1 << 26)) != 0 { + break; + } + let ok = (!bit(m, 20) || c.u32().is_some()) + && (!bit(m, 24) || c.u16().is_some()) + && (!bit(m, 25) || c.u16().is_some()) + && (!bit(m, 26) || c.u32().is_some()); + // TextSIException: spelling, language, alternate language, bidi, pp10 extension, smart tags. + if !ok || read_si(&mut c).is_none() { + break; + } + } + out +} + +fn read_pf9(c: &mut Cursor) -> Option { + let m = c.u32()?; + if bit(m, 23) { + c.i16()?; // bulletBlipRef + } + let has_auto = if bit(m, 25) { Some(c.u16()? != 0) } else { None }; + let scheme = if bit(m, 24) { Some((c.u16()?, c.i16()?)) } else { None }; + if bit(m, 26) { + c.u32()?; // pp10 extension + } + Some(Pf9 { auto_number: if has_auto == Some(true) { Some(scheme.unwrap_or((3, 1))) } else { None } }) +} + +fn read_si(c: &mut Cursor) -> Option<()> { + let m = c.u32()?; + if m & !0x027F != 0 { + return None; + } + for b in [0, 1, 2, 6] { + if bit(m, b) { + c.u16()?; + } + } + if bit(m, 5) { + c.u32()?; // pp10runid and reserved + } + if bit(m, 9) { + let n = c.u32()?; + for _ in 0..n { + c.u32()?; + } + } + Some(()) +} + +/// The DrawingML numbering scheme of a `TextAutoNumberSchemeEnum` value. +pub fn auto_number_scheme(v: u16) -> &'static str { + match v { + 0 => "alphaLcPeriod", + 1 => "alphaUcPeriod", + 2 => "arabicParenR", + 4 => "romanLcParenBoth", + 5 => "romanLcParenR", + 6 => "romanLcPeriod", + 7 => "romanUcPeriod", + 8 => "alphaLcParenBoth", + 9 => "alphaLcParenR", + 10 => "alphaUcParenBoth", + 11 => "alphaUcParenR", + 12 => "arabicParenBoth", + 13 => "arabicPlain", + 14 => "romanUcParenBoth", + 15 => "romanUcParenR", + 0x10 => "ea1ChsPlain", + 0x11 => "ea1ChsPeriod", + 0x12 => "circleNumDbPlain", + 0x13 => "circleNumWdWhitePlain", + 0x14 => "circleNumWdBlackPlain", + 0x15 => "ea1ChtPlain", + 0x16 => "ea1ChtPeriod", + 0x17 => "arabic1Minus", + 0x18 => "arabic2Minus", + 0x19 => "hebrew2Minus", + 0x1A => "ea1JpnKorPlain", + 0x1B => "ea1JpnKorPeriod", + 0x1C => "arabicDbPlain", + 0x1D => "arabicDbPeriod", + 0x1E => "thaiAlphaPeriod", + 0x1F => "thaiAlphaParenR", + 0x20 => "thaiAlphaParenBoth", + 0x21 => "thaiNumPeriod", + 0x22 => "thaiNumParenR", + 0x23 => "thaiNumParenBoth", + 0x24 => "hindiAlphaPeriod", + 0x25 => "hindiNumPeriod", + 0x26 => "ea1JpnChsDbPeriod", + 0x27 => "hindiNumParenR", + 0x28 => "hindiAlpha1Period", + _ => "arabicPeriod", + } +} + +/// Text types (`TextHeaderAtom.textType`). +pub mod ty { + pub const TITLE: u32 = 0; + pub const BODY: u32 = 1; + pub const NOTES: u32 = 2; + pub const OTHER: u32 = 4; + pub const CENTER_BODY: u32 = 5; + pub const CENTER_TITLE: u32 = 6; + pub const HALF_BODY: u32 = 7; + pub const QUARTER_BODY: u32 = 8; +} + +/// One master text style: up to five levels of paragraph and character formatting. +#[derive(Clone, Debug, Default)] +pub struct LevelStyles { + pub levels: Vec<(Pf, Cf)>, +} + +/// A `TextMasterStyleAtom` body. +pub fn read_master_style(r: &Rec) -> LevelStyles { + let mut c = Cursor::new(r.data); + let mut out = LevelStyles::default(); + let Some(n) = c.u16() else { return out }; + for i in 0..usize::from(n.min(5)) { + // From the centre-body type on, each level names itself (TextMasterStyleLevel.level). + let level = if u32::from(r.instance) >= ty::CENTER_BODY { + let Some(l) = c.u16() else { break }; + usize::from(l) + } else { + i + }; + let Some(pf) = read_pf(&mut c) else { break }; + let Some(cf) = read_cf(&mut c) else { break }; + // Only five levels exist; one naming another is read past. + if level >= 5 { + continue; + } + if out.levels.len() <= level { + out.levels.resize(level + 1, Default::default()); + } + if let Some(slot) = out.levels.get_mut(level) { + *slot = (pf, cf); + } + } + out +} + +/// The text styles in effect for a master: the document defaults plus the master's styles by text +/// type. +#[derive(Clone, Debug, Default)] +pub struct StyleSheet { + pub default_pf: Pf, + pub default_cf: Cf, + /// Indexed by text type (0–8). + pub types: Vec>, +} + +impl StyleSheet { + /// Read the defaults of the document environment and, over them, a master's styles. + pub fn new(environment: Option, master: Option<&Rec>) -> Self { + let mut s = StyleSheet { types: vec![None; 9], ..Default::default() }; + if let Some(env) = environment { + if let Some(pf) = env.child(rt::TEXT_PF_EXCEPTION).and_then(|r| read_pf(&mut Cursor { b: r.data, at: 2 })) { + s.default_pf = pf; + } + if let Some(cf) = env.child(rt::TEXT_CF_EXCEPTION).and_then(|r| read_cf(&mut Cursor::new(r.data))) { + s.default_cf = cf; + } + for r in env.children_of(rt::TEXT_MASTER_STYLE) { + if let Some(slot) = s.types.get_mut(usize::from(r.instance)) { + *slot = Some(read_master_style(&r)); + } + } + } + if let Some(m) = master { + for r in m.children_of(rt::TEXT_MASTER_STYLE) { + if let Some(slot) = s.types.get_mut(usize::from(r.instance)) { + *slot = Some(read_master_style(&r)); + } + } + } + s + } + + /// The formatting of text type `ty` at outline level `level`: defaults, then the base type's + /// level 1 and level, then this type's. + pub fn resolve(&self, ty: u32, level: u8) -> (Pf, Cf) { + let (mut pf, mut cf) = (self.default_pf.clone(), self.default_cf.clone()); + let base = match ty { + ty::CENTER_TITLE => Some(ty::TITLE), + ty::CENTER_BODY | ty::HALF_BODY | ty::QUARTER_BODY => Some(ty::BODY), + _ => None, + }; + for t in base.into_iter().chain(std::iter::once(ty)) { + let Some(Some(st)) = self.types.get(t as usize) else { continue }; + for l in [0usize, usize::from(level)] { + if let Some((p, c)) = st.levels.get(l) { + pf.apply(p); + cf.apply(c); + } + if level == 0 { + break; + } + } + } + (pf, cf) + } +} + +/// A field inside text: its character position and kind. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FieldKind { + SlideNumber, + DateTime, +} + +/// A block of text with its formatting runs. +#[derive(Clone, Debug, Default)] +pub struct TextBlock { + pub text_type: u32, + pub chars: Vec, + /// (character count, indent level, paragraph exception). + pub para_runs: Vec<(u32, u8, Pf)>, + /// (character count, character exception). + pub char_runs: Vec<(u32, Cf)>, + /// Ruler overrides per level: (left margin, indent) in master units. + pub ruler: [(Option, Option); 5], + pub fields: Vec<(u32, FieldKind)>, + /// An `OutlineTextRefAtom`: the text is the n-th outline block of the slide list entry. + pub outline_ref: Option, + /// The slide list's outline block this text was read from. + pub outline_index: Option, +} + +/// Read a text block from a run of records starting at its `TextHeaderAtom` (inside a client text +/// box, or in the slide list). Stops at the next header or slide persist atom. A client text box +/// may hold only an `OutlineTextRefAtom` ([MS-PPT] OfficeArtClientTextbox), with no header: that +/// is still a block, so the caller can follow the reference. +pub fn read_block<'a>(records: impl Iterator>) -> Option { + let mut b = TextBlock::default(); + let mut started = false; + let mut style: Option = None; + for r in records { + match r.kind { + rt::TEXT_HEADER if started => break, + rt::SLIDE_PERSIST_ATOM => break, + rt::TEXT_HEADER => { + started = true; + b.text_type = r.u32(0).unwrap_or(ty::OTHER); + } + rt::TEXT_CHARS => b.chars = r.data.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(), + rt::TEXT_BYTES => b.chars = r.data.iter().map(|&c| u16::from(c)).collect(), + rt::STYLE_TEXT_PROP => style = Some(r), + rt::TEXT_RULER => b.ruler = read_ruler(&r), + rt::OUTLINE_TEXT_REF => b.outline_ref = r.u32(0), + rt::SLIDE_NUMBER_MC => b.fields.extend(r.u32(0).map(|p| (p, FieldKind::SlideNumber))), + rt::DATETIME_MC | rt::GENERIC_DATE_MC => b.fields.extend(r.u32(0).map(|p| (p, FieldKind::DateTime))), + _ => {} + } + } + if !started && b.outline_ref.is_none() { + return None; + } + if let Some(st) = style { + // Text past u32::MAX characters can't be addressed by the runs; saturate rather than wrap. + read_style_runs(&st, u32::try_from(b.chars.len()).unwrap_or(u32::MAX).saturating_add(1), &mut b); + } + Some(b) +} + +/// The paragraph runs then the character runs of a `StyleTextPropAtom`; each set covers the text +/// plus one (the final paragraph mark). +fn read_style_runs(r: &Rec, total: u32, b: &mut TextBlock) { + let mut c = Cursor::new(r.data); + let mut covered = 0u32; + while covered < total { + let Some(n) = c.u32() else { return }; + let Some(level) = c.u16() else { return }; + let Some(pf) = read_pf(&mut c) else { return }; + b.para_runs.push((n, level.min(8) as u8, pf)); + covered = covered.saturating_add(n.max(1)); + } + covered = 0; + while covered < total { + let Some(n) = c.u32() else { return }; + let Some(cf) = read_cf(&mut c) else { return }; + b.char_runs.push((n, cf)); + covered = covered.saturating_add(n.max(1)); + } +} + +fn read_ruler(r: &Rec) -> [(Option, Option); 5] { + let mut out = [(None, None); 5]; + let mut c = Cursor::new(r.data); + let Some(m) = c.u32() else { return out }; + if bit(m, 1) && c.u16().is_none() { + return out; + } + if bit(m, 0) && c.u16().is_none() { + return out; + } + if bit(m, 2) && read_tabs(&mut c).is_none() { + return out; + } + for (l, slot) in out.iter_mut().enumerate() { + let l = l as u32; + if bit(m, 3 + l) { + slot.0 = c.u16(); + } + if bit(m, 8 + l) { + slot.1 = c.u16(); + } + } + out +} + +#[cfg(test)] +pub(crate) mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::record::build::*; + + /// A PF exception with alignment and bullets on or off. + pub fn pf_bytes(align: u16, bullet: bool) -> Vec { + let mut v = (0x0000_0801u32).to_le_bytes().to_vec(); // hasBullet + align + v.extend_from_slice(&u16::from(bullet).to_le_bytes()); + v.extend_from_slice(&align.to_le_bytes()); + v + } + + /// A CF exception with bold, a font, a size and an RGB colour. + pub fn cf_bytes(bold: bool, font: u16, size: u16, rgb: [u8; 3]) -> Vec { + let mut v = (0x0007_0001u32).to_le_bytes().to_vec(); // bold + typeface + size + color + v.extend_from_slice(&u16::from(bold).to_le_bytes()); + v.extend_from_slice(&font.to_le_bytes()); + v.extend_from_slice(&size.to_le_bytes()); + v.extend_from_slice(&[rgb[0], rgb[1], rgb[2], 0xFE]); + v + } + + /// The `StyleTextProp9Atom` entries as PowerPoint writes them: three, the second numbered "1." + /// from 1. Short or unknown data keeps the entries read before it. + #[test] + fn reads_numbering_entries() { + let mut b = vec![0u8; 12]; + b.extend_from_slice(&[0, 0, 0, 3, 1, 0, 3, 0, 1, 0]); + b.extend_from_slice(&[0; 8]); + b.extend_from_slice(&[0; 12]); + let e = read_style9(&b); + assert_eq!(e.iter().map(|p| p.auto_number).collect::>(), [None, Some((3, 1)), None]); + assert_eq!(read_style9(b.get(..20).unwrap()).len(), 1); + assert_eq!(read_style9(b.get(..22).unwrap()).len(), 2); + assert_eq!(read_style9(&[0xFF; 64]).len(), 1); + assert!(read_style9(&[]).is_empty()); + assert_eq!(auto_number_scheme(3), "arabicPeriod"); + assert_eq!(auto_number_scheme(0), "alphaLcPeriod"); + } + + /// The East Asian, bidi, Thai and Hindi schemes (0x10–0x28) have DrawingML names of their + /// own; only an unknown value falls back to "1.". + #[test] + fn every_numbering_scheme_has_its_drawingml_name() { + assert_eq!(auto_number_scheme(0x10), "ea1ChsPlain"); + assert_eq!(auto_number_scheme(0x13), "circleNumWdWhitePlain"); + assert_eq!(auto_number_scheme(0x19), "hebrew2Minus"); + assert_eq!(auto_number_scheme(0x26), "ea1JpnChsDbPeriod"); + assert_eq!(auto_number_scheme(0x28), "hindiAlpha1Period"); + let names: std::collections::HashSet<_> = (0..=0x28).map(auto_number_scheme).collect(); + assert_eq!(names.len(), 0x29, "each value its own scheme"); + assert_eq!(auto_number_scheme(0x29), "arabicPeriod"); + } + + /// From the centre-body type on, a master style level names its level: it is stored there, + /// and a level past the fifth is read past. + #[test] + fn master_style_levels_go_where_they_say() { + let level = |l: u16, size: u16| [&l.to_le_bytes()[..], &0u32.to_le_bytes(), &cf_bytes(false, 0, size, [0, 0, 0])].concat(); + let body = [&3u16.to_le_bytes()[..], &level(2, 20), &level(7, 30), &level(0, 40)].concat(); + let rec = crate::record::build::atom(rt::TEXT_MASTER_STYLE, ty::CENTER_BODY as u16, &body); + let st = read_master_style(&Rec::at(&rec, 0).unwrap()); + let sizes: Vec<_> = st.levels.iter().map(|(_, cf)| cf.size).collect(); + assert_eq!(sizes, [Some(40), None, Some(20)]); + // Before it, levels are in order. + let body = [&1u16.to_le_bytes()[..], &0u32.to_le_bytes(), &cf_bytes(false, 0, 12, [0, 0, 0])].concat(); + let rec = crate::record::build::atom(rt::TEXT_MASTER_STYLE, ty::BODY as u16, &body); + assert_eq!(read_master_style(&Rec::at(&rec, 0).unwrap()).levels[0].1.size, Some(12)); + } + + /// A paragraph exception with many tab stops keeps the first [`MAX_TABS`] and reads the + /// fields after the list where they are. + #[test] + fn tab_stops_are_capped_and_read_past() { + let mut b = ((1u32 << 20) | (1 << 21)).to_le_bytes().to_vec(); // tabStops + textDirection + b.extend_from_slice(&1000u16.to_le_bytes()); + for i in 0..1000u16 { + b.extend_from_slice(&(i as i16).to_le_bytes()); + b.extend_from_slice(&1u16.to_le_bytes()); + } + b.extend_from_slice(&0x1234u16.to_le_bytes()); // textDirection + b.push(0xAB); + let mut c = Cursor::new(&b); + let pf = read_pf(&mut c).unwrap(); + let tabs = pf.tabs.unwrap(); + assert_eq!(tabs.len(), MAX_TABS); + assert_eq!(tabs[MAX_TABS - 1], (MAX_TABS as i16 - 1, 1)); + assert_eq!(c.u8(), Some(0xAB), "the cursor stopped past textDirection"); + } + + #[test] + fn reads_exceptions_in_mask_order() { + let pf = read_pf(&mut Cursor::new(&pf_bytes(1, true))).unwrap(); + assert_eq!(pf.has_bullet, Some(true)); + assert_eq!(pf.align, Some(1)); + assert_eq!(pf.bullet_has_font, None); + let cf = read_cf(&mut Cursor::new(&cf_bytes(true, 3, 28, [1, 2, 3]))).unwrap(); + assert_eq!((cf.bold, cf.italic, cf.font, cf.size, cf.color), (Some(true), None, Some(3), Some(28), Some(TextColor::Rgb(1, 2, 3)))); + // A mask promising more than the bytes hold reads nothing. + assert!(read_cf(&mut Cursor::new(&0x0007_0000u32.to_le_bytes())).is_none()); + } + + #[test] + fn reads_a_text_block_with_runs() { + let chars: Vec = "Hi\rthere".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let mut style = vec![]; + for (n, lvl) in [(3u32, 0u16), (6, 1)] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&lvl.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, lvl == 1)); + } + for n in [2u32, 7] { + style.extend_from_slice(&n.to_le_bytes()); + style.extend_from_slice(&cf_bytes(n == 2, 0, 20, [0, 0, 0])); + } + let recs = [ + atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), + atom(rt::TEXT_CHARS, 0, &chars), + atom(rt::STYLE_TEXT_PROP, 0, &style), + atom(rt::TEXT_HEADER, 0, &0u32.to_le_bytes()), + ] + .concat(); + let b = read_block(crate::record::Records::new(&recs)).unwrap(); + assert_eq!(b.text_type, ty::BODY); + assert_eq!(String::from_utf16_lossy(&b.chars), "Hi\rthere"); + assert_eq!(b.para_runs.len(), 2); + assert_eq!(b.para_runs[1].1, 1); + assert_eq!(b.char_runs.len(), 2); + assert_eq!(b.char_runs[0].1.bold, Some(true)); + } + + /// A CF exception with only the fields PowerPoint 2002 and later add after `position`: + /// pp10runid (bit 20), newEAFontRef (bit 24), csFontRef (bit 25) and pp11ext (bit 26). + fn cf_later_fields() -> Vec { + let mut v = (1u32 << 20 | 1 << 24 | 1 << 25 | 1 << 26).to_le_bytes().to_vec(); + v.extend_from_slice(&0x0000_0003u32.to_le_bytes()); // pp10runid + unused + v.extend_from_slice(&7u16.to_le_bytes()); // newEAFontRef + v.extend_from_slice(&8u16.to_le_bytes()); // csFontRef + v.extend_from_slice(&0u32.to_le_bytes()); // pp11ext + v + } + + #[test] + fn later_character_fields_are_read_past() { + let bytes = cf_later_fields(); + let mut c = Cursor::new(&bytes); + assert!(read_cf(&mut c).is_some()); + assert!(c.u8().is_none(), "the cursor stopped inside the exception"); + + // A run carrying those fields, then a bold 18 pt run: the second must read as written. + let chars: Vec = "abcd".encode_utf16().flat_map(u16::to_le_bytes).collect(); + let mut style = vec![]; + style.extend_from_slice(&5u32.to_le_bytes()); + style.extend_from_slice(&0u16.to_le_bytes()); + style.extend_from_slice(&pf_bytes(0, false)); + style.extend_from_slice(&2u32.to_le_bytes()); + style.extend_from_slice(&cf_later_fields()); + style.extend_from_slice(&3u32.to_le_bytes()); + style.extend_from_slice(&cf_bytes(true, 1, 18, [0, 0, 0])); + let recs = [atom(rt::TEXT_HEADER, 0, &1u32.to_le_bytes()), atom(rt::TEXT_CHARS, 0, &chars), atom(rt::STYLE_TEXT_PROP, 0, &style)].concat(); + let b = read_block(crate::record::Records::new(&recs)).unwrap(); + assert_eq!(b.char_runs.len(), 2, "{:?}", b.char_runs); + let (n, cf) = &b.char_runs[1]; + assert_eq!((*n, cf.bold, cf.font, cf.size), (3, Some(true), Some(1), Some(18))); + } + + #[test] + fn styles_inherit_from_level_one_and_the_base_type() { + let mut s = StyleSheet { types: vec![None; 9], ..Default::default() }; + let lvl = |size: u16, align: u16| (Pf { align: Some(align), ..Default::default() }, Cf { size: Some(size), ..Default::default() }); + s.types[ty::BODY as usize] = Some(LevelStyles { levels: vec![lvl(32, 0), (Pf::default(), Cf { size: Some(28), ..Default::default() })] }); + s.types[ty::CENTER_BODY as usize] = Some(LevelStyles { levels: vec![(Pf { align: Some(1), ..Default::default() }, Cf::default())] }); + let (pf, cf) = s.resolve(ty::CENTER_BODY, 1); + assert_eq!(cf.size, Some(28)); + assert_eq!(pf.align, Some(1)); + let (pf, cf) = s.resolve(ty::BODY, 0); + assert_eq!((pf.align, cf.size), (Some(0), Some(32))); + } +} diff --git a/crates/ppt-binary/tests/fixtures/old-talk.pps b/crates/ppt-binary/tests/fixtures/old-talk.pps new file mode 100644 index 0000000000000000000000000000000000000000..9c5d02004a799ada581558530442ecc10a24db8a GIT binary patch literal 4096 zcmeHKO>9h26#m}4(W%zBuT4|Z_?bu}B25SuA|if9=!VAcQl)JW)h5$YwHj-X{~5_rth6|&pGcq_niCAy{}Im*9=~| z+3*r&v<5zgi_=k2qW36ID;WJHh+eLk$2<3^u+^+{Ph z@-mq+A79FtqM|J+^GU{baxd~R`0B55@_T=_^d&x}VgQ@UP{FOnsq^_f`FY@xhSY_B zlrNhQ$E%dZ<1gh92{7IAbs2-I ztP98_wWSy&?JDvBp+2GHtAM4bwzU+GdsI~3^8$JlISoArC`)B`&GCf2;<#@wI6m?0+WFkb+%$b=7w0hG4S8qk zZX^wAqG~;;cGaOrnwLS^Vl3WzIoxibi(R`E(Hx5#mOV}+1Bfgl{q&-F{Mo*NXtBM6v zFk_+1Rp@$;%F!26vz-;{M+W=R!J2ilkJH%UMqSkQ(RzdyAU8{0>|rhMzyNFXoRhod zTK03)>A;ZBPax7qE(l#lefdZ~NvLa{-8WV$r(3pcN>?>#;nU5Vv)jnEf{99Pn7P~O zMzXoh*>yXPdR{Hw7Tt#9HXYq`ZF-pccJkWY7j#7P#x2?F>swDqo}z!K0^8Un-P~I; z*vPZCm#26Cgl1RIzKB0}N1b_pK#Bifkjn-fX3QM>QqeQmi5|*2Va7)dd@B`S@22?p zo{CO4I=3+UJ{M7vzBe?BEaf)N>`*kX-=i*y;w!f3_ntp3+D(>4-`OpU*~XZvLI-o7 hDAh*sg*o2%I$`2(9Ib_Fr?rzDU*82bMU%b)KL8(#ksSa4 literal 0 HcmV?d00001 From 4ce34ca37efd2a4f518c67f2ad7701c08e0639c2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 23:23:21 -0500 Subject: [PATCH 22/79] Add bounded borrowed certificate inspection views (#2325) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep wire evidence separate from existing verification and trust APIs. Inspection semantics acknowledge Afloat’s original Craft Anything raw-field and non-minimal-length contributions. --- crates/pkcs7/README.md | 9 ++ crates/pkcs7/src/inspection.rs | 184 ++++++++++++++++++++++++++++ crates/pkcs7/src/lib.rs | 1 + crates/pkcs7/tests/it/inspection.rs | 119 ++++++++++++++++++ crates/pkcs7/tests/it/main.rs | 1 + 5 files changed, 314 insertions(+) create mode 100644 crates/pkcs7/src/inspection.rs create mode 100644 crates/pkcs7/tests/it/inspection.rs diff --git a/crates/pkcs7/README.md b/crates/pkcs7/README.md index fc715c3b9d..b0339a848e 100644 --- a/crates/pkcs7/README.md +++ b/crates/pkcs7/README.md @@ -7,6 +7,11 @@ message or a digital ID file is made of. keeps its exact encoding, so a signed structure is verified over the bytes that were signed. Reading is strict DER; `parse_ber` also takes indefinite lengths and segmented strings, which PKCS #12 files from Windows use. Nesting is bounded. +- **`inspection`**: borrowed definite-length cursors without child-list allocations and borrowed X.509 wire fields. + Each sibling list is bounded to 4,096 elements and child cursors to depth 32; callers must + separately bound whole-document traversal. Redundant lengths are flagged. Optional and + trailing fields remain explicitly uninspected until their cursors are consumed. This is + evidence extraction, not a complete certificate validator or a signature/trust verdict. - **`x509`**: certificates (RFC 5280): names, validity, key, the extensions that matter for signing (basic constraints, key usage, extended key usage, key identifiers, OCSP and CRL locations), `build_chain` / `build_chain_noted` (issuers that may issue, path length, validity, @@ -42,3 +47,7 @@ Weak algorithms are read, not refused, because old signed documents use them: `DigestAlg::weakness` and `PublicKey::weakness` say when one is weak, and the caller decides. Moved from PdfCraft's `pdfcraft-sign`. + +The inspection profile follows Craft Anything’s bounded reader and Afloat’s raw-certificate +and non-minimal-length contributions (craft-anything #1131, #1514, #1646). Existing verification +and trust APIs are unchanged; high-level CMS/metadata adapters remain separate work. diff --git a/crates/pkcs7/src/inspection.rs b/crates/pkcs7/src/inspection.rs new file mode 100644 index 0000000000..93b9eed39c --- /dev/null +++ b/crates/pkcs7/src/inspection.rs @@ -0,0 +1,184 @@ +//! Bounded, borrowed inspection of definite-length ASN.1 and X.509 wire fields. +//! +//! These views are evidence, not validated certificates or signature/trust verdicts. They do +//! not replace [`crate::x509::Certificate`]. Unknown algorithms and original encodings are kept. +//! The profile follows Craft Anything's inspection reader (including Afloat's raw-field and +//! non-minimal-length work); callers retain their existing semantic and verification checks. + +use crate::der::{Tlv, tag}; + +/// Maximum siblings read by one cursor, matching the inspection consumer's bound. +pub const MAX_CHILDREN: usize = 4096; +/// Maximum nesting accepted when obtaining child cursors. Root elements have depth zero. +pub const MAX_DEPTH: usize = 32; + +/// An inspection stopped without establishing that the remaining bytes are complete. +#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)] +pub enum InspectionError { + #[error("malformed or unsupported definite-length element")] + Malformed, + #[error("inspection child limit reached")] + ChildLimit, + #[error("inspection depth limit reached")] + DepthLimit, + #[error("missing or unexpected certificate field")] + Field, +} + +/// One borrowed wire element. Redundant definite lengths are readable but explicitly noted. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Element<'a> { + tlv: Tlv<'a>, + depth: usize, + non_minimal_length: bool, +} + +impl<'a> Element<'a> { + pub fn tag(&self) -> u8 { + self.tlv.tag + } + pub fn raw(&self) -> &'a [u8] { + self.tlv.raw + } + pub fn value(&self) -> &'a [u8] { + self.tlv.value + } + pub fn non_minimal_length(&self) -> bool { + self.non_minimal_length + } + + /// Inspect children without allocating a child list. Primitive values are not interpreted as children. + pub fn children(&self) -> Result, InspectionError> { + if self.tlv.tag & 0x20 == 0 { + return Err(InspectionError::Field); + } + // Prevent callers following nested wire fields from silently exceeding the profile. + if self.depth >= MAX_DEPTH { + return Err(InspectionError::DepthLimit); + } + Ok(Cursor::at_depth(self.tlv.value, self.depth + 1)) + } +} + +/// A non-recursive sibling cursor with a hard per-list work bound and no child-list allocation. +/// +/// Successful reads allocate no memory; the underlying parser may allocate an error message. +/// `Ok(None)` means complete input, never a malformed/limited prefix. Errors are sticky and +/// leave the offending remainder available. Separate cursors have separate sibling budgets; +/// this does not impose a global budget on an application's traversal of many lists. +#[derive(Clone, Debug)] +pub struct Cursor<'a> { + remaining: &'a [u8], + count: usize, + depth: usize, + stopped: Option, +} + +impl<'a> Cursor<'a> { + pub fn new(input: &'a [u8]) -> Self { + Self::at_depth(input, 0) + } + fn at_depth(input: &'a [u8], depth: usize) -> Self { + Self { remaining: input, count: 0, depth, stopped: None } + } + /// Bytes not yet inspected. An empty remainder alone is not a recursive DER validation. + pub fn remaining(&self) -> &'a [u8] { + self.remaining + } + pub fn next_element(&mut self) -> Result>, InspectionError> { + if let Some(error) = self.stopped { + return Err(error); + } + if self.remaining.is_empty() { + return Ok(None); + } + if self.count == MAX_CHILDREN { + self.stopped = Some(InspectionError::ChildLimit); + return Err(InspectionError::ChildLimit); + } + let input = self.remaining; + let (tlv, rest) = match Tlv::parse(input) { + Ok(value) => value, + Err(_) => { + self.stopped = Some(InspectionError::Malformed); + return Err(InspectionError::Malformed); + } + }; + let non_minimal_length = input.get(1).is_some_and(|b| b & 0x80 != 0) && (input.get(2) == Some(&0) || tlv.value.len() < 128); + self.remaining = rest; + self.count += 1; + Ok(Some(Element { tlv, depth: self.depth, non_minimal_length })) + } + fn required(&mut self, expected: u8) -> Result, InspectionError> { + self.next_element()?.filter(|e| e.tag() == expected).ok_or(InspectionError::Field) + } +} + +/// Borrowed required X.509 wire fields, without algorithm, signature, key or trust validation. +/// +/// The BIT STRING is retained whole, including its unused-bit count. Both AlgorithmIdentifier +/// encodings are retained independently: their equality and parameter policy are the verifier's +/// responsibility. Optional/trailing fields remain in bounded cursors rather than being silently +/// reported as complete. Parsing this view does not walk nested names, keys or extensions. +#[derive(Clone, Debug)] +pub struct CertificateView<'a> { + pub certificate: Element<'a>, + pub tbs: Element<'a>, + pub version: Option>, + pub serial: Element<'a>, + pub signed_algorithm: Element<'a>, + pub issuer: Element<'a>, + pub validity: Element<'a>, + pub subject: Element<'a>, + pub spki: Element<'a>, + pub signature_algorithm: Element<'a>, + pub signature_bits: Element<'a>, + pub remaining_certificate_fields: Cursor<'a>, + pub remaining_tbs_fields: Cursor<'a>, +} + +impl<'a> CertificateView<'a> { + /// Inspect required fields of the first certificate; return bytes following its outer TLV. + /// Readable prefixes do not imply complete optional fields. Inspect the returned cursors to + /// distinguish complete, malformed, and limited tails. Existing strict verification stays separate. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), InspectionError> { + let mut roots = Cursor::new(input); + let certificate = roots.required(tag::SEQUENCE)?; + let mut outer = certificate.children()?; + let tbs = outer.required(tag::SEQUENCE)?; + let signature_algorithm = outer.required(tag::SEQUENCE)?; + let signature_bits = outer.required(tag::BIT_STRING)?; + let mut fields = tbs.children()?; + let first = fields.next_element()?.ok_or(InspectionError::Field)?; + let (version, serial) = if first.tag() == tag::ctx(0) { + (Some(first), fields.required(tag::INTEGER)?) + } else if first.tag() == tag::INTEGER { + (None, first) + } else { + return Err(InspectionError::Field); + }; + let signed_algorithm = fields.required(tag::SEQUENCE)?; + let issuer = fields.required(tag::SEQUENCE)?; + let validity = fields.required(tag::SEQUENCE)?; + let subject = fields.required(tag::SEQUENCE)?; + let spki = fields.required(tag::SEQUENCE)?; + Ok(( + Self { + certificate, + tbs, + version, + serial, + signed_algorithm, + issuer, + validity, + subject, + spki, + signature_algorithm, + signature_bits, + remaining_certificate_fields: outer, + remaining_tbs_fields: fields, + }, + roots.remaining(), + )) + } +} diff --git a/crates/pkcs7/src/lib.rs b/crates/pkcs7/src/lib.rs index 776be2749e..0b501515d5 100644 --- a/crates/pkcs7/src/lib.rs +++ b/crates/pkcs7/src/lib.rs @@ -29,6 +29,7 @@ pub mod cms; pub mod der; mod ec512; +pub mod inspection; pub mod keys; pub mod pkcs12; pub mod revocation; diff --git a/crates/pkcs7/tests/it/inspection.rs b/crates/pkcs7/tests/it/inspection.rs new file mode 100644 index 0000000000..e079a19f51 --- /dev/null +++ b/crates/pkcs7/tests/it/inspection.rs @@ -0,0 +1,119 @@ +//! Benign wire parity and boundary tests; no signature/trust decisions are made by these views. +use craft_pkcs7::der::{self, tag}; +use craft_pkcs7::inspection::{CertificateView, Cursor, InspectionError, MAX_CHILDREN, MAX_DEPTH}; + +#[test] +fn cursor_keeps_exact_bytes_and_length_notes() { + for (encoded, note) in [(vec![4, 3, 1, 2, 3], false), (vec![4, 0x81, 3, 1, 2, 3], true), (vec![4, 0x82, 0, 3, 1, 2, 3], true)] { + let mut cursor = Cursor::new(&encoded); + let element = cursor.next_element().unwrap().unwrap(); + assert_eq!(element.raw(), encoded); + assert_eq!(element.raw().as_ptr(), encoded.as_ptr()); + assert_eq!(element.value(), &[1, 2, 3]); + assert_eq!(element.non_minimal_length(), note); + assert_eq!(cursor.next_element(), Ok(None)); + } + let canonical = der::octets(&[7; 128]); + assert!(!Cursor::new(&canonical).next_element().unwrap().unwrap().non_minimal_length()); +} + +#[test] +fn cursor_distinguishes_completion_and_sticky_partial_results() { + let bytes = [5, 0, 4]; // One complete NULL followed by an incomplete header. + let mut cursor = Cursor::new(&bytes); + assert_eq!(cursor.next_element().unwrap().unwrap().tag(), tag::NULL); + assert_eq!(cursor.next_element(), Err(InspectionError::Malformed)); + assert_eq!(cursor.next_element(), Err(InspectionError::Malformed)); + assert_eq!(cursor.remaining(), &[4]); + assert_eq!(Cursor::new(&[0x30, 0x80, 0, 0]).next_element(), Err(InspectionError::Malformed)); + assert_eq!(Cursor::new(&[0x30, 0]).next_element().unwrap().unwrap().raw(), &[0x30, 0]); +} + +#[test] +fn sibling_limit_allows_exact_completion_without_allocating_a_child_list() { + let mut bytes = [5, 0].repeat(MAX_CHILDREN); + let mut cursor = Cursor::new(&bytes); + for _ in 0..MAX_CHILDREN { + assert!(cursor.next_element().unwrap().is_some()); + } + assert_eq!(cursor.next_element(), Ok(None)); + bytes.extend_from_slice(&[5, 0]); + let mut cursor = Cursor::new(&bytes); + for _ in 0..MAX_CHILDREN { + cursor.next_element().unwrap(); + } + assert_eq!(cursor.next_element(), Err(InspectionError::ChildLimit)); + assert_eq!(cursor.next_element(), Err(InspectionError::ChildLimit)); + assert_eq!(cursor.remaining(), &[5, 0]); +} + +#[test] +fn nested_cursor_depth_is_explicitly_bounded() { + let mut bytes = der::seq(&[]); + for _ in 0..MAX_DEPTH { + bytes = der::seq(&[&bytes]); + } + let mut element = Cursor::new(&bytes).next_element().unwrap().unwrap(); + for _ in 0..MAX_DEPTH { + element = element.children().unwrap().next_element().unwrap().unwrap(); + } + assert!(matches!(element.children(), Err(InspectionError::DepthLimit))); +} + +fn certificate(version: bool, tail: &[u8]) -> (Vec, Vec, Vec, Vec) { + // Unknown algorithms are still inspectable. These are wire fixtures, not signed certificates. + let algorithm = der::seq(&[&der::oid("1.2.3.4"), &der::tlv(tag::NULL, &[])]); + let name = der::seq(&[]); + let spki = der::seq(&[&algorithm, &der::bit_string(&[1, 2, 3])]); + let version_field = if version { der::explicit(0, &der::int(2)) } else { vec![] }; + let tbs = der::seq(&[&version_field, &der::int(7), &algorithm, &name, &der::seq(&[]), &name, &spki, tail]); + let cert = der::seq(&[&tbs, &algorithm, &der::bit_string(&[9, 8, 7])]); + (cert, tbs, algorithm, spki) +} + +#[test] +fn certificate_fields_are_borrowed_exact_and_do_not_consume_trailing_input() { + for version in [false, true] { + let (mut bytes, tbs, algorithm, spki) = certificate(version, &[]); + let len = bytes.len(); + bytes.extend_from_slice(&[5, 0]); + let (mut view, rest) = CertificateView::parse(&bytes).unwrap(); + assert_eq!(view.certificate.raw(), &bytes[..len]); + assert_eq!(view.certificate.raw().as_ptr(), bytes.as_ptr()); + assert_eq!(view.tbs.raw(), tbs); + assert_eq!(view.signed_algorithm.raw(), algorithm); + assert_eq!(view.signature_algorithm.raw(), algorithm); + assert_eq!(view.spki.raw(), spki); + assert_eq!(view.serial.value(), &[7]); + assert_eq!(view.signature_bits.value(), &[0, 9, 8, 7]); + assert_eq!(view.version.is_some(), version); + assert_eq!(rest, &[5, 0]); + assert_eq!(view.remaining_tbs_fields.next_element(), Ok(None)); + assert_eq!(view.remaining_certificate_fields.next_element(), Ok(None)); + } +} + +#[test] +fn required_fields_do_not_hide_optional_tail_diagnostics() { + let (bytes, _, _, _) = certificate(false, &[0xa3]); + let (mut view, _) = CertificateView::parse(&bytes).unwrap(); + assert_eq!(view.remaining_tbs_fields.remaining(), &[0xa3]); + assert_eq!(view.remaining_tbs_fields.next_element(), Err(InspectionError::Malformed)); + // This partial wire view is deliberately not accepted as a validated certificate. + assert!(craft_pkcs7::Certificate::parse(&bytes).is_err()); +} + +#[test] +fn existing_certificate_fixture_retains_signed_components() { + let cert = craft_pkcs7::x509::load_certificates(include_bytes!("../data/ca.crt.pem")).unwrap().remove(0); + let (view, rest) = CertificateView::parse(&cert.raw).unwrap(); + assert!(rest.is_empty()); + let parts = cert.clone().into_parts(); + assert_eq!(view.tbs.raw(), parts.tbs); + assert_eq!(view.signature_algorithm.raw(), parts.sig_alg); + assert_eq!(view.signature_bits.value().first(), Some(&0)); + assert_eq!(&view.signature_bits.value()[1..], parts.signature); + assert_eq!(view.issuer.raw(), parts.issuer.raw); + assert_eq!(view.subject.raw(), parts.subject.raw); + assert_eq!(view.spki.raw(), parts.public_key.spki()); +} diff --git a/crates/pkcs7/tests/it/main.rs b/crates/pkcs7/tests/it/main.rs index 4a10ec7935..c4a2f0fbae 100644 --- a/crates/pkcs7/tests/it/main.rs +++ b/crates/pkcs7/tests/it/main.rs @@ -5,4 +5,5 @@ mod ber; mod chain; mod cms; mod crypto; +mod inspection; mod store_keys; From 2e6f11eabb14878f46dfa93c0c4b16c80280f7b3 Mon Sep 17 00:00:00 2001 From: Aleksander Helgaker Date: Thu, 19 Nov 2026 05:25:56 +0100 Subject: [PATCH 23/79] craft-video: TrackDecoder for H.264, HEVC, VP9, AV1 and MPEG-2 (#1231) (#2022) * craft-video: TrackDecoder, codec-agnostic decoding for H.264, HEVC, VP9, AV1 and MPEG-2 (#1231) Add `craft_video::TrackDecoder`, the counterpart of craft-audio's: built from a track's `CodecParams`, it takes packets in decode order with their timestamps and returns `VideoFrame`s in display order, with `flush` and `reset`. Each codec is behind its decoder feature. Configuration: an `avcC` / `hvcC` record, Annex B parameter sets (AVI with global headers) or nothing (MPEG-TS) for H.264 and HEVC; the `av1C` config OBUs for AV1; a sequence header for MPEG-2. Picture data in the configuration is refused (or, for MPEG-2, dropped by the decoder's reset). `reset` keeps the configuration: H.264 applies it again, HEVC and AV1 build a new decoder from it. A call that fails keeps the frames it finished for the next call. Add `VideoError` (Unsupported, Malformed, Frame), into which each decoder's error converts. `av1::decode::bits` becomes `pub(crate)` for its LEB128 reader. Tests: unit tests for codec selection, configuration checks, hostile configuration and kept frames; `tests/track` decodes ffmpeg-made MP4, MPEG-TS and AVI files and compares with ffmpeg's decode, then decodes again after a reset and from a later key packet. Co-Authored-By: Claude Opus 5.5 * craft-video: TrackDecoder review fixes (#1231) - MPEG-2: configuration is checked before it is decoded. Every start code must be a sequence header, extension, user data or GOP header; a picture after a valid sequence header was decoded and then dropped by a reset, so construction succeeded. It is now Malformed. - The decode and flush docs and the README say what each codec keeps after its own decoding error: H.264 keeps finished pictures, HEVC only its newest 32 while calls keep failing, VP9 those of earlier packets, MPEG-2 unless the packet made too many, and AV1 drops those of the failing decode or flush. Frames that fail to convert are still kept for the next call. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/video/Cargo.toml | 9 +- crates/video/README.md | 28 ++ crates/video/src/av1/decode/mod.rs | 2 +- crates/video/src/error.rs | 73 +++++ crates/video/src/lib.rs | 11 + crates/video/src/track.rs | 413 +++++++++++++++++++++++++ crates/video/src/track/tests.rs | 266 ++++++++++++++++ crates/video/tests/track/av1.rs | 72 +++++ crates/video/tests/track/common/mod.rs | 201 ++++++++++++ crates/video/tests/track/h264.rs | 63 ++++ crates/video/tests/track/hevc.rs | 68 ++++ crates/video/tests/track/main.rs | 18 ++ crates/video/tests/track/mpeg2.rs | 55 ++++ crates/video/tests/track/vp9.rs | 14 + 14 files changed, 1290 insertions(+), 3 deletions(-) create mode 100644 crates/video/src/error.rs create mode 100644 crates/video/src/track.rs create mode 100644 crates/video/src/track/tests.rs create mode 100644 crates/video/tests/track/av1.rs create mode 100644 crates/video/tests/track/common/mod.rs create mode 100644 crates/video/tests/track/h264.rs create mode 100644 crates/video/tests/track/hevc.rs create mode 100644 crates/video/tests/track/main.rs create mode 100644 crates/video/tests/track/mpeg2.rs create mode 100644 crates/video/tests/track/vp9.rs diff --git a/crates/video/Cargo.toml b/crates/video/Cargo.toml index 6a8cb336ac..0989feb738 100644 --- a/crates/video/Cargo.toml +++ b/crates/video/Cargo.toml @@ -80,8 +80,13 @@ rav1e = { version = "0.8", default-features = false, optional = true } [dev-dependencies] craft-media-testkit = { workspace = true } -# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test, and the VMD demuxer for the VMD decoder's. -craft-media = { workspace = true, features = ["avi", "vmd"] } +# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test; the MP4, MPEG-TS and AVI +# demuxers, for the track decoder's tests; the VMD demuxer, for the VMD decoder's. +craft-media = { workspace = true, features = ["avi", "isobmff", "mpegts", "vmd"] } + +# Built with any decoder feature; each codec's tests need its own. +[[test]] +name = "track" [[test]] name = "vmd" diff --git a/crates/video/README.md b/crates/video/README.md index c2c5b27457..d05d503122 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -55,3 +55,31 @@ comes with its codec's feature): The constructors check that every plane's buffer, stride and size fit the frame, so a picture with inconsistent fields is an error, not an out-of-bounds read. + +## Decoding a track + +`TrackDecoder` is the counterpart of `craft_audio::TrackDecoder` for an app with its own demuxer. +It picks the decoder from a track's `CodecParams`, takes packets in decode order with their +timestamps, and returns `VideoFrame`s in display order. `flush` returns the frames still held at +the end of the stream, and `reset` prepares for decoding from another key frame after a seek. It +is built with any of the decoder features below and decodes the codecs whose feature is on. + +| Codec | Feature | `extradata` | +|---|---|---| +| H.264 | `h264-decode` | an `avcC` record (length-prefixed packets), Annex B parameter sets, or empty (Annex B packets) | +| HEVC | `hevc-decode` | an `hvcC` record (length-prefixed packets), Annex B parameter sets, or empty (Annex B packets) | +| VP9 | `vp9-decode` | ignored | +| AV1 | `av1-decode` | an `av1C` record, or empty | +| MPEG-2 and MPEG-1 video | `mpeg2-decode` | a sequence header and its extensions, or empty | + +Configuration that holds picture data (a slice, a frame OBU, an MPEG-2 picture) is refused. +Errors are `VideoError`: `Unsupported`, `Malformed`, or a picture that did not convert. + +When a picture does not convert, the frames finished with it are kept and the next call returns +them first. When the codec itself fails, the pictures it had finished are up to the codec: + +- H.264 keeps them for later calls, also when the error comes at `flush`. +- HEVC does too, but only its newest 32 while calls keep failing, which bounds its memory. +- VP9 keeps those of earlier packets. +- MPEG-2 returns them with the call, unless the packet made too many pictures. +- AV1 drops those the failing `decode` or `flush` had finished. diff --git a/crates/video/src/av1/decode/mod.rs b/crates/video/src/av1/decode/mod.rs index 63f66120a1..b5e4103414 100644 --- a/crates/video/src/av1/decode/mod.rs +++ b/crates/video/src/av1/decode/mod.rs @@ -5,7 +5,7 @@ #![allow(clippy::needless_range_loop, clippy::type_complexity)] -mod bits; +pub(crate) mod bits; mod cdef; mod cdf; mod decoder; diff --git a/crates/video/src/error.rs b/crates/video/src/error.rs new file mode 100644 index 0000000000..21706aaf93 --- /dev/null +++ b/crates/video/src/error.rs @@ -0,0 +1,73 @@ +//! [`VideoError`], the error of the codec-agnostic layer ([`crate::TrackDecoder`]). + +use crate::frame::FrameError; + +/// Errors from the codec-agnostic layer. +/// +/// Codec errors convert into it, so code mixing [`crate::TrackDecoder`] with the codec modules can +/// use `?` throughout: a codec's "unsupported" stays [`VideoError::Unsupported`], anything else in +/// the input is [`VideoError::Malformed`]. The message starts with the codec's name. +#[non_exhaustive] +#[derive(Debug, thiserror::Error)] +pub enum VideoError { + /// The codec, or a feature of the stream, is valid but not supported (or its decoder is not + /// in this build). + #[error("unsupported video: {0}")] + Unsupported(String), + /// The input is corrupt or not what it claims to be. + #[error("malformed video: {0}")] + Malformed(String), + /// A decoded picture did not convert into a [`crate::frame::VideoFrame`]. + #[error(transparent)] + Frame(#[from] FrameError), +} + +#[cfg(feature = "h264-decode")] +impl From for VideoError { + fn from(e: crate::h264::decode::Error) -> Self { + match e { + crate::h264::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("H.264: {e}")), + _ => VideoError::Malformed(format!("H.264: {e}")), + } + } +} + +#[cfg(feature = "hevc-decode")] +impl From for VideoError { + fn from(e: crate::hevc::decode::Error) -> Self { + match e { + crate::hevc::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("HEVC: {e}")), + _ => VideoError::Malformed(format!("HEVC: {e}")), + } + } +} + +#[cfg(feature = "vp9-decode")] +impl From for VideoError { + fn from(e: crate::vp9::decode::Error) -> Self { + match e { + crate::vp9::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("VP9: {e}")), + _ => VideoError::Malformed(format!("VP9: {e}")), + } + } +} + +#[cfg(feature = "av1-decode")] +impl From for VideoError { + fn from(e: crate::av1::decode::Error) -> Self { + match e { + crate::av1::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("AV1: {e}")), + _ => VideoError::Malformed(format!("AV1: {e}")), + } + } +} + +#[cfg(feature = "mpeg2-decode")] +impl From for VideoError { + fn from(e: crate::mpeg2::Error) -> Self { + match e { + crate::mpeg2::Error::Unsupported(_) => VideoError::Unsupported(format!("MPEG-2: {e}")), + crate::mpeg2::Error::Invalid(_) => VideoError::Malformed(format!("MPEG-2: {e}")), + } + } +} diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index 249f1a1b48..174e7573ae 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -28,12 +28,23 @@ //! Each decoder returns its own picture type. [`frame::VideoFrame`] is the codec-agnostic form //! they all convert into (`VideoFrame::try_from`). //! +//! `TrackDecoder` picks the decoder for a track from its `craft_media::CodecParams` and returns +//! `VideoFrame`s, for H.264, HEVC, VP9, AV1 and MPEG-2 (built with any of their decoder features). +//! //! Containers and bit-level I/O are in `craft-media`; the codecs here share its `bitstream` //! module and describe their streams with `craft_media::CodecParams`. pub mod budget; +mod error; pub mod frame; +pub use error::VideoError; + +#[cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))] +mod track; +#[cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))] +pub use track::TrackDecoder; + #[cfg(any(feature = "apv-decode", feature = "apv-encode"))] pub mod apv; diff --git a/crates/video/src/track.rs b/crates/video/src/track.rs new file mode 100644 index 0000000000..a4f2462713 --- /dev/null +++ b/crates/video/src/track.rs @@ -0,0 +1,413 @@ +//! [`TrackDecoder`]: one video track's packets in, [`VideoFrame`]s out, whatever the codec. The +//! counterpart of `craft_audio::TrackDecoder`, for an app with its own demuxer. + +#[cfg(feature = "av1-decode")] +use crate::av1; +use crate::error::VideoError; +use crate::frame::{FrameError, VideoFrame}; +#[cfg(feature = "h264-decode")] +use crate::h264; +#[cfg(feature = "hevc-decode")] +use crate::hevc; +#[cfg(feature = "mpeg2-decode")] +use crate::mpeg2; +#[cfg(feature = "vp9-decode")] +use crate::vp9; +use craft_media::{CodecId, CodecParams}; + +/// The codec-specific decoder behind a [`TrackDecoder`]. +enum Inner { + /// The decoder, and the `avcC` record or Annex B parameter sets that [`TrackDecoder::reset`] + /// applies again (the decoder's own reset forgets them). + #[cfg(feature = "h264-decode")] + H264 { dec: Box, config: Vec }, + /// The decoder, and the `hvcC` record or Annex B parameter sets a reset rebuilds it from. + #[cfg(feature = "hevc-decode")] + Hevc { dec: Box, config: Vec }, + #[cfg(feature = "vp9-decode")] + Vp9(Box), + /// The decoder, and the `av1C` config OBUs a reset rebuilds it from. + #[cfg(feature = "av1-decode")] + Av1 { dec: Box, config_obus: Vec }, + #[cfg(feature = "mpeg2-decode")] + Mpeg2(Box), +} + +/// A decoder for one video track, whatever its codec: built from the track's [`CodecParams`], +/// it takes the track's packets in decode order and returns [`VideoFrame`]s in display order. +/// +/// | Codec | Feature | `extradata` | +/// |---|---|---| +/// | H.264 | `h264-decode` | an `avcC` record, Annex B parameter sets, or empty | +/// | HEVC | `hevc-decode` | an `hvcC` record, Annex B parameter sets, or empty | +/// | VP9 | `vp9-decode` | ignored (the frame headers repeat the `vpcC` values) | +/// | AV1 | `av1-decode` | an `av1C` record, or empty | +/// | MPEG-2 and MPEG-1 video | `mpeg2-decode` | a sequence header and its extensions, or empty | +/// +/// With an `avcC` or `hvcC` record, packets are length-prefixed NAL units, as MP4 and Matroska +/// store them. Otherwise they are Annex B, as MPEG-TS and AVI store them, and the parameter sets +/// may come in the packets themselves. The configuration must not hold picture data: an `avcC` +/// or `hvcC` record holds parameter sets (and SEI for `hvcC`), Annex B `extradata` holds +/// parameter sets, SEI and access unit delimiters, `av1C` config OBUs are sequence headers and +/// metadata, and MPEG-2 `extradata` holds sequence headers, their extensions, user data and GOP +/// headers. +/// +/// Other codecs are [`VideoError::Unsupported`], as is a codec whose decoder feature is off. +/// +/// A packet carries its presentation timestamp, in any unit; each frame returns with the timestamp +/// of the packet that coded it, through reordering ([`VideoFrame::pts`]). +/// +/// ```no_run +/// # fn run(params: &craft_media::CodecParams, packets: &[(Vec, i64)]) -> Result<(), craft_video::VideoError> { +/// use craft_video::TrackDecoder; +/// +/// let mut dec = TrackDecoder::new(params)?; +/// for (packet, pts) in packets { +/// for frame in dec.decode(packet, *pts)? { +/// println!("{}x{} at {:?}", frame.width(), frame.height(), frame.pts); +/// } +/// } +/// for frame in dec.flush()? { +/// let _ = frame; +/// } +/// # Ok(()) } +/// ``` +pub struct TrackDecoder { + inner: Inner, + codec: CodecId, + /// Frames finished by a call that then failed, which the next call returns first. + held: Vec, +} + +impl std::fmt::Debug for TrackDecoder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TrackDecoder").field("codec", &self.codec).field("held", &self.held.len()).finish_non_exhaustive() + } +} + +impl TrackDecoder { + /// A decoder for the track `params` describes. Only `codec` and `extradata` are read; the + /// picture size and format come from the stream. + /// + /// Configuration that the codec refuses, or that holds picture data, is + /// [`VideoError::Malformed`]. + pub fn new(params: &CodecParams) -> Result { + Ok(TrackDecoder { inner: Inner::new(params.codec, ¶ms.extradata)?, codec: params.codec, held: Vec::new() }) + } + + /// The track's codec, as `params` gave it. + pub fn codec(&self) -> CodecId { + self.codec + } + + /// Decode one packet (an access unit, a VP9 frame or superframe, an AV1 temporal unit) with + /// its presentation timestamp. Returns the frames that became ready for display, in display + /// order; a decoder that reorders or decodes on worker threads returns a packet's frame from a + /// later call or from [`TrackDecoder::flush`]. + /// + /// When a call fails because a picture does not convert, the frames finished with it are + /// kept: the next call returns them first. When the codec itself fails, the pictures it had + /// finished are up to the codec. H.264 keeps them for later calls. HEVC does too, but only + /// its newest 32 while calls keep failing, which bounds its memory. VP9 keeps those of earlier + /// packets. MPEG-2 returns them with the call, unless the packet made too many pictures. AV1 + /// drops those the failing call had finished. + /// + /// Decoding can go on with the next packet; a decoder that lost its references waits for the + /// next random access point or conceals, as the codec does. + pub fn decode(&mut self, packet: &[u8], pts: i64) -> Result, VideoError> { + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, .. } => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, .. } => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, .. } => { + let pics = dec.decode_pts(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(dec) => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + } + } + + /// End of stream: every frame the decoder still holds, in display order. + /// + /// A decoding error found while finishing them is returned instead; the H.264 and HEVC frames + /// are then kept for the next call, while the AV1 decoder drops its own. + pub fn flush(&mut self) -> Result, VideoError> { + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, .. } => { + let pics = dec.flush(); + let err = dec.take_error().map(VideoError::from); + self.output(pics, err) + } + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, .. } => { + let pics = dec.flush(); + let err = dec.take_error().map(VideoError::from); + self.output(pics, err) + } + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => { + let pics = dec.flush(); + self.output(pics, None) + } + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, .. } => { + let pics = dec.flush_result()?; + self.output(pics, None) + } + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(dec) => { + let pics = dec.flush(); + self.output(pics, None) + } + } + } + + /// Forget the pictures and references, and the frames kept from a failed call, before decoding + /// from another random access point (after a seek). The track's configuration is kept: H.264 + /// and HEVC parameter sets from `extradata`, the AV1 sequence header from `av1C`, and the + /// MPEG-2 sequence; parameter sets that came in packets are forgotten (MPEG-2 keeps its + /// latest sequence header). + /// + /// An error is the configuration failing to apply again, which it did not when the decoder was + /// built. + pub fn reset(&mut self) -> Result<(), VideoError> { + self.held.clear(); + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, config } => { + dec.reset(); + configure_h264(dec, config) + } + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, config } => { + // The HEVC decoder has no reset of its own: a new one starts from nothing. + let mut fresh = Box::new(hevc::decode::Decoder::new()); + configure_hevc(&mut fresh, config)?; + *dec = fresh; + Ok(()) + } + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => { + dec.reset(); + Ok(()) + } + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, config_obus } => { + // The AV1 decoder has no reset of its own: a new one starts from nothing. + let mut fresh = Box::new(av1::decode::Decoder::new()); + configure_av1(&mut fresh, config_obus)?; + *dec = fresh; + Ok(()) + } + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(dec) => { + dec.reset(); + Ok(()) + } + } + } + + /// The frames kept from a failed call, then `pics` converted. On `err`, or on a picture that + /// does not convert, the frames are kept for the next call and the (first) error returned. + fn output

(&mut self, pics: Vec

, err: Option) -> Result, VideoError> + where + VideoFrame: TryFrom, + { + let mut frames = std::mem::take(&mut self.held); + frames.reserve(pics.len()); + let mut err = err; + for pic in pics { + match VideoFrame::try_from(pic) { + Ok(frame) => frames.push(frame), + Err(e) => { + err.get_or_insert(e.into()); + } + } + } + match err { + None => Ok(frames), + Some(e) => { + self.held = frames; + Err(e) + } + } + } +} + +impl Inner { + fn new(codec: CodecId, extradata: &[u8]) -> Result { + #[cfg(not(any(feature = "h264-decode", feature = "hevc-decode", feature = "av1-decode", feature = "mpeg2-decode")))] + let _ = extradata; + match codec { + #[cfg(feature = "h264-decode")] + CodecId::H264 => { + let mut dec = Box::new(h264::decode::Decoder::new()); + configure_h264(&mut dec, extradata)?; + Ok(Inner::H264 { dec, config: extradata.to_vec() }) + } + #[cfg(feature = "hevc-decode")] + CodecId::Hevc => { + let mut dec = Box::new(hevc::decode::Decoder::new()); + configure_hevc(&mut dec, extradata)?; + Ok(Inner::Hevc { dec, config: extradata.to_vec() }) + } + #[cfg(feature = "vp9-decode")] + CodecId::Vp9 => Ok(Inner::Vp9(Box::default())), + #[cfg(feature = "av1-decode")] + CodecId::Av1 => { + let config_obus = av1c_config_obus(extradata)?.to_vec(); + let mut dec = Box::new(av1::decode::Decoder::new()); + configure_av1(&mut dec, &config_obus)?; + Ok(Inner::Av1 { dec, config_obus }) + } + #[cfg(feature = "mpeg2-decode")] + CodecId::Mpeg2Video => { + let mut dec = Box::new(mpeg2::Decoder::new()); + if !extradata.is_empty() { + check_mpeg2_config(extradata)?; + dec.decode(extradata, 0)?; + } + Ok(Inner::Mpeg2(dec)) + } + other => Err(VideoError::Unsupported(format!("no {} decoder in this build", other.name()))), + } + } +} + +/// Whether `extradata` is Annex B (starts with a start code) rather than an `avcC` / `hvcC` record. +#[cfg(any(feature = "h264-decode", feature = "hevc-decode"))] +fn is_annex_b(extradata: &[u8]) -> bool { + extradata.starts_with(&[0, 0, 1]) || extradata.starts_with(&[0, 0, 0, 1]) +} + +/// Annex B `extradata` holds only NAL units whose type `allowed` accepts (`codec` names it in the +/// error). +#[cfg(any(feature = "h264-decode", feature = "hevc-decode"))] +fn check_annex_b(codec: &str, extradata: &[u8], nal_type: fn(u8) -> u8, allowed: &[u8]) -> Result<(), VideoError> { + for nal in craft_media::bitstream::annexb_nals(extradata) { + let t = nal.first().map_or(u8::MAX, |&b| nal_type(b)); + if !allowed.contains(&t) { + return Err(VideoError::Malformed(format!("{codec}: configuration holds NAL unit type {t}, not a parameter set"))); + } + } + Ok(()) +} + +/// H.264 NAL unit types Annex B `extradata` may hold: SEI, SPS, PPS, access unit delimiter, SPS +/// extension and subset SPS. +#[cfg(feature = "h264-decode")] +const H264_CONFIG_NALS: [u8; 6] = [6, 7, 8, 9, 13, 15]; + +/// HEVC NAL unit types Annex B `extradata` may hold: VPS, SPS, PPS, access unit delimiter, prefix +/// and suffix SEI. +#[cfg(feature = "hevc-decode")] +const HEVC_CONFIG_NALS: [u8; 6] = [32, 33, 34, 35, 39, 40]; + +/// Apply H.264 `extradata`: an `avcC` record, Annex B parameter sets, or nothing. +#[cfg(feature = "h264-decode")] +fn configure_h264(dec: &mut h264::decode::Decoder, extradata: &[u8]) -> Result<(), VideoError> { + if extradata.is_empty() { + Ok(()) + } else if is_annex_b(extradata) { + check_annex_b("H.264", extradata, |b| b & 0x1f, &H264_CONFIG_NALS)?; + dec.decode(extradata, 0)?; + Ok(()) + } else { + Ok(dec.configure_avcc(extradata)?) + } +} + +/// Apply HEVC `extradata`: an `hvcC` record, Annex B parameter sets, or nothing. +#[cfg(feature = "hevc-decode")] +fn configure_hevc(dec: &mut hevc::decode::Decoder, extradata: &[u8]) -> Result<(), VideoError> { + if extradata.is_empty() { + Ok(()) + } else if is_annex_b(extradata) { + check_annex_b("HEVC", extradata, |b| (b >> 1) & 0x3f, &HEVC_CONFIG_NALS)?; + dec.decode(extradata, 0)?; + Ok(()) + } else { + Ok(dec.configure_hvcc(extradata)?) + } +} + +/// MPEG-2 start codes `extradata` may hold: user data, sequence header, extension and GOP header. +#[cfg(feature = "mpeg2-decode")] +const MPEG2_CONFIG_CODES: [u8; 4] = [0xb2, 0xb3, 0xb5, 0xb8]; + +/// MPEG-2 `extradata` holds no picture: every start code in it is one of [`MPEG2_CONFIG_CODES`]. +#[cfg(feature = "mpeg2-decode")] +fn check_mpeg2_config(extradata: &[u8]) -> Result<(), VideoError> { + for w in extradata.windows(4) { + if let [0, 0, 1, code] = *w + && !MPEG2_CONFIG_CODES.contains(&code) + { + return Err(VideoError::Malformed(format!("MPEG-2: configuration holds start code {code:#04x}, not a sequence header"))); + } + } + Ok(()) +} + +/// The config OBUs of an `av1C` record (empty for empty `extradata`), once they are checked to +/// hold only sequence headers and metadata. +#[cfg(feature = "av1-decode")] +fn av1c_config_obus(extradata: &[u8]) -> Result<&[u8], VideoError> { + const SEQUENCE_HEADER: u8 = 1; + const METADATA: u8 = 5; + if extradata.is_empty() { + return Ok(&[]); + } + // marker (1) and version (1), then three bytes of profile, level and chroma fields + let obus = match extradata { + [0x81, _, _, _, obus @ ..] => obus, + _ => return Err(VideoError::Malformed("AV1: configuration is not an av1C record (version 1)".into())), + }; + let mut rest = obus; + while let Some(&header) = rest.first() { + let obu_type = (header >> 3) & 0xf; + if obu_type != SEQUENCE_HEADER && obu_type != METADATA { + return Err(VideoError::Malformed(format!("AV1: av1C holds OBU type {obu_type}, not a sequence header or metadata"))); + } + // obu_extension_flag adds a byte; without obu_has_size_field the OBU runs to the end + let start = 1 + usize::from(header & 4 != 0); + let body = rest.get(start..).ok_or_else(|| VideoError::Malformed("AV1: av1C OBU header truncated".into()))?; + rest = if header & 2 != 0 { + let (size, n) = av1::decode::bits::leb128(body)?; + let end = usize::try_from(size).ok().and_then(|s| s.checked_add(n)); + end.and_then(|end| body.get(end..)).ok_or_else(|| VideoError::Malformed("AV1: av1C OBU truncated".into()))? + } else { + &[] + }; + } + Ok(obus) +} + +/// Apply `av1C` config OBUs (sequence headers and metadata, checked by [`av1c_config_obus`]). +#[cfg(feature = "av1-decode")] +fn configure_av1(dec: &mut av1::decode::Decoder, config_obus: &[u8]) -> Result<(), VideoError> { + if !config_obus.is_empty() { + dec.decode_pts(config_obus, 0)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/video/src/track/tests.rs b/crates/video/src/track/tests.rs new file mode 100644 index 0000000000..5b20e81f11 --- /dev/null +++ b/crates/video/src/track/tests.rs @@ -0,0 +1,266 @@ +//! Unit tests of the track decoder: codec selection, configuration checks and the frames kept +//! from a failed call. Decoding real streams is in `tests/track`. + +use super::*; + +fn params(codec: CodecId, extradata: &[u8]) -> CodecParams { + CodecParams::new(codec).with_extradata(extradata.to_vec()) +} + +fn new_err(codec: CodecId, extradata: &[u8]) -> VideoError { + match TrackDecoder::new(¶ms(codec, extradata)) { + Ok(_) => panic!("{codec:?} with extradata {extradata:02x?} was accepted"), + Err(e) => e, + } +} + +#[test] +fn a_codec_without_a_decoder_is_unsupported() { + let off = [ + CodecId::Theora, + CodecId::Aac, + CodecId::Unknown, + #[cfg(not(feature = "h264-decode"))] + CodecId::H264, + #[cfg(not(feature = "hevc-decode"))] + CodecId::Hevc, + #[cfg(not(feature = "vp9-decode"))] + CodecId::Vp9, + #[cfg(not(feature = "av1-decode"))] + CodecId::Av1, + #[cfg(not(feature = "mpeg2-decode"))] + CodecId::Mpeg2Video, + ]; + for codec in off { + let err = new_err(codec, &[]); + assert!(matches!(err, VideoError::Unsupported(_)), "{codec:?}: {err}"); + assert!(err.to_string().contains(codec.name()), "{err}"); + } +} + +#[test] +fn every_built_decoder_starts_without_configuration() { + let on = [ + #[cfg(feature = "h264-decode")] + CodecId::H264, + #[cfg(feature = "hevc-decode")] + CodecId::Hevc, + #[cfg(feature = "vp9-decode")] + CodecId::Vp9, + #[cfg(feature = "av1-decode")] + CodecId::Av1, + #[cfg(feature = "mpeg2-decode")] + CodecId::Mpeg2Video, + ]; + for codec in on { + let mut dec = TrackDecoder::new(¶ms(codec, &[])).unwrap(); + assert_eq!(dec.codec(), codec); + assert!(dec.flush().unwrap().is_empty(), "{codec:?}"); + dec.reset().unwrap(); + assert!(dec.decode(&[], 0).unwrap_or_default().is_empty(), "{codec:?}"); + } +} + +#[test] +fn track_decoder_is_send() { + fn send() {} + send::(); +} + +/// An Annex B configuration that holds a slice would start a picture: it is refused before any +/// NAL unit reaches the decoder (which would report the slice's missing parameter set instead). +#[cfg(feature = "h264-decode")] +#[test] +fn h264_annex_b_configuration_with_a_slice_is_refused() { + let err = new_err(CodecId::H264, &[0, 0, 0, 1, 0x65, 0x88, 0x84, 0x00]); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("NAL unit type 5"), "{err}"); +} + +#[cfg(feature = "hevc-decode")] +#[test] +fn hevc_annex_b_configuration_with_a_slice_is_refused() { + // IDR_W_RADL (19): (19 << 1) = 0x26 + let err = new_err(CodecId::Hevc, &[0, 0, 1, 0x26, 0x01, 0xaf, 0x00]); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("NAL unit type 19"), "{err}"); +} + +/// A picture after a valid sequence header is refused, not decoded and then dropped. +#[cfg(feature = "mpeg2-decode")] +#[test] +fn mpeg2_configuration_with_a_picture_is_refused() { + // 32x32, 4:3, 25 fps + let header = [0, 0, 1, 0xb3, 0x02, 0x00, 0x20, 0x23, 0xff, 0xff, 0xe0, 0x18]; + assert!(TrackDecoder::new(¶ms(CodecId::Mpeg2Video, &header)).is_ok()); + // a picture header (I picture) and the start of its first slice + let picture = [0, 0, 1, 0x00, 0x00, 0x0f, 0xff, 0xf8, 0, 0, 1, 0x01, 0x12, 0x34]; + let err = new_err(CodecId::Mpeg2Video, &[&header[..], &picture].concat()); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("start code 0x00"), "{err}"); +} + +/// A record that is neither Annex B nor version 1 is the codec's own error. +#[cfg(feature = "h264-decode")] +#[test] +fn h264_configuration_that_is_not_avcc_is_refused() { + let err = new_err(CodecId::H264, &[2, 0x42, 0, 0x1e, 0xff, 0xe0, 0]); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("avcC"), "{err}"); +} + +#[cfg(feature = "av1-decode")] +mod av1c { + use super::*; + + const HEADER: [u8; 4] = [0x81, 0x00, 0x0c, 0x00]; + + fn with_obus(obus: &[u8]) -> Vec { + [&HEADER[..], obus].concat() + } + + #[test] + fn empty_and_header_only_records_hold_no_obus() { + assert_eq!(av1c_config_obus(&[]).unwrap(), &[] as &[u8]); + assert_eq!(av1c_config_obus(&HEADER).unwrap(), &[] as &[u8]); + } + + #[test] + fn sequence_headers_and_metadata_pass() { + // a sequence header (size 2), one with an extension byte (size 0), metadata (size 1), and + // a sequence header without a size field that runs to the end + let obus = [0x0a, 2, 0xaa, 0xbb, 0x0e, 0x00, 0, 0x2a, 1, 0xcc, 0x08, 0xdd, 0xee]; + assert_eq!(av1c_config_obus(&with_obus(&obus)).unwrap(), &obus); + } + + #[test] + fn a_record_that_is_not_av1c_version_1_is_refused() { + for bad in [&[0x81, 0, 0][..], &[0x80, 0, 0, 0], &[0x82, 0, 0, 0], &[0x0a, 0, 0, 0, 0]] { + let err = av1c_config_obus(bad).unwrap_err(); + assert!(err.to_string().contains("not an av1C record"), "{bad:02x?}: {err}"); + } + } + + #[test] + fn a_frame_or_temporal_delimiter_is_refused() { + // temporal delimiter (2), frame header (3), tile group (4), frame (6), after a valid OBU + for t in [2u8, 3, 4, 6] { + let obus = [0x0a, 0, (t << 3) | 2, 0]; + let err = av1c_config_obus(&with_obus(&obus)).unwrap_err(); + assert!(err.to_string().contains(&format!("OBU type {t}")), "{t}: {err}"); + } + assert!(matches!(new_err(CodecId::Av1, &with_obus(&[0x32, 0])), VideoError::Malformed(_))); + } + + #[test] + fn truncated_obus_are_refused() { + for obus in [&[0x0a, 5, 1, 2][..], &[0x0a, 0x80], &[0x0a, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], &[0x0e]] { + let err = av1c_config_obus(&with_obus(obus)).unwrap_err(); + assert!(matches!(err, VideoError::Malformed(_)), "{obus:02x?}: {err}"); + } + } + + #[test] + fn hostile_records_do_not_panic() { + let seed = with_obus(&[0x0a, 2, 0xaa, 0xbb, 0x2a, 1, 0xcc]); + craft_media_testkit::hostile::hammer("av1C config OBUs", &seed, 2000, |data| { + let _ = av1c_config_obus(data); + }); + } +} + +/// Configuration bytes of every codec, damaged, never panic the decoder that applies them. +#[test] +fn hostile_configuration_does_not_panic() { + let seeds: &[(CodecId, &[u8])] = &[ + #[cfg(feature = "h264-decode")] + (CodecId::H264, &[1, 0x42, 0xc0, 0x1e, 0xff, 0xe1, 0x00, 0x04, 0x67, 0x42, 0xc0, 0x1e, 0x01, 0x00, 0x02, 0x68, 0xce]), + #[cfg(feature = "h264-decode")] + (CodecId::H264, &[0, 0, 0, 1, 0x67, 0x42, 0xc0, 0x1e, 0, 0, 1, 0x68, 0xce]), + #[cfg(feature = "hevc-decode")] + (CodecId::Hevc, &[0, 0, 0, 1, 0x40, 0x01, 0x0c, 0, 0, 1, 0x42, 0x01, 0x01, 0, 0, 1, 0x44, 0x01, 0xc1]), + #[cfg(feature = "av1-decode")] + (CodecId::Av1, &[0x81, 0x00, 0x0c, 0x00, 0x0a, 0x0b, 0x00, 0x00, 0x00, 0x24, 0xc4, 0xff, 0xdf, 0x00, 0x68, 0x02, 0x10]), + #[cfg(feature = "mpeg2-decode")] + (CodecId::Mpeg2Video, &[0, 0, 1, 0xb3, 0x02, 0x00, 0x20, 0x13, 0xff, 0xff, 0xe0, 0x18, 0, 0, 1, 0xb5, 0x14, 0x8a, 0x00, 0x01, 0x00, 0x00]), + ]; + for &(codec, seed) in seeds { + craft_media_testkit::hostile::hammer(codec.name(), seed, 300, move |data| { + if let Ok(mut dec) = TrackDecoder::new(¶ms(codec, data)) { + let _ = dec.reset(); + } + }); + } +} + +#[cfg(feature = "h264-decode")] +mod held { + use super::*; + + /// A 4x2 picture with timestamp `pts`; `y_len` other than 8 makes it fail to convert. + fn picture(y_len: usize, pts: i64) -> h264::decode::Picture { + h264::decode::Picture { + width: 4, + height: 2, + chroma_width: 2, + chroma_height: 1, + y: vec![16; y_len], + u: vec![128; 2], + v: vec![128; 2], + y_stride: 4, + uv_stride: 2, + pts, + poc: 0, + key: true, + color: h264::decode::ColorInfo { full_range: false, primaries: 1, transfer: 1, matrix: 1 }, + sar: (0, 0), + draft: false, + } + } + + fn decoder() -> TrackDecoder { + TrackDecoder::new(¶ms(CodecId::H264, &[])).unwrap() + } + + fn pts(frames: &[VideoFrame]) -> Vec> { + frames.iter().map(|f| f.pts).collect() + } + + /// A picture that does not convert fails the call; the others come with the next call, ahead + /// of its own frames and in order. + #[test] + fn frames_around_a_picture_that_does_not_convert_come_next() { + let mut dec = decoder(); + let err = dec.output(vec![picture(8, 1), picture(3, 2), picture(8, 3)], None).unwrap_err(); + assert!(matches!(err, VideoError::Frame(FrameError::Plane(_))), "{err}"); + assert_eq!(pts(&dec.output(vec![picture(8, 4)], None).unwrap()), [Some(1), Some(3), Some(4)]); + assert!(dec.output(Vec::::new(), None).unwrap().is_empty()); + } + + /// An error reported with the pictures (a flush whose decoding job failed) keeps them too. + #[test] + fn frames_finished_with_an_error_come_next() { + let mut dec = decoder(); + let err = dec.output(vec![picture(8, 1)], Some(VideoError::Malformed("job".into()))).unwrap_err(); + assert!(matches!(err, VideoError::Malformed(_))); + assert_eq!(pts(&dec.flush().unwrap()), [Some(1)]); + } + + /// An error from the codec itself leaves the kept frames for the call after it. + #[test] + fn a_failed_packet_does_not_drop_kept_frames() { + let mut dec = decoder(); + assert!(dec.output(vec![picture(8, 1), picture(0, 2)], None).is_err()); + // an IDR slice without parameter sets + assert!(dec.decode(&[0, 0, 1, 0x65, 0x88, 0x84], 5).is_err()); + assert_eq!(pts(&dec.decode(&[], 6).unwrap()), [Some(1)]); + } + + #[test] + fn reset_drops_kept_frames() { + let mut dec = decoder(); + assert!(dec.output(vec![picture(8, 1), picture(0, 2)], None).is_err()); + dec.reset().unwrap(); + assert!(dec.flush().unwrap().is_empty()); + } +} diff --git a/crates/video/tests/track/av1.rs b/crates/video/tests/track/av1.rs new file mode 100644 index 0000000000..cef856f2bc --- /dev/null +++ b/crates/video/tests/track/av1.rs @@ -0,0 +1,72 @@ +//! AV1 in MP4 (an `av1C` record whose config OBUs hold the sequence header). + +use crate::common; +use craft_media::CodecId; + +/// libaom when ffmpeg has it, else SVT-AV1: a fixture name and the encoder arguments. +fn encoder() -> Option<(&'static str, &'static [&'static str])> { + if common::has_encoder("libaom-av1") { + Some(("av1_aom", &["-c:v", "libaom-av1", "-cpu-used", "8", "-b:v", "300k", "-g", "12", "-pix_fmt", "yuv420p"])) + } else if common::has_encoder("libsvtav1") { + Some(("av1_svt", &["-c:v", "libsvtav1", "-preset", "12", "-g", "12", "-pix_fmt", "yuv420p"])) + } else { + craft_media_testkit::skip("ffmpeg has neither libaom-av1 nor libsvtav1") + } +} + +fn fixture() -> Option<(common::Track, common::Fixture)> { + let (name, args) = encoder()?; + let f = common::fixture(name, "mp4", args, "yuv420p")?; + let track = common::mp4(&f.file); + assert_eq!(track.params.codec, CodecId::Av1); + Some((track, f)) +} + +/// The OBUs of a packet as (type, bytes); every OBU has a size field, as MP4 stores them. +fn obus(data: &[u8]) -> Vec<(u8, &[u8])> { + let mut out = Vec::new(); + let mut pos = 0; + while pos < data.len() { + let header = data[pos]; + assert!(header & 2 != 0, "an OBU without a size field"); + let mut p = pos + 1 + usize::from(header & 4 != 0); + let mut size = 0usize; + for i in 0.. { + let b = data[p]; + p += 1; + size |= usize::from(b & 0x7f) << (7 * i); + if b & 0x80 == 0 { + break; + } + } + out.push(((header >> 3) & 0xf, &data[pos..p + size])); + pos = p + size; + } + out +} + +#[test] +fn mp4_av1c() { + let Some((track, f)) = fixture() else { return }; + common::check_track(&track, &f); +} + +/// With every sequence header taken out of the packets, the one in `av1C` is what decodes them. +/// +/// The record's config OBUs are the stream's own sequence header: SVT-AV1 writes `av1C` before it +/// encodes, with a sequence header that differs from the one it then puts in the stream. +#[test] +fn sequence_header_from_av1c() { + let Some((mut track, f)) = fixture() else { return }; + let header = obus(&track.packets[0].data).into_iter().find(|o| o.0 == 1).unwrap().1.to_vec(); + track.params.extradata = [&track.params.extradata[..4], &header].concat(); + for p in &mut track.packets { + p.data = obus(&p.data).into_iter().filter(|o| o.0 != 1).flat_map(|o| o.1.to_vec()).collect(); + } + let mut bare = track.clone(); + bare.params.extradata.clear(); + let mut dec = craft_video::TrackDecoder::new(&bare.params).unwrap(); + let decoded = bare.packets.iter().filter_map(|p| dec.decode(&p.data, p.pts).ok()).flatten().count(); + assert_eq!(decoded, 0, "the packets decode without a sequence header"); + common::check_track(&track, &f); +} diff --git a/crates/video/tests/track/common/mod.rs b/crates/video/tests/track/common/mod.rs new file mode 100644 index 0000000000..bd3f144615 --- /dev/null +++ b/crates/video/tests/track/common/mod.rs @@ -0,0 +1,201 @@ +//! Fixtures (ffmpeg encodes a short clip into a container), demuxing with craft-media, ffmpeg's +//! own decode of each fixture as the reference, and the checks every codec runs. +#![allow(dead_code)] + +use craft_media::CodecParams; +use craft_video::TrackDecoder; +use craft_video::frame::{Samples, VideoFrame}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Frames in every fixture. +pub const FRAMES: usize = 24; + +/// One packet of a demuxed track, in decode order. +#[derive(Clone)] +pub struct Packet { + pub data: Vec, + pub pts: i64, + /// The container marks it as a random access point. + pub key: bool, +} + +/// A demuxed video track. +#[derive(Clone)] +pub struct Track { + pub params: CodecParams, + pub packets: Vec, +} + +/// A fixture and ffmpeg's decode of it. +pub struct Fixture { + pub file: PathBuf, + /// Raw frames in display order, planes one after another, 16-bit samples little-endian. + pub reference: Vec, + /// How far a sample may be from the reference: 0 (bit-exact) unless a test sets it. + pub max_diff: u8, +} + +/// Lowest PSNR of a frame decoded within a tolerance, as the MPEG-2 oracle tests require. +const MIN_PSNR: f64 = 58.0; + +/// `name.ext` made by ffmpeg from 24 frames of a noisy test pattern at 176x144, with `args` +/// choosing the encoder, and its decode as `pix_fmt` raw video. `None` (a skip) without ffmpeg or +/// the encoder; a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`. +pub fn fixture(name: &str, ext: &str, args: &[&str], pix_fmt: &str) -> Option { + let ff = craft_media_testkit::ffmpeg()?; + let dir = craft_media_testkit::fixture_subdir("video-track"); + let required = craft_media_testkit::oracles_required(); + let file = dir.join(format!("{name}.{ext}")); + let raw = dir.join(format!("{name}.{ext}.{pix_fmt}.raw")); + craft_media_testkit::generate_and_report(name, &[file.clone(), raw.clone()], || { + if !file.exists() { + let tmp = craft_media_testkit::temp_path(&file); + let mut cmd = Command::new(&ff); + cmd.args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i"]) + .arg("testsrc2=size=176x144:rate=25,noise=alls=12:allf=t+u") + .args(["-frames:v", &FRAMES.to_string(), "-an"]) + .args(args) + .arg(&tmp); + craft_media_testkit::run_generator(&mut cmd, &tmp, &file, required)?; + } + if !raw.exists() { + let tmp = craft_media_testkit::temp_path(&raw); + let mut cmd = Command::new(&ff); + cmd.args(["-hide_banner", "-loglevel", "error", "-y", "-i"]) + .arg(&file) + .args(["-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt]) + .arg(&tmp); + craft_media_testkit::run_generator(&mut cmd, &tmp, &raw, required)?; + } + Some(Fixture { reference: std::fs::read(&raw).unwrap(), file: file.clone(), max_diff: 0 }) + }) +} + +/// Whether ffmpeg has `encoder`, without skipping. +pub fn has_encoder(encoder: &str) -> bool { + craft_media_testkit::tool("ffmpeg").is_some_and(|ff| craft_media_testkit::ffmpeg_has_encoder(&ff, encoder)) +} + +/// The video track of an MP4 file. +pub fn mp4(path: &Path) -> Track { + use craft_media::isobmff::{TrackKind, open}; + let bytes = std::fs::read(path).unwrap(); + let file = open(bytes.as_slice()).unwrap(); + let t = file.track_of_kind(TrackKind::Video).unwrap(); + let track = &file.tracks[t]; + let packets = (track.samples.iter().enumerate()) + .map(|(i, s)| Packet { data: file.read_sample(bytes.as_slice(), t, i).unwrap(), pts: s.pts, key: s.is_sync }) + .collect(); + Track { params: track.codec_params(), packets } +} + +/// The video stream of an MPEG transport stream. +pub fn ts(path: &Path) -> Track { + use craft_media::mpegts::{Kind, open}; + let bytes = std::fs::read(path).unwrap(); + let file = open(bytes.as_slice()).unwrap(); + let s = file.find(Kind::Video, |_| true).unwrap(); + let stream = &file.streams[s]; + let packets = (stream.units.iter().enumerate()) + .map(|(i, u)| Packet { data: file.read_unit(bytes.as_slice(), s, i).unwrap(), pts: u.pts.unwrap(), key: u.key }) + .collect(); + Track { params: stream.codec_params(), packets } +} + +/// The video stream of an AVI file. AVI has no timestamps: a chunk's index stands in. +pub fn avi(path: &Path) -> Track { + use craft_media::avi::{StreamKind, open}; + let bytes = std::fs::read(path).unwrap(); + let file = open(bytes.as_slice()).unwrap(); + let s = file.streams.iter().position(|s| s.kind == StreamKind::Video).unwrap(); + let stream = &file.streams[s]; + let packets = (stream.chunks.iter().enumerate()) + .map(|(i, c)| Packet { data: file.read_chunk(bytes.as_slice(), s, i).unwrap(), pts: i as i64, key: c.key }) + .collect(); + Track { params: stream.codec_params(), packets } +} + +/// Decode `packets` with `dec` and flush it. +pub fn run(dec: &mut TrackDecoder, packets: &[Packet]) -> Vec { + let mut frames = Vec::new(); + for (i, p) in packets.iter().enumerate() { + frames.extend(dec.decode(&p.data, p.pts).unwrap_or_else(|e| panic!("packet {i}: {e}"))); + } + frames.extend(dec.flush().unwrap()); + frames +} + +/// Every frame of `track`, from a new decoder. +pub fn decode(track: &Track) -> Vec { + run(&mut TrackDecoder::new(&track.params).unwrap(), &track.packets) +} + +/// The samples of `frame`, planes one after another, as ffmpeg's raw video has them: a byte per +/// sample up to 8 bits (whatever the storage; AV1 stores 8-bit samples in `u16`), else two bytes +/// little-endian. +pub fn frame_bytes(frame: &VideoFrame) -> Vec { + let mut out = Vec::new(); + for p in frame.planes() { + for y in 0..p.height() { + match p.samples() { + Samples::U8(_) => out.extend_from_slice(p.row_u8(y).unwrap()), + Samples::U16(_) if p.bit_depth() <= 8 => out.extend(p.row_u16(y).unwrap().iter().map(|&s| u8::try_from(s).unwrap())), + Samples::U16(_) => out.extend(p.row_u16(y).unwrap().iter().flat_map(|s| s.to_le_bytes())), + } + } + } + out +} + +/// `frames` are every frame of `track` in display order, each with the timestamp of the packet +/// that coded it, and their samples are ffmpeg's (within `fixture.max_diff`). +pub fn check_frames(track: &Track, frames: &[VideoFrame], fixture: &Fixture) { + let reference = &fixture.reference; + assert_eq!(frames.len(), FRAMES, "frame count"); + let got: Vec = frames.iter().map(|f| f.pts.unwrap()).collect(); + let mut want: Vec = track.packets.iter().map(|p| p.pts).collect(); + want.sort_unstable(); + assert_eq!(got, want, "timestamps in display order"); + let size = reference.len() / FRAMES; + assert_eq!(size * FRAMES, reference.len(), "reference size"); + for (i, (frame, want)) in frames.iter().zip(reference.chunks(size)).enumerate() { + assert_eq!((frame.width(), frame.height()), (176, 144), "frame {i} size"); + let got = frame_bytes(frame); + assert_eq!(got.len(), want.len(), "frame {i} bytes"); + let diff: Vec = (0..got.len()).filter(|&k| got[k] != want[k]).collect(); + let max = diff.iter().map(|&k| got[k].abs_diff(want[k])).max().unwrap_or(0); + let what = format!("frame {i} (pts {:?}): {} of {} bytes differ from ffmpeg's decode, by up to {max}", frame.pts, diff.len(), got.len()); + if fixture.max_diff == 0 { + assert!(diff.is_empty(), "{what}"); + } else { + let sse: f64 = diff.iter().map(|&k| f64::from(got[k].abs_diff(want[k])).powi(2)).sum(); + let psnr = if sse == 0.0 { f64::INFINITY } else { 10.0 * (255.0f64.powi(2) * got.len() as f64 / sse).log10() }; + assert!(max <= fixture.max_diff && psnr >= MIN_PSNR, "{what}, PSNR {psnr:.1} dB"); + } + } +} + +/// Decode `track`, check it against `fixture`'s reference, then reset the decoder twice: once +/// halfway through, decoding the whole track again, and once to decode from its last key packet +/// (a seek), which gives the frames of the packets from there on. +pub fn check_track(track: &Track, fixture: &Fixture) { + let frames = decode(track); + check_frames(track, &frames, fixture); + + let mut dec = TrackDecoder::new(&track.params).unwrap(); + let half = track.packets.len() / 2; + for p in &track.packets[..half] { + dec.decode(&p.data, p.pts).unwrap(); + } + dec.reset().unwrap(); + assert!(run(&mut dec, &track.packets) == frames, "decoding again after a reset"); + + let key = track.packets.iter().rposition(|p| p.key).unwrap(); + assert!(key > 0, "the track has a second key packet"); + dec.reset().unwrap(); + let seek = run(&mut dec, &track.packets[key..]); + let pts: Vec = track.packets[key..].iter().map(|p| p.pts).collect(); + let want: Vec<&VideoFrame> = frames.iter().filter(|f| pts.contains(&f.pts.unwrap())).collect(); + assert!(seek.iter().eq(want.iter().copied()), "decoding from key packet {key} after a reset"); +} diff --git a/crates/video/tests/track/h264.rs b/crates/video/tests/track/h264.rs new file mode 100644 index 0000000000..74a9477de6 --- /dev/null +++ b/crates/video/tests/track/h264.rs @@ -0,0 +1,63 @@ +//! H.264 in MP4 (an `avcC` record, length-prefixed packets), MPEG-TS (Annex B, no configuration) +//! and AVI with the parameter sets in the stream header only (an Annex B configuration). + +use crate::common; +use craft_media::CodecId; +use craft_video::{TrackDecoder, VideoError}; + +const X264: &[&str] = &["-c:v", "libx264", "-preset", "fast", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p"]; + +/// The NAL unit types of an Annex B packet. +fn nal_types(data: &[u8]) -> Vec { + craft_media::bitstream::annexb_nals(data).iter().filter_map(|n| n.first()).map(|b| b & 0x1f).collect() +} + +/// The parameter sets are in the `avcC` record only, so decoding again after a reset needs them +/// applied again. +#[test] +fn mp4_avcc() { + let Some(f) = common::fixture("h264_avcc", "mp4", X264, "yuv420p") else { return }; + let track = common::mp4(&f.file); + assert_eq!((track.params.codec, track.params.extradata.first()), (CodecId::H264, Some(&1)), "an avcC record"); + common::check_track(&track, &f); +} + +#[test] +fn ts_annex_b() { + let Some(f) = common::fixture("h264", "ts", X264, "yuv420p") else { return }; + let track = common::ts(&f.file); + assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::H264, 0)); + common::check_track(&track, &f); +} + +fn global_header_avi() -> Option<(common::Track, common::Fixture)> { + let args = ["-c:v", "libx264", "-preset", "fast", "-bf", "0", "-g", "12", "-pix_fmt", "yuv420p", "-flags", "+global_header"]; + let f = common::fixture("h264_global_header", "avi", &args, "yuv420p")?; + let track = common::avi(&f.file); + assert_eq!(track.params.codec, CodecId::H264); + assert_eq!(nal_types(&track.params.extradata).iter().filter(|&&t| t == 7 || t == 8).count(), 2, "an SPS and a PPS in the stream header"); + for (i, p) in track.packets.iter().enumerate() { + assert!(!nal_types(&p.data).contains(&7), "chunk {i} repeats the SPS"); + } + Some((track, f)) +} + +/// AVI written with global headers: the chunks need the parameter sets from the stream header. +#[test] +fn avi_annex_b_configuration() { + let Some((track, f)) = global_header_avi() else { return }; + common::check_track(&track, &f); +} + +/// Annex B configuration with the first picture's slice after the parameter sets is refused, +/// rather than decoding that picture into the reference store. +#[test] +fn annex_b_configuration_with_a_slice_is_refused() { + let Some((mut track, _)) = global_header_avi() else { return }; + track.params.extradata.extend_from_slice(&track.packets[0].data); + assert!(nal_types(&track.params.extradata).contains(&5), "an IDR slice"); + match TrackDecoder::new(&track.params) { + Err(VideoError::Malformed(m)) => assert!(m.contains("NAL unit type 5"), "{m}"), + other => panic!("{other:?}"), + } +} diff --git a/crates/video/tests/track/hevc.rs b/crates/video/tests/track/hevc.rs new file mode 100644 index 0000000000..ac2cf672d9 --- /dev/null +++ b/crates/video/tests/track/hevc.rs @@ -0,0 +1,68 @@ +//! HEVC in MP4 (an `hvcC` record, length-prefixed packets) and MPEG-TS (Annex B, no +//! configuration), 8-bit and 10-bit. + +use crate::common; +use craft_media::CodecId; + +/// Closed GOPs every 12 frames with B-frames, so decoding from a key packet gives every frame +/// from there on. +const X265: &[&str] = &["-c:v", "libx265", "-preset", "fast", "-x265-params", "log-level=error:keyint=12:min-keyint=12:open-gop=0:bframes=2"]; + +fn args(pix_fmt: &str, mp4: bool) -> Vec<&str> { + let mut a = X265.to_vec(); + a.extend(["-pix_fmt", pix_fmt]); + if mp4 { + a.extend(["-tag:v", "hvc1"]); + } + a +} + +/// The parameter sets are in the `hvcC` record only, so decoding again after a reset needs them +/// applied again. +#[test] +fn mp4_hvcc() { + let Some(f) = common::fixture("hevc_hvcc", "mp4", &args("yuv420p", true), "yuv420p") else { return }; + let track = common::mp4(&f.file); + assert_eq!((track.params.codec, track.params.extradata.first()), (CodecId::Hevc, Some(&1)), "an hvcC record"); + common::check_track(&track, &f); +} + +#[test] +fn mp4_hvcc_10bit() { + let Some(f) = common::fixture("hevc_hvcc_10bit", "mp4", &args("yuv420p10le", true), "yuv420p10le") else { return }; + let track = common::mp4(&f.file); + let frames = common::decode(&track); + assert!(frames.iter().all(|f| f.bit_depth() == 10)); + common::check_track(&track, &f); +} + +#[test] +fn ts_annex_b() { + let Some(f) = common::fixture("hevc", "ts", &args("yuv420p", false), "yuv420p") else { return }; + let track = common::ts(&f.file); + assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::Hevc, 0)); + common::check_track(&track, &f); +} + +/// The NAL unit types of an Annex B packet. +fn nal_types(data: &[u8]) -> Vec { + craft_media::bitstream::annexb_nals(data).iter().filter_map(|n| n.first()).map(|b| (b >> 1) & 0x3f).collect() +} + +/// AVI written with global headers: the chunks need the VPS, SPS and PPS from the stream header. +/// (ffmpeg writes an empty FourCC for HEVC in AVI unless it is given one.) +#[test] +fn avi_annex_b_configuration() { + // AVI has no timestamps (a chunk's index stands in), so no B-frames. + let params = "log-level=error:keyint=12:min-keyint=12:open-gop=0:bframes=0"; + let a = ["-c:v", "libx265", "-preset", "fast", "-x265-params", params, "-pix_fmt", "yuv420p", "-flags", "+global_header", "-tag:v", "HEVC"]; + let Some(f) = common::fixture("hevc_global_header", "avi", &a, "yuv420p") else { return }; + let track = common::avi(&f.file); + assert_eq!(track.params.codec, CodecId::Hevc); + let sets = nal_types(&track.params.extradata); + assert!([32, 33, 34].iter().all(|t| sets.contains(t)), "a VPS, an SPS and a PPS in the stream header: {sets:?}"); + for (i, p) in track.packets.iter().enumerate() { + assert!(!nal_types(&p.data).contains(&33), "chunk {i} repeats the SPS"); + } + common::check_track(&track, &f); +} diff --git a/crates/video/tests/track/main.rs b/crates/video/tests/track/main.rs new file mode 100644 index 0000000000..425302df49 --- /dev/null +++ b/crates/video/tests/track/main.rs @@ -0,0 +1,18 @@ +//! `TrackDecoder` on real streams: ffmpeg encodes a short clip into MP4, MPEG-TS or AVI, +//! craft-media demuxes it, and the decoder's frames must be ffmpeg's decode of the file, in display +//! order, with the timestamps of the packets that coded them. Each codec also checks that a reset +//! decodes the track again and decodes from a later key packet. +#![cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))] + +mod common; + +#[cfg(feature = "av1-decode")] +mod av1; +#[cfg(feature = "h264-decode")] +mod h264; +#[cfg(feature = "hevc-decode")] +mod hevc; +#[cfg(feature = "mpeg2-decode")] +mod mpeg2; +#[cfg(feature = "vp9-decode")] +mod vp9; diff --git a/crates/video/tests/track/mpeg2.rs b/crates/video/tests/track/mpeg2.rs new file mode 100644 index 0000000000..e0fc193289 --- /dev/null +++ b/crates/video/tests/track/mpeg2.rs @@ -0,0 +1,55 @@ +//! MPEG-2 video in MPEG-TS (no configuration), and with its sequence header moved from the +//! packets into `extradata`. + +use crate::common; +use craft_media::CodecId; + +/// Closed GOPs every 12 frames with B-frames (ffmpeg's encoder needs scene change detection off +/// for closed GOPs). +const MPEG2: &[&str] = + &["-c:v", "mpeg2video", "-bf", "2", "-g", "12", "-flags", "+cgop", "-sc_threshold", "1000000000", "-q:v", "4", "-pix_fmt", "yuv420p"]; + +/// MPEG-2's IDCT is not bit-exact by definition (any IEEE 1180-accurate IDCT conforms), so the +/// frames are compared with ffmpeg's within the MPEG-2 oracle tests' tolerance. +fn fixture() -> Option<(common::Track, common::Fixture)> { + let mut f = common::fixture("mpeg2", "ts", MPEG2, "yuv420p")?; + f.max_diff = 4; + let track = common::ts(&f.file); + assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::Mpeg2Video, 0)); + Some((track, f)) +} + +/// The byte range of the sequence header and its extensions in `data`: from the sequence header +/// start code to the next start code that is not an extension. +fn sequence_header(data: &[u8]) -> Option> { + let codes: Vec<(usize, u8)> = (0..data.len().saturating_sub(3)).filter(|&i| data[i..i + 3] == [0, 0, 1]).map(|i| (i, data[i + 3])).collect(); + let k = codes.iter().position(|c| c.1 == 0xb3)?; + let end = codes[k + 1..].iter().find(|c| c.1 != 0xb5).map_or(data.len(), |c| c.0); + Some(codes[k].0..end) +} + +#[test] +fn ts() { + let Some((track, f)) = fixture() else { return }; + common::check_track(&track, &f); +} + +/// With every sequence header taken out of the packets, the one in `extradata` is what decodes +/// them, before and after a reset. +#[test] +fn sequence_header_from_extradata() { + let Some((mut track, f)) = fixture() else { return }; + let first = sequence_header(&track.packets[0].data).unwrap(); + track.params.extradata = track.packets[0].data[first].to_vec(); + for p in &mut track.packets { + while let Some(r) = sequence_header(&p.data) { + p.data.drain(r); + } + } + let mut bare = track.clone(); + bare.params.extradata.clear(); + let mut dec = craft_video::TrackDecoder::new(&bare.params).unwrap(); + let decoded = bare.packets.iter().filter_map(|p| dec.decode(&p.data, p.pts).ok()).flatten().count(); + assert_eq!(decoded, 0, "the packets decode without a sequence header"); + common::check_track(&track, &f); +} diff --git a/crates/video/tests/track/vp9.rs b/crates/video/tests/track/vp9.rs new file mode 100644 index 0000000000..3fd75484c0 --- /dev/null +++ b/crates/video/tests/track/vp9.rs @@ -0,0 +1,14 @@ +//! VP9 in MP4 (a `vpcC` record, which the decoder does not need). + +use crate::common; +use craft_media::CodecId; + +#[test] +fn mp4() { + let args = ["-c:v", "libvpx-vp9", "-deadline", "good", "-cpu-used", "5", "-b:v", "400k", "-g", "12", "-pix_fmt", "yuv420p"]; + let Some(f) = common::fixture("vp9", "mp4", &args, "yuv420p") else { return }; + let track = common::mp4(&f.file); + assert_eq!(track.params.codec, CodecId::Vp9); + assert!(!track.params.extradata.is_empty(), "a vpcC record"); + common::check_track(&track, &f); +} From 7aaa2f80100143c854f38cdb31498c68396096ce Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Wed, 18 Nov 2026 20:26:00 -0800 Subject: [PATCH 24/79] craft-media: mpegts::mux writes MPEG-2 transport streams frame by frame to any io::Write (#1998) * craft-media: mpegts::mux writes MPEG-2 transport streams frame by frame to any io::Write The mpegts feature gains a transport stream writer (ITU-T H.222.0 | ISO/IEC 13818-1) next to the demuxer: - PAT and PMT with the CRC-32 the demuxer checks (ts::crc32_mpeg), at the start, every psi_interval, directly before video keyframes, and after replace_writer and discontinuity; a PMT longer than one packet spans packets. - One PES packet per frame for H.264, HEVC, MPEG-1, MPEG-2 and MPEG-4 Part 2 video, AV1 (Carriage of AV1 in MPEG-2 TS), AAC (ADTS, or raw frames given an ADTS header), Opus (Opus transport draft V0.1.3, including explicit channel mappings and trims), AC-3, E-AC-3 and MPEG audio, with PTS and DTS modulo 2^33. - The PCR on a stream's PID or its own, at most pcr_interval apart (100 ms at most), PCR-only packets in gaps, advance() for idle live outputs, continuity counters, random access and discontinuity indicators. - Packets go out in batches of batch_packets (7 by default) built in fixed buffers; replace_writer returns per-segment facts. - Frames are checked before anything is written; video frames are limited to MAX_UNIT_BYTES so the demuxer reads every one back. Tests read every codec back with the demuxer (bytes, PTS, DTS, keyframes, PCR range, no continuity or CRC warnings), check the PES header bits and the refusals, and fuzz programs, timelines, idle gaps and output swaps. * craft-media: mpegts::mux leaves out zero-ended AV1 padding and refuses 960-sample AAC configs An AV1 padding OBU that ends with a zero byte, an empty one included, is now left out like a temporal delimiter instead of failing the whole temporal unit. Decoders ignore padding, and the trailing zero would otherwise form a forbidden sequence with the next start code. Codec::aac_from_asc refuses an AudioSpecificConfig with frameLengthFlag 1: an ADTS header has no field for 960-sample frames, so decoders would read the stream as 1024-sample frames. * craft-media: the transport stream packet checker refuses a PCR flag in an adaptation field shorter than seven bytes * craft-media: README states the multistream layout for 3 to 8 channel Opus An Opus { channels } access unit is one Opus packet for 1 or 2 channels. For 3 to 8 channels it holds the mapping family 1 streams in the order of table 4-3 of the Opus transport draft, every stream but the last self-delimited (RFC 6716 Appendix B). The README now says so, matching the Codec::Opus doc comment. --- crates/media/Cargo.toml | 13 +- crates/media/README.md | 118 +- crates/media/src/lib.rs | 2 +- crates/media/src/mpegts/mod.rs | 2 + crates/media/src/mpegts/mux/av1.rs | 232 ++++ crates/media/src/mpegts/mux/mod.rs | 1192 +++++++++++++++++++++ crates/media/src/mpegts/mux/pes.rs | 389 +++++++ crates/media/src/mpegts/mux/psi.rs | 216 ++++ crates/media/src/mpegts/mux/tests.rs | 915 ++++++++++++++++ crates/media/tests/mpegts_mux/mod.rs | 260 +++++ crates/media/tests/mpegts_mux_fuzz.rs | 229 ++++ crates/media/tests/mpegts_mux_readback.rs | 356 ++++++ 12 files changed, 3918 insertions(+), 6 deletions(-) create mode 100644 crates/media/src/mpegts/mux/av1.rs create mode 100644 crates/media/src/mpegts/mux/mod.rs create mode 100644 crates/media/src/mpegts/mux/pes.rs create mode 100644 crates/media/src/mpegts/mux/psi.rs create mode 100644 crates/media/src/mpegts/mux/tests.rs create mode 100644 crates/media/tests/mpegts_mux/mod.rs create mode 100644 crates/media/tests/mpegts_mux_fuzz.rs create mode 100644 crates/media/tests/mpegts_mux_readback.rs diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 929aa9a24a..612c3e035e 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-media" -description = "Bit-level I/O, clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) and MXF demuxers and muxers, and Ogg, AVI and MPEG-TS/PS demuxers." +description = "Bit-level I/O, clean-room ISO BMFF (MP4), QuickTime (MOV) and Matroska (MKV, WebM) and MXF demuxers and muxers, an MPEG-TS/PS demuxer and MPEG-TS muxer, and Ogg and AVI demuxers." version.workspace = true edition.workspace = true license.workspace = true @@ -22,7 +22,8 @@ matroska = [] avi = [] # MXF demuxer and writer (`craft_media::mxf`); the writer formats dates with chrono. mxf = ["dep:chrono"] -# MPEG-2 Systems demuxer: transport streams and program streams (`craft_media::mpegts`). +# MPEG-2 Systems demuxer: transport streams and program streams (`craft_media::mpegts`), and the +# transport stream writer (`craft_media::mpegts::mux`). mpegts = [] # Sierra VMD (Video and Music Data) demuxer (`craft_media::vmd`). vmd = [] @@ -69,6 +70,14 @@ required-features = ["matroska"] name = "oracle_mpegts" required-features = ["mpegts"] +[[test]] +name = "mpegts_mux_fuzz" +required-features = ["mpegts"] + +[[test]] +name = "mpegts_mux_readback" +required-features = ["mpegts"] + [[test]] name = "oracle_mux" required-features = ["isobmff"] diff --git a/crates/media/README.md b/crates/media/README.md index 16ad74434c..a90b559932 100644 --- a/crates/media/README.md +++ b/crates/media/README.md @@ -1,8 +1,9 @@ # craft-media Media containers and bit-level I/O for the Craft apps: an MSB-first bit reader and writer, -clean-room ISO BMFF (MP4), QuickTime (MOV), Matroska (MKV, WebM), MXF and AVI demuxers and muxers, and -Ogg, MPEG-2 Systems (transport and program stream) and Sierra VMD demuxers, written from the public specifications. No `unsafe`, no panics on malformed +clean-room ISO BMFF (MP4), QuickTime (MOV), Matroska (MKV, WebM), MXF and AVI demuxers and muxers, +an MPEG-2 Systems (transport and program stream) demuxer and transport stream muxer, and Ogg and +Sierra VMD demuxers, written from the public specifications. No `unsafe`, no panics on malformed input, builds for `wasm32-unknown-unknown`. Dependencies: `thiserror` (for `isobmff`), `chrono` (for `mxf`), `serde` (optional). @@ -549,7 +550,8 @@ FourCC, size, frame rate, packet count, audio format and duration. A clean-room MPEG-2 Systems demuxer from FilmCraft's `filmcraft-mpegts` (storytold/filmcraft@4bec22b): transport streams (188-byte, 192-byte BDAV / M2TS, 204-byte) and program streams (MPEG-1/2 PS, VOB, MOD). No GPL/LGPL code (FFmpeg, libavformat) was consulted; -FFmpeg is a fixture generator and test oracle only. No muxer, no decoding. +FFmpeg is a fixture generator and test oracle only. No decoding. The transport stream writer is +`mpegts::mux` ([below](#transport-stream-writer)). ```rust use craft_media::mpegts::{Kind, open}; @@ -637,6 +639,116 @@ helpers on arbitrary bytes. `tests/oracle_mpegts.rs` compares ten ffmpeg-made fi and HEVC video; MP2, ADTS and LATM AAC, AC-3, E-AC-3, Blu-ray and DVD LPCM; TS, M2TS, VOB and MPEG-1 system streams) with ffprobe's packets: unit counts, sizes, timestamps and key flags. +### Transport stream writer + +`mpegts::mux::Muxer` writes one program to any `std::io::Write` as frames arrive, so the same code +writes `.ts` files, HLS segments and SRT payloads. Its `Codec`, `Stream` and `Error` types are its +own, separate from the demuxer's. + +```rust +use craft_media::mpegts::mux::{Codec, Config, Frame, Muxer, Stream}; + +let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)]; +let mut ts = Muxer::new(Vec::new(), Config::default(), &streams)?; +let idr = [0, 0, 0, 1, 0x65, 0x88, 0x84]; +ts.write_frame(0, &Frame { data: &idr, pts: 90_000, dts: None, key: true })?; +let bytes = ts.finish()?; +assert_eq!(bytes.len() % 188, 0); +``` + +- A program association section and a program map section, each ending with its CRC-32. They are + written at the start, every `Config::psi_interval`, before every video keyframe when + `Config::psi_before_keyframes` is set, and before the first frame after `Muxer::replace_writer` + or `Muxer::discontinuity`. +- One PES packet per frame, with PTS and, when it differs from the PTS, DTS: + + | `Codec` | stream_type | stream_id | Frames passed in | + |---|---|---|---| + | `H264` | 0x1B | 0xE0 | Annex B access units; an access unit delimiter is added when missing | + | `Hevc` | 0x24 | 0xE0 | Annex B access units; an access unit delimiter is added when missing | + | `Mpeg2Video` | 0x02 | 0xE0 | MPEG-2 pictures from their first start code | + | `Mpeg1Video` | 0x01 | 0xE0 | MPEG-1 pictures from their first start code | + | `Mpeg4Part2` | 0x10 | 0xE0 | MPEG-4 Part 2 visual frames from their first start code | + | `Av1(Av1Config)` | 0x06 | 0xBD | temporal units in the low overhead format (every OBU has `obu_size`) | + | `AacAdts` | 0x0F | 0xC0 | ADTS frames; their `frame_length` fields must tile the frame | + | `Aac { .. }` | 0x0F | 0xC0 | raw AAC frames; the writer adds the ADTS header | + | `Opus { channels }` | 0x06 | 0xBD | Opus access units, 1 to 8 channels; the writer adds the Opus control header | + | `OpusMapped(OpusMapping)` | 0x06 | 0xBD | Opus multistream access units with an explicit channel mapping | + | `Ac3` | 0x81 | 0xBD | AC-3 sync frames | + | `Eac3` | 0x87 | 0xBD | E-AC-3 sync frames (bsid 11 to 16) | + | `MpegAudio { low_sample_rate }` | 0x03 or 0x04 | 0xC0 | MPEG audio frames, layers I to III, whose version matches the stream type | + + `Codec::aac_from_asc` turns an AudioSpecificConfig into the `Aac` fields, and refuses one that + an ADTS header cannot carry (frameLengthFlag 1, for one). An `Opus { channels }` access unit is + one Opus packet for 1 or 2 channels. For 3 to 8 channels it holds the streams of mapping family 1 + in the order that table 4-3 of the Opus transport draft gives, and every stream but the last uses + the self-delimited framing of RFC 6716 Appendix B. `OpusMapped` takes any other layout. +- Descriptors in the program map section: a registration descriptor `AC-3` or `EAC3` on AC-3 and + E-AC-3 streams; a registration descriptor `Opus` and an extension descriptor (tag 0x7F, + extension tag 0x80) on Opus streams, whose channel_config_code is the channel count for + `Opus { channels }` and 0x81 with the mapping family, stream counts and channel mapping for + `OpusMapped`; a registration descriptor `AV01` and the AV1 video descriptor (tag 0x80) built + from `Av1Config` (`Av1Config::from_av1c` reads an AV1CodecConfigurationRecord); and an + ISO 639 language descriptor on any stream that has a language. +- For AV1, each OBU follows the start code 0x000001 with emulation prevention bytes, temporal + delimiters and padding OBUs that end with a zero byte are left out, and each PES packet holds + one temporal unit. A keyframe must carry a + sequence header, and tile list OBUs are refused. +- For Opus, `Muxer::write_frame_with_trim` writes the control header's start and end trims (each + at most 8 191 samples, `MAX_OPUS_TRIM`). A start trim is allowed only while every earlier frame + of the stream was trimmed whole, 65 535 samples in all. +- The PCR on `Config::pcr_pid`: one of the streams' PIDs, or a PID that carries only PCRs. PCRs + are never more than `Config::pcr_interval` apart (at most 100 ms, H.222.0 §2.7.2). The PCR is + the largest DTS so far minus `Config::pcr_delay`, 1 to 90 000 ticks (`MAX_PCR_DELAY`, the + one-second limit of §2.4.2.6). A live output calls `Muxer::advance` while no frames arrive; its + time is on the DTS scale, so the PCR it writes is that time minus `pcr_delay`. +- A continuity counter per PID, the random access indicator on keyframes, adaptation field + stuffing, and timestamps written modulo 2^33. `Muxer::discontinuity` starts a new time base: + the next packet of every stream PID and of the PCR PID sets the discontinuity_indicator + (§2.4.3.5), and timestamps may then go back. + +Packets go to the output in batches of `Config::batch_packets` (7 by default, 1 316 bytes, one UDP +datagram), each in one `write` call, and the rest of a batch at the end of every `write_frame` and +`advance` unless `Config::hold_packets` is set. The batch is allocated once, in `Muxer::new`. After +an `Error::Io` the output may hold part of a packet; `Stats::packets` counts only whole packets. +`Muxer::replace_writer` returns the old output in a `Segment` (packet and frame counts, first and +last PTS, whether it starts with a keyframe, any error from its last packets), and the new output +starts with the PAT, the PMT and a PCR. `Muxer::replace_writer_continuing` swaps the output +without adding them. + +Frames are checked before anything is written. A stream's DTS must not go back, a video stream's +DTS must increase, a DTS may not be after its PTS, and a frame may be at most `pcr_delay` behind +the largest DTS written so far (`Error::Timestamp`). Audio frames must fit in one PES packet, and +video frames are at most `MAX_VIDEO_FRAME` (`MAX_UNIT_BYTES`, counting the start codes and escape +bytes the writer adds; `Error::FrameTooLarge`). A program has 1 to 32 streams on PIDs 0x0010 to +0x1FFE (`Error::BadPid`, `Error::DuplicatePid`), and its program map section is at most 1 021 bytes +(`Error::PsiTooLarge`). A gap in the timeline longer than `MAX_PCR_FILL` PCR intervals gets one PCR +at its end and is counted in `Stats::pcr_gaps`. + +`Config::default()`: program 1 with its PMT on PID 0x1000, the PCR on the first video stream (or +the first stream) every 40 ms and 700 ms behind the DTS, the PAT and PMT every 100 ms and before +keyframes, and writes of 7 packets. + +Gaps: one program per stream; no null packets (no constant bit rate); not written: LPCM (H.222.0 +defines no LPCM stream type for transport streams), AAC in LATM, DTS, subtitles and teletext. The +demuxer reads Opus and AV1 streams as `Unknown(6)` and MPEG-4 Part 2 as `Unknown(0x10)`, one unit +per PES packet. + +Specifications: the ones above, and Opus Interactive Audio Codec Transport Multiplexing Standard, +draft TS V0.1.3 (2015-10), for the Opus control header and descriptors; RFC 6716 for Opus packet +durations and self-delimited framing; Carriage of AV1 in MPEG-2 TS (Alliance for Open Media +working draft) and the AV1 Bitstream & Decoding Process Specification for AV1; ISO/IEC 14496-3 +for the AudioSpecificConfig; ATSC A/52 for the AC-3 and E-AC-3 stream types and registration +descriptors. + +Tests: `tests/mpegts_mux_readback.rs` reads the output back with the demuxer: streams, codecs, +languages, every frame's bytes, PTS and DTS, keyframes and the PCR range, with no continuity or +CRC warnings, including AV1 units, Opus with an explicit mapping and a start trim, both sides of a +discontinuity, and the output that follows an I/O error. `tests/mpegts_mux_fuzz.rs` muxes random +programs and timelines with idle gaps and output swaps and reads them back, and feeds random bytes +to every codec. Unit tests check every PES header's fixed bits, the sections' CRC, and that every +refused frame writes nothing. + ## `mxf` A clean-room MXF demuxer and writer from FilmCraft's `filmcraft-mxf` (storytold/filmcraft@4bec22b): diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 0c0d18211d..a0e2d0c069 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -11,7 +11,7 @@ //! - `avi` (feature `avi`): a clean-room AVI (RIFF) and OpenDML 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). +//! program streams) and transport stream writer. //! - `vmd` (feature `vmd`): a clean-room Sierra VMD (Video and Music Data) demuxer. //! - [`Container`] and [`CodecId`] (no feature): the identifiers the codec crates report a file's //! container and codec with. diff --git a/crates/media/src/mpegts/mod.rs b/crates/media/src/mpegts/mod.rs index a0a62efa5f..32356be02d 100644 --- a/crates/media/src/mpegts/mod.rs +++ b/crates/media/src/mpegts/mod.rs @@ -15,6 +15,7 @@ //! reference and field structure. That index is the seeking table. //! - Units are read back on demand by re-reading the file from the unit's first packet, so the //! index costs a few dozen bytes per access unit. +//! - [`mux`] writes one program as a transport stream to any `io::Write`, frame by frame. //! //! The module does no decoding. No dependencies beyond `std`, no `unsafe`, builds for //! `wasm32-unknown-unknown`. @@ -26,6 +27,7 @@ mod es; pub use es::{FrameInfo, frame_bytes, frame_info, sei_has_recovery_point}; +pub mod mux; mod pes; mod ps; mod ts; diff --git a/crates/media/src/mpegts/mux/av1.rs b/crates/media/src/mpegts/mux/av1.rs new file mode 100644 index 0000000000..22d0d7cd5f --- /dev/null +++ b/crates/media/src/mpegts/mux/av1.rs @@ -0,0 +1,232 @@ +//! AV1 in a transport stream (Carriage of AV1 in MPEG-2 TS, §3): each OBU after the start code +//! 0x000001, with emulation prevention so that 0x000000, 0x000001, 0x000002 and 0x000003 never +//! appear inside it. Temporal delimiters are left out, and so are padding OBUs that end with a +//! zero byte (an empty one included), which decoders ignore. + +use super::Error; + +const OBU_SEQUENCE_HEADER: u8 = 1; +const OBU_TEMPORAL_DELIMITER: u8 = 2; +const OBU_TILE_LIST: u8 = 8; +const OBU_PADDING: u8 = 15; + +struct Obu { + /// Bytes from the OBU header to the end of its payload. + len: usize, + kind: u8, +} + +/// The OBU at the start of `d`. +fn obu(d: &[u8]) -> Result { + let &h = d.first().ok_or(Error::BadFrame("an AV1 frame ends inside an OBU header"))?; + if h & 0x80 != 0 { + return Err(Error::BadFrame("an AV1 OBU has its forbidden bit set")); + } + if h & 0x02 == 0 { + return Err(Error::BadFrame("AV1 OBUs must carry obu_size (the low overhead bitstream format)")); + } + let mut at = 1 + usize::from(h & 0x04 != 0); + let mut size: u64 = 0; + for i in 0..8 { + let &b = d.get(at).ok_or(Error::BadFrame("an AV1 frame ends inside an OBU header"))?; + at += 1; + size |= u64::from(b & 0x7F) << (7 * i); + if b & 0x80 == 0 { + break; + } + if i == 7 { + return Err(Error::BadFrame("an AV1 obu_size is longer than eight bytes")); + } + } + let len = usize::try_from(size).ok().filter(|&s| s <= u32::MAX as usize).and_then(|s| at.checked_add(s)).filter(|&l| l <= d.len()); + let len = len.ok_or(Error::BadFrame("an AV1 OBU runs past the end of the frame"))?; + Ok(Obu { len, kind: (h >> 3) & 0x0F }) +} + +/// The OBU `bytes` (as `obu` found it) is not written: a temporal delimiter, or a padding OBU +/// that ends with a zero byte. +fn left_out(o: &Obu, bytes: &[u8]) -> bool { + o.kind == OBU_TEMPORAL_DELIMITER || (o.kind == OBU_PADDING && bytes.last() == Some(&0)) +} + +/// Emulation prevention bytes `bytes` needs after a start code. +fn escapes(bytes: &[u8]) -> usize { + let (mut n, mut zeros) = (0, 0u8); + for &b in bytes { + if zeros >= 2 && b <= 3 { + n += 1; + zeros = 0; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + } + n +} + +/// Checks a temporal unit and returns the bytes it takes in the PES packet: start codes, OBUs +/// and emulation prevention bytes. +pub(crate) fn check(data: &[u8], key: bool) -> Result { + let (mut at, mut body, mut seq, mut any) = (0, 0usize, false, false); + while at < data.len() { + let o = obu(&data[at..])?; + let bytes = &data[at..at + o.len]; + at += o.len; + if left_out(&o, bytes) { + continue; + } + match o.kind { + OBU_TILE_LIST => return Err(Error::BadFrame("tile list OBUs are not carried in a transport stream")), + OBU_SEQUENCE_HEADER => seq = true, + _ => {} + } + if bytes.last() == Some(&0) { + return Err(Error::BadFrame("an AV1 OBU ends with a zero byte, which the next start code would turn into a forbidden sequence")); + } + body = body.saturating_add(3 + bytes.len() + escapes(bytes)); + any = true; + } + if !any { + return Err(Error::BadFrame("the AV1 frame holds only temporal delimiters and padding")); + } + if key && !seq { + return Err(Error::BadFrame("an AV1 keyframe must carry a sequence header")); + } + Ok(body) +} + +/// Writes a checked temporal unit in start code form, a packet at a time. +pub(crate) struct Escaper<'a> { + data: &'a [u8], + at: usize, + /// End of the OBU being written. + end: usize, + /// Start code bytes still to write. + start_code: u8, + zeros: u8, +} + +impl<'a> Escaper<'a> { + pub(crate) fn new(data: &'a [u8]) -> Self { + Self { data, at: 0, end: 0, start_code: 0, zeros: 0 } + } + + /// Fills `out` as far as the temporal unit goes; returns the bytes written. + pub(crate) fn fill(&mut self, out: &mut [u8]) -> usize { + let mut n = 0; + while n < out.len() { + if self.start_code > 0 { + out[n] = u8::from(self.start_code == 1); + self.start_code -= 1; + n += 1; + } else if self.at < self.end { + let b = self.data[self.at]; + if self.zeros >= 2 && b <= 3 { + out[n] = 3; + self.zeros = 0; + } else { + out[n] = b; + self.at += 1; + self.zeros = if b == 0 { self.zeros + 1 } else { 0 }; + } + n += 1; + } else { + let rest = self.data.get(self.at..).unwrap_or(&[]); + let Ok(o) = obu(rest) else { break }; + if left_out(&o, &rest[..o.len]) { + self.at += o.len; + continue; + } + self.end = self.at + o.len; + self.start_code = 3; + self.zeros = 0; + } + } + n + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Removes start codes and emulation prevention bytes: the OBUs back. + fn unescape(es: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut zeros = 0; + let mut i = 0; + while i < es.len() { + if es[i..].starts_with(&[0, 0, 1]) { + i += 3; + zeros = 0; + continue; + } + let b = es[i]; + i += 1; + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + out.push(b); + } + out + } + + fn write(data: &[u8], chunk: usize) -> Vec { + let mut e = Escaper::new(data); + let mut out = Vec::new(); + loop { + let mut b = vec![0u8; chunk]; + let n = e.fill(&mut b); + out.extend_from_slice(&b[..n]); + if n < chunk { + return out; + } + } + } + + #[test] + fn obus_get_start_codes_and_escapes() { + // a temporal delimiter, a sequence header, a frame OBU whose payload holds every + // sequence that needs an escape + let tu = [0x12, 0x00, 0x0A, 0x03, 0x00, 0x00, 0x01, 0x32, 0x0A, 0, 0, 0, 0, 0, 1, 0, 0, 3, 0x7F]; + let body = check(&tu, true).unwrap(); + for chunk in [1, 2, 5, 184] { + let es = write(&tu, chunk); + assert_eq!(es.len(), body, "chunk {chunk}"); + assert!(es.starts_with(&[0, 0, 1, 0x0A, 0x03, 0x00, 0x00, 0x03, 0x01, 0, 0, 1, 0x32])); + for w in es[3..].windows(3) { + assert!(!(w[0] == 0 && w[1] == 0 && w[2] <= 2) || w == [0, 0, 1], "{es:02X?}"); + } + assert_eq!(unescape(&es), tu[2..].to_vec()); + } + } + + #[test] + fn padding_that_ends_with_a_zero_byte_is_left_out() { + // a sequence header, an empty padding OBU, a frame OBU, a padding OBU ending in 0x00, + // and a padding OBU that is written + let tu = [0x0A, 0x01, 0x05, 0x7A, 0x00, 0x32, 0x01, 0x07, 0x7A, 0x02, 0x09, 0x00, 0x7A, 0x01, 0x09]; + let body = check(&tu, true).unwrap(); + for chunk in [1, 2, 5, 184] { + let es = write(&tu, chunk); + assert_eq!(es.len(), body, "chunk {chunk}"); + assert_eq!(es, [0, 0, 1, 0x0A, 0x01, 0x05, 0, 0, 1, 0x32, 0x01, 0x07, 0, 0, 1, 0x7A, 0x01, 0x09], "chunk {chunk}"); + } + } + + #[test] + fn bad_temporal_units_are_refused() { + assert!(check(&[0x12, 0x00], false).is_err(), "only a temporal delimiter"); + assert!(check(&[0x32, 0x01, 0x05], true).is_err(), "a keyframe without a sequence header"); + assert!(check(&[0x32, 0x01, 0x05], false).is_ok()); + assert!(check(&[0x30, 0x05], false).is_err(), "no obu_size"); + assert!(check(&[0xB2, 0x01, 0x05], false).is_err(), "forbidden bit"); + assert!(check(&[0x32, 0x05, 0x05], false).is_err(), "past the end"); + assert!(check(&[0x32, 0x01, 0x00], false).is_err(), "ends with a zero byte"); + assert!(check(&[0x42, 0x01, 0x05], false).is_err(), "tile list"); + assert!(check(&[0x7A, 0x00], false).is_err(), "only empty padding"); + assert!(check(&[0x7A, 0x02, 0x05, 0x00], false).is_err(), "only padding that ends with a zero byte"); + assert!(check(&[0x32, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01], false).is_err(), "a nine-byte size"); + assert!(check(&[0x32, 0x80, 0x80, 0x80, 0x80, 0x10], false).is_err(), "over 2^32 - 1"); + } +} diff --git a/crates/media/src/mpegts/mux/mod.rs b/crates/media/src/mpegts/mux/mod.rs new file mode 100644 index 0000000000..2bf808e171 --- /dev/null +++ b/crates/media/src/mpegts/mux/mod.rs @@ -0,0 +1,1192 @@ +//! MPEG-2 transport stream writer (ITU-T H.222.0 | ISO/IEC 13818-1). +//! +//! [`Muxer`] writes one program to any [`Write`] as frames arrive: +//! +//! - a program association section and a program map section, each ending with its CRC-32, at the +//! start, every [`Config::psi_interval`], before every video keyframe (optional), after +//! [`Muxer::replace_writer`] and after [`Muxer::discontinuity`]; +//! - one PES packet per frame for H.264, HEVC, MPEG-1, MPEG-2 and MPEG-4 Part 2 video, AV1, AAC in +//! ADTS frames (passed in, or built from raw AAC frames), Opus, AC-3, E-AC-3 and MPEG audio +//! (layers I to III), with PTS and, when it differs, DTS; +//! - the program clock reference on [`Config::pcr_pid`], in the adaptation field of the PCR +//! stream's frames or in packets of its own, never more than [`Config::pcr_interval`] apart +//! (at most 100 ms, §2.7.2); +//! - a continuity counter per PID, the random access indicator on keyframes, the discontinuity +//! indicator after [`Muxer::discontinuity`], and adaptation field stuffing in each frame's last +//! packet. +//! +//! Timestamps are 90 kHz ticks. They are written modulo 2^33, so a stream may run past the +//! wrap. The PCR follows the largest DTS so far minus [`Config::pcr_delay`]. +//! +//! # Arrival order +//! +//! Frames of different streams may arrive in any order, as long as each frame's DTS is no more +//! than [`Config::pcr_delay`] behind the largest DTS written so far (or the largest time given to +//! [`Muxer::advance`]). Within one stream the DTS never goes back, and for video it goes forward +//! with every frame. A caller whose encoders drift further apart than `pcr_delay` (at most +//! [`MAX_PCR_DELAY`], one second) queues frames and writes them in DTS order. +//! +//! # Output and failures +//! +//! Packets are built in a 188-byte buffer and collected in a batch of [`Config::batch_packets`] +//! packets, allocated once. A full batch is handed to the output in one `write` call, repeated +//! only when the output takes part of it; the default of 7 packets (1316 bytes) is one SRT or UDP +//! payload. Unless [`Config::hold_packets`] is set, the +//! rest of the batch is written at the end of every [`Muxer::write_frame`] and [`Muxer::advance`] +//! call, so a live output never waits for the next frame. A file output can set `hold_packets` +//! and a larger batch (for example 348 packets, 65 424 bytes) and then needs no `BufWriter`. +//! +//! The output must block until it has taken each write: an [`io::ErrorKind::WouldBlock`] error +//! is an I/O error like any other. After an I/O error the rest of that batch is dropped, the +//! output may hold part of a packet, and the continuity counters have moved on. +//! [`Stats::packets`] and [`Segment::packets`] count only the whole packets the output took. To +//! recover, give the muxer a new output with +//! [`Muxer::replace_writer`]: the new output starts at a packet boundary with the PAT, the PMT and +//! a PCR, and reads on its own. +//! +//! The names here ([`Codec`], [`Stream`], [`Error`]) are the writer's own and differ from the +//! demuxer's in [`crate::mpegts`]. + +mod av1; +mod pes; +mod psi; + +use std::fmt; +use std::io::{self, Write}; + +/// Bytes in a transport stream packet. +pub const PACKET_SIZE: usize = 188; +/// Timestamp ticks per second. +pub const TICKS_PER_SECOND: u32 = 90_000; +/// Largest PCR interval, 100 ms in 90 kHz ticks (H.222.0 §2.7.2). +pub const MAX_PCR_INTERVAL: u32 = 9_000; +/// Largest [`Config::pcr_delay`], one second in 90 kHz ticks: data may spend at most one second +/// in the decoder's buffers (H.222.0 §2.4.2.6). +pub const MAX_PCR_DELAY: u32 = 90_000; +/// Most elementary streams in one program. +pub const MAX_STREAMS: usize = 32; +/// Largest number of PCR-only packets, and of PAT and PMT repeats, written to fill one gap in the +/// timeline. A gap that needs more PCRs gets one PCR at its end and is counted in +/// [`Stats::pcr_gaps`]. +pub const MAX_PCR_FILL: u32 = 1024; +/// Largest video frame, [`super::MAX_UNIT_BYTES`] (128 MiB): the largest unit the demuxer +/// returns. +pub const MAX_VIDEO_FRAME: usize = super::MAX_UNIT_BYTES as usize; +/// Largest [`Config::batch_packets`]. +pub const MAX_BATCH_PACKETS: u16 = 1024; +/// Largest Opus start or end trim, in samples at 48 kHz (a 13-bit field). +pub const MAX_OPUS_TRIM: u16 = 8191; + +/// Errors from writing a transport stream. +#[non_exhaustive] +#[derive(Debug)] +pub enum Error { + /// Writing the output failed. + Io(io::Error), + /// The configuration or the stream list is not valid. + Config(String), + /// This PID is outside 0x0010 to 0x1FFE. + BadPid(u16), + /// This PID is used for two things. + DuplicatePid(u16), + /// The program map section would be longer than 1021 bytes. + PsiTooLarge { + /// The section_length it would have. + length: usize, + }, + /// [`Config::pcr_delay`] is outside 1 to [`MAX_PCR_DELAY`]. + PcrDelay(u32), + /// There is no stream with this index. + NoSuchStream(usize), + /// The frame has no bytes. + EmptyFrame, + /// The frame is not in the form its codec needs. + BadFrame(&'static str), + /// The frame is larger than its codec allows. + FrameTooLarge { + /// Bytes in the frame. + size: usize, + /// Most bytes the frame may have. + limit: usize, + }, + /// The frame's timestamps are not valid. + Timestamp(&'static str), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Io(e) => write!(f, "I/O: {e}"), + Error::Config(s) => write!(f, "transport stream settings: {s}"), + Error::BadPid(pid) => write!(f, "PID 0x{pid:04X} is outside 0x0010 to 0x1FFE"), + Error::DuplicatePid(pid) => write!(f, "PID 0x{pid:04X} is used twice"), + Error::PsiTooLarge { length } => write!(f, "the program map section would be {length} bytes long; the limit is 1021"), + Error::PcrDelay(d) => write!(f, "a PCR delay of {d} ticks is outside 1 to {MAX_PCR_DELAY}"), + Error::NoSuchStream(i) => write!(f, "no stream {i}"), + Error::EmptyFrame => write!(f, "the frame is empty"), + Error::BadFrame(s) => write!(f, "{s}"), + Error::FrameTooLarge { size, limit } => write!(f, "the frame is {size} bytes; the limit is {limit}"), + Error::Timestamp(s) => write!(f, "{s}"), + } + } +} + +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 the writer. +pub type Result = std::result::Result; + +/// The fields of the AV1 video descriptor (Carriage of AV1 in MPEG-2 TS, §2.2), taken from the +/// stream's sequence header. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Av1Config { + /// seq_profile, 0 to 2. + pub seq_profile: u8, + /// seq_level_idx[0], 0 to 31. + pub seq_level_idx_0: u8, + /// seq_tier[0]. + pub seq_tier_0: bool, + /// high_bitdepth. + pub high_bitdepth: bool, + /// twelve_bit. + pub twelve_bit: bool, + /// mono_chrome. + pub monochrome: bool, + /// subsampling_x. + pub chroma_subsampling_x: bool, + /// subsampling_y. + pub chroma_subsampling_y: bool, + /// chroma_sample_position, 0 to 3. + pub chroma_sample_position: u8, + /// 0 SDR, 1 wide color gamut, 2 HDR and wide color gamut, 3 no indication. + pub hdr_wcg_idc: u8, +} + +impl Av1Config { + /// The fields from the first four bytes of an ISOBMFF `av1C` record (marker and version 1), + /// with `hdr_wcg_idc` 3 (no indication). + pub fn from_av1c(record: &[u8]) -> Result { + let &[b0, b1, b2, _, ..] = record else { return Err(Error::Config("an av1C record has at least four bytes".into())) }; + if b0 != 0x81 { + return Err(Error::Config("an av1C record has at least four bytes and starts with marker 1 and version 1".into())); + } + let c = Self { + seq_profile: b1 >> 5, + seq_level_idx_0: b1 & 0x1F, + seq_tier_0: b2 & 0x80 != 0, + high_bitdepth: b2 & 0x40 != 0, + twelve_bit: b2 & 0x20 != 0, + monochrome: b2 & 0x10 != 0, + chroma_subsampling_x: b2 & 0x08 != 0, + chroma_subsampling_y: b2 & 0x04 != 0, + chroma_sample_position: b2 & 3, + hdr_wcg_idc: 3, + }; + c.check().map_err(Error::Config)?; + Ok(c) + } + + fn check(&self) -> std::result::Result<(), String> { + if self.seq_profile > 2 { + return Err(format!("AV1 seq_profile {} is not 0 to 2", self.seq_profile)); + } + if self.seq_level_idx_0 > 31 || self.chroma_sample_position > 3 || self.hdr_wcg_idc > 3 { + return Err("an AV1 descriptor field is out of range".into()); + } + Ok(()) + } +} + +/// An Opus channel configuration coded in full (channel_config_code 0x81 of the Opus transport +/// draft): the channel mapping family, the stream counts and the channel mapping. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OpusMapping { + /// Output channels, 1 to 8. + pub channels: u8, + /// Channel mapping family (RFC 7845 §5.1.1): 0 for one mono or stereo stream, 1 for the + /// standard surround orders, 255 for an application-defined order. Other families are + /// refused. + pub family: u8, + /// Opus streams in each access unit, 1 to `channels` (1 for family 0). + pub streams: u8, + /// Streams that decode to two channels, at most `streams` (`channels - 1` for family 0). + pub coupled: u8, + /// For each output channel, the coded channel it is taken from (below `streams + coupled`), + /// or 255 for silence. Entries past `channels` are ignored. Family 0 carries no mapping in + /// the descriptor, so its entries must be 0 and 1. + pub mapping: [u8; 8], +} + +impl OpusMapping { + fn check(&self) -> std::result::Result<(), String> { + let ch = usize::from(self.channels); + if !(1..=8).contains(&ch) { + return Err(format!("{ch} Opus channels; 1 to 8 are supported")); + } + if self.family == 0 { + if ch > 2 || self.streams != 1 || u16::from(self.coupled) + 1 != u16::from(self.channels) { + return Err("Opus mapping family 0 is one stream of 1 or 2 channels".into()); + } + // the descriptor carries no mapping for family 0: the channels are in coded order + if self.mapping[..ch].iter().enumerate().any(|(i, &m)| usize::from(m) != i) { + return Err("Opus mapping family 0 keeps the channels in coded order (mapping 0, 1)".into()); + } + return Ok(()); + } + if !matches!(self.family, 1 | 255) { + return Err(format!("Opus mapping family {}; 0, 1 and 255 are supported", self.family)); + } + if self.streams == 0 || self.streams > self.channels || self.coupled > self.streams { + return Err("Opus streams are 1 to the channel count, and coupled streams at most the stream count".into()); + } + let coded = self.streams + self.coupled; + if self.mapping[..ch].iter().any(|&m| m >= coded && m != 255) { + return Err("an Opus channel mapping entry names a coded channel that does not exist".into()); + } + Ok(()) + } +} + +/// What an elementary stream carries, and the form its frames take. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Codec { + /// H.264 access units in Annex B form, with the parameter sets on keyframes. An access unit + /// delimiter is added when a frame does not start with one. + H264, + /// HEVC access units in Annex B form, with the parameter sets on keyframes. An access unit + /// delimiter is added when a frame does not start with one. + Hevc, + /// MPEG-1 video pictures (ISO/IEC 11172-2), from their first start code. + Mpeg1Video, + /// MPEG-2 video pictures, from their first start code. + Mpeg2Video, + /// MPEG-4 Part 2 visual frames (ISO/IEC 14496-2), from their first start code. + Mpeg4Part2, + /// AV1 temporal units in the low overhead bitstream format (every OBU with its size field), + /// with a sequence header on keyframes. Each OBU is written after a start code with emulation + /// prevention. Temporal delimiters, and padding OBUs that end with a zero byte, are left out + /// (Carriage of AV1 in MPEG-2 TS). + Av1(Av1Config), + /// AAC frames that already carry their ADTS headers; one call may pass several frames. + AacAdts, + /// Raw AAC frames; each one gets an ADTS header built from these fields. + Aac { + /// Audio object type, 1 to 4 (2 is AAC LC). + object_type: u8, + /// Sampling frequency index, 0 to 12 (3 is 48 kHz). + sample_rate_index: u8, + /// Channel configuration, 1 to 7. + channels: u8, + }, + /// Opus access units, one per frame; each gets an Opus control header. For 1 or 2 channels + /// the access unit is one Opus packet. For 3 to 8 channels it holds the streams of mapping + /// family 1 in the order the Opus transport draft's table 4-3 gives, all but the last + /// self-delimited; use [`Codec::OpusMapped`] for any other layout. + Opus { + /// Channel count, 1 to 8. + channels: u8, + }, + /// Opus access units with a channel configuration given in full. + OpusMapped(OpusMapping), + /// AC-3 sync frames. + Ac3, + /// E-AC-3 sync frames (bsid 11 to 16). + Eac3, + /// MPEG-1 or MPEG-2 audio frames, layers I to III (MP2, MP3). + MpegAudio { + /// The stream uses the MPEG-2 low sampling frequencies (16, 22.05 and 24 kHz) or the + /// lower MPEG 2.5 rates. Each frame's version bits must agree. + low_sample_rate: bool, + }, +} + +impl Codec { + /// The PMT stream_type. + pub fn stream_type(self) -> u8 { + match self { + Codec::H264 => 0x1B, + Codec::Hevc => 0x24, + Codec::Mpeg1Video => 0x01, + Codec::Mpeg2Video => 0x02, + Codec::Mpeg4Part2 => 0x10, + Codec::AacAdts | Codec::Aac { .. } => 0x0F, + Codec::Av1(_) | Codec::Opus { .. } | Codec::OpusMapped(_) => 0x06, + Codec::Ac3 => 0x81, + Codec::Eac3 => 0x87, + Codec::MpegAudio { low_sample_rate: false } => 0x03, + Codec::MpegAudio { low_sample_rate: true } => 0x04, + } + } + + /// The PES stream_id. + pub fn stream_id(self) -> u8 { + match self { + Codec::H264 | Codec::Hevc | Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::Mpeg4Part2 => 0xE0, + Codec::AacAdts | Codec::Aac { .. } | Codec::MpegAudio { .. } => 0xC0, + Codec::Av1(_) | Codec::Opus { .. } | Codec::OpusMapped(_) | Codec::Ac3 | Codec::Eac3 => 0xBD, + } + } + + /// The stream carries pictures. + pub fn is_video(self) -> bool { + matches!(self, Codec::H264 | Codec::Hevc | Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::Mpeg4Part2 | Codec::Av1(_)) + } + + fn is_opus(self) -> bool { + matches!(self, Codec::Opus { .. } | Codec::OpusMapped(_)) + } + + /// Raw AAC described by an AudioSpecificConfig (ISO/IEC 14496-3 §1.6.2.1). Configurations + /// that an ADTS header cannot carry are refused: an object type outside 1 to 4 (SBR and PS + /// signaled explicitly included), an explicit sampling frequency, channel configuration 0, + /// and frameLengthFlag 1 (960-sample frames). + pub fn aac_from_asc(asc: &[u8]) -> Result { + let &[a, b, ..] = asc else { return Err(Error::Config("an AudioSpecificConfig has at least two bytes".into())) }; + let object_type = a >> 3; + let sample_rate_index = (a & 7) << 1 | b >> 7; + let channels = (b >> 3) & 0x0F; + let codec = Codec::Aac { object_type, sample_rate_index, channels }; + codec.check().map_err(Error::Config)?; + // GASpecificConfig's frameLengthFlag follows the channel configuration (ISO/IEC 14496-3 §4.4.1). + if b & 0x04 != 0 { + return Err(Error::Config("AAC frameLengthFlag 1 (960-sample frames) cannot be carried by an ADTS header".into())); + } + Ok(codec) + } + + fn check(self) -> std::result::Result<(), String> { + match self { + Codec::Aac { object_type, sample_rate_index, channels } => { + if !(1..=4).contains(&object_type) { + return Err(format!("AAC object type {object_type} is not 1 to 4")); + } + if sample_rate_index > 12 { + return Err(format!("AAC sampling frequency index {sample_rate_index} is not 0 to 12")); + } + if !(1..=7).contains(&channels) { + return Err(format!("AAC channel configuration {channels} is not 1 to 7")); + } + Ok(()) + } + Codec::Opus { channels } if !(1..=8).contains(&channels) => Err(format!("{channels} Opus channels; 1 to 8 are supported")), + Codec::OpusMapped(m) => m.check(), + Codec::Av1(c) => c.check(), + _ => Ok(()), + } + } +} + +/// One elementary stream of the program. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Stream { + /// The PID its packets carry, 0x0010 to 0x1FFE. + pub pid: u16, + /// What it carries. + pub codec: Codec, + /// ISO 639-2 language code (three lowercase letters), written as a language descriptor. + pub language: Option<[u8; 3]>, +} + +impl Stream { + /// A stream on `pid` without a language. + pub fn new(pid: u16, codec: Codec) -> Self { + Self { pid, codec, language: None } + } + + /// The same stream with a language code. + pub fn with_language(mut self, language: [u8; 3]) -> Self { + self.language = Some(language); + self + } +} + +/// Program, timing and output settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Config { + /// transport_stream_id in the program association section. + pub transport_stream_id: u16, + /// program_number, not 0. + pub program_number: u16, + /// The PID of the program map section, 0x0010 to 0x1FFE. + pub pmt_pid: u16, + /// The PID that carries the PCR: one of the streams' PIDs, or a PID of its own. + /// `None` uses the first video stream, or the first stream when there is no video. + pub pcr_pid: Option, + /// Largest gap between PCRs, 90 kHz ticks, 1 to [`MAX_PCR_INTERVAL`]. + pub pcr_interval: u32, + /// How far the PCR runs behind the largest DTS so far, 90 kHz ticks, 1 to + /// [`MAX_PCR_DELAY`]. It is also the largest skew between streams (see the crate docs). + pub pcr_delay: u32, + /// How often the PAT and PMT are repeated, 90 kHz ticks, at least 1. + pub psi_interval: u32, + /// Repeat the PAT and PMT before every video keyframe, so each keyframe starts a segment that + /// decodes on its own. + pub psi_before_keyframes: bool, + /// Packets collected before one write to the output, 1 to [`MAX_BATCH_PACKETS`]. + pub batch_packets: u16, + /// Keep a partly filled batch between calls instead of writing it at the end of each + /// [`Muxer::write_frame`] and [`Muxer::advance`]. For file outputs; [`Muxer::flush`], + /// [`Muxer::replace_writer`] and [`Muxer::finish`] still write it. + pub hold_packets: bool, +} + +impl Default for Config { + /// Program 1 with its PMT on PID 0x1000; the PCR at most 40 ms apart and 700 ms behind the + /// DTS; the PAT and PMT every 100 ms and before keyframes; writes of 7 packets, and the rest + /// at the end of every call. + fn default() -> Self { + Self { + transport_stream_id: 1, + program_number: 1, + pmt_pid: 0x1000, + pcr_pid: None, + pcr_interval: 3_600, + pcr_delay: 63_000, + psi_interval: 9_000, + psi_before_keyframes: true, + batch_packets: 7, + hold_packets: false, + } + } +} + +/// One frame to write. +#[derive(Clone, Copy, Debug)] +pub struct Frame<'a> { + /// The coded frame. + pub data: &'a [u8], + /// Presentation time, 90 kHz ticks. + pub pts: i64, + /// Decoding time, 90 kHz ticks; `None` when it equals `pts`. Never after `pts`, never before + /// the stream's previous DTS (for video, always after it), and never behind the clock: the + /// largest DTS so far, or the largest time given to [`Muxer::advance`], minus + /// [`Config::pcr_delay`]. + pub dts: Option, + /// Decoding can start at this frame (an IDR or other random access picture; any audio frame). + pub key: bool, +} + +/// Samples to discard from an Opus access unit, at 48 kHz (the Opus control header's start_trim +/// and end_trim). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OpusTrim { + /// Samples discarded from the start: the encoder's pre-skip, on the first access units of a + /// stream only, 65 535 in all. + pub start: u16, + /// Samples discarded from the end, on the last access unit. + pub end: u16, +} + +/// Counts of what has been written. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Stats { + /// Transport stream packets the outputs took whole. Packets still in the batch, and packets + /// dropped after an I/O error, are not counted. + pub packets: u64, + /// Frames. + pub frames: u64, + /// Times the PAT and PMT were written. + pub psi: u64, + /// PCRs, in frames' packets and in packets of their own. + pub pcrs: u64, + /// Gaps in the timeline longer than [`MAX_PCR_FILL`] PCR intervals. + pub pcr_gaps: u64, +} + +impl Stats { + /// Bytes written. + pub fn bytes(&self) -> u64 { + self.packets.saturating_mul(PACKET_SIZE as u64) + } +} + +/// What one output received, returned when [`Muxer::replace_writer`] or +/// [`Muxer::replace_writer_continuing`] closes it. An HLS packager reads the segment's duration +/// and independence from it. +#[derive(Debug)] +pub struct Segment { + /// The output. + pub writer: W, + /// Transport stream packets it took whole. After an error it may also hold part of a packet. + pub packets: u64, + /// Frames written to it. + pub frames: u64, + /// PTS of its first frame. + pub first_pts: Option, + /// Largest PTS of its frames. + pub last_pts: Option, + /// Its first video frame is a keyframe (with no video stream: it holds a frame), so it + /// decodes on its own when it also starts with the tables. + pub starts_with_keyframe: bool, + /// Writing the last packets to it, or flushing it, failed; those packets are lost. + pub error: Option, +} + +struct State { + pid: u16, + codec: Codec, + /// The counter the next packet with a payload carries. + cc: u8, + last_dts: Option, + /// The next packet carries the discontinuity indicator. + disc: bool, + /// Every Opus access unit so far was discarded whole by its start trim. + opus_lead_in: bool, + /// Opus samples discarded by start trims so far. + opus_start_trimmed: u32, +} + +impl State { + /// The counter an adaptation-field-only packet carries: the one before the next payload + /// packet's (§2.4.3.3), so the counter goes up by one at the next payload packet. + fn held_cc(&self) -> u8 { + self.cc.wrapping_sub(1) & 0x0F + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum PcrOn { + Stream(usize), + Own(u16), +} + +/// The output and the batch of packets waiting for it. +struct Sink { + out: W, + batch: Vec, + cap: usize, + /// Whole packets the output has taken. + packets: u64, + /// A mark that moves with every packet built and every batch dropped after an error, so + /// the muxer can tell whether given packets are still the last ones the output gets. + pushed: u64, +} + +impl Sink { + fn push(&mut self, p: &[u8; PACKET_SIZE]) -> io::Result<()> { + self.pushed += 1; + self.batch.extend_from_slice(p); + if self.batch.len() >= self.cap { self.drain() } else { Ok(()) } + } + + /// Writes the batch, counting the whole packets the output takes. On an error the rest of the + /// batch is dropped. + fn drain(&mut self) -> io::Result<()> { + let mut done = 0; + let mut r = Ok(()); + while done < self.batch.len() { + match self.out.write(&self.batch[done..]) { + Ok(0) => { + r = Err(io::Error::from(io::ErrorKind::WriteZero)); + break; + } + Ok(n) => done += n, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => { + r = Err(e); + break; + } + } + } + self.packets += (done / PACKET_SIZE) as u64; + if r.is_err() && done < self.batch.len() { + self.pushed += 1; + } + self.batch.clear(); + r + } +} + +/// What the current output has received. +#[derive(Default)] +struct SegState { + start_packets: u64, + frames: u64, + first_pts: Option, + last_pts: Option, + first_video_key: Option, +} + +/// The bytes of a frame after its PES header and prefix. +enum Payload<'a> { + Plain(&'a [u8]), + Av1(av1::Escaper<'a>), +} + +impl Payload<'_> { + /// Fills `out` as far as the payload goes; returns the bytes written. + fn fill(&mut self, out: &mut [u8]) -> usize { + match self { + Payload::Plain(d) => { + let n = d.len().min(out.len()); + out[..n].copy_from_slice(&d[..n]); + *d = &d[n..]; + n + } + Payload::Av1(e) => e.fill(out), + } + } +} + +/// Writes one program as a transport stream. +pub struct Muxer { + sink: Sink, + cfg: Config, + streams: Vec, + has_video: bool, + pat: Vec, + pmt: Vec, + pat_cc: u8, + pmt_cc: u8, + pcr_on: PcrOn, + /// The next PCR on a PID of its own carries the discontinuity indicator. + own_pcr_disc: bool, + /// The 27 MHz clock: the largest DTS so far minus the PCR delay. + clock: Option, + last_pcr: Option, + last_psi: Option, + /// [`Sink::pushed`] right after the last PAT and PMT; `None` once something else may follow + /// them. + psi_end: Option, + psi_forced: bool, + /// The next frame or advance writes a PCR whatever the interval (a new writer). + pcr_forced: bool, + stats: Stats, + seg: SegState, +} + +fn check_pid(pid: u16) -> Result<()> { + if (0x0010..=0x1FFE).contains(&pid) { Ok(()) } else { Err(Error::BadPid(pid)) } +} + +impl Muxer { + /// A muxer for `streams` writing to `out`. Nothing is written until the first frame or + /// [`Muxer::advance`]. + pub fn new(out: W, cfg: Config, streams: &[Stream]) -> Result { + if streams.is_empty() || streams.len() > MAX_STREAMS { + return Err(Error::Config(format!("{} streams; 1 to {MAX_STREAMS} are supported", streams.len()))); + } + if cfg.program_number == 0 { + return Err(Error::Config("program number 0 is reserved for the network PID".into())); + } + check_pid(cfg.pmt_pid)?; + if !(1..=MAX_PCR_INTERVAL).contains(&cfg.pcr_interval) { + return Err(Error::Config(format!("a PCR interval of {} ticks is outside 1 to {MAX_PCR_INTERVAL}", cfg.pcr_interval))); + } + if !(1..=MAX_PCR_DELAY).contains(&cfg.pcr_delay) { + return Err(Error::PcrDelay(cfg.pcr_delay)); + } + if cfg.psi_interval == 0 { + return Err(Error::Config("the PAT and PMT interval must be at least 1 tick".into())); + } + if !(1..=MAX_BATCH_PACKETS).contains(&cfg.batch_packets) { + return Err(Error::Config(format!("a batch of {} packets is outside 1 to {MAX_BATCH_PACKETS}", cfg.batch_packets))); + } + for (i, s) in streams.iter().enumerate() { + check_pid(s.pid)?; + if s.pid == cfg.pmt_pid || streams[..i].iter().any(|t| t.pid == s.pid) { + return Err(Error::DuplicatePid(s.pid)); + } + s.codec.check().map_err(Error::Config)?; + if let Some(l) = s.language + && !l.iter().all(u8::is_ascii_lowercase) + { + return Err(Error::Config("a language code is three lowercase letters".into())); + } + } + let pcr_on = match cfg.pcr_pid { + Some(pid) => { + check_pid(pid)?; + if pid == cfg.pmt_pid { + return Err(Error::DuplicatePid(pid)); + } + streams.iter().position(|s| s.pid == pid).map_or(PcrOn::Own(pid), PcrOn::Stream) + } + None => PcrOn::Stream(streams.iter().position(|s| s.codec.is_video()).unwrap_or(0)), + }; + let pcr_pid = match pcr_on { + PcrOn::Stream(i) => streams.get(i).map_or(0x1FFF, |s| s.pid), + PcrOn::Own(pid) => pid, + }; + let cap = usize::from(cfg.batch_packets) * PACKET_SIZE; + Ok(Self { + sink: Sink { out, batch: Vec::with_capacity(cap), cap, packets: 0, pushed: 0 }, + cfg, + streams: streams + .iter() + .map(|s| State { pid: s.pid, codec: s.codec, cc: 0, last_dts: None, disc: false, opus_lead_in: true, opus_start_trimmed: 0 }) + .collect(), + has_video: streams.iter().any(|s| s.codec.is_video()), + pat: psi::pat(cfg.transport_stream_id, cfg.program_number, cfg.pmt_pid)?, + pmt: psi::pmt(cfg.program_number, pcr_pid, streams)?, + pat_cc: 0, + pmt_cc: 0, + pcr_on, + own_pcr_disc: false, + clock: None, + last_pcr: None, + last_psi: None, + psi_end: None, + psi_forced: false, + pcr_forced: false, + stats: Stats::default(), + seg: SegState::default(), + }) + } + + /// The PID that carries the PCR. + pub fn pcr_pid(&self) -> u16 { + match self.pcr_on { + PcrOn::Stream(i) => self.streams.get(i).map_or(0x1FFF, |s| s.pid), + PcrOn::Own(pid) => pid, + } + } + + /// What has been written so far. + pub fn stats(&self) -> Stats { + Stats { packets: self.sink.packets, ..self.stats } + } + + /// The output. + pub fn get_ref(&self) -> &W { + &self.sink.out + } + + /// The output, for writing between packets. With [`Config::hold_packets`] set, call + /// [`Muxer::flush`] first so no held packet follows what is written here. + pub fn get_mut(&mut self) -> &mut W { + // what the caller writes may separate the last tables from the next keyframe + self.psi_end = None; + &mut self.sink.out + } + + /// Writes the held packets and flushes the output. + pub fn flush(&mut self) -> Result<()> { + self.sink.drain()?; + self.sink.out.flush()?; + Ok(()) + } + + /// Closes the current output for a new segment and sends the following packets to `out`. + /// The held packets go to the old output first, and it is flushed. The new output starts with + /// the PAT and PMT, and the next frame (or [`Muxer::advance`]) writes a PCR; continuity + /// counters and the clock carry on. To start every segment with a keyframe, call this right + /// before writing a video keyframe. + pub fn replace_writer(&mut self, out: W) -> Segment { + self.swap(out, true) + } + + /// Like [`Muxer::replace_writer`], but the packet flow is unchanged: no tables or PCR are + /// added, so the outputs joined end to end hold the same bytes as one output would. For the + /// parts of a low-latency HLS segment. + pub fn replace_writer_continuing(&mut self, out: W) -> Segment { + self.swap(out, false) + } + + fn swap(&mut self, out: W, restart: bool) -> Segment { + let error = self.sink.drain().err().or_else(|| self.sink.out.flush().err()); + if restart { + self.psi_forced = true; + self.pcr_forced = true; + } + let writer = std::mem::replace(&mut self.sink.out, out); + let seg = std::mem::replace(&mut self.seg, SegState { start_packets: self.sink.packets, ..SegState::default() }); + let starts_with_keyframe = if self.has_video { seg.first_video_key.unwrap_or(false) } else { seg.frames > 0 }; + Segment { + writer, + packets: self.sink.packets - seg.start_packets, + frames: seg.frames, + first_pts: seg.first_pts, + last_pts: seg.last_pts, + starts_with_keyframe, + error, + } + } + + /// Writes the PAT and PMT before the next frame. + pub fn repeat_psi(&mut self) { + self.psi_forced = true; + } + + /// Starts a new time base, for an encoder or source that restarts with timestamps that do not + /// follow the old ones. The clock and every stream's previous DTS are forgotten, the next + /// packet of every stream PID and of the PCR PID carries the discontinuity indicator + /// (§2.4.3.5), and the next frame or [`Muxer::advance`] writes the PAT, the PMT and a PCR of + /// the new time base first. Continuity counters carry on. An Opus stream may carry a start + /// trim again, as at its start. + pub fn discontinuity(&mut self) { + self.clock = None; + self.last_pcr = None; + self.last_psi = None; + self.psi_forced = true; + self.pcr_forced = true; + self.own_pcr_disc = matches!(self.pcr_on, PcrOn::Own(_)); + for s in &mut self.streams { + s.last_dts = None; + s.disc = true; + // a restarted Opus encoder starts with its own pre-skip + s.opus_lead_in = true; + s.opus_start_trimmed = 0; + } + } + + /// Writes the held packets, flushes and returns the output. A transport stream has no + /// trailer. + pub fn finish(mut self) -> Result { + self.flush()?; + Ok(self.sink.out) + } + + /// The 27 MHz clock value for a DTS. + fn time(&self, dts: i64) -> Result { + dts.checked_sub(i64::from(self.cfg.pcr_delay)).and_then(|v| v.checked_mul(300)).ok_or(Error::Timestamp("the timestamp is out of range")) + } + + /// Writes the batch unless the configuration holds packets between calls. + fn end_call(&mut self) -> Result<()> { + if !self.cfg.hold_packets { + self.sink.drain()?; + } + Ok(()) + } + + /// Moves the clock without a frame, writing the PCRs and the PAT and PMT that fall due. A + /// live output calls this while no frames arrive, so the PCR stays within its interval. + /// + /// `time` is on the DTS scale (90 kHz): the PCR sent is `time - pcr_delay`, the clock a + /// frame with DTS `time` would set. After `advance(t)`, frames whose DTS is below + /// `t - pcr_delay` are refused. A time behind the clock has no effect. + pub fn advance(&mut self, time: i64) -> Result<()> { + let r = self.advance_inner(time); + let end = self.end_call(); + r.and(end) + } + + fn advance_inner(&mut self, time: i64) -> Result<()> { + let t = self.time(time)?; + let clock = self.clock.map_or(t, |c| c.max(t)); + self.clock = Some(clock); + self.fill_pcr(clock)?; + self.psi_if_due(clock, false)?; + if self.pcr_due(clock) { + self.pcr_packet(clock)?; + } + Ok(()) + } + + /// A PCR packet is due: none yet, a new writer, or the interval has passed. + fn pcr_due(&self, clock: i64) -> bool { + self.pcr_forced || self.last_pcr.is_none_or(|l| clock.saturating_sub(l) >= self.limit()) + } + + /// Writes one frame of stream `index` (an index into the list given to [`Muxer::new`]). + /// The frame is checked before anything is written. + pub fn write_frame(&mut self, index: usize, frame: &Frame<'_>) -> Result<()> { + self.write_frame_with_trim(index, frame, OpusTrim::default()) + } + + /// Writes one Opus frame whose control header carries `trim`. A start trim is allowed only + /// while every earlier access unit of the stream (since the start or the last + /// [`Muxer::discontinuity`]) was discarded whole, and the trims of one + /// access unit cannot exceed its duration. A zero trim writes a plain frame, for any codec. + pub fn write_frame_with_trim(&mut self, index: usize, frame: &Frame<'_>, trim: OpusTrim) -> Result<()> { + let r = self.write_inner(index, frame, trim); + let end = self.end_call(); + r.and(end) + } + + fn write_inner(&mut self, index: usize, frame: &Frame<'_>, trim: OpusTrim) -> Result<()> { + let st = self.streams.get(index).ok_or(Error::NoSuchStream(index))?; + if frame.data.is_empty() { + return Err(Error::EmptyFrame); + } + let codec = st.codec; + let dts = frame.dts.unwrap_or(frame.pts); + if dts > frame.pts { + return Err(Error::Timestamp("the decoding time is after the presentation time")); + } + if let Some(l) = st.last_dts { + if dts < l { + return Err(Error::Timestamp("the decoding time is before the stream's previous one")); + } + if dts == l && codec.is_video() { + return Err(Error::Timestamp("a video frame's decoding time must be after the stream's previous one")); + } + } + let trimmed = trim != OpusTrim::default(); + let mut duration = 0; + if trimmed { + if !codec.is_opus() { + return Err(Error::BadFrame("only Opus frames carry trims")); + } + if trim.start > MAX_OPUS_TRIM || trim.end > MAX_OPUS_TRIM { + return Err(Error::BadFrame("an Opus trim is at most 8191 samples")); + } + if trim.start > 0 && (!st.opus_lead_in || st.opus_start_trimmed + u32::from(trim.start) > 0xFFFF) { + return Err(Error::BadFrame("a start trim is allowed only at the start of an Opus stream, 65 535 samples in all")); + } + duration = pes::opus_samples(frame.data).ok_or(Error::BadFrame("the Opus packet's table of contents is incomplete"))?; + if u32::from(trim.start) + u32::from(trim.end) > duration { + return Err(Error::BadFrame("the trim is longer than the Opus access unit")); + } + } + let with_dts = dts != frame.pts; + let header_len = if with_dts { 19 } else { 14 }; + let trim_bytes = if trim.start > 0 { 2 } else { 0 } + if trim.end > 0 { 2 } else { 0 }; + let limit = pes::data_limit(codec, header_len - 6, trim_bytes); + if frame.data.len() > limit { + return Err(Error::FrameTooLarge { size: frame.data.len(), limit }); + } + let mut prefix = [0u8; pes::PREFIX_MAX]; + let prep = pes::prepare(codec, frame.data, frame.key, trim, &mut prefix)?; + // start codes, escapes and delimiters count toward the reader's limit too + let encoded = prep.prefix_len.saturating_add(prep.body_len); + if codec.is_video() && encoded > MAX_VIDEO_FRAME { + return Err(Error::FrameTooLarge { size: encoded, limit: MAX_VIDEO_FRAME }); + } + // bytes after PES_packet_length + let body = (header_len - 6) + prep.prefix_len + prep.body_len; + let length = match u16::try_from(body) { + Ok(n) => n, + Err(_) if codec.is_video() => 0, + Err(_) => return Err(Error::FrameTooLarge { size: frame.data.len(), limit }), + }; + let t = self.time(dts)?; + // the frame must arrive no later than it decodes: its DTS may not be behind the clock + // that PCRs already sent (the largest DTS so far minus the PCR delay, or an advance) + if dts.checked_mul(300).is_none_or(|d| self.clock.is_some_and(|c| d < c)) { + return Err(Error::Timestamp("the decoding time is behind the transport stream clock")); + } + let mut header = [0u8; pes::HEADER_MAX]; + pes::header(&mut header, codec.stream_id(), length, frame.pts, with_dts.then_some(dts)); + + let clock = self.clock.map_or(t, |c| c.max(t)); + self.clock = Some(clock); + self.fill_pcr(clock)?; + // a keyframe needs the tables right in front of it: not again when they are the last + // packets written, but again when PCRs filling a gap came after them + let tables_last = self.psi_end == Some(self.sink.pushed); + self.psi_if_due(clock, frame.key && codec.is_video() && !tables_last)?; + let mut pcr = None; + if self.pcr_on == PcrOn::Stream(index) { + if self.pcr_forced || self.last_pcr.is_none_or(|l| clock > l) { + pcr = Some(clock); + self.last_pcr = Some(clock); + self.pcr_forced = false; + self.stats.pcrs += 1; + } + } else if self.pcr_due(clock) { + self.pcr_packet(clock)?; + } + let payload = match codec { + Codec::Av1(_) => Payload::Av1(av1::Escaper::new(frame.data)), + _ => Payload::Plain(frame.data), + }; + self.pes_packets(index, &header[..header_len], &prefix[..prep.prefix_len], payload, prep.body_len, pcr, frame.key)?; + if let Some(st) = self.streams.get_mut(index) { + st.last_dts = Some(dts); + if codec.is_opus() { + st.opus_start_trimmed += u32::from(trim.start); + if !trimmed || u32::from(trim.start) < duration { + st.opus_lead_in = false; + } + } + } + self.stats.frames += 1; + let seg = &mut self.seg; + seg.frames += 1; + seg.first_pts.get_or_insert(frame.pts); + seg.last_pts = Some(seg.last_pts.map_or(frame.pts, |p| p.max(frame.pts))); + if codec.is_video() { + seg.first_video_key.get_or_insert(frame.key); + } + Ok(()) + } + + /// The PCR interval at 27 MHz. + fn limit(&self) -> i64 { + i64::from(self.cfg.pcr_interval) * 300 + } + + fn psi_if_due(&mut self, clock: i64, keyframe: bool) -> Result<()> { + let due = self.psi_forced + || self.last_psi.is_none_or(|l| clock.saturating_sub(l) >= i64::from(self.cfg.psi_interval) * 300) + || (keyframe && self.cfg.psi_before_keyframes); + if due { + section_packets(&mut self.sink, 0, &mut self.pat_cc, &self.pat)?; + section_packets(&mut self.sink, self.cfg.pmt_pid, &mut self.pmt_cc, &self.pmt)?; + self.last_psi = Some(clock); + self.psi_end = Some(self.sink.pushed); + self.psi_forced = false; + self.stats.psi += 1; + } + Ok(()) + } + + /// Fills the gap up to `clock`: PCR-only packets until the gap to `clock` is within the PCR + /// interval, and the PAT and PMT wherever they fall due before `clock`, in time order. A new + /// writer gets the PAT and PMT before anything else. + fn fill_pcr(&mut self, clock: i64) -> Result<()> { + let Some(last_pcr) = self.last_pcr else { return Ok(()) }; + if self.psi_forced { + self.psi_if_due(last_pcr, false)?; + } + let limit = self.limit(); + let psi = i64::from(self.cfg.psi_interval) * 300; + // each kind of packet is capped on its own, so a short PAT and PMT interval cannot use + // up the PCRs' share + let (mut pcrs, mut tables) = (0, 0); + loop { + let mut pcr_at = self.last_pcr.map(|l| l.saturating_add(limit)).filter(|&t| t < clock); + if pcrs >= MAX_PCR_FILL && pcr_at.is_some() { + if pcrs == MAX_PCR_FILL { + // counted once: the PCR at `clock` that follows closes the gap + self.stats.pcr_gaps += 1; + pcrs += 1; + } + pcr_at = None; + } + let psi_at = self.last_psi.map(|l| l.saturating_add(psi)).filter(|&t| t < clock && tables < MAX_PCR_FILL); + match (psi_at, pcr_at) { + (Some(s), Some(p)) if s <= p => { + self.psi_if_due(s, false)?; + tables += 1; + } + (Some(s), None) => { + self.psi_if_due(s, false)?; + tables += 1; + } + (_, Some(p)) => { + self.pcr_packet(p)?; + pcrs += 1; + } + (None, None) => return Ok(()), + } + } + } + + /// A packet on the PCR PID with only an adaptation field holding the PCR. + fn pcr_packet(&mut self, pcr: i64) -> Result<()> { + let (pid, cc, disc) = match self.pcr_on { + PcrOn::Stream(i) => match self.streams.get_mut(i) { + Some(s) => (s.pid, s.held_cc(), std::mem::take(&mut s.disc)), + None => (0x1FFF, 0, false), + }, + PcrOn::Own(pid) => (pid, 0, std::mem::take(&mut self.own_pcr_disc)), + }; + let mut b = [0xFF; PACKET_SIZE]; + b[..6].copy_from_slice(&[0x47, (pid >> 8) as u8 & 0x1F, pid as u8, 0x20 | cc, 183, 0x10 | if disc { 0x80 } else { 0 }]); + b[6..12].copy_from_slice(&pes::pcr(pcr)); + self.sink.push(&b)?; + self.stats.pcrs += 1; + self.last_pcr = Some(pcr); + self.pcr_forced = false; + Ok(()) + } + + /// Splits one PES packet (`header`, `prefix`, then `body_len` bytes of `payload`) into + /// transport packets. + #[allow(clippy::too_many_arguments)] + fn pes_packets( + &mut self, + index: usize, + header: &[u8], + prefix: &[u8], + mut payload: Payload<'_>, + body_len: usize, + pcr: Option, + key: bool, + ) -> Result<()> { + let Some(st) = self.streams.get_mut(index) else { return Err(Error::NoSuchStream(index)) }; + let pid = st.pid; + let mut parts = [header, prefix]; + let mut left = header.len() + prefix.len() + body_len; + let mut first = true; + while left > 0 { + let pcr_here = if first { pcr } else { None }; + let rai = first && key; + let disc = first && st.disc; + let fixed = if pcr_here.is_some() || rai || disc { 2 + if pcr_here.is_some() { 6 } else { 0 } } else { 0 }; + let take = left.min(184 - fixed); + // the adaptation field, its length byte included + let af = 184 - take; + let mut b = [0u8; PACKET_SIZE]; + b[0] = 0x47; + b[1] = if first { 0x40 } else { 0 } | (pid >> 8) as u8 & 0x1F; + b[2] = pid as u8; + b[3] = if af > 0 { 0x30 } else { 0x10 } | st.cc; + st.cc = (st.cc + 1) & 0x0F; + if af > 0 { + b[4] = (af - 1) as u8; + if af > 1 { + b[5] = if disc { 0x80 } else { 0 } | if rai { 0x40 } else { 0 } | if pcr_here.is_some() { 0x10 } else { 0 }; + let mut p = 6; + if let Some(v) = pcr_here { + b[6..12].copy_from_slice(&pes::pcr(v)); + p = 12; + } + b[p..4 + af].fill(0xFF); + } + } + if disc { + st.disc = false; + } + let mut at = 4 + af; + for part in &mut parts { + let n = part.len().min(PACKET_SIZE - at); + b[at..at + n].copy_from_slice(&part[..n]); + *part = &part[n..]; + at += n; + } + if at < PACKET_SIZE { + payload.fill(&mut b[at..]); + } + self.sink.push(&b)?; + left -= take; + first = false; + } + Ok(()) + } +} + +/// Writes a PSI section on `pid`: a pointer field of 0, the section, and 0xFF stuffing. +fn section_packets(sink: &mut Sink, pid: u16, cc: &mut u8, section: &[u8]) -> Result<()> { + let mut rest = section; + let mut first = true; + while first || !rest.is_empty() { + let mut b = [0xFF; PACKET_SIZE]; + b[0] = 0x47; + b[1] = if first { 0x40 } else { 0 } | (pid >> 8) as u8 & 0x1F; + b[2] = pid as u8; + b[3] = 0x10 | *cc; + *cc = (*cc + 1) & 0x0F; + let mut at = 4; + if first { + b[4] = 0; + at = 5; + } + let n = rest.len().min(PACKET_SIZE - at); + b[at..at + n].copy_from_slice(&rest[..n]); + rest = &rest[n..]; + sink.push(&b)?; + first = false; + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/media/src/mpegts/mux/pes.rs b/crates/media/src/mpegts/mux/pes.rs new file mode 100644 index 0000000000..89127c627d --- /dev/null +++ b/crates/media/src/mpegts/mux/pes.rs @@ -0,0 +1,389 @@ +//! PES packet headers (H.222.0 §2.4.3.6), the adaptation field's PCR (§2.4.3.4), and the bytes +//! written ahead of a frame: access unit delimiters, ADTS headers and Opus control headers. + +use super::{Codec, Error, MAX_VIDEO_FRAME, OpusTrim, av1}; + +/// 2^33: PTS, DTS and the PCR base are 33-bit counters. +pub(crate) const WRAP_90K: i64 = 1 << 33; + +/// Largest PES header this writer produces: 9 bytes, PTS and DTS. +pub(crate) const HEADER_MAX: usize = 19; + +/// Largest prefix: an Opus control header for a 65 535-byte packet (2 bytes, 257 size bytes, a +/// start and an end trim). +pub(crate) const PREFIX_MAX: usize = 2 + 0xFFFF / 255 + 1 + 4; + +/// What [`prepare`] found: the prefix it wrote, and the bytes the frame takes after it. +pub(crate) struct Prepared { + pub(crate) prefix_len: usize, + pub(crate) body_len: usize, +} + +/// Most frame bytes `codec` allows when the PES header has `header` bytes after +/// PES_packet_length and an Opus control header carries `trim` trim bytes. +pub(crate) fn data_limit(codec: Codec, header: usize, trim: usize) -> usize { + let room = 0xFFFF - header; + match codec { + c if c.is_video() => MAX_VIDEO_FRAME, + // ADTS frame_length is 13 bits + Codec::Aac { .. } => (0x1FFF - 7).min(room - 7), + Codec::Opus { .. } | Codec::OpusMapped(_) => { + // the control header takes 3 bytes, a size byte per 255 bytes, and the trims + let budget = room - 3 - trim; + let mut l = budget * 255 / 256; + while l + 1 + (l + 1) / 255 <= budget { + l += 1; + } + while l + l / 255 > budget { + l -= 1; + } + l + } + _ => room, + } +} + +/// Samples per channel at 48 kHz in an Opus packet, from its table of contents (RFC 6716 §3.1). +pub(crate) fn opus_samples(data: &[u8]) -> Option { + let toc = *data.first()?; + let config = usize::from(toc >> 3); + let frame = match config { + 0..=11 => [480, 960, 1920, 2880][config % 4], + 12..=15 => [480, 960][config % 2], + _ => [120, 240, 480, 960][config % 4], + }; + let count = match toc & 3 { + 0 => 1, + 1 | 2 => 2, + _ => u32::from(*data.get(1)? & 0x3F), + }; + Some(frame * count) +} + +/// Checks that an ADTS frame or a run of them fills `data` exactly. +fn check_adts(data: &[u8]) -> Result<(), Error> { + let mut at = 0; + while at < data.len() { + let f = &data[at..]; + let &[0xFF, b1, _, b3, b4, b5, _, ..] = f else { return Err(Error::BadFrame("an AAC frame must start with an ADTS header")) }; + if b1 & 0xF6 != 0xF0 { + return Err(Error::BadFrame("an AAC frame must start with an ADTS header")); + } + let header = if b1 & 1 == 0 { 9 } else { 7 }; + let len = usize::from(b3 & 3) << 11 | usize::from(b4) << 3 | usize::from(b5 >> 5); + if len < header || len > f.len() { + return Err(Error::BadFrame("an ADTS frame_length does not match the frame")); + } + at += len; + } + Ok(()) +} + +/// A 33-bit timestamp with its 4-bit prefix and marker bits (§2.4.3.7). +fn timestamp(prefix: u8, v: i64) -> [u8; 5] { + let v = v.rem_euclid(WRAP_90K); + [prefix << 4 | ((v >> 29) & 0x0E) as u8 | 1, (v >> 22) as u8, ((v >> 14) & 0xFE) as u8 | 1, (v >> 7) as u8, ((v << 1) & 0xFE) as u8 | 1] +} + +/// Writes a PES header into `out` and returns its length. `length` is the PES_packet_length field +/// (0 for an unbounded video packet). +pub(crate) fn header(out: &mut [u8; HEADER_MAX], stream_id: u8, length: u16, pts: i64, dts: Option) -> usize { + let [hi, lo] = length.to_be_bytes(); + // '10', not scrambled, no priority, data_alignment_indicator set, not copyrighted, a copy + out[..7].copy_from_slice(&[0, 0, 1, stream_id, hi, lo, 0x84]); + match dts { + Some(dts) => { + out[7] = 0xC0; + out[8] = 10; + out[9..14].copy_from_slice(×tamp(3, pts)); + out[14..19].copy_from_slice(×tamp(1, dts)); + 19 + } + None => { + out[7] = 0x80; + out[8] = 5; + out[9..14].copy_from_slice(×tamp(2, pts)); + 14 + } + } +} + +/// The six program_clock_reference bytes for a 27 MHz clock value: the 33-bit base (clock / 300), +/// six reserved bits, and the 9-bit extension (clock % 300). +pub(crate) fn pcr(clock: i64) -> [u8; 6] { + let v = clock.rem_euclid(WRAP_90K * 300); + let (base, ext) = (v / 300, v % 300); + [(base >> 25) as u8, (base >> 17) as u8, (base >> 9) as u8, (base >> 1) as u8, ((base & 1) << 7) as u8 | 0x7E | (ext >> 8) as u8, ext as u8] +} + +/// The first NAL unit's first header byte, when `data` starts with an Annex B start code. +fn first_nal(data: &[u8]) -> Option { + let at = if data.starts_with(&[0, 0, 1]) { + 3 + } else if data.starts_with(&[0, 0, 0, 1]) { + 4 + } else { + return None; + }; + data.get(at).copied() +} + +/// Checks that `data` is a frame of `codec`, writes what goes in front of it into `out`, and +/// returns the prefix length and the bytes the frame itself takes. +pub(crate) fn prepare(codec: Codec, data: &[u8], key: bool, trim: OpusTrim, out: &mut [u8; PREFIX_MAX]) -> Result { + if let Codec::Av1(_) = codec { + return Ok(Prepared { prefix_len: 0, body_len: av1::check(data, key)? }); + } + let prefix_len = prefix(codec, data, trim, out)?; + Ok(Prepared { prefix_len, body_len: data.len() }) +} + +/// Checks a frame of a codec carried as it is and writes its prefix. Returns the prefix length. +fn prefix(codec: Codec, data: &[u8], trim: OpusTrim, out: &mut [u8; PREFIX_MAX]) -> Result { + match codec { + Codec::H264 => { + let nal = first_nal(data).ok_or(Error::BadFrame("an H.264 frame must start with an Annex B start code"))?; + if nal & 0x1F == 9 { + return Ok(0); + } + // access unit delimiter, primary_pic_type 7 (any slice type) (H.222.0 §2.14) + out[..6].copy_from_slice(&[0, 0, 0, 1, 0x09, 0xF0]); + Ok(6) + } + Codec::Hevc => { + let nal = first_nal(data).ok_or(Error::BadFrame("an HEVC frame must start with an Annex B start code"))?; + if (nal >> 1) & 0x3F == 35 { + return Ok(0); + } + // access unit delimiter (nal_unit_type 35), pic_type 2 (any slice type) (H.222.0 §2.17) + out[..7].copy_from_slice(&[0, 0, 0, 1, 0x46, 0x01, 0x50]); + Ok(7) + } + Codec::Mpeg1Video | Codec::Mpeg2Video | Codec::Mpeg4Part2 => { + first_nal(data).ok_or(Error::BadFrame("an MPEG video frame must start with a start code"))?; + Ok(0) + } + Codec::AacAdts => { + check_adts(data)?; + Ok(0) + } + Codec::Aac { object_type, sample_rate_index, channels } => { + let len = data.len() + 7; + if len > 0x1FFF { + return Err(Error::FrameTooLarge { size: data.len(), limit: 0x1FFF - 7 }); + } + // ADTS fixed and variable header (ISO/IEC 13818-7 §6.2): MPEG-4, no CRC, buffer + // fullness 0x7FF (variable rate), one raw data block + out[..7].copy_from_slice(&[ + 0xFF, + 0xF1, + (object_type - 1) << 6 | sample_rate_index << 2 | channels >> 2, + (channels & 3) << 6 | (len >> 11) as u8, + (len >> 3) as u8, + ((len & 7) as u8) << 5 | 0x1F, + 0xFC, + ]); + Ok(7) + } + Codec::Opus { .. } | Codec::OpusMapped(_) => { + // opus_control_header: the 11-bit prefix 0x3FF, the trim flags, no extension, the + // payload size as 0xFF bytes and a last byte, then the trims (3 reserved bits and + // 13 bits each) + let n = data.len() / 255; + let trims = if trim.start > 0 { 2 } else { 0 } + if trim.end > 0 { 2 } else { 0 }; + if 3 + n + trims > PREFIX_MAX { + return Err(Error::FrameTooLarge { size: data.len(), limit: data_limit(codec, 8, trims) }); + } + out[0] = 0x7F; + out[1] = 0xE0 | if trim.start > 0 { 0x10 } else { 0 } | if trim.end > 0 { 0x08 } else { 0 }; + out[2..2 + n].fill(0xFF); + out[2 + n] = (data.len() % 255) as u8; + let mut at = 3 + n; + for t in [trim.start, trim.end] { + if t > 0 { + out[at..at + 2].copy_from_slice(&(t & 0x1FFF).to_be_bytes()); + at += 2; + } + } + Ok(at) + } + Codec::Ac3 => match data { + [0x0B, 0x77, ..] => Ok(0), + _ => Err(Error::BadFrame("an AC-3 frame must start with its sync word")), + }, + Codec::Eac3 => match data { + // bsid, the top five bits of byte 5, is 11 to 16 for E-AC-3 (ATSC A/52) + [0x0B, 0x77, _, _, _, b5, ..] if (11..=16).contains(&(b5 >> 3)) => Ok(0), + _ => Err(Error::BadFrame("an E-AC-3 frame must start with its sync word and a bsid of 11 to 16")), + }, + Codec::MpegAudio { low_sample_rate } => match data { + [0xFF, b, ..] if b & 0xE0 == 0xE0 => { + // version: 3 MPEG-1, 2 MPEG-2, 0 MPEG 2.5, 1 reserved; layer 0 is reserved + let version = (b >> 3) & 3; + if version == 1 || (b >> 1) & 3 == 0 { + return Err(Error::BadFrame("the MPEG audio frame header has a reserved version or layer")); + } + if (version == 3) == low_sample_rate { + return Err(Error::BadFrame("the MPEG audio frame's version does not match the stream's low_sample_rate")); + } + Ok(0) + } + _ => Err(Error::BadFrame("an MPEG audio frame must start with its sync word")), + }, + Codec::Av1(_) => Err(Error::BadFrame("AV1 frames are not carried with a prefix")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Reads a 33-bit timestamp back from its five bytes. + fn read(b: &[u8]) -> i64 { + (((b[0] >> 1) & 7) as i64) << 30 | (b[1] as i64) << 22 | ((b[2] >> 1) as i64) << 15 | (b[3] as i64) << 7 | (b[4] >> 1) as i64 + } + + #[test] + fn timestamps_carry_their_prefix_and_markers() { + for v in [0, 1, 90_000, (1 << 32) + 12_345, WRAP_90K - 1] { + let b = timestamp(2, v); + assert_eq!(b[0] >> 4, 2); + assert_eq!([b[0] & 1, b[2] & 1, b[4] & 1], [1, 1, 1]); + assert_eq!(read(&b), v); + } + assert_eq!(read(×tamp(2, WRAP_90K + 5)), 5, "wraps at 2^33"); + assert_eq!(read(×tamp(2, -1)), WRAP_90K - 1); + } + + #[test] + fn headers_hold_pts_and_dts() { + let mut h = [0u8; HEADER_MAX]; + assert_eq!(header(&mut h, 0xE0, 0, 3000, Some(0)), 19); + assert_eq!(&h[..9], &[0, 0, 1, 0xE0, 0, 0, 0x84, 0xC0, 10]); + assert_eq!((h[9] >> 4, read(&h[9..14]), h[14] >> 4, read(&h[14..19])), (3, 3000, 1, 0)); + assert_eq!(header(&mut h, 0xC0, 300, 7, None), 14); + assert_eq!(&h[4..9], &[1, 44, 0x84, 0x80, 5]); + } + + #[test] + fn pcr_splits_base_and_extension() { + let clock = 123_456_789i64 * 300 + 299; + let b = pcr(clock); + let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64; + let ext = ((b[4] & 1) as i64) << 8 | b[5] as i64; + assert_eq!((base, ext, b[4] & 0x7E), (123_456_789, 299, 0x7E)); + } + + const NO_TRIM: OpusTrim = OpusTrim { start: 0, end: 0 }; + + #[test] + fn access_unit_delimiters_are_added_once() { + let mut p = [0u8; PREFIX_MAX]; + assert_eq!(prefix(Codec::H264, &[0, 0, 0, 1, 0x65, 0x88], NO_TRIM, &mut p).unwrap(), 6); + assert_eq!(prefix(Codec::H264, &[0, 0, 1, 0x09, 0xF0, 0, 0, 1, 0x65], NO_TRIM, &mut p).unwrap(), 0); + assert_eq!(prefix(Codec::Hevc, &[0, 0, 0, 1, 0x26, 0x01], NO_TRIM, &mut p).unwrap(), 7); + assert_eq!(prefix(Codec::Hevc, &[0, 0, 1, 0x46, 0x01, 0x50], NO_TRIM, &mut p).unwrap(), 0); + assert!(matches!(prefix(Codec::H264, &[0x65, 0x88], NO_TRIM, &mut p), Err(Error::BadFrame(_)))); + assert!(matches!(prefix(Codec::H264, &[0, 0, 1], NO_TRIM, &mut p), Err(Error::BadFrame(_)))); + } + + #[test] + fn opus_control_header_codes_the_size_and_trims() { + let mut p = [0u8; PREFIX_MAX]; + let opus = Codec::Opus { channels: 2 }; + assert_eq!(prefix(opus, &[0xFC; 254], NO_TRIM, &mut p).unwrap(), 3); + assert_eq!(&p[..3], &[0x7F, 0xE0, 254]); + assert_eq!(prefix(opus, &[0xFC; 510], NO_TRIM, &mut p).unwrap(), 5); + assert_eq!(&p[..5], &[0x7F, 0xE0, 0xFF, 0xFF, 0]); + assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 312, end: 0 }, &mut p).unwrap(), 5); + assert_eq!(&p[..5], &[0x7F, 0xF0, 10, 0x01, 0x38]); + assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 1, end: 8191 }, &mut p).unwrap(), 7); + assert_eq!(&p[..7], &[0x7F, 0xF8, 10, 0, 1, 0x1F, 0xFF]); + assert_eq!(prefix(opus, &[0xFC; 10], OpusTrim { start: 0, end: 2 }, &mut p).unwrap(), 5); + assert_eq!(&p[..5], &[0x7F, 0xE8, 10, 0, 2]); + } + + #[test] + fn opus_limits_match_the_pes_length() { + for (header, trim) in [(8, 0), (13, 0), (8, 4), (13, 2)] { + let l = data_limit(Codec::Opus { channels: 2 }, header, trim); + let body = |n: usize| header + 3 + n / 255 + trim + n; + assert!(body(l) <= 0xFFFF && body(l + 1) > 0xFFFF, "{header} {trim}: {l}"); + } + assert_eq!(data_limit(Codec::Ac3, 8, 0), 0xFFFF - 8); + assert_eq!(data_limit(Codec::Mpeg4Part2, 13, 0), MAX_VIDEO_FRAME); + } + + #[test] + fn opus_durations_from_the_table_of_contents() { + assert_eq!(opus_samples(&[0xFC]), Some(960), "CELT 20 ms, one frame"); + assert_eq!(opus_samples(&[0x08 | 1]), Some(1920), "SILK 20 ms, two frames"); + assert_eq!(opus_samples(&[0x18 | 3, 3]), Some(3 * 2880), "SILK 60 ms, three frames"); + assert_eq!(opus_samples(&[0x80]), Some(120), "CELT 2.5 ms"); + assert_eq!(opus_samples(&[0x03]), None); + assert_eq!(opus_samples(&[]), None); + } + + #[test] + fn adts_header_for_raw_aac() { + let mut p = [0u8; PREFIX_MAX]; + let codec = Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }; + assert_eq!(prefix(codec, &[0; 100], NO_TRIM, &mut p).unwrap(), 7); + // AAC LC, 48 kHz, 2 channels, 107 bytes + assert_eq!(&p[..7], &[0xFF, 0xF1, 0x4C, 0x80, 0x0D, 0x7F, 0xFC]); + assert!(matches!(prefix(codec, &[0; 8185], NO_TRIM, &mut p), Err(Error::FrameTooLarge { .. }))); + assert_eq!(data_limit(codec, 8, 0), 8184); + } + + fn adts(len: usize) -> Vec { + let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC]; + v.resize(len, 0x11); + v + } + + #[test] + fn adts_frame_lengths_must_tile_the_frame() { + let mut p = [0u8; PREFIX_MAX]; + assert_eq!(prefix(Codec::AacAdts, &adts(100), NO_TRIM, &mut p).unwrap(), 0); + let two = [adts(100), adts(57)].concat(); + assert_eq!(prefix(Codec::AacAdts, &two, NO_TRIM, &mut p).unwrap(), 0); + let mut short = adts(100); + short.pop(); + assert!(matches!(prefix(Codec::AacAdts, &short, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "one byte short"); + let mut long = adts(100); + long.push(0); + assert!(matches!(prefix(Codec::AacAdts, &long, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "a trailing byte"); + let mut zero = adts(100); + zero[3] &= 0xFC; + zero[4] = 0; + zero[5] &= 0x1F; + assert!(matches!(prefix(Codec::AacAdts, &zero, NO_TRIM, &mut p), Err(Error::BadFrame(_))), "frame_length 0"); + // a header with a CRC is 9 bytes, so a frame_length of 8 does not hold it + let mut crc = adts(8); + crc[1] = 0xF0; + assert!(matches!(prefix(Codec::AacAdts, &crc, NO_TRIM, &mut p), Err(Error::BadFrame(_)))); + } + + #[test] + fn mpeg_audio_versions_match_the_stream_type() { + let mut p = [0u8; PREFIX_MAX]; + let (mpeg1, mpeg2, mpeg25, reserved) = ([0xFF, 0xFB, 0x90], [0xFF, 0xF3, 0x90], [0xFF, 0xE3, 0x90], [0xFF, 0xEB, 0x90]); + let high = Codec::MpegAudio { low_sample_rate: false }; + let low = Codec::MpegAudio { low_sample_rate: true }; + assert!(prefix(high, &mpeg1, NO_TRIM, &mut p).is_ok()); + assert!(prefix(low, &mpeg2, NO_TRIM, &mut p).is_ok()); + assert!(prefix(low, &mpeg25, NO_TRIM, &mut p).is_ok()); + assert!(prefix(low, &mpeg1, NO_TRIM, &mut p).is_err()); + assert!(prefix(high, &mpeg2, NO_TRIM, &mut p).is_err()); + assert!(prefix(high, &reserved, NO_TRIM, &mut p).is_err()); + assert!(prefix(high, &[0xFF, 0xF9, 0x90], NO_TRIM, &mut p).is_err(), "layer 0"); + } + + #[test] + fn eac3_needs_its_bsid() { + let mut p = [0u8; PREFIX_MAX]; + assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34, 16 << 3], NO_TRIM, &mut p).is_ok()); + assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34, 8 << 3], NO_TRIM, &mut p).is_err(), "AC-3's bsid"); + assert!(prefix(Codec::Eac3, &[0x0B, 0x77, 0, 0x7F, 0x34], NO_TRIM, &mut p).is_err()); + } +} diff --git a/crates/media/src/mpegts/mux/psi.rs b/crates/media/src/mpegts/mux/psi.rs new file mode 100644 index 0000000000..b4c55c3fb4 --- /dev/null +++ b/crates/media/src/mpegts/mux/psi.rs @@ -0,0 +1,216 @@ +//! Program specific information: the program association section and the program map section +//! (H.222.0 §2.4.4), each ending with the CRC-32 of Annex A that the demuxer checks. + +pub(crate) use super::super::ts::crc32_mpeg as crc32; +use super::{Codec, Error, OpusMapping, Stream}; + +/// Largest `section_length` of a program association or program map section (§2.4.4.3, §2.4.4.8). +pub(crate) const MAX_SECTION_LENGTH: usize = 1021; + +/// Writes `section_length` into bytes 1 and 2 and appends the CRC. `s` holds the section from +/// `table_id` up to the CRC. +fn finish(mut s: Vec) -> Result, Error> { + let length = s.len() + 4 - 3; + if length > MAX_SECTION_LENGTH { + return Err(Error::PsiTooLarge { length }); + } + s[1] = 0xB0 | (length >> 8) as u8; + s[2] = length as u8; + let crc = crc32(&s); + s.extend_from_slice(&crc.to_be_bytes()); + Ok(s) +} + +/// The program association section with one program. +pub(crate) fn pat(transport_stream_id: u16, program_number: u16, pmt_pid: u16) -> Result, Error> { + let mut s = vec![0x00, 0, 0]; + s.extend_from_slice(&transport_stream_id.to_be_bytes()); + // reserved, version_number 0, current_next_indicator 1; section_number 0, last_section_number 0 + s.extend_from_slice(&[0xC1, 0x00, 0x00]); + s.extend_from_slice(&program_number.to_be_bytes()); + s.extend_from_slice(&(0xE000 | pmt_pid).to_be_bytes()); + finish(s) +} + +/// The program map section. +pub(crate) fn pmt(program_number: u16, pcr_pid: u16, streams: &[Stream]) -> Result, Error> { + let mut s = vec![0x02, 0, 0]; + s.extend_from_slice(&program_number.to_be_bytes()); + s.extend_from_slice(&[0xC1, 0x00, 0x00]); + s.extend_from_slice(&(0xE000 | pcr_pid).to_be_bytes()); + // program_info_length 0 + s.extend_from_slice(&[0xF0, 0x00]); + for st in streams { + s.push(st.codec.stream_type()); + s.extend_from_slice(&(0xE000 | st.pid).to_be_bytes()); + let at = s.len(); + s.extend_from_slice(&[0xF0, 0x00]); + descriptors(st, &mut s); + let len = s.len() - at - 2; + s[at] = 0xF0 | (len >> 8) as u8; + s[at + 1] = len as u8; + } + finish(s) +} + +/// The elementary stream descriptors of one stream. +fn descriptors(st: &Stream, s: &mut Vec) { + match st.codec { + // registration_descriptor (§2.6.8) with the format identifier "AC-3" + Codec::Ac3 => s.extend_from_slice(&[0x05, 4, b'A', b'C', b'-', b'3']), + // registration "EAC3" (ATSC A/52) with stream type 0x87 + Codec::Eac3 => s.extend_from_slice(&[0x05, 4, b'E', b'A', b'C', b'3']), + Codec::Opus { channels } => { + // registration_descriptor "Opus", then the Opus audio descriptor as an extension + // descriptor (tag 0x7F) whose channel_config_code is the channel count (1 to 8) + s.extend_from_slice(&[0x05, 4, b'O', b'p', b'u', b's']); + s.extend_from_slice(&[0x7F, 2, OPUS_DESCRIPTOR_EXTENSION, channels]); + } + Codec::OpusMapped(m) => { + s.extend_from_slice(&[0x05, 4, b'O', b'p', b'u', b's']); + let mut body = [0u8; 10]; + let n = opus_explicit(&m, &mut body); + s.extend_from_slice(&[0x7F, 1 + n as u8, OPUS_DESCRIPTOR_EXTENSION]); + s.extend_from_slice(&body[..n]); + } + Codec::Av1(c) => { + // registration_descriptor "AV01" first, then the AV1 video descriptor (tag 0x80) + // (Carriage of AV1 in MPEG-2 TS, §2) + s.extend_from_slice(&[0x05, 4, b'A', b'V', b'0', b'1']); + let b = |v: bool, shift: u8| u8::from(v) << shift; + s.extend_from_slice(&[ + 0x80, + 4, + 0x81, + c.seq_profile << 5 | c.seq_level_idx_0, + b(c.seq_tier_0, 7) + | b(c.high_bitdepth, 6) + | b(c.twelve_bit, 5) + | b(c.monochrome, 4) + | b(c.chroma_subsampling_x, 3) + | b(c.chroma_subsampling_y, 2) + | c.chroma_sample_position, + // hdr_wcg_idc, then reserved zeros and no initial_presentation_delay + c.hdr_wcg_idc << 6, + ]); + } + _ => {} + } + if let Some(lang) = st.language { + // ISO_639_language_descriptor (§2.6.18), audio_type 0 (undefined) + s.extend_from_slice(&[0x0A, 4, lang[0], lang[1], lang[2], 0]); + } +} + +/// `descriptor_tag_extension` of the Opus audio descriptor. The Opus transport draft leaves the +/// value open; 0x80 is the value in use for it. +pub(crate) const OPUS_DESCRIPTOR_EXTENSION: u8 = 0x80; + +/// Bits needed for the values 0 to `n - 1`: ceil(log2(n)). +fn bits_for(n: u32) -> u32 { + if n <= 1 { 0 } else { 32 - (n - 1).leading_zeros() } +} + +/// The opus_audio_descriptor body for an explicit channel configuration (channel_config_code +/// 0x81): channel_count, mapping_family and, for a family above 0, stream_count_minus_one, +/// coupled_stream_count and the channel mapping in as few bits as the draft gives each, padded +/// with zero bits to a byte. Returns its length. +fn opus_explicit(m: &OpusMapping, out: &mut [u8; 10]) -> usize { + out[..3].copy_from_slice(&[0x81, m.channels, m.family]); + if m.family == 0 { + return 3; + } + let (ch, streams, coupled) = (u32::from(m.channels), u32::from(m.streams), u32::from(m.coupled)); + let mut acc: u64 = 0; + let mut bits = 0; + let mut put = |v: u32, n: u32| { + acc = acc << n | u64::from(v & ((1 << n) - 1)); + bits += n; + }; + put(streams - 1, bits_for(ch)); + put(coupled, bits_for(streams + 1)); + let width = bits_for(streams + coupled + 1); + for &c in &m.mapping[..usize::from(m.channels)] { + put(if c == 255 { (1 << width) - 1 } else { u32::from(c) }, width); + } + let bytes = bits.div_ceil(8) as usize; + let acc = acc << (bytes as u32 * 8 - bits); + for (i, o) in out[3..3 + bytes].iter_mut().enumerate() { + *o = (acc >> (8 * (bytes - 1 - i))) as u8; + } + 3 + bytes +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crc_check_value() { + // the CRC-32/MPEG-2 check value of the ASCII digits 1 to 9 + assert_eq!(crc32(b"123456789"), 0x0376_E6E7); + } + + #[test] + fn sections_end_with_a_crc_over_the_whole_section() { + let pat = pat(7, 1, 0x1000).unwrap(); + assert_eq!(pat.len(), 16); + assert_eq!(crc32(&pat), 0); + assert_eq!(&pat[..3], &[0x00, 0xB0, 13]); + assert_eq!(&pat[8..12], &[0x00, 0x01, 0xF0, 0x00]); + let st = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Opus { channels: 2 }).with_language(*b"eng")]; + let pmt = pmt(1, 0x100, &st).unwrap(); + assert_eq!(crc32(&pmt), 0); + assert_eq!(pmt.len(), 3 + ((pmt[1] as usize & 0x0F) << 8 | pmt[2] as usize)); + assert_eq!(&pmt[8..10], &[0xE1, 0x00], "PCR_PID"); + assert_eq!(&pmt[12..17], &[0x1B, 0xE1, 0x00, 0xF0, 0x00], "H.264 without descriptors"); + assert_eq!(&pmt[17..22], &[0x06, 0xE1, 0x01, 0xF0, 16]); + } + + #[test] + fn a_section_past_the_length_limit_is_refused() { + let st: Vec = (0..200).map(|i| Stream::new(0x100 + i, Codec::Ac3).with_language(*b"eng")).collect(); + assert!(matches!(pmt(1, 0x100, &st), Err(Error::PsiTooLarge { .. }))); + } + + /// The descriptors of one stream's PMT entry. + fn stream_descriptors(codec: Codec) -> Vec { + let pmt = pmt(1, 0x100, &[Stream::new(0x100, codec)]).unwrap(); + let len = ((pmt[15] as usize & 0x0F) << 8) | pmt[16] as usize; + pmt[17..17 + len].to_vec() + } + + #[test] + fn explicit_opus_mappings_pack_their_fields() { + // 6 channels, family 1, 4 streams, 2 coupled: 3 + 3 + 6 * 3 = 24 bits + let m = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }; + let d = stream_descriptors(Codec::OpusMapped(m)); + let want = 0b011 << 21 | 0b010 << 18 | 0b000_100_001_010_011_101; + assert_eq!(&d[6..], &[0x7F, 7, 0x80, 0x81, 6, 1, (want >> 16) as u8, (want >> 8) as u8, want as u8]); + // 3 channels, family 255, 3 streams, none coupled, one silent: 2 + 2 + 3 * 2 = 10 bits + let m = OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [2, 255, 0, 0, 0, 0, 0, 0] }; + let d = stream_descriptors(Codec::OpusMapped(m)); + assert_eq!(&d[6..], &[0x7F, 6, 0x80, 0x81, 3, 255, 0b10_00_10_11, 0b00_000000]); + // family 0 carries no stream fields + let m = OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] }; + assert_eq!(&stream_descriptors(Codec::OpusMapped(m))[6..], &[0x7F, 4, 0x80, 0x81, 2, 0]); + } + + #[test] + fn av1_and_eac3_descriptors() { + let c = crate::mpegts::mux::Av1Config { + seq_profile: 1, + seq_level_idx_0: 8, + seq_tier_0: false, + high_bitdepth: true, + twelve_bit: false, + monochrome: false, + chroma_subsampling_x: false, + chroma_subsampling_y: false, + chroma_sample_position: 0, + hdr_wcg_idc: 3, + }; + assert_eq!(stream_descriptors(Codec::Av1(c)), [0x05, 4, b'A', b'V', b'0', b'1', 0x80, 4, 0x81, 0x28, 0x40, 0xC0]); + assert_eq!(stream_descriptors(Codec::Eac3), [0x05, 4, b'E', b'A', b'C', b'3']); + } +} diff --git a/crates/media/src/mpegts/mux/tests.rs b/crates/media/src/mpegts/mux/tests.rs new file mode 100644 index 0000000000..d007ea7550 --- /dev/null +++ b/crates/media/src/mpegts/mux/tests.rs @@ -0,0 +1,915 @@ +use super::*; + +use std::cell::RefCell; +use std::rc::Rc; + +const WIDE_OPUS: OpusMapping = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }; + +/// One packet's header fields. +#[derive(Debug, Clone, Copy)] +struct Pk { + pid: u16, + pusi: bool, + cc: u8, + payload: bool, + rai: bool, + disc: bool, + pcr: Option, +} + +fn walk(ts: &[u8]) -> Vec { + assert_eq!(ts.len() % PACKET_SIZE, 0); + ts.chunks(PACKET_SIZE) + .map(|p| { + assert_eq!(p[0], 0x47); + let afc = p[3] >> 4 & 3; + let (mut rai, mut disc, mut pcr) = (false, false, None); + if afc & 2 != 0 { + let len = p[4] as usize; + assert!(len <= 183); + if afc == 2 { + assert_eq!(len, 183); + } + if len > 0 { + rai = p[5] & 0x40 != 0; + disc = p[5] & 0x80 != 0; + if p[5] & 0x10 != 0 { + let b = &p[6..12]; + let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64; + pcr = Some(base * 300 + (((b[4] & 1) as i64) << 8 | b[5] as i64)); + } + } + } + Pk { pid: ((p[1] & 0x1F) as u16) << 8 | p[2] as u16, pusi: p[1] & 0x40 != 0, cc: p[3] & 0x0F, payload: afc & 1 != 0, rai, disc, pcr } + }) + .collect() +} + +fn h264(key: bool) -> Vec { + if key { + vec![0, 0, 0, 1, 0x67, 0x42, 0, 0x1E, 0, 0, 0, 1, 0x68, 0xCE, 0, 0, 1, 0x65, 0x88, 0x84, 0x21] + } else { + vec![0, 0, 0, 1, 0x41, 0x9A, 0x11] + } +} + +fn mux(cfg: Config, streams: &[Stream], f: impl FnOnce(&mut Muxer>)) -> Vec { + let mut m = Muxer::new(Vec::new(), cfg, streams).unwrap(); + f(&mut m); + m.finish().unwrap() +} + +#[test] +fn starts_with_pat_pmt_and_a_pcr_on_the_first_frame() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| { + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + assert_eq!(pk.len(), 3); + assert_eq!((pk[0].pid, pk[0].pusi), (0, true)); + assert_eq!((pk[1].pid, pk[1].pusi), (0x1000, true)); + assert_eq!((pk[2].pid, pk[2].pusi, pk[2].rai), (0x100, true, true)); + assert_eq!(pk[2].pcr, Some((90_000 - 63_000) * 300)); + // the payload ends the packet: the access unit delimiter, then the frame + let frame = h264(true); + let p = &ts[2 * PACKET_SIZE..]; + assert_eq!(&p[PACKET_SIZE - frame.len()..PACKET_SIZE], &frame[..]); + assert_eq!(&p[PACKET_SIZE - frame.len() - 6 - 14..PACKET_SIZE - frame.len() - 6][..4], &[0, 0, 1, 0xE0]); + assert_eq!(&p[PACKET_SIZE - frame.len() - 6..PACKET_SIZE - frame.len()], &[0, 0, 0, 1, 9, 0xF0]); +} + +#[test] +fn every_stuffing_length_fills_the_packet() { + // frames whose PES packet ends at every offset of a packet, with and without a PCR + for n in 1..=400usize { + let ts = mux(Config { pcr_pid: Some(0x200), ..Config::default() }, &[Stream::new(0x100, Codec::MpegAudio { low_sample_rate: false })], |m| { + let mut data = vec![0u8; n]; + data[0] = 0xFF; + if n > 1 { + data[1] = 0xFB; + } + if n == 1 { + assert!(matches!(m.write_frame(0, &Frame { data: &data, pts: 90_000, dts: None, key: true }), Err(Error::BadFrame(_)))); + return; + } + m.write_frame(0, &Frame { data: &data, pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &data, pts: 92_000, dts: None, key: false }).unwrap(); + }); + if n == 1 { + continue; + } + let pk = walk(&ts); + let mut payload = 0; + for (p, raw) in pk.iter().zip(ts.chunks(PACKET_SIZE)) { + if p.pid == 0x100 { + let start = if raw[3] & 0x20 != 0 { 5 + raw[4] as usize } else { 4 }; + payload += PACKET_SIZE - start; + } + } + assert_eq!(payload, 2 * (14 + n), "{n}"); + } +} + +#[test] +fn continuity_counters_count_payload_packets_per_pid() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| { + let big = { + let mut v = h264(true); + v.resize(10_000, 0x55); + v + }; + for k in 0..40i64 { + m.write_frame(0, &Frame { data: &big, pts: 90_000 + k * 3000, dts: None, key: k % 10 == 0 }).unwrap(); + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 1, 2, 3], pts: 90_000 + k * 3000, dts: None, key: true }).unwrap(); + } + }); + let mut last: std::collections::HashMap = Default::default(); + for p in walk(&ts) { + if let Some(&c) = last.get(&p.pid) { + let want = if p.payload { (c + 1) & 0x0F } else { c }; + assert_eq!(p.cc, want, "PID {:#x}", p.pid); + } + last.insert(p.pid, p.cc); + } +} + +#[test] +fn pcr_never_lapses_past_the_interval() { + for interval in [900u32, 3600, MAX_PCR_INTERVAL] { + // video on 0x100 carries the PCR; a 2 s gap in the video is filled from the audio clock + let ts = + mux(Config { pcr_interval: interval, ..Config::default() }, &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| { + let mut t = 90_000i64; + for k in 0..200i64 { + if !(50..110).contains(&k) { + m.write_frame(0, &Frame { data: &h264(k == 0), pts: t, dts: None, key: k == 0 }).unwrap(); + } + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 0], pts: t, dts: None, key: true }).unwrap(); + t += 3000; + } + }); + let pcrs: Vec = walk(&ts).iter().filter(|p| p.pid == 0x100).filter_map(|p| p.pcr).collect(); + assert!(pcrs.len() > 1); + for w in pcrs.windows(2) { + assert!(w[1] > w[0], "PCR goes forward"); + assert!(w[1] - w[0] <= i64::from(interval) * 300, "interval {interval}: {} apart", w[1] - w[0]); + } + } +} + +#[test] +fn pcr_on_a_pid_of_its_own_and_through_advance() { + let mut m = Muxer::new(Vec::new(), Config { pcr_pid: Some(0x1FF), ..Config::default() }, &[Stream::new(0x101, Codec::Ac3)]).unwrap(); + assert_eq!(m.pcr_pid(), 0x1FF); + m.advance(63_000).unwrap(); + m.advance(63_000 + 90_000).unwrap(); + m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000 + 90_000, dts: None, key: true }).unwrap(); + let st = m.stats(); + let ts = m.finish().unwrap(); + let pk = walk(&ts); + let pcrs: Vec = pk.iter().filter(|p| p.pid == 0x1FF).map(|p| p.pcr.unwrap()).collect(); + assert_eq!(pcrs.first(), Some(&0)); + assert_eq!(pcrs.last(), Some(&(90_000 * 300))); + assert!(pcrs.windows(2).all(|w| w[1] - w[0] <= 3600 * 300)); + assert!(pk.iter().filter(|p| p.pid == 0x1FF).all(|p| !p.payload && p.cc == 0)); + assert_eq!(st.pcrs as usize, pcrs.len()); + assert_eq!(pcrs.len(), 26, "one PCR, 24 to fill the second, one at its end"); + // at the start, then every 100 ms of the gap, the last one at its end + assert_eq!(st.psi, 11); + let mut last_psi = None; + let mut pcr = 0; + for p in &pk { + if let Some(v) = p.pcr { + pcr = v; + } + if p.pid == 0 { + if let Some(l) = last_psi { + assert!(pcr - l <= (9000 + 3600) * 300, "PAT {} after the last", pcr - l); + } + last_psi = Some(pcr); + } + } + assert_eq!(st.bytes(), ts.len() as u64); +} + +#[test] +fn a_pcr_packet_before_the_first_payload_keeps_the_counter_continuous() { + // the audio frame comes first, so the video PID carries a PCR-only packet before its first + // payload packet + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)], |m| { + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + }); + let video: Vec = walk(&ts).into_iter().filter(|p| p.pid == 0x100).collect(); + assert_eq!(video.len(), 2); + assert!(!video[0].payload && video[0].pcr.is_some()); + assert!(video[1].payload); + assert_eq!(video[1].cc, (video[0].cc + 1) & 0x0F); +} + +#[test] +fn a_long_gap_is_closed_by_one_pcr() { + let mut m = Muxer::new(Vec::new(), Config { pcr_interval: 1, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap(); + m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &[0x0B, 0x77], pts: 63_000 + 90_000, dts: None, key: true }).unwrap(); + assert_eq!(m.stats().pcr_gaps, 1); + let pcrs: Vec = walk(&m.finish().unwrap()).iter().filter_map(|p| p.pcr).collect(); + assert_eq!(pcrs.len() as u32, 2 + MAX_PCR_FILL); + assert_eq!(pcrs.last(), Some(&(90_000 * 300))); +} + +#[test] +fn psi_repeats_on_keyframes_and_new_writers() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(false), pts: 93_000, dts: None, key: false }).unwrap(); + assert_eq!(m.stats().psi, 1); + m.write_frame(0, &Frame { data: &h264(true), pts: 96_000, dts: None, key: true }).unwrap(); + assert_eq!(m.stats().psi, 2); + let first = m.replace_writer(Vec::new()).writer; + m.write_frame(0, &Frame { data: &h264(false), pts: 99_000, dts: None, key: false }).unwrap(); + let second = m.finish().unwrap(); + let pk = walk(&second); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "a new segment starts with the PAT and PMT"); + let pk_first = walk(&first); + let last_video = pk_first.iter().rev().find(|p| p.pid == 0x100).unwrap().cc; + assert_eq!(pk.iter().find(|p| p.pid == 0x100).unwrap().cc, (last_video + 1) & 0x0F, "counters carry on"); +} + +#[test] +fn a_keyframe_after_a_gap_follows_the_tables_directly() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| { + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + // the gap reaches past the table interval and several PCR intervals + m.write_frame(0, &Frame { data: &h264(true), pts: 110_000, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + let keys: Vec = pk.iter().enumerate().filter(|(_, p)| p.pid == 0x100 && p.rai).map(|(i, _)| i).collect(); + assert_eq!(keys.len(), 2); + for k in keys { + assert_eq!((pk[k - 2].pid, pk[k - 1].pid), (0, 0x1000), "the PAT and PMT right before the keyframe at packet {k}"); + } + assert!(pk.iter().any(|p| p.pid == 0x100 && !p.payload), "PCR-only packets fill the gap"); + // a packet the caller writes between the tables and a keyframe brings the tables again + let mut null = [0xFF; PACKET_SIZE]; + null[..4].copy_from_slice(&[0x47, 0x1F, 0xFF, 0x10]); + let cfg = Config { pcr_interval: 9_000, psi_interval: 3_600, ..Config::default() }; + let ts = mux(cfg, &[Stream::new(0x100, Codec::H264)], |m| { + m.advance(90_000).unwrap(); + // the tables fall due here and the PCR does not, so the tables are the last packets + m.advance(93_600).unwrap(); + m.get_mut().extend_from_slice(&null); + m.write_frame(0, &Frame { data: &h264(true), pts: 93_600, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + let k = pk.iter().position(|p| p.pid == 0x100 && p.rai).unwrap(); + assert_eq!((pk[k - 3].pid, pk[k - 2].pid, pk[k - 1].pid), (0x1FFF, 0, 0x1000)); +} + +#[test] +fn tables_lost_with_a_failed_write_come_again_before_a_keyframe() { + let cfg = Config { pcr_interval: 9_000, psi_interval: 3_600, ..Config::default() }; + // the second write fails: the one at the end of the second advance + let mut m = Muxer::new(Flaky { fail_on: Some(2), calls: 0, data: Vec::new() }, cfg, &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.advance(90_000).unwrap(); + // the tables fall due and are dropped with the failed batch + assert!(matches!(m.advance(93_600), Err(Error::Io(_)))); + m.write_frame(0, &Frame { data: &h264(true), pts: 93_600, dts: None, key: true }).unwrap(); + let pk = walk(&m.finish().unwrap().data); + let k = pk.iter().position(|p| p.pid == 0x100 && p.rai).unwrap(); + assert_eq!((pk[k - 2].pid, pk[k - 1].pid), (0, 0x1000)); +} + +#[test] +fn every_new_segment_carries_a_pcr() { + for pcr_pid in [None, Some(0x1F0)] { + let mut m = Muxer::new(Vec::new(), Config { pcr_pid, ..Config::default() }, &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + m.replace_writer(Vec::new()); + // a frame within the PCR interval + m.write_frame(0, &Frame { data: &h264(false), pts: 90_001, dts: None, key: false }).unwrap(); + let segment = m.replace_writer(Vec::new()).writer; + m.advance(91_000).unwrap(); + let third = m.finish().unwrap(); + let want = pcr_pid.unwrap_or(0x100); + for (n, ts) in [segment, third].iter().enumerate() { + let pk = walk(ts); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "{pcr_pid:?} segment {n}"); + assert!(pk.iter().any(|p| p.pid == want && p.pcr.is_some()), "{pcr_pid:?} segment {n} has a PCR"); + } + } +} + +#[test] +fn a_segment_after_an_idle_gap_starts_with_the_tables() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + m.replace_writer(Vec::new()); + m.advance(180_000).unwrap(); + let pk = walk(&m.finish().unwrap()); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000)); + assert!(pk.len() > 10, "the gap is filled with PCRs"); +} + +#[test] +fn short_table_intervals_hold_in_idle_gaps() { + let mut m = Muxer::new(Vec::new(), Config { psi_interval: 900, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap(); + m.advance(63_000).unwrap(); + m.advance(63_000 + 90_000).unwrap(); + // every 900 ticks: at the start, 99 times inside the second, and at its end + assert_eq!(m.stats().psi, 101); + // a table interval of one tick fills at most MAX_PCR_FILL repeats per gap, and the PCRs still + // fill the gap + let mut m = Muxer::new(Vec::new(), Config { psi_interval: 1, ..Config::default() }, &[Stream::new(0x100, Codec::Ac3)]).unwrap(); + m.advance(63_000).unwrap(); + m.advance(63_000 + 90_000).unwrap(); + assert_eq!(m.stats().psi, 2 + u64::from(MAX_PCR_FILL)); + assert_eq!((m.stats().pcrs, m.stats().pcr_gaps), (26, 0)); +} + +#[test] +fn frames_behind_the_sent_clock_are_refused() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)]).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 900_000, dts: None, key: true }).unwrap(); + // the clock is 900 000 - 63 000: audio up to the PCR delay behind the video is fine + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_000, dts: None, key: true }).unwrap(); + let before = m.get_ref().len(); + assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_001, dts: None, key: true }), Err(Error::Timestamp(_)))); + m.advance(2_000_000).unwrap(); + let after = m.get_ref().len(); + assert!(after > before); + assert!(matches!(m.write_frame(0, &Frame { data: &h264(false), pts: 1_000_000, dts: None, key: false }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), after, "nothing is written for a refused frame"); +} + +#[test] +fn timestamps_and_dts() { + let ts = mux(Config::default(), &[Stream::new(0x100, Codec::H264)], |m| { + m.write_frame(0, &Frame { data: &h264(true), pts: (1 << 33) + 6000, dts: Some((1 << 33) + 3000), key: true }).unwrap(); + }); + let p = &ts[2 * PACKET_SIZE..]; + let start = 5 + p[4] as usize; + let h = &p[start..]; + assert_eq!(&h[..9], &[0, 0, 1, 0xE0, 0, (3 + 10 + 6 + h264(true).len()) as u8, 0x84, 0xC0, 10]); + assert_eq!(h[9] >> 4, 3); + assert_eq!(h[14] >> 4, 1); +} + +#[test] +fn bad_frames_and_timestamps_write_nothing() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)]).unwrap(); + fn f(data: &[u8], pts: i64, dts: Option) -> Frame<'_> { + Frame { data, pts, dts, key: true } + } + assert!(matches!(m.write_frame(2, &f(&h264(true), 90_000, None)), Err(Error::NoSuchStream(2)))); + assert!(matches!(m.write_frame(0, &f(&[], 90_000, None)), Err(Error::EmptyFrame))); + assert!(matches!(m.write_frame(0, &f(&h264(true), 90_000, Some(90_001))), Err(Error::Timestamp(_)))); + assert!(matches!(m.write_frame(0, &f(&[0x65, 0x88], 90_000, None)), Err(Error::BadFrame(_)))); + assert!(matches!(m.write_frame(1, &f(&[0xFF, 0xF1, 0, 0, 0, 0], 90_000, None)), Err(Error::BadFrame(_)))); + // ten ADTS frames of 7000 bytes: each is valid, together they pass the PES length + let one = { + let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (7000 >> 11) as u8, (7000 >> 3) as u8, ((7000 & 7) as u8) << 5 | 0x1F, 0xFC]; + v.resize(7000, 0x11); + v + }; + let long_adts = one.repeat(10); + assert!(matches!(m.write_frame(1, &f(&long_adts, 90_000, None)), Err(Error::FrameTooLarge { limit: 65_527, .. }))); + assert!(matches!(m.write_frame(0, &f(&h264(true), i64::MIN, None)), Err(Error::Timestamp(_)))); + assert!(m.get_ref().is_empty()); + m.write_frame(0, &f(&h264(true), 90_000, None)).unwrap(); + assert!(matches!(m.write_frame(0, &f(&h264(true), 80_000, None)), Err(Error::Timestamp(_)))); + // video has no PES length limit + let mut big = h264(true); + big.resize(200_000, 1); + m.write_frame(0, &f(&big, 93_000, None)).unwrap(); +} + +#[test] +fn settings_are_checked() { + let one = [Stream::new(0x100, Codec::H264)]; + let bad = |cfg: Config, streams: &[Stream]| matches!(Muxer::new(Vec::new(), cfg, streams), Err(Error::Config(_))); + let err = |cfg: Config, streams: &[Stream]| Muxer::new(Vec::new(), cfg, streams).err(); + let d = Config::default(); + assert!(bad(d, &[])); + assert!(bad(d, &[Stream::new(0x100, Codec::H264); MAX_STREAMS + 1])); + assert!(bad(Config { program_number: 0, ..d }, &one)); + assert!(matches!(err(Config { pmt_pid: 0x0F, ..d }, &one), Some(Error::BadPid(0x0F)))); + assert!(matches!(err(Config { pmt_pid: 0x1FFF, ..d }, &one), Some(Error::BadPid(0x1FFF)))); + assert!(bad(Config { pcr_interval: 0, ..d }, &one)); + assert!(bad(Config { pcr_interval: MAX_PCR_INTERVAL + 1, ..d }, &one)); + assert!(bad(Config { psi_interval: 0, ..d }, &one)); + assert!(bad(Config { batch_packets: 0, ..d }, &one)); + assert!(bad(Config { batch_packets: MAX_BATCH_PACKETS + 1, ..d }, &one)); + assert!(matches!(err(Config { pcr_delay: 0, ..d }, &one), Some(Error::PcrDelay(0)))); + assert!(matches!(err(Config { pcr_delay: MAX_PCR_DELAY + 1, ..d }, &one), Some(Error::PcrDelay(90_001)))); + assert!(err(Config { pcr_delay: MAX_PCR_DELAY, ..d }, &one).is_none()); + assert!(err(Config { pcr_delay: 1, ..d }, &one).is_none()); + assert!(matches!(err(Config { pcr_pid: Some(0x1000), ..d }, &one), Some(Error::DuplicatePid(0x1000)))); + assert!(matches!(err(Config { pcr_pid: Some(0x2000), ..d }, &one), Some(Error::BadPid(0x2000)))); + assert!(matches!(err(d, &[Stream::new(0x0005, Codec::H264)]), Some(Error::BadPid(5)))); + assert!(matches!(err(d, &[Stream::new(0x1000, Codec::H264)]), Some(Error::DuplicatePid(0x1000)))); + assert!(matches!(err(d, &[Stream::new(0x100, Codec::H264), Stream::new(0x100, Codec::Ac3)]), Some(Error::DuplicatePid(0x100)))); + assert!(!bad(Config { pcr_pid: Some(0x1FFE), ..d }, &one)); +} + +#[test] +fn stream_settings_are_checked() { + let bad = |cfg: Config, streams: &[Stream]| matches!(Muxer::new(Vec::new(), cfg, streams), Err(Error::Config(_))); + let err = |cfg: Config, streams: &[Stream]| Muxer::new(Vec::new(), cfg, streams).err(); + let d = Config::default(); + // the widest program fits: 32 streams of the longest descriptors + let wide: Vec = (0..MAX_STREAMS as u16).map(|i| Stream::new(0x100 + i, Codec::OpusMapped(WIDE_OPUS)).with_language(*b"eng")).collect(); + assert!(err(d, &wide).is_none()); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { streams: 7, ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { coupled: 5, ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [0, 1, 2, 3, 4, 10, 0, 0], ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 0, ..WIDE_OPUS }))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 2, ..WIDE_OPUS }))]), "a reserved family"); + assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { family: 255, ..WIDE_OPUS }))])); + let stereo = OpusMapping { channels: 2, family: 0, streams: 1, coupled: 1, mapping: [0, 1, 0, 0, 0, 0, 0, 0] }; + assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(stereo))])); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { coupled: 255, ..stereo }))]), "no overflow"); + assert!(bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [1, 0, 0, 0, 0, 0, 0, 0], ..stereo }))]), "swapped"); + assert!(!bad(d, &[Stream::new(0x100, Codec::OpusMapped(OpusMapping { mapping: [0, 1, 2, 3, 4, 255, 0, 0], ..WIDE_OPUS }))])); + let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + assert!(!bad(d, &[Stream::new(0x100, Codec::Av1(av1))])); + assert!(bad(d, &[Stream::new(0x100, Codec::Av1(Av1Config { seq_profile: 3, ..av1 }))])); + assert!(Av1Config::from_av1c(&[0x01, 0x08, 0x0C, 0x00]).is_err()); + assert!(Av1Config::from_av1c(&[0x81, 0x08, 0x0C]).is_err()); + assert!(bad(d, &[Stream::new(0x100, Codec::Opus { channels: 0 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Opus { channels: 9 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 0, sample_rate_index: 3, channels: 2 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 2, sample_rate_index: 13, channels: 2 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 0 })])); + assert!(bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"e1g")])); + assert!(bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"ENG")])); + assert!(!bad(d, &[Stream::new(0x100, Codec::Ac3).with_language(*b"eng")])); + // the first video stream carries the PCR by default + let m = Muxer::new(Vec::new(), d, &[Stream::new(0x101, Codec::Ac3), Stream::new(0x100, Codec::H264)]).unwrap(); + assert_eq!(m.pcr_pid(), 0x100); +} + +#[test] +fn wide_programs_split_the_pmt_across_packets() { + let streams: Vec = (0..MAX_STREAMS as u16).map(|i| Stream::new(0x100 + i, Codec::Opus { channels: 2 }).with_language(*b"eng")).collect(); + let ts = mux(Config::default(), &streams, |m| { + m.write_frame(0, &Frame { data: &[0xFC, 1], pts: 90_000, dts: None, key: true }).unwrap(); + }); + let pk = walk(&ts); + let pmt: Vec<_> = pk.iter().filter(|p| p.pid == 0x1000).collect(); + assert_eq!(pmt.len(), 4, "32 stream entries of 21 bytes"); + assert!(pmt[0].pusi && pmt[1..].iter().all(|p| !p.pusi)); + assert_eq!(pmt.iter().map(|p| p.cc).collect::>(), [0, 1, 2, 3]); + let mut section: Vec = + ts.chunks(PACKET_SIZE).zip(&pk).filter(|(_, p)| p.pid == 0x1000).flat_map(|(raw, p)| raw[if p.pusi { 5 } else { 4 }..].to_vec()).collect(); + let len = 3 + ((section[1] as usize & 0x0F) << 8 | section[2] as usize); + section.truncate(len); + assert_eq!(psi::crc32(§ion), 0); +} + +/// An output that records the length of every write call. +#[derive(Clone, Default)] +struct Calls(Rc>>); + +impl Write for Calls { + fn write(&mut self, b: &[u8]) -> io::Result { + self.0.borrow_mut().push(b.len()); + Ok(b.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +/// Video and audio for `seconds`, a 2 s GOP at 30 frames a second, in DTS order: (stream, frame). +fn av_timeline(seconds: i64) -> Vec<(usize, Vec, i64, bool)> { + let mut v = Vec::new(); + for k in 0..seconds * 30 { + let key = k % 60 == 0; + let mut f = h264(key); + f.resize(if key { 3000 } else { 700 }, 0x55); + v.push((0, f, 90_000 + k * 3000, key)); + } + for k in 0..seconds * 1000 / 32 { + v.push((1, vec![0x0B, 0x77, 0, 0, 0x08, 0x40, 0x40, 1, 2, 3], 90_000 + k * 2880, true)); + } + v.sort_by_key(|f| f.2); + v +} + +fn av_streams() -> [Stream; 2] { + [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)] +} + +#[test] +fn packets_go_out_in_batches() { + for hold in [false, true] { + let calls = Calls::default(); + let mut m = Muxer::new(calls.clone(), Config { hold_packets: hold, ..Config::default() }, &av_streams()).unwrap(); + for (s, f, t, key) in av_timeline(2) { + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + let before = m.stats(); + m.flush().unwrap(); + let st = m.stats(); + // held packets are counted once the output takes them + assert_eq!(before.packets == st.packets, !hold); + m.finish().unwrap(); + let lens = calls.0.borrow(); + assert!(lens.iter().all(|&n| n % PACKET_SIZE == 0 && n > 0 && n <= 7 * PACKET_SIZE), "{lens:?}"); + assert_eq!(lens.iter().sum::() as u64, st.bytes()); + if hold { + assert!(lens[..lens.len() - 1].iter().all(|&n| n == 7 * PACKET_SIZE), "held: full batches only"); + } else { + assert!(lens.len() as u64 >= st.frames, "a write at the end of every call"); + } + } +} + +#[test] +fn held_packets_reach_the_old_writer_before_a_swap() { + let cfg = Config { hold_packets: true, batch_packets: 348, ..Config::default() }; + let mut m = Muxer::new(Vec::new(), cfg, &av_streams()).unwrap(); + let mut segments = Vec::new(); + for (s, f, t, key) in av_timeline(10) { + if s == 0 && key && t > 90_000 { + segments.push(m.replace_writer(Vec::new())); + } + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + // held packets count once they reach the output + let held = m.stats(); + let last = m.replace_writer(Vec::new()); + let st = m.stats(); + assert!(held.packets < st.packets); + segments.push(last); + assert_eq!(segments.len(), 5, "a 2 s GOP over 10 s"); + let mut packets = 0; + let mut frames = 0; + for (n, seg) in segments.iter().enumerate() { + assert!(seg.error.is_none()); + assert_eq!(seg.writer.len() as u64, seg.packets * PACKET_SIZE as u64, "segment {n}"); + assert!(seg.starts_with_keyframe, "segment {n}"); + let pk = walk(&seg.writer); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000), "segment {n}"); + assert!(pk[2].pid == 0x100 && pk[2].pcr.is_some() && pk[2].rai, "segment {n}: the keyframe with a PCR"); + assert_eq!(seg.first_pts, Some(90_000 + n as i64 * 180_000)); + assert!(seg.last_pts.unwrap() < 90_000 + (n as i64 + 1) * 180_000); + packets += seg.packets; + frames += seg.frames; + } + assert_eq!((packets, frames), (st.packets, st.frames)); + // a segment cut before a frame that is not a keyframe says so + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 90_000, dts: None, key: true }).unwrap(); + assert!(m.replace_writer(Vec::new()).starts_with_keyframe); + m.write_frame(0, &Frame { data: &h264(false), pts: 93_000, dts: None, key: false }).unwrap(); + assert!(!m.replace_writer(Vec::new()).starts_with_keyframe); +} + +#[test] +fn a_continuing_swap_leaves_the_packets_unchanged() { + let one = mux(Config::default(), &av_streams(), |m| { + for (s, f, t, key) in av_timeline(3) { + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + }); + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + let mut parts = Vec::new(); + for (n, (s, f, t, key)) in av_timeline(3).into_iter().enumerate() { + if n % 7 == 6 { + parts.push(m.replace_writer_continuing(Vec::new()).writer); + } + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + parts.push(m.finish().unwrap()); + assert!(parts.len() > 10); + assert_eq!(parts.concat(), one); +} + +#[test] +fn a_discontinuity_starts_a_new_time_base() { + for pcr_pid in [None, Some(0x1F0)] { + let mut m = Muxer::new(Vec::new(), Config { pcr_pid, ..Config::default() }, &av_streams()).unwrap(); + for (s, f, t, key) in av_timeline(2) { + m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).unwrap(); + } + let before = m.stats().packets as usize; + m.discontinuity(); + // the encoder restarts at a smaller timestamp, the audio first this time + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 9], pts: 100_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 100_000, dts: None, key: true }).unwrap(); + m.write_frame(0, &Frame { data: &h264(false), pts: 103_000, dts: None, key: false }).unwrap(); + let ts = m.finish().unwrap(); + let pk = walk(&ts); + assert!(pk[..before].iter().all(|p| !p.disc)); + let after = &pk[before..]; + assert_eq!((after[0].pid, after[1].pid), (0, 0x1000), "{pcr_pid:?}: the tables first"); + let pcr_on = pcr_pid.unwrap_or(0x100); + let first_pcr = after.iter().find(|p| p.pcr.is_some()).unwrap(); + assert_eq!((first_pcr.pid, first_pcr.disc, first_pcr.pcr), (pcr_on, true, Some((100_000 - 63_000) * 300)), "{pcr_pid:?}"); + for pid in [0x100, 0x101] { + let first = after.iter().find(|p| p.pid == pid).unwrap(); + assert!(first.disc, "{pcr_pid:?}: PID {pid:#x}"); + assert_eq!(after.iter().filter(|p| p.pid == pid && p.disc).count(), 1, "{pcr_pid:?}: once on PID {pid:#x}"); + } + } +} + +#[test] +fn the_clock_after_advance_is_on_the_dts_scale() { + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + m.advance(900_000).unwrap(); + let pcrs: Vec = walk(m.get_ref()).iter().filter_map(|p| p.pcr).collect(); + assert_eq!(pcrs, [(900_000 - 63_000) * 300]); + let before = m.get_ref().len(); + assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 63_001, dts: None, key: true }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), before); + m.write_frame(0, &Frame { data: &h264(true), pts: 900_000 - 63_000, dts: None, key: true }).unwrap(); +} + +#[test] +fn streams_may_skew_by_the_pcr_delay() { + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + // video 500 ms ahead of the audio + for k in 0..30i64 { + m.write_frame(0, &Frame { data: &h264(k == 0), pts: 135_000 + k * 3000, dts: None, key: k == 0 }).unwrap(); + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000 + k * 3000, dts: None, key: true }).unwrap(); + } + // 800 ms behind the video is refused + let before = m.get_ref().len(); + m.write_frame(0, &Frame { data: &h264(false), pts: 900_000, dts: None, key: false }).unwrap(); + let mid = m.get_ref().len(); + assert!(mid > before); + assert!(matches!(m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 900_000 - 72_000, dts: None, key: true }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), mid); +} + +#[test] +fn video_decoding_times_must_increase() { + let mut m = Muxer::new(Vec::new(), Config::default(), &av_streams()).unwrap(); + m.write_frame(0, &Frame { data: &h264(true), pts: 93_000, dts: Some(90_000), key: true }).unwrap(); + let before = m.get_ref().len(); + assert!(matches!(m.write_frame(0, &Frame { data: &h264(false), pts: 96_000, dts: Some(90_000), key: false }), Err(Error::Timestamp(_)))); + assert_eq!(m.get_ref().len(), before); + // audio frames may share a time + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap(); + m.write_frame(1, &Frame { data: &[0x0B, 0x77], pts: 90_000, dts: None, key: true }).unwrap(); +} + +#[test] +fn video_frames_past_the_reader_limit_are_refused() { + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::H264)]).unwrap(); + // zeroed pages are not touched before the size check + let mut big = vec![0u8; MAX_VIDEO_FRAME + 1]; + big[..5].copy_from_slice(&[0, 0, 0, 1, 0x65]); + assert!(matches!( + m.write_frame(0, &Frame { data: &big, pts: 90_000, dts: None, key: true }), + Err(Error::FrameTooLarge { limit: MAX_VIDEO_FRAME, .. }) + )); + assert_eq!(m.stats(), Stats::default()); + assert!(m.get_ref().is_empty()); + // an AV1 frame under the limit whose escapes take it over + let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + let mut m = Muxer::new(Vec::new(), Config::default(), &[Stream::new(0x100, Codec::Av1(av1))]).unwrap(); + let mut tu = vec![0x0A, 0x05, 0x00, 0x00, 0x00, 0x02, 0x7F, 0x32]; + let payload = MAX_VIDEO_FRAME - 100; + let mut n = payload; + while n >= 0x80 { + tu.push((n & 0x7F) as u8 | 0x80); + n >>= 7; + } + tu.push(n as u8); + tu.resize(tu.len() + payload, 0); + *tu.last_mut().unwrap() = 1; + assert!(tu.len() <= MAX_VIDEO_FRAME); + assert!(matches!( + m.write_frame(0, &Frame { data: &tu, pts: 90_000, dts: None, key: true }), + Err(Error::FrameTooLarge { limit: MAX_VIDEO_FRAME, size }) if size > MAX_VIDEO_FRAME + )); + assert!(m.get_ref().is_empty()); +} + +#[test] +fn audio_specific_configs_become_adts_fields() { + let asc = |b: [u8; 2]| Codec::aac_from_asc(&b); + assert_eq!(asc([0x11, 0x90]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }); + assert_eq!(asc([0x12, 0x08]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 4, channels: 1 }); + assert_eq!(asc([0x11, 0xB0]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 6 }); + assert_eq!(asc([0x11, 0xB8]).unwrap(), Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 7 }); + assert!(asc([0x17, 0x80]).is_err(), "explicit sampling frequency"); + assert!(asc([0x29, 0x90]).is_err(), "SBR"); + assert!(asc([0x11, 0x80]).is_err(), "channel configuration 0"); + assert!(asc([0x11, 0x94]).is_err(), "frameLengthFlag 1"); + assert!(Codec::aac_from_asc(&[0x11]).is_err()); +} + +#[test] +fn opus_trims_follow_the_draft_rules() { + let opus = [Stream::new(0x100, Codec::Opus { channels: 2 }), Stream::new(0x101, Codec::Ac3)]; + let mut m = Muxer::new(Vec::new(), Config::default(), &opus).unwrap(); + // 8 CELT frames of 20 ms: 7680 samples + let au = [0xFF, 8, 0x11, 0x22]; + let f = |k: i64| Frame { data: &au, pts: 90_000 + k * 14_400, dts: None, key: true }; + assert!(matches!(m.write_frame_with_trim(1, &f(0), OpusTrim { start: 1, end: 0 }), Err(Error::BadFrame(_))), "not Opus"); + assert!(matches!(m.write_frame_with_trim(0, &f(0), OpusTrim { start: 7681, end: 0 }), Err(Error::BadFrame(_))), "longer than the unit"); + assert!(matches!(m.write_frame_with_trim(0, &f(0), OpusTrim { start: 8192, end: 0 }), Err(Error::BadFrame(_))), "13 bits"); + assert!(m.get_ref().is_empty()); + // whole units may be discarded at the start, 65 535 samples in all + for k in 0..8 { + m.write_frame_with_trim(0, &f(k), OpusTrim { start: 7680, end: 0 }).unwrap(); + } + assert!(matches!(m.write_frame_with_trim(0, &f(8), OpusTrim { start: 7680, end: 0 }), Err(Error::BadFrame(_)))); + m.write_frame_with_trim(0, &f(8), OpusTrim { start: 312, end: 0 }).unwrap(); + // the lead-in is over + assert!(matches!(m.write_frame_with_trim(0, &f(9), OpusTrim { start: 1, end: 0 }), Err(Error::BadFrame(_)))); + m.write_frame(0, &f(9)).unwrap(); + m.write_frame_with_trim(0, &f(10), OpusTrim { start: 0, end: 100 }).unwrap(); + // a restarted encoder trims its own start again + m.discontinuity(); + m.write_frame_with_trim(0, &f(0), OpusTrim { start: 312, end: 0 }).unwrap(); + m.write_frame_with_trim(0, &f(1), OpusTrim { start: 0, end: 100 }).unwrap(); + let ts = m.finish().unwrap(); + // the last unit's control header: end trim flag, size 4, end_trim 100 + let last = ts.chunks(PACKET_SIZE).rev().find(|p| p[1] & 0x40 != 0 && (u16::from(p[1] & 0x1F) << 8 | u16::from(p[2])) == 0x100).unwrap(); + let pes = &last[5 + last[4] as usize..]; + assert_eq!(&pes[14..19], &[0x7F, 0xE8, 4, 0, 100]); +} + +/// Each stream PID's PES packets: (random access indicator of the first packet, bytes). +fn pes_of(ts: &[u8], pids: &[u16]) -> std::collections::HashMap)>> { + let mut out: std::collections::HashMap)>> = Default::default(); + for (raw, p) in ts.chunks(PACKET_SIZE).zip(walk(ts)) { + if !pids.contains(&p.pid) || !p.payload { + continue; + } + let start = if raw[3] & 0x20 != 0 { 5 + raw[4] as usize } else { 4 }; + let list = out.entry(p.pid).or_default(); + if p.pusi { + list.push((p.rai, Vec::new())); + } + list.last_mut().unwrap().1.extend_from_slice(&raw[start..]); + } + out +} + +/// Reads a timestamp, checking its prefix and marker bits. +fn read_ts(b: &[u8], prefix: u8) -> i64 { + assert_eq!(b[0] >> 4, prefix); + assert_eq!([b[0] & 1, b[2] & 1, b[4] & 1], [1, 1, 1], "marker bits"); + (((b[0] >> 1) & 7) as i64) << 30 | (b[1] as i64) << 22 | ((b[2] >> 1) as i64) << 15 | (b[3] as i64) << 7 | (b[4] >> 1) as i64 +} + +#[test] +fn pes_headers_hold_their_fixed_bits_lengths_and_keyframes() { + let streams = [ + Stream::new(0x100, Codec::H264), + Stream::new(0x101, Codec::Ac3), + Stream::new(0x102, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }), + ]; + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + let mut frames: [Vec<(bool, i64, i64)>; 3] = Default::default(); + let mut outputs = Vec::new(); + for k in 0..120i64 { + if k % 40 == 0 && k > 0 { + outputs.push(m.replace_writer(Vec::new()).writer); + } + let key = k % 20 == 0; + let mut v = h264(key); + v.resize(if key { 30_000 } else { 70_000 + (k as usize * 997) % 9000 }, 0x55); + let dts = 90_000 + k * 3000; + let pts = dts + if key { 0 } else { 6000 }; + m.write_frame(0, &Frame { data: &v, pts, dts: Some(dts), key }).unwrap(); + frames[0].push((key, pts, dts)); + m.write_frame(1, &Frame { data: &[0x0B, 0x77, 1, 2, 3], pts: dts, dts: None, key: true }).unwrap(); + frames[1].push((true, dts, dts)); + m.write_frame(2, &Frame { data: &vec![7; 1 + (k as usize * 31) % 1500], pts: dts, dts: None, key: true }).unwrap(); + frames[2].push((true, dts, dts)); + } + outputs.push(m.finish().unwrap()); + let mut seen = [0usize; 3]; + for ts in &outputs { + for (pid, list) in pes_of(ts, &[0x100, 0x101, 0x102]) { + let s = usize::from(pid - 0x100); + for (rai, pes) in list { + let (key, pts, dts) = frames[s][seen[s]]; + seen[s] += 1; + assert_eq!(&pes[..3], &[0, 0, 1]); + assert_eq!(pes[3], streams[s].codec.stream_id()); + assert_eq!(pes[6], 0x84, "'10', data_alignment_indicator"); + let length = usize::from(pes[4]) << 8 | usize::from(pes[5]); + if s == 0 && pes.len() - 6 > 0xFFFF { + assert_eq!(length, 0); + } else { + assert_eq!(length, pes.len() - 6, "PID {pid:#x}"); + } + assert_eq!(rai, key, "PID {pid:#x}"); + if pts == dts { + assert_eq!((pes[7], pes[8]), (0x80, 5)); + assert_eq!(read_ts(&pes[9..14], 2), pts); + } else { + assert_eq!((pes[7], pes[8]), (0xC0, 10)); + assert_eq!((read_ts(&pes[9..14], 3), read_ts(&pes[14..19], 1)), (pts, dts)); + } + } + } + } + assert_eq!(seen, [120, 120, 120]); +} + +/// An output that fails on one write call. +struct Flaky { + fail_on: Option, + calls: usize, + data: Vec, +} + +impl Write for Flaky { + fn write(&mut self, b: &[u8]) -> io::Result { + self.calls += 1; + if Some(self.calls) == self.fail_on { + return Err(io::Error::other("upload failed")); + } + self.data.extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn a_new_writer_recovers_from_an_io_error() { + let mut m = Muxer::new(Flaky { fail_on: Some(3), calls: 0, data: Vec::new() }, Config::default(), &av_streams()).unwrap(); + let mut failed = false; + let mut recovered = None; + for (s, f, t, key) in av_timeline(2) { + match m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }) { + Ok(()) => {} + Err(Error::Io(_)) if !failed => { + failed = true; + let old = m.replace_writer(Flaky { fail_on: None, calls: 0, data: Vec::new() }); + assert_eq!(old.writer.data.len() % PACKET_SIZE, 0); + recovered = Some(m.stats().packets); + } + Err(e) => panic!("{e}"), + } + } + assert!(failed && recovered.is_some()); + let ts = m.finish().unwrap().data; + let pk = walk(&ts); + assert_eq!((pk[0].pid, pk[1].pid), (0, 0x1000)); + assert!(pk.iter().take(4).any(|p| p.pcr.is_some()), "a PCR right after the tables"); + // counters run on within the new output + let mut last: std::collections::HashMap = Default::default(); + for p in &pk { + if let Some(&c) = last.get(&p.pid) { + assert_eq!(p.cc, if p.payload { (c + 1) & 0x0F } else { c }); + } + last.insert(p.pid, p.cc); + } +} + +/// An output that takes `take` bytes in all and then fails. +struct Short { + take: usize, + data: Vec, +} + +impl Write for Short { + fn write(&mut self, b: &[u8]) -> io::Result { + if self.data.len() >= self.take { + return Err(io::Error::other("disk full")); + } + // at most 100 bytes a call, so a batch goes out in several calls + let n = b.len().min(100).min(self.take - self.data.len()); + self.data.extend_from_slice(&b[..n]); + Ok(n) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[test] +fn packet_counts_hold_only_what_the_output_took() { + let take = 5 * PACKET_SIZE + 50; + let mut m = Muxer::new(Short { take, data: Vec::new() }, Config::default(), &av_streams()).unwrap(); + let mut failed = false; + for (s, f, t, key) in av_timeline(1) { + if m.write_frame(s, &Frame { data: &f, pts: t, dts: None, key }).is_err() { + failed = true; + break; + } + } + assert!(failed); + assert_eq!(m.stats().packets, 5); + let seg = m.replace_writer(Short { take: usize::MAX, data: Vec::new() }); + assert_eq!((seg.packets, seg.writer.data.len()), (5, take)); + // the new output takes a partial write in several calls and counts every packet + m.write_frame(0, &Frame { data: &h264(true), pts: 200_000, dts: None, key: true }).unwrap(); + let st = m.stats(); + let seg = m.replace_writer(Short { take: 0, data: Vec::new() }); + assert_eq!(seg.writer.data.len() as u64, seg.packets * PACKET_SIZE as u64); + assert_eq!(st.packets, 5 + seg.packets); +} diff --git a/crates/media/tests/mpegts_mux/mod.rs b/crates/media/tests/mpegts_mux/mod.rs new file mode 100644 index 0000000000..4a3e6f2d11 --- /dev/null +++ b/crates/media/tests/mpegts_mux/mod.rs @@ -0,0 +1,260 @@ +//! Frames for the read-back tests, and a packet-level check of what the muxer wrote. + +#![allow(dead_code)] + +use std::collections::HashMap; + +use craft_media::mpegts::mux::{Codec, Frame, Muxer, PACKET_SIZE}; + +/// A frame queued for the muxer, with the bytes the demuxer should give back for it. +pub struct Item { + pub stream: usize, + pub data: Vec, + pub pts: i64, + pub dts: i64, + pub key: bool, + pub expect: Vec, +} + +/// Writes `items` in DTS order (stable, so equal DTS keep their order). +pub fn write_all(m: &mut Muxer>, items: &mut [Item]) { + items.sort_by_key(|i| i.dts); + for i in items.iter() { + let dts = (i.dts != i.pts).then_some(i.dts); + m.write_frame(i.stream, &Frame { data: &i.data, pts: i.pts, dts, key: i.key }).unwrap(); + } +} + +pub fn h264(key: bool, disposable: bool, size: usize, seed: u8) -> Vec { + let mut v = if key { + vec![0, 0, 0, 1, 0x67, 0x42, 0xC0, 0x1E, 0xDA, 0, 0, 0, 1, 0x68, 0xCE, 0x3C, 0x80, 0, 0, 1, 0x65, 0x88, 0x84] + } else if disposable { + vec![0, 0, 0, 1, 0x01, 0x9E] + } else { + vec![0, 0, 0, 1, 0x41, 0x9A] + }; + fill(&mut v, size, seed); + v +} + +pub fn hevc(key: bool, size: usize, seed: u8) -> Vec { + let mut v = if key { + vec![0, 0, 0, 1, 0x40, 0x01, 0x0C, 0, 0, 0, 1, 0x42, 0x01, 0x01, 0, 0, 0, 1, 0x44, 0x01, 0xC1, 0, 0, 1, 0x26, 0x01, 0xAF] + } else { + vec![0, 0, 0, 1, 0x02, 0x01, 0xD0] + }; + fill(&mut v, size, seed); + v +} + +/// An MPEG-2 picture (I with a sequence and GOP header, or P), `size` bytes. +pub fn mpeg2(key: bool, temporal_reference: u16, size: usize, seed: u8) -> Vec { + let mut v = Vec::new(); + if key { + v.extend_from_slice(&[0, 0, 1, 0xB3, 0x14, 0x00, 0xF0, 0x13, 0xFF, 0xFF, 0xE0, 0x18]); + v.extend_from_slice(&[0, 0, 1, 0xB8, 0x00, 0x08, 0x00, 0x00]); + } + let pct: u8 = if key { 1 } else { 2 }; + let tr = temporal_reference & 0x3FF; + v.extend_from_slice(&[0, 0, 1, 0x00, (tr >> 2) as u8, ((tr & 3) as u8) << 6 | pct << 3 | 0x07, 0xFF, 0xF8]); + v.extend_from_slice(&[0, 0, 1, 0x01, 0x12]); + fill(&mut v, size, seed); + v +} + +/// Pads with bytes that never form a start code. +pub fn fill(v: &mut Vec, size: usize, seed: u8) { + let mut x = seed as u32 | 1; + while v.len() < size { + x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345); + v.push(((x >> 16) as u8).max(1)); + } +} + +/// An ADTS frame: AAC LC, 48 kHz, 2 channels, `payload` bytes after the header. +pub fn adts(payload: usize, seed: u8) -> Vec { + let len = payload + 7; + let mut v = vec![0xFF, 0xF1, 0x4C, 0x80 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC]; + fill(&mut v, len, seed); + v +} + +/// An AC-3 sync frame: 48 kHz, 64 kbit/s, 256 bytes. +pub fn ac3(seed: u8) -> Vec { + let mut v = vec![0x0B, 0x77, 0, 0, 0x08, 0x40, 0x40]; + fill(&mut v, 256, seed); + v +} + +/// An MPEG-1 Layer III frame (48 kHz, 128 kbit/s, 384 bytes), or with `low` an MPEG-2 one +/// (24 kHz, 64 kbit/s, 192 bytes). +pub fn mp3(low: bool, seed: u8) -> Vec { + let (mut v, size) = if low { (vec![0xFF, 0xF3, 0x84, 0x44], 192) } else { (vec![0xFF, 0xFB, 0x94, 0x44], 384) }; + fill(&mut v, size, seed); + v +} + +/// An E-AC-3 sync frame: independent substream 0, 256 bytes, 48 kHz, six blocks, 2/0, bsid 16. +pub fn eac3(seed: u8) -> Vec { + let mut v = vec![0x0B, 0x77, 0x00, 0x7F, 0x34, 0x80]; + fill(&mut v, 256, seed); + v +} + +/// An MPEG-4 Part 2 frame: a visual object sequence, visual object, video object layer and an +/// I-VOP, or a P-VOP alone. +pub fn mpeg4(key: bool, size: usize, seed: u8) -> Vec { + let mut v = if key { + vec![0, 0, 1, 0xB0, 0x01, 0, 0, 1, 0xB5, 0x09, 0, 0, 1, 0x00, 0, 0, 1, 0x20, 0x00, 0x84, 0x40, 0, 0, 1, 0xB6, 0x10] + } else { + vec![0, 0, 1, 0xB6, 0x50] + }; + fill(&mut v, size, seed); + v +} + +pub fn leb128(mut n: usize, v: &mut Vec) { + loop { + let b = (n & 0x7F) as u8; + n >>= 7; + if n == 0 { + v.push(b); + return; + } + v.push(b | 0x80); + } +} + +/// An AV1 temporal unit in the low overhead format: a temporal delimiter, a sequence header on +/// keyframes, and a frame OBU whose payload holds sequences that need emulation prevention. +pub fn av1(key: bool, size: usize, seed: u8) -> Vec { + let mut v = vec![0x12, 0x00]; + if key { + v.extend_from_slice(&[0x0A, 0x05, 0x00, 0x00, 0x00, 0x02, 0x7F]); + } + let mut payload = vec![0, 0, 1, 0, 0, 3, 0, 0, 0]; + fill(&mut payload, size, seed); + v.push(0x32); + leb128(payload.len(), &mut v); + v.extend_from_slice(&payload); + v +} + +/// The OBUs of a temporal unit without its temporal delimiters. +pub fn av1_without_delimiters(tu: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut at = 0; + while at < tu.len() { + let h = tu[at]; + let mut i = at + 1 + usize::from(h & 4 != 0); + let (mut size, mut shift) = (0usize, 0); + loop { + let b = tu[i]; + i += 1; + size |= usize::from(b & 0x7F) << shift; + shift += 7; + if b & 0x80 == 0 { + break; + } + } + if (h >> 3) & 0x0F != 2 { + out.extend_from_slice(&tu[at..i + size]); + } + at = i + size; + } + out +} + +/// Takes the start codes and emulation prevention bytes out of an AV1 PES payload, checking +/// that no 0x000000, 0x000001 or 0x000002 appears inside an OBU and that every 0x000003 is +/// followed by 0x00 to 0x03. +pub fn av1_unescape(es: &[u8]) -> Vec { + assert!(es.starts_with(&[0, 0, 1])); + let mut out = Vec::new(); + let (mut zeros, mut i) = (0, 0); + while i < es.len() { + if zeros == 0 && es[i..].starts_with(&[0, 0, 1]) { + i += 3; + continue; + } + let b = es[i]; + i += 1; + if zeros >= 2 { + assert!(b >= 3, "0x0000{b:02X} inside an OBU"); + zeros = 0; + if b == 3 { + assert!(es.get(i).is_some_and(|&n| n <= 3), "0x000003 followed by a byte that needs no escape"); + continue; + } + out.push(b); + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + out.push(b); + } + out +} + +/// The Opus control header and packet the demuxer gives back for an Opus frame. +pub fn opus_unit(packet: &[u8]) -> Vec { + let mut v = vec![0x7F, 0xE0]; + v.extend(std::iter::repeat_n(0xFF, packet.len() / 255)); + v.push((packet.len() % 255) as u8); + v.extend_from_slice(packet); + v +} + +/// What the demuxer gives back for a video frame: an access unit delimiter first. +pub fn with_aud(codec: Codec, data: &[u8]) -> Vec { + let mut v = match codec { + Codec::H264 => vec![0, 0, 0, 1, 0x09, 0xF0], + Codec::Hevc => vec![0, 0, 0, 1, 0x46, 0x01, 0x50], + _ => Vec::new(), + }; + v.extend_from_slice(data); + v +} + +/// Checks the packet layer: sync bytes, continuity counters, adaptation fields, and the PCR on +/// `pcr_pid` never more than `limit` (27 MHz) apart. Returns the PCRs. +pub fn check_packets(ts: &[u8], pcr_pid: u16, limit: i64) -> Vec { + assert_eq!(ts.len() % PACKET_SIZE, 0); + let mut cc: HashMap = HashMap::new(); + let mut pcrs = Vec::new(); + for p in ts.chunks(PACKET_SIZE) { + assert_eq!(p[0], 0x47); + assert_eq!(p[1] & 0x80, 0, "transport error indicator"); + assert_eq!(p[3] & 0xC0, 0, "scrambling"); + let pid = ((p[1] & 0x1F) as u16) << 8 | p[2] as u16; + let afc = p[3] >> 4 & 3; + assert_ne!(afc, 0); + let payload = afc & 1 != 0; + if let Some(&c) = cc.get(&pid) { + assert_eq!(p[3] & 0x0F, if payload { (c + 1) & 0x0F } else { c }, "continuity on PID {pid:#x}"); + } + cc.insert(pid, p[3] & 0x0F); + if afc & 2 != 0 { + let len = p[4] as usize; + assert!(if payload { len <= 182 } else { len == 183 }); + if len > 0 && p[5] & 0x10 != 0 { + assert!(len >= 7, "PCR flag in an adaptation field of {len} byte{}", if len == 1 { "" } else { "s" }); + assert_eq!(pid, pcr_pid, "a PCR off the PCR PID"); + let b = &p[6..12]; + assert_eq!(b[4] & 0x7E, 0x7E, "reserved bits"); + let base = (b[0] as i64) << 25 | (b[1] as i64) << 17 | (b[2] as i64) << 9 | (b[3] as i64) << 1 | (b[4] >> 7) as i64; + let ext = ((b[4] & 1) as i64) << 8 | b[5] as i64; + assert!(ext < 300); + pcrs.push(base * 300 + ext); + } + if len > 1 { + assert!(p[6 + if p[5] & 0x10 != 0 { 6 } else { 0 }..5 + len].iter().all(|&b| b == 0xFF), "stuffing bytes"); + } + } + } + let wrap = (1i64 << 33) * 300; + for w in pcrs.windows(2) { + let d = (w[1] - w[0]).rem_euclid(wrap); + assert!(d > 0 && d <= limit, "PCRs {} apart (limit {limit})", d); + } + pcrs +} diff --git a/crates/media/tests/mpegts_mux_fuzz.rs b/crates/media/tests/mpegts_mux_fuzz.rs new file mode 100644 index 0000000000..61cb3ee012 --- /dev/null +++ b/crates/media/tests/mpegts_mux_fuzz.rs @@ -0,0 +1,229 @@ +//! Random programs, frames and timelines: the packet layer stays valid, and every frame reads back +//! with the demuxer, across random idle gaps and output swaps. Random bytes for every codec never +//! panic. +// Test code: a failed unwrap is a failed test. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod mpegts_mux; + +use craft_media::mpegts; +use craft_media::mpegts::mux::{Av1Config, Codec, Config, Error, Frame, MAX_PCR_DELAY, MAX_PCR_INTERVAL, Muxer, OpusMapping, OpusTrim, Stream}; +use mpegts_mux::*; +use proptest::prelude::*; + +/// One step of a plan: (stream, size, DTS step, PTS offset, key, idle time before it, cut before +/// it: 0 none, 1 a new segment, 2 a continuing swap). +type Step = (usize, usize, i64, i64, bool, Option, u8); + +#[derive(Debug, Clone)] +struct Plan { + pcr_interval: u32, + pcr_own: bool, + pcr_delay: u32, + psi_interval: u32, + psi_before_keyframes: bool, + batch_packets: u16, + hold_packets: bool, + frames: Vec, +} + +/// The streams of the read-back property, in the order of `Step`'s stream index. +const STREAMS: usize = 8; + +fn plan() -> impl Strategy { + let step = (0usize..STREAMS, 1usize..4000, 1i64..12_000, 0i64..9000, any::(), prop::option::weighted(0.2, 0i64..40_000), 0u8..3); + ( + 1u32..=MAX_PCR_INTERVAL, + any::(), + 1u32..=MAX_PCR_DELAY, + 1u32..200_000, + any::(), + 1u16..400, + any::(), + prop::collection::vec(step, 5..60), + ) + .prop_map(|(pcr_interval, pcr_own, pcr_delay, psi_interval, psi_before_keyframes, batch_packets, hold_packets, frames)| Plan { + pcr_interval, + pcr_own, + pcr_delay, + psi_interval, + psi_before_keyframes, + batch_packets, + hold_packets, + frames, + }) +} + +/// A frame of stream `s` and the bytes the demuxer gives back for it. +fn frame(s: usize, size: usize, key: bool, n: usize) -> (Vec, Vec) { + let seed = n as u8; + match s { + 0 => { + let d = h264(key, false, size.max(30), seed); + let e = with_aud(Codec::H264, &d); + (d, e) + } + 1 => { + let mut d = vec![0xFC]; + fill(&mut d, size.min(1500), seed); + let e = opus_unit(&d); + (d, e) + } + 2 => { + let mut d = Vec::new(); + fill(&mut d, size.min(2000), seed); + let len = d.len() + 7; + let mut e = vec![0xFF, 0xF1, 0x50, 0x40 | (len >> 11) as u8, (len >> 3) as u8, ((len & 7) as u8) << 5 | 0x1F, 0xFC]; + e.extend_from_slice(&d); + (d, e) + } + 3 => { + let d = hevc(key, size.max(40), seed); + let e = with_aud(Codec::Hevc, &d); + (d, e) + } + 4 => (ac3(seed), ac3(seed)), + 5 => (eac3(seed), eac3(seed)), + 6 => (mp3(false, seed), mp3(false, seed)), + _ => { + let d = mpeg2(key, (n % 1024) as u16, size.max(40), seed); + (d.clone(), d) + } + } +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + #[test] + fn random_programs_read_back(p in plan()) { + let streams = [ + Stream::new(0x100, Codec::H264), + Stream::new(0x101, Codec::Opus { channels: 2 }), + Stream::new(0x102, Codec::Aac { object_type: 2, sample_rate_index: 4, channels: 1 }), + Stream::new(0x103, Codec::Hevc), + Stream::new(0x104, Codec::Ac3), + Stream::new(0x105, Codec::Eac3), + Stream::new(0x106, Codec::MpegAudio { low_sample_rate: false }), + Stream::new(0x107, Codec::Mpeg2Video), + ]; + let cfg = Config { + pcr_interval: p.pcr_interval, + pcr_pid: p.pcr_own.then_some(0x1F0), + pcr_delay: p.pcr_delay, + psi_interval: p.psi_interval, + psi_before_keyframes: p.psi_before_keyframes, + batch_packets: p.batch_packets, + hold_packets: p.hold_packets, + ..Config::default() + }; + let mut m = Muxer::new(Vec::new(), cfg, &streams).unwrap(); + let mut t = 100_000i64; + let mut want: [Vec<(Vec, i64, i64)>; STREAMS] = Default::default(); + let mut segments = Vec::new(); + let mut restarted = false; + for (n, &(s, size, step, offset, key, idle, cut)) in p.frames.iter().enumerate() { + if let Some(idle) = idle { + // an idle gap that ends no later than the next frame's DTS + m.advance(t + idle.min(step)).unwrap(); + } + t += step; + match cut { + 1 => { + segments.push((true, m.replace_writer(Vec::new()))); + restarted = true; + } + 2 => segments.push((false, m.replace_writer_continuing(Vec::new()))), + _ => {} + } + let (data, expect) = frame(s, size, key, n); + let pts = if matches!(s, 0 | 3 | 7) { t + offset } else { t }; + m.write_frame(s, &Frame { data: &data, pts, dts: Some(t), key }).unwrap(); + want[s].push((expect, pts, t)); + } + let pcr_pid = m.pcr_pid(); + m.flush().unwrap(); + let stats = m.stats(); + let last = m.finish().unwrap(); + // an output that follows `replace_writer` starts with the PAT + let mut parts: Vec> = Vec::new(); + let mut fresh = false; + for (restart, seg) in segments { + prop_assert!(seg.error.is_none()); + prop_assert_eq!(seg.writer.len() as u64, seg.packets * 188); + if fresh && !seg.writer.is_empty() { + prop_assert_eq!((seg.writer[1] & 0x1F, seg.writer[2]), (0, 0)); + } + fresh = restart; + parts.push(seg.writer); + } + if fresh && !last.is_empty() { + prop_assert_eq!((last[1] & 0x1F, last[2]), (0, 0)); + } + parts.push(last); + let ts = parts.concat(); + prop_assert_eq!(ts.len() as u64, stats.bytes()); + if stats.pcr_gaps == 0 && !restarted { + check_packets(&ts, pcr_pid, i64::from(p.pcr_interval) * 300); + } + let file = mpegts::open(&ts).unwrap(); + prop_assert!(file.warnings.is_empty(), "{:?}", file.warnings); + for (k, w) in want.iter().enumerate() { + let units = &file.streams[k].units; + prop_assert_eq!(units.len(), w.len(), "stream {}", k); + for (n, (u, (bytes, pts, dts))) in units.iter().zip(w).enumerate() { + prop_assert_eq!(u.pts, Some(*pts)); + prop_assert_eq!(u.dts.or(u.pts), Some(*dts)); + prop_assert_eq!(&file.read_unit(&ts, k, n).unwrap(), bytes); + } + } + } + + #[test] + fn random_bytes_never_panic( + codec in 0usize..14, + frames in prop::collection::vec((prop::collection::vec(any::(), 0..3000), any::(), prop::option::of(any::()), any::(), any::(), any::()), 1..30), + interval in 0u32..20_000, + ) { + let av1 = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + let mapped = OpusMapping { channels: 6, family: 1, streams: 4, coupled: 2, mapping: [0, 4, 1, 2, 3, 5, 0, 0] }; + let codec = [ + Codec::H264, + Codec::Hevc, + Codec::Mpeg2Video, + Codec::AacAdts, + Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }, + Codec::Opus { channels: 2 }, + Codec::Ac3, + Codec::MpegAudio { low_sample_rate: false }, + Codec::MpegAudio { low_sample_rate: true }, + Codec::Mpeg1Video, + Codec::Mpeg4Part2, + Codec::Av1(av1), + Codec::Eac3, + Codec::OpusMapped(mapped), + ][codec]; + let cfg = Config { pcr_interval: interval, ..Config::default() }; + let Ok(mut m) = Muxer::new(Vec::new(), cfg, &[Stream::new(0x100, codec)]) else { + prop_assert!(interval == 0 || interval > MAX_PCR_INTERVAL); + return Ok(()); + }; + for (n, (data, pts, dts, key, start, end)) in frames.iter().enumerate() { + let trim = if n % 3 == 0 { OpusTrim { start: *start, end: *end } } else { OpusTrim::default() }; + match m.write_frame_with_trim(0, &Frame { data, pts: *pts, dts: *dts, key: *key }, trim) { + Ok(()) | Err(Error::BadFrame(_) | Error::EmptyFrame | Error::Timestamp(_) | Error::FrameTooLarge { .. }) => {} + Err(e) => prop_assert!(false, "{e}"), + } + let _ = m.advance(*pts); + if n % 7 == 6 { + m.discontinuity(); + } + } + let ts = m.finish().unwrap(); + prop_assert_eq!(ts.len() % 188, 0); + // the demuxer recognizes a transport stream by five sync bytes in a row + if ts.len() >= 5 * 188 { + prop_assert!(mpegts::open(&ts).is_ok()); + } + } +} diff --git a/crates/media/tests/mpegts_mux_readback.rs b/crates/media/tests/mpegts_mux_readback.rs new file mode 100644 index 0000000000..ba2d70956a --- /dev/null +++ b/crates/media/tests/mpegts_mux_readback.rs @@ -0,0 +1,356 @@ +//! The transport stream writer's output read back with the demuxer: streams, codecs, every +//! frame's bytes and timestamps, keyframes, the PCR, and no continuity or CRC warnings. +// Test code: a failed unwrap is a failed test. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod mpegts_mux; + +use craft_media::mpegts::mux::{Av1Config, Codec, Config, Error, Frame, MAX_PCR_INTERVAL, Muxer, OpusMapping, Stream}; +use craft_media::mpegts::{self, Codec as Demuxed, StreamId}; +use mpegts_mux::*; + +const DELAY: i64 = 63_000; + +/// Muxes `items`, reads the file back and compares every unit. Returns the file and the PCRs. +fn round_trip(cfg: Config, streams: &[Stream], items: &mut [Item], want: &[Demuxed]) -> (Vec, Vec) { + let mut m = Muxer::new(Vec::new(), cfg, streams).unwrap(); + write_all(&mut m, items); + let pcr_pid = m.pcr_pid(); + let stats = m.stats(); + let ts = m.finish().unwrap(); + assert_eq!(stats.bytes(), ts.len() as u64); + assert_eq!(stats.frames, items.len() as u64); + let pcrs = check_packets(&ts, pcr_pid, i64::from(cfg.pcr_interval) * 300); + + let file = mpegts::open(&ts).unwrap(); + assert_eq!(file.format, mpegts::Format::Ts { packet_size: 188, sync_offset: 0 }); + assert!(file.warnings.is_empty(), "{:?}", file.warnings); + assert_eq!(file.program, Some(cfg.program_number)); + assert_eq!(file.streams.len(), streams.len()); + assert!(file.pcr_range.is_some()); + for (s, (st, codec)) in file.streams.iter().zip(streams.iter().zip(want)) { + assert_eq!(s.id, StreamId::Pid(st.pid)); + assert_eq!(&s.codec, codec, "PID {:#x}", st.pid); + assert_eq!(s.stream_type, st.codec.stream_type()); + assert_eq!(s.language, st.language.map(|l| String::from_utf8(l.to_vec()).unwrap())); + } + for (k, _) in streams.iter().enumerate() { + let mine: Vec<&Item> = items.iter().filter(|i| i.stream == k).collect(); + let units = &file.streams[k].units; + assert_eq!(units.len(), mine.len(), "stream {k}"); + for (n, (u, i)) in units.iter().zip(&mine).enumerate() { + assert_eq!(u.pts, Some(i.pts), "stream {k} unit {n}"); + assert_eq!(u.dts.or(u.pts), Some(i.dts), "stream {k} unit {n}"); + if streams[k].codec.is_video() && !matches!(want[k], Demuxed::Unknown(_)) { + assert_eq!(u.key, i.key, "stream {k} unit {n}"); + } + assert_eq!(file.read_unit(&ts, k, n).unwrap(), i.expect, "stream {k} unit {n}"); + } + } + (ts, pcrs) +} + +#[test] +fn every_codec_in_one_program() { + let streams = [ + Stream::new(0x100, Codec::H264), + Stream::new(0x101, Codec::Aac { object_type: 2, sample_rate_index: 3, channels: 2 }).with_language(*b"eng"), + Stream::new(0x102, Codec::Opus { channels: 2 }).with_language(*b"deu"), + Stream::new(0x103, Codec::Ac3), + Stream::new(0x104, Codec::MpegAudio { low_sample_rate: false }), + ]; + let mut items = Vec::new(); + let t0 = 90_000; + for k in 0..90i64 { + // decode order I P B B P B B ...: P pictures shown 3 frames later, B pictures 1 later + let key = k % 30 == 0; + let (disposable, show) = match k % 3 { + 0 => (false, 3), + _ => (true, 1), + }; + let size = if key { 9000 } else { 300 + (k as usize * 37) % 2000 }; + let data = h264(key, disposable && !key, size, k as u8); + let dts = t0 + k * 3000; + items.push(Item { stream: 0, expect: with_aud(Codec::H264, &data), data, pts: dts + show * 3000, dts, key }); + } + for k in 0..140i64 { + let raw = { + let mut v = Vec::new(); + fill(&mut v, 200 + (k as usize * 13) % 600, k as u8); + v + }; + let mut expect = adts(0, 0)[..7].to_vec(); + let len = raw.len() + 7; + expect[3] = 0x80 | (len >> 11) as u8; + expect[4] = (len >> 3) as u8; + expect[5] = ((len & 7) as u8) << 5 | 0x1F; + expect.extend_from_slice(&raw); + items.push(Item { stream: 1, data: raw, pts: t0 + k * 1920, dts: t0 + k * 1920, key: true, expect }); + } + for k in 0..150i64 { + let mut p = vec![0xFC]; + fill(&mut p, 1 + (k as usize * 41) % 700, k as u8); + items.push(Item { stream: 2, expect: opus_unit(&p), data: p, pts: t0 + k * 1800, dts: t0 + k * 1800, key: true }); + } + for k in 0..90i64 { + let f = ac3(k as u8); + items.push(Item { stream: 3, expect: f.clone(), data: f, pts: t0 + k * 2880, dts: t0 + k * 2880, key: true }); + } + for k in 0..120i64 { + let f = mp3(false, k as u8); + items.push(Item { stream: 4, expect: f.clone(), data: f, pts: t0 + k * 2160, dts: t0 + k * 2160, key: true }); + } + let want = [Demuxed::H264, Demuxed::AacAdts, Demuxed::Unknown(6), Demuxed::Ac3, Demuxed::MpegAudio]; + let (ts, pcrs) = round_trip(Config::default(), &streams, &mut items, &want); + let file = mpegts::open(&ts).unwrap(); + assert_eq!(file.pcr_range, Some((pcrs[0], *pcrs.last().unwrap()))); + assert_eq!(pcrs[0], (t0 - DELAY) * 300); + // the frames' own headers read back with the demuxer's frame parser + let aac = file.read_unit(&ts, 1, 0).unwrap(); + assert_eq!(mpegts::frame_info(&Demuxed::AacAdts, &aac).map(|i| (i.sample_rate, i.channels)), Some((48_000, 2))); +} + +#[test] +fn hevc_with_adts_and_a_pcr_pid_of_its_own() { + let streams = [Stream::new(0x1FFE, Codec::Hevc), Stream::new(0x0010, Codec::AacAdts)]; + let cfg = Config { pcr_pid: Some(0x0011), pcr_interval: MAX_PCR_INTERVAL, psi_interval: 45_000, ..Config::default() }; + let mut items = Vec::new(); + for k in 0..60i64 { + let key = k % 20 == 0; + let data = hevc(key, if key { 20_000 } else { 700 }, k as u8); + let t = 70_000 + k * 3003; + items.push(Item { stream: 0, expect: with_aud(Codec::Hevc, &data), data, pts: t, dts: t, key }); + } + for k in 0..95i64 { + let f = adts(150 + k as usize, k as u8); + let t = 70_000 + k * 1920; + items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); + } + let (ts, _) = round_trip(cfg, &streams, &mut items, &[Demuxed::Hevc, Demuxed::AacAdts]); + let file = mpegts::open(&ts).unwrap(); + assert!(file.pcr_range.is_some(), "the demuxer reads the PCR from the PMT's PCR_PID"); +} + +#[test] +fn mpeg2_video_and_low_rate_mpeg_audio() { + let streams = [Stream::new(0x200, Codec::Mpeg2Video), Stream::new(0x201, Codec::MpegAudio { low_sample_rate: true })]; + let mut items = Vec::new(); + for k in 0..50i64 { + let key = k % 12 == 0; + let data = mpeg2(key, (k % 12) as u16, if key { 4000 } else { 900 }, k as u8); + let t = 100_000 + k * 3600; + items.push(Item { stream: 0, expect: data.clone(), data, pts: t, dts: t, key }); + } + for k in 0..70i64 { + let f = mp3(true, k as u8); + let t = 100_000 + k * 2160; + items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); + } + round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg2Video, Demuxed::MpegAudio]); +} + +#[test] +fn timestamps_run_past_the_33_bit_wrap() { + let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Opus { channels: 1 })]; + let start = (1i64 << 33) - 90_000; + let mut items = Vec::new(); + for k in 0..90i64 { + let data = h264(k == 0, false, 500, k as u8); + let t = start + k * 3000; + items.push(Item { stream: 0, expect: with_aud(Codec::H264, &data), data, pts: t, dts: t, key: k == 0 }); + } + for k in 0..140i64 { + let p = vec![0x08, k as u8 | 1, 0x55]; + let t = start + k * 1800; + items.push(Item { stream: 1, expect: opus_unit(&p), data: p, pts: t, dts: t, key: true }); + } + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264, Demuxed::Unknown(6)]); +} + +#[test] +fn eac3_mpeg1_video_and_mpeg4_part2() { + let streams = + [Stream::new(0x100, Codec::Mpeg1Video), Stream::new(0x101, Codec::Eac3).with_language(*b"spa"), Stream::new(0x102, Codec::Mpeg4Part2)]; + let mut items = Vec::new(); + for k in 0..50i64 { + let key = k % 12 == 0; + let data = mpeg2(key, (k % 12) as u16, if key { 4000 } else { 900 }, k as u8); + let t = 100_000 + k * 3600; + items.push(Item { stream: 0, expect: data.clone(), data, pts: t, dts: t, key }); + let data = mpeg4(key, if key { 3000 } else { 600 }, k as u8); + items.push(Item { stream: 2, expect: data.clone(), data, pts: t, dts: t, key }); + } + for k in 0..60i64 { + let f = eac3(k as u8); + let t = 100_000 + k * 2880; + items.push(Item { stream: 1, expect: f.clone(), data: f, pts: t, dts: t, key: true }); + } + round_trip(Config::default(), &streams, &mut items, &[Demuxed::Mpeg1Video, Demuxed::Eac3, Demuxed::Unknown(0x10)]); +} + +#[test] +fn av1_reads_back_as_its_obus() { + let config = Av1Config::from_av1c(&[0x81, 0x08, 0x0C, 0x00]).unwrap(); + let streams = [Stream::new(0x100, Codec::Av1(config)), Stream::new(0x101, Codec::Opus { channels: 2 })]; + let mut tus = Vec::new(); + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + for k in 0..60i64 { + let key = k % 30 == 0; + let tu = av1(key, if key { 20_000 } else { 300 + (k as usize * 113) % 3000 }, k as u8); + let t = 90_000 + k * 3000; + m.write_frame(0, &Frame { data: &tu, pts: t, dts: None, key }).unwrap(); + m.write_frame(1, &Frame { data: &[0xFC, k as u8 | 1], pts: t, dts: None, key: true }).unwrap(); + tus.push((tu, t)); + } + let ts = m.finish().unwrap(); + check_packets(&ts, 0x100, 3600 * 300); + let file = mpegts::open(&ts).unwrap(); + assert!(file.warnings.is_empty(), "{:?}", file.warnings); + assert_eq!(file.streams[0].codec, Demuxed::Unknown(6)); + assert_eq!(file.streams[0].stream_type, 0x06); + let units = &file.streams[0].units; + assert_eq!(units.len(), tus.len()); + for (n, (u, (tu, t))) in units.iter().zip(&tus).enumerate() { + assert_eq!(u.pts, Some(*t)); + let es = file.read_unit(&ts, 0, n).unwrap(); + assert_eq!(av1_unescape(&es), av1_without_delimiters(tu), "unit {n}"); + } +} + +#[test] +fn opus_with_an_explicit_mapping_and_trims() { + let mapping = OpusMapping { channels: 3, family: 255, streams: 3, coupled: 0, mapping: [0, 1, 2, 0, 0, 0, 0, 0] }; + let streams = [Stream::new(0x100, Codec::OpusMapped(mapping))]; + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + let mut want = Vec::new(); + for k in 0..20i64 { + // three streams of 20 ms: two self-delimited packets, then the last one + let au = [0xFC, 1, 0x55, 0xFC, 1, 0x66, 0xFC, 0x77]; + let trim = if k == 0 { craft_media::mpegts::mux::OpusTrim { start: 312, end: 0 } } else { Default::default() }; + let t = 90_000 + k * 1800; + m.write_frame_with_trim(0, &Frame { data: &au, pts: t, dts: None, key: true }, trim).unwrap(); + let mut unit = if k == 0 { vec![0x7F, 0xF0, 8] } else { vec![0x7F, 0xE0, 8] }; + if k == 0 { + unit.extend_from_slice(&312u16.to_be_bytes()); + } + unit.extend_from_slice(&au); + want.push(unit); + } + let ts = m.finish().unwrap(); + let file = mpegts::open(&ts).unwrap(); + assert!(file.warnings.is_empty(), "{:?}", file.warnings); + assert_eq!(file.streams[0].units.len(), want.len()); + for (n, w) in want.iter().enumerate() { + assert_eq!(&file.read_unit(&ts, 0, n).unwrap(), w); + } +} + +#[test] +fn a_discontinuity_reads_back_in_both_time_bases() { + let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::AacAdts)]; + let mut m = Muxer::new(Vec::new(), Config::default(), &streams).unwrap(); + let mut want: [Vec<(Vec, i64)>; 2] = Default::default(); + for (part, start) in [(0, 900_000i64), (1, 200_000)] { + if part == 1 { + m.discontinuity(); + } + for k in 0..30i64 { + let data = h264(k == 0, false, 400, k as u8); + let t = start + k * 3000; + m.write_frame(0, &Frame { data: &data, pts: t, dts: None, key: k == 0 }).unwrap(); + want[0].push((with_aud(Codec::H264, &data), t)); + let f = adts(100, k as u8); + m.write_frame(1, &Frame { data: &f, pts: t, dts: None, key: true }).unwrap(); + want[1].push((f, t)); + } + } + let ts = m.finish().unwrap(); + let file = mpegts::open(&ts).unwrap(); + for (k, w) in want.iter().enumerate() { + let units = &file.streams[k].units; + assert_eq!(units.len(), w.len(), "stream {k}"); + for (n, (u, (bytes, t))) in units.iter().zip(w).enumerate() { + assert_eq!(u.pts.map(|p| p.rem_euclid(1 << 33)), Some(*t), "stream {k} unit {n}"); + assert_eq!(&file.read_unit(&ts, k, n).unwrap(), bytes, "stream {k} unit {n}"); + } + } +} + +/// An output that fails on its third write call. +struct Flaky { + fail_on: Option, + calls: usize, + data: Vec, +} + +impl std::io::Write for Flaky { + fn write(&mut self, b: &[u8]) -> std::io::Result { + self.calls += 1; + if Some(self.calls) == self.fail_on { + return Err(std::io::Error::other("upload failed")); + } + self.data.extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +#[test] +fn the_output_after_an_io_error_reads_on_its_own() { + let streams = [Stream::new(0x100, Codec::H264), Stream::new(0x101, Codec::Ac3)]; + let mut m = Muxer::new(Flaky { fail_on: Some(3), calls: 0, data: Vec::new() }, Config::default(), &streams).unwrap(); + let mut after = [0usize; 2]; + let mut failed = false; + for k in 0..60i64 { + let t = 90_000 + k * 3000; + let data = h264(k % 30 == 0, false, 2000, k as u8); + for (s, frame) in + [(0, Frame { data: &data, pts: t, dts: None, key: k % 30 == 0 }), (1, Frame { data: &ac3(k as u8), pts: t, dts: None, key: true })] + { + match m.write_frame(s, &frame) { + Ok(()) if failed => after[s] += 1, + Ok(()) => {} + Err(Error::Io(_)) if !failed => { + failed = true; + m.replace_writer(Flaky { fail_on: None, calls: 0, data: Vec::new() }); + } + Err(e) => panic!("{e}"), + } + } + } + assert!(failed); + let ts = m.finish().unwrap().data; + let file = mpegts::open(&ts).unwrap(); + assert!(file.warnings.is_empty(), "{:?}", file.warnings); + // every frame written after the error reads back + assert_eq!(file.streams[1].units.len(), after[1]); + assert_eq!(file.streams[0].units.len(), after[0]); +} + +#[test] +fn a_single_frame_and_a_huge_one() { + let streams = [Stream::new(0x100, Codec::H264)]; + // 1000 bytes: the demuxer needs five packets in a row to recognize the file + let one = h264(true, false, 1000, 1); + let mut items = vec![Item { stream: 0, expect: with_aud(Codec::H264, &one), data: one, pts: 90_000, dts: 90_000, key: true }]; + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264]); + // past PES_packet_length's 65 535 bytes: an unbounded video PES packet + let big = h264(true, false, 3_000_000, 2); + let small = h264(false, false, 100, 3); + let mut items = vec![ + Item { stream: 0, expect: with_aud(Codec::H264, &big), data: big, pts: 90_000, dts: 90_000, key: true }, + Item { stream: 0, expect: with_aud(Codec::H264, &small), data: small, pts: 93_000, dts: 93_000, key: false }, + ]; + round_trip(Config::default(), &streams, &mut items, &[Demuxed::H264]); +} + +#[test] +#[should_panic(expected = "PCR flag in an adaptation field of 1 byte")] +fn the_packet_checker_refuses_a_pcr_flag_in_a_short_adaptation_field() { + // adaptation_field_length 1 holds only the flags byte, so the six bytes after it are payload + let mut p = vec![0x7E; 188]; + p[..6].copy_from_slice(&[0x47, 0x01, 0x00, 0x30, 0x01, 0x10]); + check_packets(&p, 0x100, 3600 * 300); +} From 0a022b61f71f160e05c34f2db88b44b2424a696d Mon Sep 17 00:00:00 2001 From: keithcsqueensu <92232107+keithcsqueensu@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:55:20 -0500 Subject: [PATCH 25/79] craft-sheet: built-in number formats 37 to 40 are the codes Excel reports (#2020) (#2291) Excel 16 (en-US) reports #,##0_);(#,##0), #,##0_);[Red](#,##0), #,##0.00_);(#,##0.00) and #,##0.00_);[Red](#,##0.00) for ids 37 to 40, not the ECMA-376 Part 1 18.8.30 text the table held. It writes neither a numFmt nor a FORMAT record for these ids, so the table is the only source of their codes when a file Excel saved is read, as .xlsx or as .xls. Co-authored-by: kiwi4boy Co-authored-by: Dylan M. Taylor --- crates/sheet/src/tables.rs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/crates/sheet/src/tables.rs b/crates/sheet/src/tables.rs index b30935d543..98f576170b 100644 --- a/crates/sheet/src/tables.rs +++ b/crates/sheet/src/tables.rs @@ -26,10 +26,14 @@ const BUILTIN_FORMATS: [(u32, &str); 36] = [ (20, "h:mm"), (21, "h:mm:ss"), (22, "m/d/yyyy h:mm"), - (37, "#,##0 ;(#,##0)"), - (38, "#,##0 ;[Red](#,##0)"), - (39, "#,##0.00;(#,##0.00)"), - (40, "#,##0.00;[Red](#,##0.00)"), + // 37 to 40 are the codes Excel reports for these ids, not the ECMA-376 Part 1 18.8.30 text + // (`#,##0 ;(#,##0)`, `#,##0.00;(#,##0.00)` and their [Red] forms). Excel pads a positive number + // by the width of a closing parenthesis (`_)`). It writes neither a numFmt nor a FORMAT record + // for them, so these codes are what a file Excel saved means. + (37, "#,##0_);(#,##0)"), + (38, "#,##0_);[Red](#,##0)"), + (39, "#,##0.00_);(#,##0.00)"), + (40, "#,##0.00_);[Red](#,##0.00)"), (41, "_(* #,##0_);_(* \\(#,##0\\);_(* \"-\"_);_(@_)"), (42, "_(\"$\"* #,##0_);_(\"$\"* \\(#,##0\\);_(\"$\"* \"-\"_);_(@_)"), (43, "_(* #,##0.00_);_(* \\(#,##0.00\\);_(* \"-\"??_);_(@_)"), @@ -86,6 +90,17 @@ mod tests { assert_eq!(builtin_format_id("yyyy"), None); } + #[test] + fn formats_37_to_40_are_the_codes_excel_reports() { + let codes = ["#,##0_);(#,##0)", "#,##0_);[Red](#,##0)", "#,##0.00_);(#,##0.00)", "#,##0.00_);[Red](#,##0.00)"]; + for (id, code) in (37..=40).zip(codes) { + assert_eq!(builtin_format(id), Some(code), "{id}"); + assert_eq!(builtin_format_id(code), Some(id), "{id}"); + } + // The 18.8.30 text is not a built-in, so it is written as a custom format. + assert_eq!(builtin_format_id("#,##0.00;(#,##0.00)"), None); + } + #[test] fn the_palette_repeats_its_eight_fixed_colours() { assert_eq!(DEFAULT_PALETTE.get(..8), DEFAULT_PALETTE.get(8..16)); From 401bf426a61f59f0ecfa6835d38584a6eb4f5c21 Mon Sep 17 00:00:00 2001 From: Diego Chagas Date: Thu, 19 Nov 2026 02:11:50 -0300 Subject: [PATCH 26/79] jxl: charge failed brob inflations, refuse large windows, walk boxes without a span list (#2275) Follow-up to the brob budget: - an over-cap or broken stream now charges the bytes it produced to the shared budget, so a file of many such streams cannot inflate the whole budget once per box; - a Brotli header that declares a large window is refused before decoding (the decoder reserves its ring buffer up front, outside the output cap); - boxes are walked one at a time instead of collected into a Vec of spans before the brob check. image-codecs: document that JPEG XL ignores keep_orientation. --- crates/image-codecs/src/options.rs | 3 +- crates/jxl/src/brob.rs | 125 ++++++++++++++++++++++------- 2 files changed, 99 insertions(+), 29 deletions(-) diff --git a/crates/image-codecs/src/options.rs b/crates/image-codecs/src/options.rs index d0ef8ee9a6..b4436055c4 100644 --- a/crates/image-codecs/src/options.rs +++ b/crates/image-codecs/src/options.rs @@ -108,7 +108,8 @@ pub struct DecodeOptions { pub limits: Limits, /// Keep the pixels as stored instead of applying the EXIF / TIFF /// orientation (by default they are turned upright and the metadata's - /// orientation is rewritten to 1). + /// orientation is rewritten to 1). JPEG XL ignores this: `craft-jxl` applies the codestream's + /// orientation while rendering, so a JPEG XL image is always upright with orientation 1. pub keep_orientation: bool, } diff --git a/crates/jxl/src/brob.rs b/crates/jxl/src/brob.rs index 6d0aefbc43..16d72c7209 100644 --- a/crates/jxl/src/brob.rs +++ b/crates/jxl/src/brob.rs @@ -47,26 +47,66 @@ fn box_at(bytes: &[u8], at: usize) -> Option { Some(BoxSpan { start: at, header, end: end.min(bytes.len()) }) } -/// Every box of the container, in order, up to the first one that cannot be read. -fn boxes(bytes: &[u8]) -> Vec { - let mut found = Vec::new(); - let mut at = 0; - while let Some(span) = box_at(bytes, at) { - at = span.end; - found.push(span); - if at >= bytes.len() { - break; - } - } - found +/// The boxes of the container, in order, up to the first one that cannot be read. One box at a +/// time: a file of eight-byte boxes must not cost three times its size in spans. +struct Boxes<'a> { + bytes: &'a [u8], + at: usize, + done: bool, } -/// Inflates `compressed`, or `None` when it is broken or would pass `cap` bytes. -pub(crate) fn inflate_capped(compressed: &[u8], cap: usize) -> Option> { +impl<'a> Boxes<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { bytes, at: 0, done: false } + } + + /// Where the next box would start: the end of the last one read, or 0 before the first. + fn end(&self) -> usize { + self.at + } +} + +impl Iterator for Boxes<'_> { + type Item = BoxSpan; + + fn next(&mut self) -> Option { + if self.done { + return None; + } + let Some(span) = box_at(self.bytes, self.at) else { + self.done = true; + return None; + }; + self.at = span.end; + self.done = self.at >= self.bytes.len(); + Some(span) + } +} + +/// Whether the Brotli stream header asks for a window of at most 16 MiB. The decoder reserves its +/// whole ring buffer up front, outside the output cap, so a header that declares a large window +/// (RFC 7932 §9.1 and the large-window extension) could ask for a gigabyte from a few bytes. +fn window_is_small(compressed: &[u8]) -> bool { + let Some(first) = compressed.first() else { return true }; + let wide = first & 1 == 1; + let long_form = (first >> 1) & 7; + let short_form = (first >> 4) & 7; + !(wide && long_form == 0 && short_form == 1) +} + +/// Inflates `compressed`. `Err` carries how many bytes were produced before it was refused +/// (broken stream, over `cap`, or a large window), so the caller can charge the work to its budget. +pub(crate) fn inflate_capped(compressed: &[u8], cap: usize) -> Result, usize> { + if !window_is_small(compressed) { + return Err(0); + } let mut out = Vec::new(); - let limit = u64::try_from(cap).ok()?.checked_add(1)?; - brotli_decompressor::Decompressor::new(compressed, 4096).take(limit).read_to_end(&mut out).ok()?; - (out.len() <= cap).then_some(out) + let limit = u64::try_from(cap).ok().and_then(|c| c.checked_add(1)).ok_or(0_usize)?; + let read = brotli_decompressor::Decompressor::new(compressed, 4096).take(limit).read_to_end(&mut out); + if read.is_err() || out.len() > cap { + return Err(out.len()); + } + Ok(out) } /// A plain box of type `kind` holding `data`. @@ -92,9 +132,18 @@ fn unwrap_brob(span: &BoxSpan, bytes: &[u8], budget: &mut usize) -> Option { + *budget -= inflated.len(); + Some(plain_box(inner, &inflated)) + } + Err(produced) => { + // The work was done even though the box is dropped: charge it, so a file of many + // over-cap streams cannot make the decoder inflate the whole budget once per box. + *budget = budget.saturating_sub(produced); + None + } + } } /// `bytes` with every `brob` box inflated, `cap` bytes in all (or removed), or `None` when the file is @@ -103,20 +152,20 @@ pub(crate) fn sanitize(bytes: &[u8], cap: usize) -> Option> { if !bytes.starts_with(SIGNATURE) { return None; } - let spans = boxes(bytes); - if !spans.iter().any(|s| s.kind(bytes) == BROB) { + if !Boxes::new(bytes).any(|s| s.kind(bytes) == BROB) { return None; } let mut budget = cap; let mut out = Vec::with_capacity(bytes.len()); - for span in &spans { + let mut walk = Boxes::new(bytes); + for span in walk.by_ref() { match (span.kind(bytes) == BROB, bytes.get(span.start..span.end)) { - (true, _) => out.extend(unwrap_brob(span, bytes, &mut budget).unwrap_or_default()), + (true, _) => out.extend(unwrap_brob(&span, bytes, &mut budget).unwrap_or_default()), (false, Some(whole)) => out.extend_from_slice(whole), (false, None) => {} } } - out.extend_from_slice(bytes.get(spans.last().map_or(0, |s| s.end)..).unwrap_or(&[])); + out.extend_from_slice(bytes.get(walk.end()..).unwrap_or(&[])); Some(out) } @@ -146,9 +195,9 @@ mod tests { #[test] fn a_bomb_passes_the_cap_and_a_real_packet_does_not() { - assert_eq!(inflate_capped(&EXIF_BR, BROB_CAP).as_deref(), Some(&b"II*\0\x08\0\0\0hello exif"[..])); - assert!(inflate_capped(&BOMB_BR, BROB_CAP).is_none()); - assert!(inflate_capped(&BOMB_BR[..20], BROB_CAP).is_none(), "a cut stream is not a result"); + assert_eq!(inflate_capped(&EXIF_BR, BROB_CAP).as_deref(), Ok(&b"II*\0\x08\0\0\0hello exif"[..])); + assert!(inflate_capped(&BOMB_BR, BROB_CAP).is_err()); + assert!(inflate_capped(&BOMB_BR[..20], BROB_CAP).is_err(), "a cut stream is not a result"); } #[test] @@ -188,6 +237,26 @@ mod tests { assert!(out.len() < SIGNATURE.len() + 2 * (exif + 8) + 1); } + #[test] + fn an_over_cap_box_uses_up_the_budget_of_the_boxes_after_it() { + let boxes = [brob_of(b"xml ", &BOMB_BR), brob_of(b"Exif", &EXIF_BR)]; + assert_eq!(sanitize(&container(&boxes), 64).unwrap(), container(&[]), "the later packet is dropped too"); + } + + #[test] + fn a_stream_that_declares_a_large_window_is_refused_before_decoding() { + // WBITS bits 1, 000, 001: the large-window marker. + assert_eq!(inflate_capped(&[0x11, 0, 0, 0], BROB_CAP), Err(0)); + assert!(window_is_small(&EXIF_BR) && window_is_small(&BOMB_BR) && window_is_small(&[])); + } + + #[test] + fn a_long_run_of_tiny_boxes_is_walked_without_a_list_of_spans() { + let boxes: Vec> = (0..1000).map(|_| plain_box(b"free", b"")).collect(); + assert!(sanitize(&container(&boxes), BROB_CAP).is_none(), "no brob box: used as it is"); + assert_eq!(Boxes::new(&container(&boxes)).count(), 1001, "the signature box and the 1000 others"); + } + #[test] fn a_cut_off_file_keeps_its_tail_verbatim() { let mut file = container(&[brob_of(b"Exif", &EXIF_BR)]); From 56847b14adf8ab3f3d45da4cd1cb64d2c23b7b8e Mon Sep 17 00:00:00 2001 From: el-j Date: Thu, 19 Nov 2026 06:11:54 +0100 Subject: [PATCH 27/79] craft-captions: MP4 timed text sample codec (mov_text / tx3g) (#1781) * craft-captions: MP4 timed text sample codec (mov_text / tx3g) Add 3GPP TS 26.245 timed text subtitle sample decoding and encoding, modifier box parsing (styl, hlit, hclr, krok, dlay, href, tbox, blnk, wrap), markup conversion and tx3g sample entry configuration under feature mov-text. Closes #1555. * craft-captions: address reviews on mov_text formatting, twrp, and timescales. --------- Co-authored-by: Dylan M. Taylor --- Cargo.lock | 1 + crates/captions/Cargo.toml | 7 + crates/captions/README.md | 4 + crates/captions/src/lib.rs | 2 + crates/captions/src/mov_text.rs | 871 +++++++++++++++++++++++++++ crates/captions/tests/it/main.rs | 2 + crates/captions/tests/it/mov_text.rs | 349 +++++++++++ 7 files changed, 1236 insertions(+) create mode 100644 crates/captions/src/mov_text.rs create mode 100644 crates/captions/tests/it/mov_text.rs diff --git a/Cargo.lock b/Cargo.lock index 0d65079709..de69d0765c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1634,6 +1634,7 @@ version = "0.1.0" name = "craft-captions" version = "0.1.0" dependencies = [ + "craft-media", "craft-media-testkit", "craft-timeline", "craft-xml", diff --git a/crates/captions/Cargo.toml b/crates/captions/Cargo.toml index cd09f7e166..1136f55f9e 100644 --- a/crates/captions/Cargo.toml +++ b/crates/captions/Cargo.toml @@ -10,6 +10,11 @@ repository.workspace = true [lints] workspace = true +[features] +default = [] +# MP4 timed text (3GPP TS 26.245 / mov_text / tx3g) sample codec. +mov-text = [] + [dependencies] craft-timeline = { workspace = true } craft-xml = { workspace = true } @@ -21,3 +26,5 @@ proptest = { workspace = true } roxmltree = "0.21" # ffmpeg as the reference for the ASS tests (tests/it/ass.rs). craft-media-testkit = { workspace = true } +# craft-media isobmff for mov_text oracle demuxing/muxing tests. +craft-media = { workspace = true, features = ["isobmff"] } diff --git a/crates/captions/README.md b/crates/captions/README.md index 7380a3ce41..b2f6a195f0 100644 --- a/crates/captions/README.md +++ b/crates/captions/README.md @@ -27,6 +27,10 @@ assert!(scc.starts_with(b"Scenarist_SCC V1.0")); and the SMPTE ST 334-2 caption distribution packet. - `plain_text` strips inline tags and decodes the common entities, for display or for formats without markup. +- Optional feature `mov-text` provides MP4 Timed Text (`mov_text` / `tx3g`, 3GPP TS 26.245) + sample decoding, encoding, modifier box parsing (`styl`, `hlit`, `hclr`, `krok`, `dlay`, `href`, + `tbox`, `blnk`, `wrap`), and `Tx3gConfig` sample entry parsing/writing for ISO BMFF (`.mp4`) and + QuickTime (`.mov`) subtitle tracks. ## Time diff --git a/crates/captions/src/lib.rs b/crates/captions/src/lib.rs index ca99dba439..2d0cf90c18 100644 --- a/crates/captions/src/lib.rs +++ b/crates/captions/src/lib.rs @@ -36,6 +36,8 @@ pub mod ass; pub mod cea608; pub mod jacosub; pub mod mcc; +#[cfg(feature = "mov-text")] +pub mod mov_text; pub mod pjs; pub mod realtext; pub mod scc; diff --git a/crates/captions/src/mov_text.rs b/crates/captions/src/mov_text.rs new file mode 100644 index 0000000000..d1a3ce2a91 --- /dev/null +++ b/crates/captions/src/mov_text.rs @@ -0,0 +1,871 @@ +//! MP4 Timed Text (`mov_text` / `tx3g`, 3GPP TS 26.245). +//! +//! A clean-room reader and writer for 3GPP Timed Text subtitle samples and sample entry +//! configurations (`tx3g`), as carried in ISO BMFF (`.mp4`) and QuickTime (`.mov`) files. +//! +//! ## Sample Structure +//! +//! A timed text sample consists of: +//! - A 16-bit big-endian text length. +//! - The text string bytes (UTF-8, or UTF-16 with BOM). +//! - Zero or more modifier boxes: +//! - `styl`: Character style runs (bold, italic, underline, font ID, font size, text color). +//! - `hlit`: Highlighted character range. +//! - `hclr`: Highlight color (RGBA). +//! - `krok`: Karaoke highlight timing and character spans. +//! - `dlay`: Scroll delay in track-timescale ticks. +//! - `href`: Hypertext link URL and alt text. +//! - `tbox`: Text box override coordinates (`top, left, bottom, right`). +//! - `blnk`: Blinking text character range. +//! - `twrp`: Text wrap flag (0 = no wrap, 1 = automatic soft wrap). +//! +//! ## Style Flags +//! +//! Style flags in `styl` records: +//! - `0x01`: Bold (`...`) +//! - `0x02`: Italic (`...`) +//! - `0x04`: Underline (`...`) + +use crate::time::Tick; +use crate::{Cue, Document, TICKS_PER_SECOND}; + +/// What went wrong reading or writing timed text. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum Error { + /// The input slice is shorter than the declared field or box size. + #[error("truncated timed text data")] + Truncated, + /// The text payload is not valid UTF-8 and contains no valid UTF-16 BOM. + #[error("invalid text encoding in timed text sample")] + InvalidText, + /// The text exceeds the 16-bit length prefix (65,535 bytes). + #[error("timed text string exceeds 65535 bytes: {0}")] + TextTooLong(usize), + /// A modifier box header has an invalid size (< 8). + #[error("invalid modifier box size: {0}")] + InvalidBox(&'static str), +} + +/// `Result` alias for timed text operations. +pub type Result = std::result::Result; + +/// Face style flag: Bold (`0x01`). +pub const STYLE_FLAG_BOLD: u8 = 0x01; +/// Face style flag: Italic (`0x02`). +pub const STYLE_FLAG_ITALIC: u8 = 0x02; +/// Face style flag: Underline (`0x04`). +pub const STYLE_FLAG_UNDERLINE: u8 = 0x04; + +/// A character styling record within a `styl` box. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct StyleRecord { + /// 0-indexed start character index (inclusive, measured in Unicode scalar values). + pub start_char: u16, + /// 0-indexed end character index (exclusive, measured in Unicode scalar values). + pub end_char: u16, + /// 16-bit font ID matching an entry in the sample description font table (`ftab`). + pub font_id: u16, + /// Face style flags: bit 0 = bold, bit 1 = italic, bit 2 = underline. + pub face_style_flags: u8, + /// Font size in points. + pub font_size: u8, + /// Text RGBA color (`[r, g, b, a]`). + pub text_color_rgba: [u8; 4], +} + +impl Default for StyleRecord { + fn default() -> Self { + Self { start_char: 0, end_char: 0, font_id: 1, face_style_flags: 0, font_size: 16, text_color_rgba: [255, 255, 255, 255] } + } +} + +impl StyleRecord { + /// Returns `true` if bold is set. + pub fn is_bold(&self) -> bool { + self.face_style_flags & STYLE_FLAG_BOLD != 0 + } + + /// Returns `true` if italic is set. + pub fn is_italic(&self) -> bool { + self.face_style_flags & STYLE_FLAG_ITALIC != 0 + } + + /// Returns `true` if underline is set. + pub fn is_underline(&self) -> bool { + self.face_style_flags & STYLE_FLAG_UNDERLINE != 0 + } +} + +/// Coordinates of a text display box (`tbox`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TextBox { + pub top: i16, + pub left: i16, + pub bottom: i16, + pub right: i16, +} + +/// An entry in a karaoke box (`krok`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct KaraokeEntry { + /// Highlight end time in timescale ticks. + pub highlight_end_time: u32, + /// Start character index (inclusive). + pub start_char: u16, + /// End character index (exclusive). + pub end_char: u16, +} + +/// A hypertext link entry (`href`). +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HyperText { + /// Start character index (inclusive). + pub start_char: u16, + /// End character index (exclusive). + pub end_char: u16, + /// Destination URL. + pub url: String, + /// Accessible alt text string. + pub alt_string: String, +} + +/// An unpacked 3GPP Timed Text (`tx3g` / `mov_text`) sample. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TextSample { + /// Decoded UTF-8 text content. + pub text: String, + /// Character styling records from the `styl` box. + pub styles: Vec, + /// Highlighted character range `(start_char, end_char)` from `hlit`. + pub highlight: Option<(u16, u16)>, + /// Highlight color `[r, g, b, a]` from `hclr`. + pub highlight_color: Option<[u8; 4]>, + /// Karaoke timing and spans `(highlight_start_time, entries)` from `krok`. + pub karaoke: Option<(u32, Vec)>, + /// Scroll delay in milliseconds from `dlay`. + pub scroll_delay: Option, + /// Hypertext links from `href` boxes. + pub hypertext: Vec, + /// Text box override from `tbox`. + pub text_box: Option, + /// Blinking character ranges `(start_char, end_char)` from `blnk` boxes. + pub blinking: Vec<(u16, u16)>, + /// Wrap flag from `wrap` box: `0` = automatic wrap, `1` = no wrap. + pub wrap_flag: Option, +} + +/// Sample description table configuration for a `tx3g` track. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Tx3gConfig { + /// 32-bit display flags (e.g. scroll in, scroll out, continuous scroll). + pub display_flags: u32, + /// Horizontal justification: 0 = left, 1 = center, -1 = right. + pub horizontal_justification: i8, + /// Vertical justification: 0 = top, 1 = center, -1 = bottom. + pub vertical_justification: i8, + /// Background RGBA color. + pub background_color: [u8; 4], + /// Default text box coordinates. + pub default_text_box: TextBox, + /// Default style record. + pub default_style: StyleRecord, + /// Font table entries `(font_id, font_name)`. + pub fonts: Vec<(u16, String)>, +} + +impl Default for Tx3gConfig { + fn default() -> Self { + Self { + display_flags: 0, + horizontal_justification: 1, // center + vertical_justification: -1, // bottom + background_color: [0, 0, 0, 255], + default_text_box: TextBox::default(), + default_style: StyleRecord::default(), + fonts: vec![(1, "Arial".to_string())], + } + } +} + +impl Tx3gConfig { + /// Parse a `tx3g` sample entry payload (after the standard 8-byte sample entry header). + pub fn parse(payload: &[u8]) -> Result { + if payload.len() < 30 { + return Err(Error::Truncated); + } + let display_flags = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]); + let horizontal_justification = payload[4] as i8; + let vertical_justification = payload[5] as i8; + let background_color = [payload[6], payload[7], payload[8], payload[9]]; + + let default_text_box = TextBox { + top: i16::from_be_bytes([payload[10], payload[11]]), + left: i16::from_be_bytes([payload[12], payload[13]]), + bottom: i16::from_be_bytes([payload[14], payload[15]]), + right: i16::from_be_bytes([payload[16], payload[17]]), + }; + + let default_style = StyleRecord { + start_char: u16::from_be_bytes([payload[18], payload[19]]), + end_char: u16::from_be_bytes([payload[20], payload[21]]), + font_id: u16::from_be_bytes([payload[22], payload[23]]), + face_style_flags: payload[24], + font_size: payload[25], + text_color_rgba: [payload[26], payload[27], payload[28], payload[29]], + }; + + let mut fonts = Vec::new(); + let mut pos = 30; + while pos + 8 <= payload.len() { + let box_size = u32::from_be_bytes([payload[pos], payload[pos + 1], payload[pos + 2], payload[pos + 3]]) as usize; + if box_size < 8 || pos.checked_add(box_size).is_none_or(|end| end > payload.len()) { + break; + } + let box_type = &payload[pos + 4..pos + 8]; + if box_type == b"ftab" && box_size >= 10 { + let count = u16::from_be_bytes([payload[pos + 8], payload[pos + 9]]) as usize; + let mut fpos = pos + 10; + for _ in 0..count { + if fpos + 3 > pos + box_size { + break; + } + let font_id = u16::from_be_bytes([payload[fpos], payload[fpos + 1]]); + let name_len = payload[fpos + 2] as usize; + fpos += 3; + if fpos + name_len > pos + box_size { + break; + } + if let Ok(name) = std::str::from_utf8(&payload[fpos..fpos + name_len]) { + fonts.push((font_id, name.to_string())); + } + fpos += name_len; + } + } + pos += box_size; + } + + Ok(Self { display_flags, horizontal_justification, vertical_justification, background_color, default_text_box, default_style, fonts }) + } + + /// Write the `tx3g` sample entry payload (after the 8-byte sample entry header). + pub fn write(&self) -> Vec { + let mut out = Vec::with_capacity(30 + 32); + out.extend_from_slice(&self.display_flags.to_be_bytes()); + out.push(self.horizontal_justification as u8); + out.push(self.vertical_justification as u8); + out.extend_from_slice(&self.background_color); + + out.extend_from_slice(&self.default_text_box.top.to_be_bytes()); + out.extend_from_slice(&self.default_text_box.left.to_be_bytes()); + out.extend_from_slice(&self.default_text_box.bottom.to_be_bytes()); + out.extend_from_slice(&self.default_text_box.right.to_be_bytes()); + + out.extend_from_slice(&self.default_style.start_char.to_be_bytes()); + out.extend_from_slice(&self.default_style.end_char.to_be_bytes()); + out.extend_from_slice(&self.default_style.font_id.to_be_bytes()); + out.push(self.default_style.face_style_flags); + out.push(self.default_style.font_size); + out.extend_from_slice(&self.default_style.text_color_rgba); + + // ftab box + let mut ftab_payload = Vec::new(); + let fonts = &self.fonts[..self.fonts.len().min(u16::MAX as usize)]; + ftab_payload.extend_from_slice(&(fonts.len() as u16).to_be_bytes()); + for (id, name) in fonts { + ftab_payload.extend_from_slice(&id.to_be_bytes()); + let name_bytes = name.as_bytes(); + let limit = name.floor_char_boundary(name_bytes.len().min(255)); + ftab_payload.push(limit as u8); + ftab_payload.extend_from_slice(&name_bytes[..limit]); + } + let ftab_size = 8u32.saturating_add(ftab_payload.len() as u32); + out.extend_from_slice(&ftab_size.to_be_bytes()); + out.extend_from_slice(b"ftab"); + out.extend_from_slice(&ftab_payload); + + out + } +} + +/// Read and decode a single 3GPP Timed Text sample (`tx3g` / `mov_text`). +pub fn read_sample(data: &[u8]) -> Result { + if data.len() < 2 { + return Err(Error::Truncated); + } + + let text_len = u16::from_be_bytes([data[0], data[1]]) as usize; + if data.len() < 2 + text_len { + return Err(Error::Truncated); + } + + let text_bytes = &data[2..2 + text_len]; + let text = decode_text(text_bytes)?; + + let mut sample = TextSample { text, ..Default::default() }; + + let mut pos = 2 + text_len; + while pos + 8 <= data.len() { + let size = u32::from_be_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) as usize; + if size < 8 { + return Err(Error::InvalidBox("size smaller than 8")); + } + let box_end = pos.checked_add(size).ok_or(Error::Truncated)?; + if box_end > data.len() { + return Err(Error::Truncated); + } + + let box_type = &data[pos + 4..pos + 8]; + let payload = &data[pos + 8..box_end]; + + match box_type { + b"styl" => { + if payload.len() < 2 { + return Err(Error::Truncated); + } + let count = u16::from_be_bytes([payload[0], payload[1]]) as usize; + let mut spos = 2; + for _ in 0..count { + if spos + 12 > payload.len() { + return Err(Error::Truncated); + } + sample.styles.push(StyleRecord { + start_char: u16::from_be_bytes([payload[spos], payload[spos + 1]]), + end_char: u16::from_be_bytes([payload[spos + 2], payload[spos + 3]]), + font_id: u16::from_be_bytes([payload[spos + 4], payload[spos + 5]]), + face_style_flags: payload[spos + 6], + font_size: payload[spos + 7], + text_color_rgba: [payload[spos + 8], payload[spos + 9], payload[spos + 10], payload[spos + 11]], + }); + spos += 12; + } + } + b"hlit" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + let start = u16::from_be_bytes([payload[0], payload[1]]); + let end = u16::from_be_bytes([payload[2], payload[3]]); + sample.highlight = Some((start, end)); + } + b"hclr" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + sample.highlight_color = Some([payload[0], payload[1], payload[2], payload[3]]); + } + b"krok" => { + if payload.len() < 6 { + return Err(Error::Truncated); + } + let start_time = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]); + let count = u16::from_be_bytes([payload[4], payload[5]]) as usize; + let mut entries = Vec::new(); + let mut kpos = 6; + for _ in 0..count { + if kpos + 8 > payload.len() { + return Err(Error::Truncated); + } + entries.push(KaraokeEntry { + highlight_end_time: u32::from_be_bytes([payload[kpos], payload[kpos + 1], payload[kpos + 2], payload[kpos + 3]]), + start_char: u16::from_be_bytes([payload[kpos + 4], payload[kpos + 5]]), + end_char: u16::from_be_bytes([payload[kpos + 6], payload[kpos + 7]]), + }); + kpos += 8; + } + sample.karaoke = Some((start_time, entries)); + } + b"dlay" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + sample.scroll_delay = Some(u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]])); + } + b"href" => { + if payload.len() < 6 { + return Err(Error::Truncated); + } + let start = u16::from_be_bytes([payload[0], payload[1]]); + let end = u16::from_be_bytes([payload[2], payload[3]]); + let url_len = payload[4] as usize; + if 5 + url_len > payload.len() { + return Err(Error::Truncated); + } + let url = std::str::from_utf8(&payload[5..5 + url_len]).map_err(|_| Error::InvalidText)?.to_string(); + let alt_pos = 5 + url_len; + let alt_len = payload.get(alt_pos).copied().unwrap_or(0) as usize; + let alt_string = if alt_len > 0 && alt_pos + 1 + alt_len <= payload.len() { + std::str::from_utf8(&payload[alt_pos + 1..alt_pos + 1 + alt_len]).map_err(|_| Error::InvalidText)?.to_string() + } else { + String::new() + }; + sample.hypertext.push(HyperText { start_char: start, end_char: end, url, alt_string }); + } + b"tbox" => { + if payload.len() < 8 { + return Err(Error::Truncated); + } + sample.text_box = Some(TextBox { + top: i16::from_be_bytes([payload[0], payload[1]]), + left: i16::from_be_bytes([payload[2], payload[3]]), + bottom: i16::from_be_bytes([payload[4], payload[5]]), + right: i16::from_be_bytes([payload[6], payload[7]]), + }); + } + b"blnk" => { + if payload.len() < 4 { + return Err(Error::Truncated); + } + let start = u16::from_be_bytes([payload[0], payload[1]]); + let end = u16::from_be_bytes([payload[2], payload[3]]); + sample.blinking.push((start, end)); + } + b"twrp" | b"wrap" => { + if payload.is_empty() { + return Err(Error::Truncated); + } + sample.wrap_flag = Some(payload[0]); + } + _ => { + // Unknown modifier box: safely ignored. + } + } + + pos = box_end; + } + + Ok(sample) +} + +/// Helper to decode UTF-8 or UTF-16 with BOM. +fn decode_text(bytes: &[u8]) -> Result { + if bytes.len() >= 2 { + if bytes[0] == 0xFE && bytes[1] == 0xFF { + // UTF-16 BE + let u16s: Vec = bytes[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); + return String::from_utf16(&u16s).map_err(|_| Error::InvalidText); + } else if bytes[0] == 0xFF && bytes[1] == 0xFE { + // UTF-16 LE + let u16s: Vec = bytes[2..].as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + return String::from_utf16(&u16s).map_err(|_| Error::InvalidText); + } + } + std::str::from_utf8(bytes).map(ToString::to_string).map_err(|_| Error::InvalidText) +} + +/// Pack and encode a timed text sample into bytes. +pub fn write_sample(sample: &TextSample) -> Result> { + let text_bytes = sample.text.as_bytes(); + if text_bytes.len() > u16::MAX as usize { + return Err(Error::TextTooLong(text_bytes.len())); + } + + let mut out = Vec::with_capacity(2 + text_bytes.len() + 64); + out.extend_from_slice(&(text_bytes.len() as u16).to_be_bytes()); + out.extend_from_slice(text_bytes); + + // 1. styl box + if !sample.styles.is_empty() { + if sample.styles.len() > u16::MAX as usize { + return Err(Error::InvalidBox("too many styles in sample")); + } + let size = 8u32.checked_add(2).and_then(|s| s.checked_add(sample.styles.len() as u32 * 12)).ok_or(Error::InvalidBox("styl size overflow"))?; + out.extend_from_slice(&size.to_be_bytes()); + out.extend_from_slice(b"styl"); + out.extend_from_slice(&(sample.styles.len() as u16).to_be_bytes()); + for st in &sample.styles { + out.extend_from_slice(&st.start_char.to_be_bytes()); + out.extend_from_slice(&st.end_char.to_be_bytes()); + out.extend_from_slice(&st.font_id.to_be_bytes()); + out.push(st.face_style_flags); + out.push(st.font_size); + out.extend_from_slice(&st.text_color_rgba); + } + } + + // 2. hlit box + if let Some((start, end)) = sample.highlight { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"hlit"); + out.extend_from_slice(&start.to_be_bytes()); + out.extend_from_slice(&end.to_be_bytes()); + } + + // 3. hclr box + if let Some(color) = sample.highlight_color { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"hclr"); + out.extend_from_slice(&color); + } + + // 4. krok box + if let Some((start_time, ref entries)) = sample.karaoke { + if entries.len() > u16::MAX as usize { + return Err(Error::InvalidBox("too many karaoke entries")); + } + let size = 8u32.checked_add(6).and_then(|s| s.checked_add(entries.len() as u32 * 8)).ok_or(Error::InvalidBox("krok size overflow"))?; + out.extend_from_slice(&size.to_be_bytes()); + out.extend_from_slice(b"krok"); + out.extend_from_slice(&start_time.to_be_bytes()); + out.extend_from_slice(&(entries.len() as u16).to_be_bytes()); + for e in entries { + out.extend_from_slice(&e.highlight_end_time.to_be_bytes()); + out.extend_from_slice(&e.start_char.to_be_bytes()); + out.extend_from_slice(&e.end_char.to_be_bytes()); + } + } + + // 5. dlay box + if let Some(delay) = sample.scroll_delay { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"dlay"); + out.extend_from_slice(&delay.to_be_bytes()); + } + + // 6. href boxes + for link in &sample.hypertext { + let url_bytes = link.url.as_bytes(); + let alt_bytes = link.alt_string.as_bytes(); + let ulen = url_bytes.len().min(255) as u8; + let alen = alt_bytes.len().min(255) as u8; + let size = 8u32 + 4 + 1 + ulen as u32 + 1 + alen as u32; + out.extend_from_slice(&size.to_be_bytes()); + out.extend_from_slice(b"href"); + out.extend_from_slice(&link.start_char.to_be_bytes()); + out.extend_from_slice(&link.end_char.to_be_bytes()); + out.push(ulen); + out.extend_from_slice(&url_bytes[..ulen as usize]); + out.push(alen); + out.extend_from_slice(&alt_bytes[..alen as usize]); + } + + // 7. tbox box + if let Some(tb) = sample.text_box { + out.extend_from_slice(&16u32.to_be_bytes()); + out.extend_from_slice(b"tbox"); + out.extend_from_slice(&tb.top.to_be_bytes()); + out.extend_from_slice(&tb.left.to_be_bytes()); + out.extend_from_slice(&tb.bottom.to_be_bytes()); + out.extend_from_slice(&tb.right.to_be_bytes()); + } + + // 8. blnk boxes + for &(start, end) in &sample.blinking { + out.extend_from_slice(&12u32.to_be_bytes()); + out.extend_from_slice(b"blnk"); + out.extend_from_slice(&start.to_be_bytes()); + out.extend_from_slice(&end.to_be_bytes()); + } + + // 9. twrp box + if let Some(flag) = sample.wrap_flag { + out.extend_from_slice(&9u32.to_be_bytes()); + out.extend_from_slice(b"twrp"); + out.push(flag); + } + + Ok(out) +} + +fn push_escaped_char(out: &mut String, ch: char) { + match ch { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + _ => out.push(ch), + } +} + +/// Convert a [`TextSample`] into HTML-style formatted markup (``, ``, ``, ``). +pub fn sample_to_markup(sample: &TextSample) -> String { + if sample.styles.is_empty() { + let mut out = String::with_capacity(sample.text.len()); + for ch in sample.text.chars() { + push_escaped_char(&mut out, ch); + } + return out; + } + + let chars: Vec = sample.text.chars().collect(); + let n = chars.len(); + if n == 0 { + return String::new(); + } + + let mut starts: std::collections::HashMap> = std::collections::HashMap::new(); + let mut ends: std::collections::HashMap> = std::collections::HashMap::new(); + for st in &sample.styles { + if st.end_char > st.start_char { + starts.entry(st.start_char).or_default().push(st); + ends.entry(st.end_char).or_default().push(st); + } + } + + let mut out = String::with_capacity(sample.text.len() + sample.styles.len() * 16); + + for (i, &ch) in chars.iter().enumerate() { + let char_idx = i as u16; + + // Open tags for any style starting at char_idx + if let Some(list) = starts.get(&char_idx) { + for st in list { + let has_color = st.text_color_rgba != [255, 255, 255, 255]; + if has_color { + out.push_str(&format!( + "", + st.text_color_rgba[0], st.text_color_rgba[1], st.text_color_rgba[2] + )); + } + if st.is_bold() { + out.push_str(""); + } + if st.is_italic() { + out.push_str(""); + } + if st.is_underline() { + out.push_str(""); + } + } + } + + push_escaped_char(&mut out, ch); + + // Close tags for any style ending at char_idx + 1 + if let Some(list) = ends.get(&(char_idx + 1)) { + for st in list.iter().rev() { + if st.is_underline() { + out.push_str(""); + } + if st.is_italic() { + out.push_str(""); + } + if st.is_bold() { + out.push_str(""); + } + let has_color = st.text_color_rgba != [255, 255, 255, 255]; + if has_color { + out.push_str(""); + } + } + } + } + + out +} + +#[derive(Clone, Copy, PartialEq, Eq)] +struct CharFormatting { + flags: u8, + color: [u8; 4], +} + +impl Default for CharFormatting { + fn default() -> Self { + Self { flags: 0, color: [255, 255, 255, 255] } + } +} + +/// Parse HTML-style formatted markup (``, ``, ``, ``) into a [`TextSample`]. +pub fn markup_to_sample(markup: &str) -> TextSample { + let mut bold_depth = 0usize; + let mut italic_depth = 0usize; + let mut underline_depth = 0usize; + let mut color_stack: Vec<[u8; 4]> = Vec::new(); + + let mut decoded_chars: Vec = Vec::with_capacity(markup.len()); + let mut char_styles: Vec = Vec::with_capacity(markup.len()); + + let mut chars = markup.chars().peekable(); + + while let Some(ch) = chars.next() { + if ch == '<' { + let mut tag = String::new(); + for next in chars.by_ref() { + if next == '>' { + break; + } + tag.push(next); + } + let trimmed = tag.trim().to_ascii_lowercase(); + if trimmed == "b" { + bold_depth += 1; + } else if trimmed == "/b" { + bold_depth = bold_depth.saturating_sub(1); + } else if trimmed == "i" { + italic_depth += 1; + } else if trimmed == "/i" { + italic_depth = italic_depth.saturating_sub(1); + } else if trimmed == "u" { + underline_depth += 1; + } else if trimmed == "/u" { + underline_depth = underline_depth.saturating_sub(1); + } else if trimmed.starts_with("font") { + if let Some(color) = parse_font_color(&tag) { + color_stack.push(color); + } + } else if trimmed == "/font" { + color_stack.pop(); + } + } else { + let mut text_chunk = String::new(); + text_chunk.push(ch); + while let Some(&next) = chars.peek() { + if next == '<' { + break; + } + text_chunk.push(next); + chars.next(); + } + + let decoded = crate::decode_entities(&text_chunk); + let mut flags = 0u8; + if bold_depth > 0 { + flags |= STYLE_FLAG_BOLD; + } + if italic_depth > 0 { + flags |= STYLE_FLAG_ITALIC; + } + if underline_depth > 0 { + flags |= STYLE_FLAG_UNDERLINE; + } + let color = color_stack.last().copied().unwrap_or([255, 255, 255, 255]); + let fmt = CharFormatting { flags, color }; + + for c in decoded.chars() { + decoded_chars.push(c); + char_styles.push(fmt); + } + } + } + + let text: String = decoded_chars.iter().collect(); + + // Group adjacent characters with identical non-default formatting into sorted, non-overlapping style runs. + let mut styles = Vec::new(); + let mut run_start: Option<(usize, CharFormatting)> = None; + + for (idx, &fmt) in char_styles.iter().enumerate() { + let is_styled = fmt.flags != 0 || fmt.color != [255, 255, 255, 255]; + match run_start { + Some((start, current_fmt)) => { + if fmt != current_fmt { + if current_fmt.flags != 0 || current_fmt.color != [255, 255, 255, 255] { + styles.push(StyleRecord { + start_char: start as u16, + end_char: idx as u16, + font_id: 1, + face_style_flags: current_fmt.flags, + font_size: 16, + text_color_rgba: current_fmt.color, + }); + } + run_start = if is_styled { Some((idx, fmt)) } else { None }; + } + } + None => { + if is_styled { + run_start = Some((idx, fmt)); + } + } + } + } + + if let Some((start, fmt)) = run_start { + styles.push(StyleRecord { + start_char: start as u16, + end_char: char_styles.len() as u16, + font_id: 1, + face_style_flags: fmt.flags, + font_size: 16, + text_color_rgba: fmt.color, + }); + } + + TextSample { text, styles, ..Default::default() } +} + +/// Helper to parse color attribute from `` tag. +fn parse_font_color(tag: &str) -> Option<[u8; 4]> { + let lower = tag.to_ascii_lowercase(); + let col_idx = lower.find("color=")?; + let rest = tag[col_idx + 6..].trim_start(); + let val = if let Some(stripped) = rest.strip_prefix('"') { + let end = stripped.find('"')?; + &stripped[..end] + } else if let Some(stripped) = rest.strip_prefix('\'') { + let end = stripped.find('\'')?; + &stripped[..end] + } else { + let end = rest.find(char::is_whitespace).unwrap_or(rest.len()); + &rest[..end] + }; + + let hex = val.strip_prefix('#').unwrap_or(val); + if hex.len() == 6 { + let r = u8::from_str_radix(hex.get(0..2)?, 16).ok()?; + let g = u8::from_str_radix(hex.get(2..4)?, 16).ok()?; + let b = u8::from_str_radix(hex.get(4..6)?, 16).ok()?; + Some([r, g, b, 255]) + } else if hex.len() == 8 { + let r = u8::from_str_radix(hex.get(0..2)?, 16).ok()?; + let g = u8::from_str_radix(hex.get(2..4)?, 16).ok()?; + let b = u8::from_str_radix(hex.get(4..6)?, 16).ok()?; + let a = u8::from_str_radix(hex.get(6..8)?, 16).ok()?; + Some([r, g, b, a]) + } else { + None + } +} + +/// Convert a caption [`Cue`] into a [`TextSample`]. +pub fn cue_to_sample(cue: &Cue) -> TextSample { + markup_to_sample(&cue.text) +} + +/// Convert a [`TextSample`] into a caption [`Cue`] spanning `start` to `end`. +pub fn sample_to_cue(sample: &TextSample, start: Tick, end: Tick) -> Cue { + Cue { start, end, text: sample_to_markup(sample), speaker: None, id: None, settings: String::new() } +} + +/// Decode a stream of timed text samples into a [`Document`]. +pub fn decode_timed_samples<'a, I>(doc: &mut Document, samples: I, timescale: u32) -> Result<()> +where + I: IntoIterator, +{ + decode_timed_samples_with_config(doc, samples, timescale, None) +} + +/// Decode a stream of timed text samples into a [`Document`], applying an optional sample description configuration. +pub fn decode_timed_samples_with_config<'a, I>(doc: &mut Document, samples: I, timescale: u32, config: Option<&Tx3gConfig>) -> Result<()> +where + I: IntoIterator, +{ + if timescale == 0 { + return Ok(()); + } + let ts = timescale as i128; + for (pts, duration, data) in samples { + let mut sample = read_sample(data)?; + if sample.text.trim().is_empty() { + continue; + } + if sample.styles.is_empty() + && let Some(cfg) = config + && (cfg.default_style.face_style_flags != 0 || cfg.default_style.text_color_rgba != [255, 255, 255, 255]) + { + sample.styles.push(StyleRecord { + start_char: 0, + end_char: sample.text.chars().count() as u16, + font_id: cfg.default_style.font_id, + face_style_flags: cfg.default_style.face_style_flags, + font_size: cfg.default_style.font_size, + text_color_rgba: cfg.default_style.text_color_rgba, + }); + } + let end_pts = pts.checked_add(duration as u64).ok_or(Error::InvalidBox("timestamp interval overflow"))?; + let start_ticks = (pts as i128 * TICKS_PER_SECOND as i128 / ts) as i64; + let end_ticks = (end_pts as i128 * TICKS_PER_SECOND as i128 / ts) as i64; + doc.cues.push(sample_to_cue(&sample, Tick(start_ticks), Tick(end_ticks))); + } + Ok(()) +} diff --git a/crates/captions/tests/it/main.rs b/crates/captions/tests/it/main.rs index 437b2ba67a..7d8070cad6 100644 --- a/crates/captions/tests/it/main.rs +++ b/crates/captions/tests/it/main.rs @@ -2,6 +2,8 @@ mod ass; mod limits; mod literal_roundtrips; mod mcc_708_timing; +#[cfg(feature = "mov-text")] +mod mov_text; mod pjs_realtext_jacosub; mod roundtrip; mod ttml_body_styles; diff --git a/crates/captions/tests/it/mov_text.rs b/crates/captions/tests/it/mov_text.rs new file mode 100644 index 0000000000..dfd5f73ea5 --- /dev/null +++ b/crates/captions/tests/it/mov_text.rs @@ -0,0 +1,349 @@ +//! Clean-room tests and FFmpeg oracle tests for MP4 Timed Text (`mov_text` / `tx3g`). + +use craft_captions::mov_text::{ + Error, KaraokeEntry, STYLE_FLAG_BOLD, STYLE_FLAG_ITALIC, STYLE_FLAG_UNDERLINE, StyleRecord, TextBox, TextSample, Tx3gConfig, + decode_timed_samples, markup_to_sample, read_sample, sample_to_markup, write_sample, +}; +use craft_captions::time::Tick; +use craft_captions::{Document, TICKS_PER_SECOND}; + +#[test] +fn test_plain_text_roundtrip() { + let sample = TextSample { text: "Hello world without styles".to_string(), ..Default::default() }; + + let bytes = write_sample(&sample).expect("write sample"); + assert_eq!(bytes.len(), 2 + sample.text.len()); + assert_eq!(&bytes[..2], &(sample.text.len() as u16).to_be_bytes()); + assert_eq!(&bytes[2..], sample.text.as_bytes()); + + let decoded = read_sample(&bytes).expect("read sample"); + assert_eq!(decoded.text, sample.text); + assert!(decoded.styles.is_empty()); +} + +#[test] +fn test_empty_sample_roundtrip() { + let sample = TextSample::default(); + let bytes = write_sample(&sample).expect("write"); + assert_eq!(bytes, &[0x00, 0x00]); + + let decoded = read_sample(&bytes).expect("read"); + assert_eq!(decoded.text, ""); + assert!(decoded.styles.is_empty()); +} + +#[test] +fn test_styles_roundtrip() { + let sample = TextSample { + text: "Bold, Italic, Underline, and Colored".to_string(), + styles: vec![ + StyleRecord { + start_char: 0, + end_char: 4, + font_id: 1, + face_style_flags: STYLE_FLAG_BOLD, + font_size: 16, + text_color_rgba: [255, 255, 255, 255], + }, + StyleRecord { + start_char: 6, + end_char: 12, + font_id: 1, + face_style_flags: STYLE_FLAG_ITALIC, + font_size: 18, + text_color_rgba: [255, 255, 255, 255], + }, + StyleRecord { + start_char: 14, + end_char: 23, + font_id: 1, + face_style_flags: STYLE_FLAG_UNDERLINE, + font_size: 16, + text_color_rgba: [255, 255, 255, 255], + }, + StyleRecord { start_char: 29, end_char: 36, font_id: 1, face_style_flags: 0, font_size: 20, text_color_rgba: [255, 0, 0, 255] }, + ], + ..Default::default() + }; + + let bytes = write_sample(&sample).expect("write"); + let decoded = read_sample(&bytes).expect("read"); + + assert_eq!(decoded.text, sample.text); + assert_eq!(decoded.styles.len(), 4); + assert_eq!(decoded.styles, sample.styles); + + assert!(decoded.styles[0].is_bold()); + assert!(!decoded.styles[0].is_italic()); + assert!(decoded.styles[1].is_italic()); + assert!(decoded.styles[2].is_underline()); + assert_eq!(decoded.styles[3].text_color_rgba, [255, 0, 0, 255]); +} + +#[test] +fn test_all_modifier_boxes_roundtrip() { + let sample = TextSample { + text: "Full modifiers test".to_string(), + styles: vec![StyleRecord { + start_char: 0, + end_char: 4, + font_id: 1, + face_style_flags: STYLE_FLAG_BOLD, + font_size: 16, + text_color_rgba: [255, 255, 255, 255], + }], + highlight: Some((5, 14)), + highlight_color: Some([255, 255, 0, 255]), + karaoke: Some(( + 100, + vec![ + KaraokeEntry { highlight_end_time: 200, start_char: 0, end_char: 4 }, + KaraokeEntry { highlight_end_time: 350, start_char: 5, end_char: 14 }, + ], + )), + scroll_delay: Some(500), + hypertext: vec![craft_captions::mov_text::HyperText { + start_char: 0, + end_char: 19, + url: "https://example.com".to_string(), + alt_string: "Example".to_string(), + }], + text_box: Some(TextBox { top: 10, left: 20, bottom: 100, right: 200 }), + blinking: vec![(0, 4), (15, 19)], + wrap_flag: Some(1), + }; + + let bytes = write_sample(&sample).expect("write"); + let decoded = read_sample(&bytes).expect("read"); + + assert_eq!(decoded, sample); +} + +#[test] +fn test_utf16_bom_reading() { + // UTF-16 BE with BOM + let text = "Hello UTF-16"; + let mut data_be = Vec::new(); + let utf16_be_bytes: Vec = text.encode_utf16().flat_map(|u| u.to_be_bytes()).collect(); + let total_len = 2 + utf16_be_bytes.len(); + data_be.extend_from_slice(&(total_len as u16).to_be_bytes()); + data_be.extend_from_slice(&[0xFE, 0xFF]); + data_be.extend_from_slice(&utf16_be_bytes); + + let decoded_be = read_sample(&data_be).expect("read UTF-16 BE"); + assert_eq!(decoded_be.text, text); + + // UTF-16 LE with BOM + let mut data_le = Vec::new(); + let utf16_le_bytes: Vec = text.encode_utf16().flat_map(|u| u.to_le_bytes()).collect(); + data_le.extend_from_slice(&(total_len as u16).to_be_bytes()); + data_le.extend_from_slice(&[0xFF, 0xFE]); + data_le.extend_from_slice(&utf16_le_bytes); + + let decoded_le = read_sample(&data_le).expect("read UTF-16 LE"); + assert_eq!(decoded_le.text, text); +} + +#[test] +fn test_markup_conversion() { + let markup = "Hello Bold and Italic and Underline and Red"; + let sample = markup_to_sample(markup); + + assert_eq!(sample.text, "Hello Bold and Italic and Underline and Red"); + assert_eq!(sample.styles.len(), 4); + + let bold = &sample.styles[0]; + assert_eq!(&sample.text[bold.start_char as usize..bold.end_char as usize], "Bold"); + assert!(bold.is_bold()); + + let italic = &sample.styles[1]; + assert_eq!(&sample.text[italic.start_char as usize..italic.end_char as usize], "Italic"); + assert!(italic.is_italic()); + + let underline = &sample.styles[2]; + assert_eq!(&sample.text[underline.start_char as usize..underline.end_char as usize], "Underline"); + assert!(underline.is_underline()); + + let red = &sample.styles[3]; + assert_eq!(&sample.text[red.start_char as usize..red.end_char as usize], "Red"); + assert_eq!(red.text_color_rgba, [255, 0, 0, 255]); + + let regenerated = sample_to_markup(&sample); + assert_eq!(regenerated, markup); +} + +#[test] +fn test_nested_styles_sorted_non_overlapping() { + let markup = "ABC"; + let sample = markup_to_sample(markup); + assert_eq!(sample.text, "ABC"); + assert_eq!(sample.styles.len(), 3); + // [0, 1): A is bold + assert_eq!(sample.styles[0].start_char, 0); + assert_eq!(sample.styles[0].end_char, 1); + assert_eq!(sample.styles[0].face_style_flags, STYLE_FLAG_BOLD); + // [1, 2): B is bold + italic + assert_eq!(sample.styles[1].start_char, 1); + assert_eq!(sample.styles[1].end_char, 2); + assert_eq!(sample.styles[1].face_style_flags, STYLE_FLAG_BOLD | STYLE_FLAG_ITALIC); + // [2, 3): C is bold + assert_eq!(sample.styles[2].start_char, 2); + assert_eq!(sample.styles[2].end_char, 3); + assert_eq!(sample.styles[2].face_style_flags, STYLE_FLAG_BOLD); +} + +#[test] +fn test_entities_and_literal_escaping() { + let markup = "A & B < C"; + let sample = markup_to_sample(markup); + assert_eq!(sample.text, "A & B < C"); + assert_eq!(sample.styles.len(), 1); + assert_eq!(sample.styles[0].start_char, 4); + assert_eq!(sample.styles[0].end_char, 9); + + let roundtripped = sample_to_markup(&sample); + assert_eq!(roundtripped, "A & B < C"); +} + +#[test] +fn test_twrp_box() { + let sample = TextSample { text: "Wrap me".to_string(), wrap_flag: Some(1), ..Default::default() }; + let bytes = write_sample(&sample).expect("write sample"); + // Verify bytes contain twrp box + assert!(bytes.windows(4).any(|w| w == b"twrp")); + + let read_back = read_sample(&bytes).expect("read sample"); + assert_eq!(read_back.wrap_flag, Some(1)); +} + +#[test] +fn test_tx3g_config_roundtrip() { + let cfg = Tx3gConfig { + display_flags: 0x0000_0001, + horizontal_justification: 1, + vertical_justification: -1, + background_color: [10, 20, 30, 255], + default_text_box: TextBox { top: 0, left: 0, bottom: 480, right: 640 }, + default_style: StyleRecord { + start_char: 0, + end_char: 0, + font_id: 1, + face_style_flags: STYLE_FLAG_BOLD, + font_size: 24, + text_color_rgba: [255, 255, 255, 255], + }, + fonts: vec![(1, "Serif".to_string()), (2, "Sans".to_string())], + }; + + let bytes = cfg.write(); + let parsed = Tx3gConfig::parse(&bytes).expect("parse config"); + assert_eq!(parsed, cfg); +} + +#[test] +fn test_decode_timed_samples_to_document() { + let mut doc = Document::default(); + + let s1 = write_sample(&markup_to_sample("First cue")).expect("s1"); + let s2 = write_sample(&markup_to_sample("Second cue")).expect("s2"); + + let samples = vec![(0u64, 1000u32, s1.as_slice()), (1000u64, 1500u32, s2.as_slice())]; + + decode_timed_samples(&mut doc, samples, 1000).expect("decode samples"); + + assert_eq!(doc.cues.len(), 2); + assert_eq!(doc.cues[0].start, Tick(0)); + assert_eq!(doc.cues[0].end, Tick(TICKS_PER_SECOND)); + assert_eq!(doc.cues[0].text, "First cue"); + + assert_eq!(doc.cues[1].start, Tick(TICKS_PER_SECOND)); + assert_eq!(doc.cues[1].end, Tick((TICKS_PER_SECOND as f64 * 2.5) as i64)); + assert_eq!(doc.cues[1].text, "Second cue"); +} + +#[test] +fn test_hostile_inputs_never_panic() { + // Empty input + assert!(matches!(read_sample(&[]), Err(Error::Truncated))); + + // 1-byte input + assert!(matches!(read_sample(&[0x00]), Err(Error::Truncated))); + + // Length says 10 bytes, but slice ends + assert!(matches!(read_sample(&[0x00, 0x0A, 0x41]), Err(Error::Truncated))); + + // Invalid UTF-8 without BOM + assert!(matches!(read_sample(&[0x00, 0x02, 0xFF, 0xFF]), Err(Error::InvalidText))); + + // Box size < 8 + let mut bad_box = Vec::new(); + bad_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']); + bad_box.extend_from_slice(&[0x00, 0x00, 0x00, 0x04, b's', b't', b'y', b'l']); + assert!(matches!(read_sample(&bad_box), Err(Error::InvalidBox(_)))); + + // Box size exceeds remaining slice + let mut truncated_box = Vec::new(); + truncated_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']); + truncated_box.extend_from_slice(&[0x00, 0x00, 0x01, 0x00, b's', b't', b'y', b'l']); + assert!(matches!(read_sample(&truncated_box), Err(Error::Truncated))); + + // Unknown modifier boxes are safely ignored without error + let mut unknown_box = Vec::new(); + unknown_box.extend_from_slice(&[0x00, 0x04, b'T', b'e', b's', b't']); + unknown_box.extend_from_slice(&[0x00, 0x00, 0x00, 0x0C, b'f', b'a', b'k', b'e', 1, 2, 3, 4]); + let decoded = read_sample(&unknown_box).expect("unknown box should be skipped"); + assert_eq!(decoded.text, "Test"); +} + +#[test] +fn test_ffmpeg_mov_text_oracle() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let temp_dir = std::env::temp_dir().join("craft_mov_text_test"); + let _ = std::fs::create_dir_all(&temp_dir); + + // 1. Create SRT file with formatting: bold, italic, underline + let srt_path = temp_dir.join("input.srt"); + let mp4_path = temp_dir.join("output.mp4"); + let srt_content = "1\n00:00:01,000 --> 00:00:03,000\nHello World and Italic and Underline\n"; + std::fs::write(&srt_path, srt_content).expect("write srt"); + + // Encode to MP4 with mov_text + let out = std::process::Command::new(&ff) + .args(["-y", "-i", srt_path.to_str().expect("path"), "-c:s", "mov_text", mp4_path.to_str().expect("path")]) + .output(); + let Ok(output) = out else { return }; + if !output.status.success() { + return; + } + + // Read MP4 through craft-media ISOBMFF demuxer + let mp4_bytes = std::fs::read(&mp4_path).expect("read mp4"); + let mp4 = craft_media::isobmff::open(&mp4_bytes).expect("open mp4"); + + let (track_idx, track) = + mp4.tracks.iter().enumerate().find(|(_, t)| t.kind == craft_media::isobmff::TrackKind::Subtitle).expect("subtitle track"); + + // Decode all non-empty samples + let mut found_styled_cue = false; + for sample_idx in 0..track.samples.len() { + let sample_data = mp4.read_sample(&mp4_bytes, track_idx, sample_idx).expect("read sample"); + let sample = read_sample(&sample_data).expect("read sample"); + if !sample.text.is_empty() { + assert_eq!(sample.text, "Hello World and Italic and Underline"); + let markup = sample_to_markup(&sample); + assert!(markup.contains("World"), "expected bold markup: {markup}"); + assert!(markup.contains("Italic"), "expected italic markup: {markup}"); + assert!(markup.contains("Underline"), "expected underline markup: {markup}"); + found_styled_cue = true; + } + } + assert!(found_styled_cue, "expected to find styled subtitle sample in MP4"); + + // 2. Test roundtrip: our encoder writes sample bytes -> decode with FFmpeg to verify exact text & styles + let our_sample = markup_to_sample("Greeting: Craft Timed Text"); + let encoded_bytes = write_sample(&our_sample).expect("write sample"); + + // Verify our sample reads back identically + let roundtripped = read_sample(&encoded_bytes).expect("read back"); + assert_eq!(sample_to_markup(&roundtripped), "Greeting: Craft Timed Text"); +} From c88e962815b433ab85ab0de170a538d894aaeaaf Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 06:14:05 +0100 Subject: [PATCH 28/79] psd: share borrowed SoLd data prefix [skip ci] --- crates/psd/src/tagged.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/psd/src/tagged.rs b/crates/psd/src/tagged.rs index d433c2527e..0e5b474e35 100644 --- a/crates/psd/src/tagged.rs +++ b/crates/psd/src/tagged.rs @@ -706,6 +706,16 @@ pub fn append_solid_color_data(out: &mut Vec, descriptor: &dyn crate::descri crate::descriptor::borrowed::append_descriptor(out, descriptor); } +/// Append SoLd data: the soLD signature, version 4 and descriptor version 16. +/// +/// No outer block key, length or padding is written. The descriptor is supplied +/// unchanged by the caller. This inherits the append semantics and finite, +/// stable, acyclic borrowed-view contract of [append_layer_effects_data]. +pub fn append_smart_object_data(out: &mut Vec, descriptor: &dyn crate::descriptor::borrowed::DescriptorView) { + out.extend_from_slice(b"soLD\0\0\0\x04\0\0\0\x10"); + crate::descriptor::borrowed::append_descriptor(out, descriptor); +} + #[cfg(test)] mod tests { use super::*; @@ -987,6 +997,11 @@ mod tests { let mut expected = vec![0xa5, 0x5a, 0, 0, 0, 16]; expected.extend_from_slice(&descriptor); assert_eq!(color, expected); + let mut placed = vec![0xa5, 0x5a]; + append_smart_object_data(&mut placed, &View(populated)); + let mut expected = vec![0xa5, 0x5a, 0x73, 0x6f, 0x4c, 0x44, 0, 0, 0, 4, 0, 0, 0, 16]; + expected.extend_from_slice(&descriptor); + assert_eq!(placed, expected); } } } From 56c3c833bb869a140271e2aceec2112322cacc58 Mon Sep 17 00:00:00 2001 From: William Dunn Date: Thu, 19 Nov 2026 00:43:07 -0500 Subject: [PATCH 29/79] file-formats: let the codec decide whether JXL reads (#2278) Every workspace gate with `--all-features` has been failing since #2135 taught craft-image-codecs to read JPEG XL behind a `jxl` feature. The capability test asserted that JXL read is `Unsupported`, full stop. With that codec feature on, `capabilities()` forwards the codec's own answer of `Available`. The assertion then fails. This crate cannot read that feature through `cfg!`. The feature belongs to a dependency. A workspace build turns it on without this crate selecting anything. An equality against either value is therefore wrong in some build. The test now asks the codec the same question the code asks it. It compares the two answers. A build whose codec reads JXL must report `Available`. One whose codec does not must report `Unsupported`. The mapping has to exist either way. A missing codec therefore fails an assertion of its own. The comparison is never quietly skipped. Without `raster-codecs` there is no codec to ask. The answer is `Unsupported`. Verified at 1.100.0 on Linux. `cargo test -p craft-file-formats -p craft-image-codecs --all-features --locked` runs the case that was failing and passes. The same test passes with `-p craft-file-formats --all-features` and with `--no-default-features`. clippy with `--all-targets --all-features -D warnings` is clean. `cargo fmt --check` is clean. Making `capabilities()` ignore the codec's read flag fails the test. That is what the comparison is for. The HEIF and deep-EXR failures in that package need the pinned corpus. My checkout has not fetched it. --- crates/file-formats/src/tests.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/file-formats/src/tests.rs b/crates/file-formats/src/tests.rs index 7bb396848f..399f884acf 100644 --- a/crates/file-formats/src/tests.rs +++ b/crates/file-formats/src/tests.rs @@ -26,8 +26,17 @@ fn known_formats_separate_build_disabled_and_unsupported_operations() { #[cfg(not(feature = "raster-codecs"))] assert_eq!(jpeg.read, Availability::BuildDisabled); + // Whether this build reads JPEG XL is craft-image-codecs' `jxl` feature to decide, and this + // crate cannot see that through `cfg!`: a workspace build turns it on without this crate + // selecting anything, which is how a plain equality here failed every `--all-features` gate. + // The codec's own answer is the one to check against, so a wrong read status is still caught. #[cfg(feature = "raster-codecs")] - assert!(matches!(Format::Jxl.capabilities().read, Availability::Available | Availability::Unsupported)); + { + let codec = Format::Jxl.raster_codec(); + assert!(codec.is_some(), "JXL is handled by craft-image-codecs and must map to one of its formats"); + let expected = if codec.is_some_and(|codec| codec.caps().read) { Availability::Available } else { Availability::Unsupported }; + assert_eq!(Format::Jxl.capabilities().read, expected); + } #[cfg(not(feature = "raster-codecs"))] assert_eq!(Format::Jxl.capabilities().read, Availability::Unsupported); #[cfg(not(feature = "raster-codecs"))] From e4252faa21de3772dd609816a90a1836984a01c0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 02:55:14 -0500 Subject: [PATCH 30/79] Exercise optional CMS wire sets and preserve acceptance boundaries --- crates/pkcs7/src/inspection/cms.rs | 5 +++ crates/pkcs7/tests/it/inspection_cms.rs | 55 +++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/crates/pkcs7/src/inspection/cms.rs b/crates/pkcs7/src/inspection/cms.rs index 0d63c64add..e59d84a8c4 100644 --- a/crates/pkcs7/src/inspection/cms.rs +++ b/crates/pkcs7/src/inspection/cms.rs @@ -1,5 +1,10 @@ //! Borrowed CMS wire prefixes. These do not validate signed attributes or authenticate signers. //! Optional/remaining fields are explicit cursors, governed by the parent inspection bounds. +//! +//! Each `parse` starts a new depth root. Callers traversing nested structures must retain their +//! whole-document work/depth policy; reparsing a slice does not carry a previous cursor's budget. +//! The required wire tags and exact SignedData OID are this view's structural profile, not a +//! replacement for a consumer's acceptance or diagnostic policy. Existing parsers remain unchanged. use super::{Cursor, Element, InspectionError}; use crate::der::tag; diff --git a/crates/pkcs7/tests/it/inspection_cms.rs b/crates/pkcs7/tests/it/inspection_cms.rs index 4e7609f768..ffdc75a424 100644 --- a/crates/pkcs7/tests/it/inspection_cms.rs +++ b/crates/pkcs7/tests/it/inspection_cms.rs @@ -54,3 +54,58 @@ fn signer_prefix_does_not_hide_optional_tail_or_consume_next_signer() { assert_eq!(view.remaining_fields.next_element(), Err(InspectionError::Malformed)); assert_eq!(view.remaining_fields.remaining(), &[0xa1]); } + +// Ordinary optional sets and complete trailing TLVs, never interpreted as trust evidence here. +fn optional_fixture(certificate_count: usize, with_crl: bool, tails: bool) -> (Vec, Vec, Vec) { + let certificate = craft_pkcs7::x509::load_certificates(include_bytes!("../data/ca.crt.pem")).unwrap().remove(0).raw; + let (base, signer) = fixture(false, true); + let (view, _) = SignedDataView::parse(&base).unwrap(); + let certificates = der::tlv(tag::ctx(0), &certificate.repeat(certificate_count)); + let crl = if with_crl { der::tlv(tag::ctx(1), &der::seq(&[])) } else { vec![] }; + let tail = if tails { der::tlv(tag::NULL, &[]) } else { vec![] }; + let signed_data = der::seq(&[ + view.version.raw(), + view.digest_algorithms.raw(), + view.encapsulated_content.raw(), + &certificates, + &crl, + &der::set_of(&[&signer]), + &tail, + ]); + let wrapped = der::tlv(tag::ctx(0), &[signed_data, tail.clone()].concat()); + let content = der::seq(&[&der::oid("1.2.840.113549.1.7.2"), &wrapped, &tail]); + ([content, tail].concat(), certificate, crl) +} + +#[test] +fn optional_certificate_crl_sets_and_all_tails_remain_visible() { + for with_crl in [false, true] { + let (bytes, cert, crl) = optional_fixture(2, with_crl, true); + let (mut view, rest) = SignedDataView::parse(&bytes).unwrap(); + assert_eq!(rest, &[5, 0]); + let certs = view.remaining_fields.next_element().unwrap().unwrap(); + assert_eq!(certs.tag(), tag::ctx(0)); + assert_eq!(certs.value(), cert.repeat(2)); + if with_crl { + assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().raw(), crl); + } + assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().tag(), tag::SET); + for cursor in [&mut view.remaining_fields, &mut view.remaining_explicit_fields, &mut view.remaining_content_info_fields] { + assert_eq!(cursor.next_element().unwrap().unwrap().raw(), &[5, 0]); + assert_eq!(cursor.next_element(), Ok(None)); + } + } +} + +#[test] +fn signer_unsigned_attributes_remain_raw_and_separate_from_signed_attributes() { + let (_, signer) = fixture(true, true); + let fields = der::Tlv::parse_all(&signer).unwrap(); + let unsigned = der::tlv(tag::ctx(1), &der::seq(&[])); + let bytes = der::seq(&[fields.value, &unsigned]); + let (mut view, rest) = SignerInfoView::parse(&bytes).unwrap(); + assert!(rest.is_empty()); + assert_eq!(view.signed_attributes.unwrap().tag(), tag::ctx(0)); + assert_eq!(view.remaining_fields.next_element().unwrap().unwrap().raw(), unsigned); + assert_eq!(view.remaining_fields.next_element(), Ok(None)); +} From 7b1a8f45151cfb0aa90c021c1d0373961db4b357 Mon Sep 17 00:00:00 2001 From: el-j Date: Thu, 19 Nov 2026 09:26:19 +0100 Subject: [PATCH 31/79] craft-audio: validate DSF container bounds and DSDIFF channel counts (#1787) --- crates/audio/src/dsd/dsdiff.rs | 38 +++++++++++----- crates/audio/src/dsd/dsf.rs | 60 +++++++++++++++++-------- crates/audio/tests/dsd_bounds.rs | 72 ++++++++++++++++++++++++++++++ crates/audio/tests/dsd_metadata.rs | 2 + crates/audio/tests/dsd_oracle.rs | 4 +- 5 files changed, 146 insertions(+), 30 deletions(-) diff --git a/crates/audio/src/dsd/dsdiff.rs b/crates/audio/src/dsd/dsdiff.rs index 0d818f53a6..f9f12d04d3 100644 --- a/crates/audio/src/dsd/dsdiff.rs +++ b/crates/audio/src/dsd/dsdiff.rs @@ -142,20 +142,36 @@ pub fn parse_dsdiff_header(bytes: &[u8]) -> Result<(Metadata, usize, usize), Err match &sub_id { b"FS " => { - if sub_data.len() >= 4 { - sample_rate = Some(u32::from_be_bytes([sub_data[0], sub_data[1], sub_data[2], sub_data[3]])); + if sub_data.len() < 4 { + return Err(Error::UnexpectedEof("truncated FS chunk")); } + if sample_rate.is_some() { + return Err(Error::InvalidHeader("duplicate FS chunk")); + } + let sr = u32::from_be_bytes([sub_data[0], sub_data[1], sub_data[2], sub_data[3]]); + if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sr) { + return Err(Error::InvalidHeader("sampling frequency out of range")); + } + sample_rate = Some(sr); } b"CHNL" => { - if sub_data.len() >= 2 { - let n = u16::from_be_bytes([sub_data[0], sub_data[1]]); - num_channels = Some(n); - let mut ch_pos = 2; - while ch_pos + 4 <= sub_data.len() && channel_names.len() < n as usize { - let id: [u8; 4] = [sub_data[ch_pos], sub_data[ch_pos + 1], sub_data[ch_pos + 2], sub_data[ch_pos + 3]]; - channel_names.push(channel_id_to_name(&id)); - ch_pos += 4; - } + if sub_data.len() < 2 { + return Err(Error::UnexpectedEof("truncated CHNL chunk")); + } + if num_channels.is_some() { + return Err(Error::InvalidHeader("duplicate CHNL chunk")); + } + let n = u16::from_be_bytes([sub_data[0], sub_data[1]]); + if n == 0 || n > MAX_CHANNELS as u16 { + return Err(Error::Unsupported("channel count must be between 1 and 8")); + } + num_channels = Some(n); + channel_names.clear(); + let mut ch_pos = 2; + while ch_pos + 4 <= sub_data.len() && channel_names.len() < n as usize { + let id: [u8; 4] = [sub_data[ch_pos], sub_data[ch_pos + 1], sub_data[ch_pos + 2], sub_data[ch_pos + 3]]; + channel_names.push(channel_id_to_name(&id)); + ch_pos += 4; } } b"CMPR" if sub_data.len() >= 4 => { diff --git a/crates/audio/src/dsd/dsf.rs b/crates/audio/src/dsd/dsf.rs index 3a09466645..1fb36c18da 100644 --- a/crates/audio/src/dsd/dsf.rs +++ b/crates/audio/src/dsd/dsf.rs @@ -137,79 +137,103 @@ fn parse_dsf_header_bounded(bytes: &[u8]) -> Result<(Metadata, usize, usize, u32 if dsd_chunk_size != 28 { return Err(Error::InvalidHeader("invalid 'DSD ' chunk size (must be 28)")); } - let _file_size = u64::from_le_bytes(bytes[12..20].try_into().map_err(|_| Error::UnexpectedEof("file size"))?); + let file_size = u64::from_le_bytes(bytes[12..20].try_into().map_err(|_| Error::UnexpectedEof("file size"))?); let metadata_offset = u64::from_le_bytes(bytes[20..28].try_into().map_err(|_| Error::UnexpectedEof("metadata offset"))?); + if file_size > bytes.len() as u64 { + return Err(Error::UnexpectedEof("declared file size extends beyond buffer")); + } + let file_len = usize::try_from(file_size).map_err(|_| Error::MemoryLimitExceeded)?; + if file_len < 28 + 52 + 12 { + return Err(Error::InvalidHeader("declared file size is smaller than required headers")); + } + let file_bytes = &bytes[..file_len]; + // 2. 'fmt ' chunk let fmt_offset = 28; - if &bytes[fmt_offset..fmt_offset + 4] != b"fmt " { + if &file_bytes[fmt_offset..fmt_offset + 4] != b"fmt " { return Err(Error::InvalidHeader("missing 'fmt ' chunk header")); } - let fmt_chunk_size = u64::from_le_bytes(bytes[fmt_offset + 4..fmt_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("fmt chunk size"))?); + let fmt_chunk_size = + u64::from_le_bytes(file_bytes[fmt_offset + 4..fmt_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("fmt chunk size"))?); if fmt_chunk_size < 52 { return Err(Error::InvalidHeader("invalid 'fmt ' chunk size (must be at least 52)")); } let fmt_size = usize::try_from(fmt_chunk_size).map_err(|_| Error::MemoryLimitExceeded)?; - if fmt_size > bytes.len().saturating_sub(fmt_offset + 12) { + if fmt_size > file_bytes.len().saturating_sub(fmt_offset) { return Err(Error::UnexpectedEof("fmt chunk extends beyond file bounds")); } - let format_version = u32::from_le_bytes(bytes[fmt_offset + 12..fmt_offset + 16].try_into().map_err(|_| Error::UnexpectedEof("format version"))?); + let format_version = + u32::from_le_bytes(file_bytes[fmt_offset + 12..fmt_offset + 16].try_into().map_err(|_| Error::UnexpectedEof("format version"))?); if format_version != 1 { return Err(Error::Unsupported("unsupported DSF format version (only version 1 is supported)")); } - let format_id = u32::from_le_bytes(bytes[fmt_offset + 16..fmt_offset + 20].try_into().map_err(|_| Error::UnexpectedEof("format id"))?); + let format_id = u32::from_le_bytes(file_bytes[fmt_offset + 16..fmt_offset + 20].try_into().map_err(|_| Error::UnexpectedEof("format id"))?); if format_id != 0 { return Err(Error::Unsupported("unsupported DSF format id (only raw DSD id=0 is supported)")); } - let channel_type = u32::from_le_bytes(bytes[fmt_offset + 20..fmt_offset + 24].try_into().map_err(|_| Error::UnexpectedEof("channel type"))?); - let channel_count = u32::from_le_bytes(bytes[fmt_offset + 24..fmt_offset + 28].try_into().map_err(|_| Error::UnexpectedEof("channel count"))?); + let channel_type = u32::from_le_bytes(file_bytes[fmt_offset + 20..fmt_offset + 24].try_into().map_err(|_| Error::UnexpectedEof("channel type"))?); + let channel_count = + u32::from_le_bytes(file_bytes[fmt_offset + 24..fmt_offset + 28].try_into().map_err(|_| Error::UnexpectedEof("channel count"))?); if channel_count == 0 || channel_count > MAX_CHANNELS as u32 { return Err(Error::Unsupported("DSF channel count must be between 1 and 8")); } let channels = channel_count as u16; - let sample_rate = u32::from_le_bytes(bytes[fmt_offset + 28..fmt_offset + 32].try_into().map_err(|_| Error::UnexpectedEof("sampling frequency"))?); + let sample_rate = + u32::from_le_bytes(file_bytes[fmt_offset + 28..fmt_offset + 32].try_into().map_err(|_| Error::UnexpectedEof("sampling frequency"))?); if !(MIN_SAMPLE_RATE..=MAX_SAMPLE_RATE).contains(&sample_rate) { return Err(Error::InvalidHeader("DSF sampling frequency out of valid range")); } let bits_per_sample = - u32::from_le_bytes(bytes[fmt_offset + 32..fmt_offset + 36].try_into().map_err(|_| Error::UnexpectedEof("bits per sample"))?); + u32::from_le_bytes(file_bytes[fmt_offset + 32..fmt_offset + 36].try_into().map_err(|_| Error::UnexpectedEof("bits per sample"))?); if bits_per_sample != 1 { return Err(Error::Unsupported("DSF bits per sample must be 1")); } - let sample_count = u64::from_le_bytes(bytes[fmt_offset + 36..fmt_offset + 44].try_into().map_err(|_| Error::UnexpectedEof("sample count"))?); + let sample_count = u64::from_le_bytes(file_bytes[fmt_offset + 36..fmt_offset + 44].try_into().map_err(|_| Error::UnexpectedEof("sample count"))?); let block_size_per_channel = - u32::from_le_bytes(bytes[fmt_offset + 44..fmt_offset + 48].try_into().map_err(|_| Error::UnexpectedEof("block size per channel"))?); + u32::from_le_bytes(file_bytes[fmt_offset + 44..fmt_offset + 48].try_into().map_err(|_| Error::UnexpectedEof("block size per channel"))?); if block_size_per_channel == 0 || block_size_per_channel > MAX_BLOCK_SIZE { return Err(Error::InvalidHeader("DSF block size per channel is invalid or too large")); } // 3. 'data' chunk - let data_offset = fmt_offset + fmt_size; - if &bytes[data_offset..data_offset + 4] != b"data" { + let data_offset = fmt_offset.saturating_add(fmt_size); + if data_offset.saturating_add(12) > file_bytes.len() { + return Err(Error::UnexpectedEof("missing 'data' chunk header")); + } + if &file_bytes[data_offset..data_offset + 4] != b"data" { return Err(Error::InvalidHeader("missing 'data' chunk header")); } let data_chunk_size = - u64::from_le_bytes(bytes[data_offset + 4..data_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("data chunk size"))?); + u64::from_le_bytes(file_bytes[data_offset + 4..data_offset + 12].try_into().map_err(|_| Error::UnexpectedEof("data chunk size"))?); if data_chunk_size < 12 { return Err(Error::InvalidHeader("invalid 'data' chunk size (must be at least 12)")); } let payload_offset = data_offset + 12; let payload_size = usize::try_from(data_chunk_size - 12).map_err(|_| Error::MemoryLimitExceeded)?; - if payload_size > bytes.len().saturating_sub(payload_offset) { + if payload_size > file_bytes.len().saturating_sub(payload_offset) { return Err(Error::UnexpectedEof("data chunk payload extends beyond file bounds")); } + let data_end = payload_offset.saturating_add(payload_size); // Parse ID3v2 metadata if pointer is valid. - let (title, artist) = - if metadata_offset > 0 && metadata_offset < bytes.len() as u64 { parse_id3v2(bytes, metadata_offset as usize) } else { (None, None) }; + let (title, artist) = if metadata_offset == 0 { + (None, None) + } else { + let meta_offset = usize::try_from(metadata_offset).map_err(|_| Error::MemoryLimitExceeded)?; + if meta_offset < data_end || meta_offset >= file_len { + return Err(Error::InvalidHeader("DSF metadata offset outside declared file bounds")); + } + parse_id3v2(file_bytes, meta_offset) + }; let channel_names = dsf_channel_names(channel_type, channels); diff --git a/crates/audio/tests/dsd_bounds.rs b/crates/audio/tests/dsd_bounds.rs index 13f6608e19..5388f2aa45 100644 --- a/crates/audio/tests/dsd_bounds.rs +++ b/crates/audio/tests/dsd_bounds.rs @@ -127,6 +127,78 @@ fn dsdiff_odd_payload_receives_pad_byte() { assert_eq!(raw.channel_bytes[0].len(), 3); } +#[test] +fn dsf_declared_file_size_and_metadata_pointer_bounds() { + let valid = encode_dsf(2_822_400, &[&[0x69; 8]], 64, 8).unwrap(); + + // Undersized file size declaration (e.g. 28) + let mut undersized = valid.clone(); + undersized[12..20].copy_from_slice(&28u64.to_le_bytes()); + assert!(read_metadata(&undersized).is_err()); + assert!(read_raw(&undersized).is_err()); + + // Oversized file size declaration beyond buffer + let mut oversized = valid.clone(); + let big_size = valid.len() as u64 + 100; + oversized[12..20].copy_from_slice(&big_size.to_le_bytes()); + assert!(read_metadata(&oversized).is_err()); + assert!(read_raw(&oversized).is_err()); + + // Metadata pointer outside the declared file bounds + let mut outside_meta = valid.clone(); + let outside_offset = valid.len() as u64 + 10; + outside_meta[20..28].copy_from_slice(&outside_offset.to_le_bytes()); + assert!(read_metadata(&outside_meta).is_err()); + assert!(read_raw(&outside_meta).is_err()); + + // Metadata pointer overlapping data chunk + let mut overlap_meta = valid.clone(); + overlap_meta[20..28].copy_from_slice(&32u64.to_le_bytes()); + assert!(read_metadata(&overlap_meta).is_err()); + assert!(read_raw(&overlap_meta).is_err()); +} + +#[test] +fn dsdiff_channel_count_and_duplicate_chunks_are_validated() { + let base = encode_dsdiff(2_822_400, &[&[0xaa; 8]], 64).unwrap(); + + // Locate PROP chunk payload and CHNL subchunk + let prop_idx = base.windows(4).position(|w| w == b"PROP").unwrap(); + let chnl_idx = base.windows(4).position(|w| w == b"CHNL").unwrap(); + + // 1. Oversized channel count (e.g. 65535 or 9) + let mut bad_count = base.clone(); + bad_count[chnl_idx + 12..chnl_idx + 14].copy_from_slice(&65535u16.to_be_bytes()); + assert!(matches!(read_metadata(&bad_count), Err(Error::Unsupported(_)))); + assert!(matches!(read_raw(&bad_count), Err(Error::Unsupported(_)))); + + let mut zero_count = base.clone(); + zero_count[chnl_idx + 12..chnl_idx + 14].copy_from_slice(&0u16.to_be_bytes()); + assert!(matches!(read_metadata(&zero_count), Err(Error::Unsupported(_)))); + + // 2. Conflicting duplicate CHNL chunk in PROP + let mut dup_chnl = base.clone(); + let chnl_chunk = dup_chnl[chnl_idx..chnl_idx + 18].to_vec(); + dup_chnl.splice(chnl_idx..chnl_idx, chnl_chunk); + // Adjust PROP size and FRM8 size + let prop_size = u64::from_be_bytes(dup_chnl[prop_idx + 4..prop_idx + 12].try_into().unwrap()) + 18; + dup_chnl[prop_idx + 4..prop_idx + 12].copy_from_slice(&prop_size.to_be_bytes()); + let frm8_size = (dup_chnl.len() - 12) as u64; + dup_chnl[4..12].copy_from_slice(&frm8_size.to_be_bytes()); + assert_eq!(read_metadata(&dup_chnl), Err(Error::InvalidHeader("duplicate CHNL chunk"))); + + // 3. Duplicate FS chunk in PROP + let fs_idx = base.windows(4).position(|w| w == b"FS ").unwrap(); + let mut dup_fs = base.clone(); + let fs_chunk = dup_fs[fs_idx..fs_idx + 16].to_vec(); + dup_fs.splice(fs_idx..fs_idx, fs_chunk); + let prop_size = u64::from_be_bytes(dup_fs[prop_idx + 4..prop_idx + 12].try_into().unwrap()) + 16; + dup_fs[prop_idx + 4..prop_idx + 12].copy_from_slice(&prop_size.to_be_bytes()); + let frm8_size = (dup_fs.len() - 12) as u64; + dup_fs[4..12].copy_from_slice(&frm8_size.to_be_bytes()); + assert_eq!(read_metadata(&dup_fs), Err(Error::InvalidHeader("duplicate FS chunk"))); +} + #[test] #[cfg(target_pointer_width = "32")] fn dsdiff_32bit_padding_overflow_is_rejected() { diff --git a/crates/audio/tests/dsd_metadata.rs b/crates/audio/tests/dsd_metadata.rs index 6b076a0e7f..74fd16f314 100644 --- a/crates/audio/tests/dsd_metadata.rs +++ b/crates/audio/tests/dsd_metadata.rs @@ -113,6 +113,8 @@ fn dsf_with_tag(tag: &[u8]) -> Vec { let offset = bytes.len() as u64; bytes[20..28].copy_from_slice(&offset.to_le_bytes()); bytes.extend_from_slice(tag); + let file_size = bytes.len() as u64; + bytes[12..20].copy_from_slice(&file_size.to_le_bytes()); bytes } diff --git a/crates/audio/tests/dsd_oracle.rs b/crates/audio/tests/dsd_oracle.rs index 55d3fef979..94334485b9 100644 --- a/crates/audio/tests/dsd_oracle.rs +++ b/crates/audio/tests/dsd_oracle.rs @@ -221,7 +221,9 @@ fn id3v2_tag_in_dsf() { id3.extend_from_slice(&frames); dsf.extend_from_slice(&id3); - // Update metadata_offset at offset 20 of 'DSD ' chunk + // Update file size and metadata_offset of 'DSD ' chunk + let file_size = dsf.len() as u64; + dsf[12..20].copy_from_slice(&file_size.to_le_bytes()); dsf[20..28].copy_from_slice(&metadata_offset.to_le_bytes()); let meta = read_metadata(&dsf).expect("read metadata with ID3"); From 9ef7889f5b59d1fb4d65c398b4b3b46a1340c3f1 Mon Sep 17 00:00:00 2001 From: alehel Date: Thu, 19 Nov 2026 10:14:21 +0100 Subject: [PATCH 32/79] craft-video: dispatch ProRes, DNx, APV, FFV1 and VP8 tracks --- crates/media/src/avi/mod.rs | 1 + crates/media/src/avi/tests.rs | 1 + crates/media/src/id.rs | 5 ++ crates/media/src/matroska/track.rs | 35 ++++++++ crates/video/README.md | 11 +++ crates/video/src/error.rs | 44 ++++++++++ crates/video/src/lib.rs | 29 ++++++- crates/video/src/track.rs | 114 ++++++++++++++++++++++++-- crates/video/src/track/tests.rs | 127 ++++++++++++++++++++++++++++- 9 files changed, 356 insertions(+), 11 deletions(-) diff --git a/crates/media/src/avi/mod.rs b/crates/media/src/avi/mod.rs index eaaa1bbe24..69e9197058 100644 --- a/crates/media/src/avi/mod.rs +++ b/crates/media/src/avi/mod.rs @@ -258,6 +258,7 @@ impl Stream { b"HEVC" | b"H265" | b"HEV1" | b"HVC1" | b"X265" => Id::Hevc, b"DIVX" | b"DX50" | b"XVID" | b"FMP4" | b"MP4V" | b"M4S2" | b"3IV2" => Id::Mpeg4Video, b"MPG2" | b"MPEG" | b"MPG1" => Id::Mpeg2Video, + b"FFV1" => Id::Ffv1, b"VP80" => Id::Vp8, b"VP90" => Id::Vp9, b"AV01" => Id::Av1, diff --git a/crates/media/src/avi/tests.rs b/crates/media/src/avi/tests.rs index 2edac310b6..f1e06ef05c 100644 --- a/crates/media/src/avi/tests.rs +++ b/crates/media/src/avi/tests.rs @@ -546,6 +546,7 @@ fn codec_params_map_fourccs_and_format_tags() { (b"XVID", CodecId::Mpeg4Video), (b"apch", CodecId::ProRes), (b"AVdn", CodecId::Dnxhd), + (b"FFV1", CodecId::Ffv1), (b"YUY2", CodecId::Unknown), (&[0; 4], CodecId::Unknown), ] { diff --git a/crates/media/src/id.rs b/crates/media/src/id.rs index 7ba597d825..71794524f4 100644 --- a/crates/media/src/id.rs +++ b/crates/media/src/id.rs @@ -121,6 +121,8 @@ pub enum CodecId { Vp8, /// VP9. Vp9, + /// FFV1 lossless video. + Ffv1, /// Apple ProRes. ProRes, /// Motion JPEG. @@ -168,6 +170,7 @@ impl CodecId { CodecId::Av1 => "AV1", CodecId::Vp8 => "VP8", CodecId::Vp9 => "VP9", + CodecId::Ffv1 => "FFV1", CodecId::ProRes => "ProRes", CodecId::Mjpeg => "Motion JPEG", CodecId::Mpeg2Video => "MPEG-2", @@ -214,6 +217,7 @@ impl CodecId { | CodecId::Av1 | CodecId::Vp8 | CodecId::Vp9 + | CodecId::Ffv1 | CodecId::ProRes | CodecId::Mjpeg | CodecId::Mpeg2Video @@ -271,6 +275,7 @@ impl PcmFormat { /// | H.264 / HEVC / AV1 | the `avcC` / `hvcC` / `av1C` record | /// | VP9 | the MP4 `vpcC` payload, or Matroska's codec feature metadata | /// | APV | the `apvC` record | +/// | FFV1 | the version 3 configuration record (dimensions are required separately) | /// | VMD video, VMD audio | the 816-byte VMD file header | /// /// `sample_rate` and `channels` are what the container declares (for HE-AAC with implicit diff --git a/crates/media/src/matroska/track.rs b/crates/media/src/matroska/track.rs index edb8fc87b0..b120ab29b9 100644 --- a/crates/media/src/matroska/track.rs +++ b/crates/media/src/matroska/track.rs @@ -258,6 +258,11 @@ impl Track { Codec::Mp3 => (Id::Mp3, Vec::new()), Codec::Mp2 => (Id::Mp2, Vec::new()), Codec::Mp1 => (Id::Mp1, Vec::new()), + Codec::Other(id) if id == "V_FFV1" => (Id::Ffv1, self.codec_private.clone()), + // VfW CodecPrivate starts with the 40-byte BITMAPINFOHEADER. + Codec::VfwFourcc { fourcc: [b'F', b'F', b'V', b'1'], bitmap_info_header } => { + (Id::Ffv1, bitmap_info_header.get(40..).unwrap_or_default().to_vec()) + } // the ALACSpecificConfig, as MP4's `alac` box holds it after its FullBox header Codec::Other(id) if id == "A_ALAC" => (Id::Alac, self.codec_private.clone()), Codec::VfwFourcc { fourcc: [b'A', b'V', b'd', b'n' | b'h'], .. } => (Id::Dnxhd, Vec::new()), @@ -439,6 +444,36 @@ mod codec_params_tests { use crate::matroska::mux::{MkvWriter, MuxOptions, TrackSpec}; use crate::matroska::{Demuxer, TrackKind}; + #[test] + fn ffv1_native_and_vfw_preserve_configuration_and_dimensions() { + let config = vec![1, 2, 3, 4, 5]; + let mut native = TrackSpec::new(TrackKind::Video, "V_FFV1"); + native.codec_private = config.clone(); + native.video_size = Some((32, 24)); + let mut vfw = TrackSpec::new(TrackKind::Video, "V_MS/VFW/FOURCC"); + let mut bih = vec![0; 40]; + bih[..4].copy_from_slice(&40u32.to_le_bytes()); + bih[16..20].copy_from_slice(b"FFV1"); + bih.extend_from_slice(&config); + vfw.codec_private = bih; + vfw.video_size = native.video_size; + let mut writer = MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![native, vfw], MuxOptions::default()).unwrap(); + for track in 0..2 { + writer.write_frame(track, 0, true, &[0; 4], None).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let demux = Demuxer::from_slice(&bytes).unwrap(); + for track in demux.tracks() { + let params = track.codec_params(); + assert_eq!(params.codec, CodecId::Ffv1); + assert_eq!(params.extradata, config); + assert_eq!((params.width, params.height), (Some(32), Some(24))); + assert!(params.codec.is_video()); + assert!(!params.codec.is_audio()); + assert_eq!(params.codec.name(), "FFV1"); + } + } + #[test] fn alac_dnx_and_opus_match_mp4() { let cookie: Vec = (0..24).collect(); diff --git a/crates/video/README.md b/crates/video/README.md index d05d503122..0413e658d3 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -71,6 +71,11 @@ is built with any of the decoder features below and decodes the codecs whose fea | VP9 | `vp9-decode` | ignored | | AV1 | `av1-decode` | an `av1C` record, or empty | | MPEG-2 and MPEG-1 video | `mpeg2-decode` | a sequence header and its extensions, or empty | +| ProRes | `prores` | ignored (frame headers carry the format) | +| DNxHD / DNxHR | `dnx` | ignored (frame headers carry the format) | +| APV | `apv-decode` | ignored (access units carry the format) | +| FFV1 | `ffv1` | required version 3 configuration record; container width and height are required too | +| VP8 | `vp8-decode` | ignored (key frames carry the format) | Configuration that holds picture data (a slice, a frame OBU, an MPEG-2 picture) is refused. Errors are `VideoError`: `Unsupported`, `Malformed`, or a picture that did not convert. @@ -83,3 +88,9 @@ them first. When the codec itself fails, the pictures it had finished are up to - VP9 keeps those of earlier packets. - MPEG-2 returns them with the call, unless the packet made too many pictures. - AV1 drops those the failing `decode` or `flush` had finished. + +ProRes, DNx, APV and FFV1 return one frame per successful packet, with its packet timestamp; +VP8 returns no picture for a hidden reference frame. These codecs have no delayed output. +APV uses the codec's default selection of the first decodable primary frame and its alpha. +FFV1 has the underlying decoder's version 3, range-coded, key-frame-only support. Reset keeps +its configuration and container dimensions; VP8 reset discards its reference pictures. diff --git a/crates/video/src/error.rs b/crates/video/src/error.rs index 21706aaf93..44be75b66d 100644 --- a/crates/video/src/error.rs +++ b/crates/video/src/error.rs @@ -71,3 +71,47 @@ impl From for VideoError { } } } + +#[cfg(feature = "prores")] +impl From for VideoError { + fn from(e: crate::prores::Error) -> Self { + match e { + crate::prores::Error::Unsupported(_) => VideoError::Unsupported(format!("ProRes: {e}")), + _ => VideoError::Malformed(format!("ProRes: {e}")), + } + } +} + +#[cfg(feature = "dnx")] +impl From for VideoError { + fn from(e: crate::dnx::Error) -> Self { + match e { + crate::dnx::Error::UnknownCid(_) => VideoError::Unsupported(format!("DNx: {e}")), + _ => VideoError::Malformed(format!("DNx: {e}")), + } + } +} + +#[cfg(feature = "apv-decode")] +impl From for VideoError { + fn from(e: crate::apv::Error) -> Self { + VideoError::Malformed(format!("APV: {e}")) + } +} + +#[cfg(feature = "ffv1")] +impl From for VideoError { + fn from(e: crate::ffv1::Error) -> Self { + match e { + crate::ffv1::Error::Unsupported(_) => VideoError::Unsupported(format!("FFV1: {e}")), + _ => VideoError::Malformed(format!("FFV1: {e}")), + } + } +} + +#[cfg(feature = "vp8-decode")] +impl From for VideoError { + fn from(e: crate::vp8::Error) -> Self { + VideoError::Malformed(format!("VP8: {e}")) + } +} diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index 174e7573ae..6101324f91 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -29,7 +29,8 @@ //! they all convert into (`VideoFrame::try_from`). //! //! `TrackDecoder` picks the decoder for a track from its `craft_media::CodecParams` and returns -//! `VideoFrame`s, for H.264, HEVC, VP9, AV1 and MPEG-2 (built with any of their decoder features). +//! `VideoFrame`s, for H.264, HEVC, VP9, AV1, MPEG-2, ProRes, DNx, APV, FFV1 and VP8 +//! (built with any of their decoder features). //! //! Containers and bit-level I/O are in `craft-media`; the codecs here share its `bitstream` //! module and describe their streams with `craft_media::CodecParams`. @@ -40,9 +41,31 @@ pub mod frame; pub use error::VideoError; -#[cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))] +#[cfg(any( + feature = "h264-decode", + feature = "hevc-decode", + feature = "vp9-decode", + feature = "av1-decode", + feature = "mpeg2-decode", + feature = "prores", + feature = "dnx", + feature = "apv-decode", + feature = "ffv1", + feature = "vp8-decode" +))] mod track; -#[cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))] +#[cfg(any( + feature = "h264-decode", + feature = "hevc-decode", + feature = "vp9-decode", + feature = "av1-decode", + feature = "mpeg2-decode", + feature = "prores", + feature = "dnx", + feature = "apv-decode", + feature = "ffv1", + feature = "vp8-decode" +))] pub use track::TrackDecoder; #[cfg(any(feature = "apv-decode", feature = "apv-encode"))] diff --git a/crates/video/src/track.rs b/crates/video/src/track.rs index a4f2462713..d89eeaeac7 100644 --- a/crates/video/src/track.rs +++ b/crates/video/src/track.rs @@ -31,6 +31,16 @@ enum Inner { Av1 { dec: Box, config_obus: Vec }, #[cfg(feature = "mpeg2-decode")] Mpeg2(Box), + #[cfg(feature = "prores")] + ProRes, + #[cfg(feature = "dnx")] + Dnx, + #[cfg(feature = "apv-decode")] + Apv, + #[cfg(feature = "ffv1")] + Ffv1(Box), + #[cfg(feature = "vp8-decode")] + Vp8(Box), } /// A decoder for one video track, whatever its codec: built from the track's [`CodecParams`], @@ -43,6 +53,11 @@ enum Inner { /// | VP9 | `vp9-decode` | ignored (the frame headers repeat the `vpcC` values) | /// | AV1 | `av1-decode` | an `av1C` record, or empty | /// | MPEG-2 and MPEG-1 video | `mpeg2-decode` | a sequence header and its extensions, or empty | +/// | ProRes | `prores` | ignored (frame headers carry the format) | +/// | DNxHD / DNxHR | `dnx` | ignored (frame headers carry the format) | +/// | APV | `apv-decode` | ignored (access units carry the format) | +/// | FFV1 | `ffv1` | required version 3 configuration record; container width and height are required too | +/// | VP8 | `vp8-decode` | ignored (key frames carry the format) | /// /// With an `avcC` or `hvcC` record, packets are length-prefixed NAL units, as MP4 and Matroska /// store them. Otherwise they are Annex B, as MPEG-TS and AVI store them, and the parameter sets @@ -52,6 +67,11 @@ enum Inner { /// metadata, and MPEG-2 `extradata` holds sequence headers, their extensions, user data and GOP /// headers. /// +/// ProRes, DNx, APV and FFV1 return one frame per packet. APV selects the first decodable +/// primary frame and its alpha, as the codec's default decoder does. FFV1 supports version 3, +/// range-coded key frames. VP8 hidden frames update references without returning a picture. +/// These five decoders have no delayed output; reset keeps FFV1 configuration and dimensions. +/// /// Other codecs are [`VideoError::Unsupported`], as is a codec whose decoder feature is off. /// /// A packet carries its presentation timestamp, in any unit; each frame returns with the timestamp @@ -86,13 +106,15 @@ impl std::fmt::Debug for TrackDecoder { } impl TrackDecoder { - /// A decoder for the track `params` describes. Only `codec` and `extradata` are read; the - /// picture size and format come from the stream. + /// A decoder for the track `params` describes. `codec` and `extradata` select and configure it; + /// FFV1 also requires nonzero `width` and `height` from the container. Other codecs get the + /// picture size and format from the stream. /// - /// Configuration that the codec refuses, or that holds picture data, is - /// [`VideoError::Malformed`]. + /// Invalid configuration, or configuration containing picture data where only headers are + /// allowed, is [`VideoError::Malformed`]. Unsupported codec features are + /// [`VideoError::Unsupported`]. pub fn new(params: &CodecParams) -> Result { - Ok(TrackDecoder { inner: Inner::new(params.codec, ¶ms.extradata)?, codec: params.codec, held: Vec::new() }) + Ok(TrackDecoder { inner: Inner::new(params)?, codec: params.codec, held: Vec::new() }) } /// The track's codec, as `params` gave it. @@ -141,6 +163,22 @@ impl TrackDecoder { let pics = dec.decode(packet, pts)?; self.output(pics, None) } + #[cfg(feature = "prores")] + Inner::ProRes => self.single(crate::prores::decode_frame(packet)?, pts), + #[cfg(feature = "dnx")] + Inner::Dnx => self.single(crate::dnx::decode_frame(packet)?, pts), + #[cfg(feature = "apv-decode")] + Inner::Apv => self.single(crate::apv::decode_frame(packet)?, pts), + #[cfg(feature = "ffv1")] + Inner::Ffv1(dec) => { + let pic = dec.decode(packet)?; + self.single(pic, pts) + } + #[cfg(feature = "vp8-decode")] + Inner::Vp8(dec) => { + let pic = dec.decode(packet, pts)?; + self.output(pic.into_iter().collect(), None) + } } } @@ -177,6 +215,16 @@ impl TrackDecoder { let pics = dec.flush(); self.output(pics, None) } + #[cfg(feature = "prores")] + Inner::ProRes => Ok(std::mem::take(&mut self.held)), + #[cfg(feature = "dnx")] + Inner::Dnx => Ok(std::mem::take(&mut self.held)), + #[cfg(feature = "apv-decode")] + Inner::Apv => Ok(std::mem::take(&mut self.held)), + #[cfg(feature = "ffv1")] + Inner::Ffv1(_) => Ok(std::mem::take(&mut self.held)), + #[cfg(feature = "vp8-decode")] + Inner::Vp8(_) => Ok(std::mem::take(&mut self.held)), } } @@ -222,11 +270,45 @@ impl TrackDecoder { dec.reset(); Ok(()) } + #[cfg(feature = "prores")] + Inner::ProRes => Ok(()), + #[cfg(feature = "dnx")] + Inner::Dnx => Ok(()), + #[cfg(feature = "apv-decode")] + Inner::Apv => Ok(()), + #[cfg(feature = "ffv1")] + Inner::Ffv1(_) => Ok(()), + #[cfg(feature = "vp8-decode")] + Inner::Vp8(dec) => { + dec.reset(); + Ok(()) + } } } + /// Frame-only decoders do not take timestamps; attach the packet timestamp after conversion. + #[cfg(any(feature = "prores", feature = "dnx", feature = "apv-decode", feature = "ffv1"))] + fn single

(&mut self, pic: P, pts: i64) -> Result, VideoError> + where + VideoFrame: TryFrom, + { + let mut frame = VideoFrame::try_from(pic)?; + frame.pts = Some(pts); + let mut frames = std::mem::take(&mut self.held); + frames.push(frame); + Ok(frames) + } + /// The frames kept from a failed call, then `pics` converted. On `err`, or on a picture that /// does not convert, the frames are kept for the next call and the (first) error returned. + #[cfg(any( + feature = "h264-decode", + feature = "hevc-decode", + feature = "vp9-decode", + feature = "av1-decode", + feature = "mpeg2-decode", + feature = "vp8-decode" + ))] fn output

(&mut self, pics: Vec

, err: Option) -> Result, VideoError> where VideoFrame: TryFrom, @@ -253,8 +335,9 @@ impl TrackDecoder { } impl Inner { - fn new(codec: CodecId, extradata: &[u8]) -> Result { - #[cfg(not(any(feature = "h264-decode", feature = "hevc-decode", feature = "av1-decode", feature = "mpeg2-decode")))] + fn new(params: &CodecParams) -> Result { + let codec = params.codec; + let extradata = ¶ms.extradata; let _ = extradata; match codec { #[cfg(feature = "h264-decode")] @@ -287,6 +370,23 @@ impl Inner { } Ok(Inner::Mpeg2(dec)) } + #[cfg(feature = "prores")] + CodecId::ProRes => Ok(Inner::ProRes), + #[cfg(feature = "dnx")] + CodecId::Dnxhd => Ok(Inner::Dnx), + #[cfg(feature = "apv-decode")] + CodecId::Apv => Ok(Inner::Apv), + #[cfg(feature = "vp8-decode")] + CodecId::Vp8 => Ok(Inner::Vp8(Box::default())), + #[cfg(feature = "ffv1")] + CodecId::Ffv1 => { + let (width, height) = params + .width + .zip(params.height) + .filter(|&(w, h)| w > 0 && h > 0) + .ok_or_else(|| VideoError::Malformed("FFV1: container dimensions are required".into()))?; + Ok(Inner::Ffv1(Box::new(crate::ffv1::Decoder::new(extradata, width, height)?))) + } other => Err(VideoError::Unsupported(format!("no {} decoder in this build", other.name()))), } } diff --git a/crates/video/src/track/tests.rs b/crates/video/src/track/tests.rs index 5b20e81f11..42d3ab861d 100644 --- a/crates/video/src/track/tests.rs +++ b/crates/video/src/track/tests.rs @@ -20,6 +20,16 @@ fn a_codec_without_a_decoder_is_unsupported() { CodecId::Theora, CodecId::Aac, CodecId::Unknown, + #[cfg(not(feature = "prores"))] + CodecId::ProRes, + #[cfg(not(feature = "dnx"))] + CodecId::Dnxhd, + #[cfg(not(feature = "apv-decode"))] + CodecId::Apv, + #[cfg(not(feature = "ffv1"))] + CodecId::Ffv1, + #[cfg(not(feature = "vp8-decode"))] + CodecId::Vp8, #[cfg(not(feature = "h264-decode"))] CodecId::H264, #[cfg(not(feature = "hevc-decode"))] @@ -39,8 +49,16 @@ fn a_codec_without_a_decoder_is_unsupported() { } #[test] -fn every_built_decoder_starts_without_configuration() { +fn decoders_other_than_ffv1_start_without_configuration() { let on = [ + #[cfg(feature = "prores")] + CodecId::ProRes, + #[cfg(feature = "dnx")] + CodecId::Dnxhd, + #[cfg(feature = "apv-decode")] + CodecId::Apv, + #[cfg(feature = "vp8-decode")] + CodecId::Vp8, #[cfg(feature = "h264-decode")] CodecId::H264, #[cfg(feature = "hevc-decode")] @@ -264,3 +282,110 @@ mod held { assert!(dec.flush().unwrap().is_empty()); } } + +#[cfg(any(feature = "prores", feature = "dnx", feature = "apv", feature = "ffv1", feature = "vp8"))] +fn check_packet(params: CodecParams, packet: &[u8], mut expected: VideoFrame) { + let mut dec = TrackDecoder::new(¶ms).unwrap(); + assert_eq!(dec.codec(), params.codec); + for pts in [-17, 91] { + expected.pts = Some(pts); + assert_eq!(dec.decode(packet, pts).unwrap(), [expected.clone()]); + assert!(dec.flush().unwrap().is_empty()); + assert!(dec.flush().unwrap().is_empty()); + assert!(matches!(dec.decode(&[], 0), Err(VideoError::Malformed(_)))); + dec.reset().unwrap(); + assert!(dec.flush().unwrap().is_empty()); + } +} + +#[cfg(feature = "prores")] +#[test] +fn prores_packet_timestamps_and_reset() { + use crate::prores::*; + let frame = Frame::new(32, 32, ChromaFormat::Yuv422, 10, false).unwrap(); + let mut enc = Encoder::new(Profile::Proxy, 32, 32); + let packet = enc.encode(&frame).unwrap(); + check_packet(enc.codec_params(), &packet, decode_frame(&packet).unwrap().try_into().unwrap()); +} + +#[cfg(feature = "dnx")] +#[test] +fn dnx_packet_timestamps_and_reset() { + use crate::dnx::*; + let frame = Frame::new(64, 64, ChromaFormat::Yuv422, 8, false); + let mut enc = Encoder::new(Profile::Lb, 64, 64).unwrap(); + let packet = enc.encode(&frame).unwrap(); + check_packet(enc.codec_params(), &packet, decode_frame(&packet).unwrap().try_into().unwrap()); +} + +#[cfg(feature = "apv")] +#[test] +fn apv_packet_timestamps_and_reset() { + use crate::apv::*; + let frame = Frame::new(32, 32, ChromaFormat::Yuv422, 10, false); + let mut enc = Encoder::new(Profile::P422_10, 32, 32).unwrap(); + let packet = enc.encode(&frame).unwrap(); + check_packet(params(CodecId::Apv, &enc.decoder_config_record()), &packet, decode_frame(&packet).unwrap().try_into().unwrap()); +} + +#[cfg(feature = "ffv1")] +#[test] +fn ffv1_configuration_dimensions_timestamps_and_reset() { + use crate::ffv1::*; + let frame = Frame { + width: 16, + height: 16, + colorspace: Colorspace::Rgb, + bit_depth: 10, + chroma_shift: (0, 0), + planes: vec![vec![128; 256], vec![512; 256], vec![768; 256], vec![1023; 256]], + }; + let enc = Encoder::new(&frame, EncoderConfig::default()).unwrap(); + let config = enc.config_record(); + let packet = enc.encode(&frame).unwrap(); + let p = params(CodecId::Ffv1, &config).with_size(16, 16); + check_packet(p.clone(), &packet, frame.try_into().unwrap()); + for (width, height) in [(None, Some(16)), (Some(16), None), (Some(0), Some(16)), (Some(16), Some(0))] { + let mut bad = p.clone(); + bad.width = width; + bad.height = height; + assert!(matches!(TrackDecoder::new(&bad), Err(VideoError::Malformed(_)))); + } + for config in [&[][..], &config[..config.len() - 1]] { + assert!(matches!(TrackDecoder::new(¶ms(CodecId::Ffv1, config).with_size(16, 16)), Err(VideoError::Malformed(_)))); + } +} + +#[cfg(feature = "vp8")] +#[test] +fn vp8_hidden_frames_timestamps_and_reset() { + use crate::vp8::*; + let packet = encode_rgba(&vec![128; 32 * 32 * 4], 32, 32, &Vp8Params::default()).unwrap().data; + let expected = Decoder::new().decode(&packet, 0).unwrap().unwrap().try_into().unwrap(); + check_packet(params(CodecId::Vp8, &[]), &packet, expected); + let mut dec = TrackDecoder::new(¶ms(CodecId::Vp8, &[])).unwrap(); + let mut hidden = packet.clone(); + hidden[0] &= !0x10; // show_frame = 0: updates references, produces no displayed picture. + assert!(dec.decode(&hidden, 33).unwrap().is_empty()); + assert!(dec.flush().unwrap().is_empty()); + dec.reset().unwrap(); + // An inter-frame tag with one byte of first partition must fail for missing references + // before its payload is parsed. Keeping the previous key frame would give a syntax error. + let err = dec.decode(&[0x31, 0, 0, 0], 34).unwrap_err(); + assert!(err.to_string().contains("missing reference frame"), "{err}"); + assert_eq!(dec.decode(&packet, 35).unwrap()[0].pts, Some(35)); +} + +#[test] +fn new_codec_errors_keep_their_category() { + #[cfg(feature = "prores")] + assert!(matches!(VideoError::from(crate::prores::Error::Unsupported("profile")), VideoError::Unsupported(_))); + #[cfg(feature = "dnx")] + assert!(matches!(VideoError::from(crate::dnx::Error::UnknownCid(0)), VideoError::Unsupported(_))); + #[cfg(feature = "apv-decode")] + assert!(matches!(VideoError::from(crate::apv::Error::Truncated), VideoError::Malformed(_))); + #[cfg(feature = "ffv1")] + assert!(matches!(VideoError::from(crate::ffv1::Error::Unsupported("inter frames")), VideoError::Unsupported(_))); + #[cfg(feature = "vp8-decode")] + assert!(matches!(VideoError::from(crate::vp8::Error::Invalid("header".into())), VideoError::Malformed(_))); +} From f86a51e6c7e9868dde254aff2f65e82ea5ac07d8 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 11:30:36 +0100 Subject: [PATCH 33/79] psd: append borrowed TySh payload framing [skip ci] --- crates/psd/src/text.rs | 63 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/psd/src/text.rs b/crates/psd/src/text.rs index 3db0153f3c..3e368152ec 100644 --- a/crates/psd/src/text.rs +++ b/crates/psd/src/text.rs @@ -1,4 +1,4 @@ -//! Type layers: the `TySh` block as a read-only view. +//! Type layers: read-only views and borrowed data framing for the `TySh` block. //! //! Layout (Adobe's specification, "Type tool object setting"): a version, six doubles of //! transform, a text version, a descriptor version and the text descriptor, whose `Txt ` is the @@ -83,6 +83,32 @@ impl LayerRecord { } } +/// Append TySh data with fixed version fields and a zero-bounds suffix. +/// +/// Writes version 1, six raw transform doubles, text version 50 and descriptor +/// version 16, the text descriptor, warp version 1 and descriptor version 16, +/// the warp descriptor, then sixteen zero bytes. No outer key, length or padding +/// is written. Text, EngineData and warp semantics remain the caller's policy. +/// Both views inherit the finite, stable, acyclic borrowed-writer contract. +/// Existing output is preserved; traversal uses O(depth) heap frames, without +/// an owned model conversion or a full serialized temporary. +pub fn append_type_layer_data_with_zero_bounds( + out: &mut Vec, + transform: &[f64; 6], + text: &dyn crate::descriptor::borrowed::DescriptorView, + warp: &dyn crate::descriptor::borrowed::DescriptorView, +) { + out.extend_from_slice(&[0, 1]); + for value in transform { + out.extend_from_slice(&value.to_be_bytes()); + } + out.extend_from_slice(&[0, 50, 0, 0, 0, 16]); + crate::descriptor::borrowed::append_descriptor(out, text); + out.extend_from_slice(&[0, 1, 0, 0, 0, 16]); + crate::descriptor::borrowed::append_descriptor(out, warp); + out.extend_from_slice(&[0; 16]); +} + #[cfg(test)] mod tests { use super::*; @@ -203,6 +229,41 @@ mod tests { assert!(TypeLayerPrefix::from_bytes_with_limits(&data, ParseLimits { max_descriptor_items: 1, ..limits }).is_err()); assert!(TypeLayerPrefix::from_bytes_with_limits(&data, ParseLimits { max_list_items: 1, ..limits }).is_err()); } + + #[test] + fn borrowed_type_data_preserves_raw_transform_two_views_and_zero_tail() { + use crate::descriptor::borrowed::{ClassRef, DescriptorView, IdRef, UnicodeRef, ValueRef}; + struct View(bool); + impl DescriptorView for View { + fn class(&self) -> ClassRef<'_> { + ClassRef { name: UnicodeRef::Units(&[]), id: IdRef::Code(*b"null") } + } + fn item(&self, index: usize) -> Option<(IdRef<'_>, ValueRef<'_>)> { + (self.0 && index == 0).then_some((IdRef::Code(*b"flag"), ValueRef::Boolean(true))) + } + } + let transform = [1.0, -0.0, f64::INFINITY, f64::NEG_INFINITY, f64::from_bits(0x7ff8_1234_5678_9abc), -3.0]; + for (text, warp) in [(false, false), (false, true), (true, false), (true, true)] { + let mut out = vec![0xa5]; + append_type_layer_data_with_zero_bounds(&mut out, &transform, &View(text), &View(warp)); + let mut expected = vec![ + 0xa5, 0, 1, 0x3f, 0xf0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0, 0x7f, 0xf0, 0, 0, 0, 0, 0, 0, 0xff, 0xf0, 0, 0, 0, 0, 0, 0, + 0x7f, 0xf8, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xc0, 8, 0, 0, 0, 0, 0, 0, 0, 50, 0, 0, 0, 16, + ]; + for (index, populated) in [text, warp].into_iter().enumerate() { + if index == 1 { + expected.extend([0, 1, 0, 0, 0, 16]); + } + expected.extend_from_slice(b"\0\0\0\0\0\0\0\0null\0\0\0"); + expected.push(u8::from(populated)); + if populated { + expected.extend_from_slice(b"\0\0\0\0flagbool\x01"); + } + } + expected.extend([0; 16]); + assert_eq!(out, expected); + } + } } /// Editable type-tool envelope with PhotoCraft-compatible recovery and geometry limits. From 8fc78247a6c9d54a15d37a19b385b585d733d8e2 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:34:11 +0700 Subject: [PATCH 34/79] Fix HPGL2 byte stream encoding (#2359) [skip ci] * fix(plotter): preserve HP-GL/2 byte encoding and pen state [skip ci] * test(plotter): cover PE continuation bytes and palette bounds [skip ci] --------- Co-authored-by: Codex --- crates/plotter/src/hpgl/write.rs | 169 ++++++++++++++++++++----------- 1 file changed, 110 insertions(+), 59 deletions(-) diff --git a/crates/plotter/src/hpgl/write.rs b/crates/plotter/src/hpgl/write.rs index 07a8ada78f..1d1cac34ea 100644 --- a/crates/plotter/src/hpgl/write.rs +++ b/crates/plotter/src/hpgl/write.rs @@ -4,7 +4,7 @@ pub mod clip; pub mod nest; -use std::fmt::Write as _; +use std::io::Write as _; /// The largest coordinate written, plotter units (2²³ − 1). pub const MAX_COORD: i64 = (1 << 23) - 1; @@ -19,67 +19,78 @@ pub struct Pen { pub rgb: [u8; 3], } -/// Encodes `paths` (each a slice of `(x, y)` in plotter units) as an HP-GL/2 `PE` command. -/// -/// Uses relative coordinates in base-64 (6 bits per byte, offset by 63, high bit set on the -/// terminating byte of each number, `=` before pen-up moves). -pub fn encode_pe(paths: &[&[(i64, i64)]]) -> String { - let mut out = String::from("PE"); - let mut cx = 0_i64; - let mut cy = 0_i64; - for path in paths { - let Some((&(x0, y0), rest)) = path.split_first() else { - continue; - }; - out.push('='); - push_pe_num(&mut out, x0 - cx); - push_pe_num(&mut out, y0 - cy); - cx = x0; - cy = y0; - for &(x, y) in rest { - push_pe_num(&mut out, x - cx); - push_pe_num(&mut out, y - cy); - cx = x; - cy = y; - } - } - out.push(';'); +/// Encodes a standalone HP-GL/2 `PE` command as bytes, not UTF-8 text. +/// The first point is absolute; each path starts with a pen-up move. +pub fn encode_pe(paths: &[&[(i64, i64)]]) -> Vec { + let mut out = b"PE".to_vec(); + append_paths(&mut out, paths.iter().copied(), &mut None); + out.push(b';'); out } -fn push_pe_num(out: &mut String, v: i64) { - let mut n = if v < 0 { ((-v) << 1) | 1 } else { v << 1 } as u64; - loop { - let byte = (n & 0x3f) as u8; - n >>= 6; - if n == 0 { - let _ = out.write_char((byte + 191) as char); - break; +fn append_paths<'a>(out: &mut Vec, paths: impl Iterator, at: &mut Option<(i64, i64)>) { + for path in paths { + for (index, &(x, y)) in path.iter().enumerate() { + if index == 0 { + // '<' lifts the pen for this move; '=' alone only selects absolute coordinates. + out.push(b'<'); + } + let relative = at.and_then(|(px, py)| { + let dx = x.checked_sub(px)?; + let dy = y.checked_sub(py)?; + (dx.unsigned_abs() <= MAX_COORD as u64 && dy.unsigned_abs() <= MAX_COORD as u64).then_some((dx, dy)) + }); + let (dx, dy) = match relative { + Some(delta) => delta, + None => { + out.push(b'='); + (x, y) + } + }; + push_pe_num(out, dx); + push_pe_num(out, dy); + *at = Some((x, y)); } - let _ = out.write_char((byte + 63) as char); } } -/// Writes an HP-GL/2 stream for `pens` and their corresponding `paths_per_pen` (in plotter units). -pub fn write_hpgl2(pens: &[Pen], paths_per_pen: &[Vec>]) -> String { - let mut out = String::from("IN;\n"); - if !pens.is_empty() { - let _ = writeln!(out, "NP{};", pens.len().min(MAX_PENS)); - for pen in pens.iter().take(MAX_PENS) { +fn push_pe_num(out: &mut Vec, value: i64) { + // Widen before shifting so even i64::MIN is encoded without overflow. + let mut number = (u128::from(value.unsigned_abs()) << 1) | u128::from(value < 0); + while number >= 64 { + out.push(63 + (number & 63) as u8); + number >>= 6; + } + out.push(191 + number as u8); +} + +/// Writes an HP-GL/2 byte stream for up to 255 pens and corresponding paths. +/// Pen numbers outside 1..=255 are ignored. Extra palettes/paths are ignored together. +/// The caller owns coordinate admission and output-size budgets. +pub fn write_hpgl2(pens: &[Pen], paths_per_pen: &[Vec>]) -> Vec { + let pens: Vec<_> = pens.iter().take(MAX_PENS).enumerate().filter(|(_, pen)| (1..=MAX_PENS).contains(&pen.number)).collect(); + let mut out = b"IN;".to_vec(); + if let Some(maximum) = pens.iter().map(|(_, pen)| pen.number).max() { + // Raster devices number pens from zero, so reserve the selected pen's slot too. + let count = (maximum + 1).next_power_of_two().max(2); + let _ = write!(out, "NP{count};"); + for (_, pen) in &pens { let [r, g, b] = pen.rgb; - let _ = writeln!(out, "PC{},{r},{g},{b};", pen.number); + let _ = write!(out, "PC{},{r},{g},{b};", pen.number); } } - for (pen, paths) in pens.iter().zip(paths_per_pen) { + let mut at = None; + for (index, pen) in pens { + let Some(paths) = paths_per_pen.get(index) else { continue }; if paths.is_empty() { continue; } - let _ = writeln!(out, "PU;SP{};", pen.number); - let slices: Vec<&[(i64, i64)]> = paths.iter().map(Vec::as_slice).collect(); - out.push_str(&encode_pe(&slices)); - out.push('\n'); + let _ = write!(out, "PU;SP{};PE", pen.number); + // Position is shared across pen changes, not reset to the origin for each PE command. + append_paths(&mut out, paths.iter().map(Vec::as_slice), &mut at); + out.push(b';'); } - out.push_str("PU;SP0;\n"); + out.extend_from_slice(b"PU;SP0;"); out } @@ -88,19 +99,59 @@ mod tests { use super::*; #[test] - fn encode_pe_basic() { - let path: &[(i64, i64)] = &[(0, 0), (10, 0), (10, 10)]; - let pe = encode_pe(&[path]); - assert!(pe.starts_with("PE=")); - assert!(pe.ends_with(';')); + fn pe_numbers_are_raw_bytes_and_paths_lift_the_pen() { + let first: &[(i64, i64)] = &[(0, 0), (10, -10)]; + let second: &[(i64, i64)] = &[(20, 0), (20, 10)]; + assert_eq!(encode_pe(&[first, second]), b"PE<=\xbf\xbf\xd3\xd4<\xd3\xd3\xbf\xd3;"); } #[test] - fn write_hpgl2_basic() { - let pens = [Pen { number: 1, rgb: [0, 0, 0] }]; - let paths = vec![vec![vec![(0, 0), (40, 0), (40, 40)]]]; - let s = write_hpgl2(&pens, &paths); - assert!(s.starts_with("IN;\nNP1;\nPC1,0,0,0;\nPU;SP1;\nPE=")); - assert!(s.ends_with("PU;SP0;\n")); + fn stream_preserves_position_across_pen_changes() { + let pens = [Pen { number: 1, rgb: [1, 2, 3] }, Pen { number: 2, rgb: [4, 5, 6] }]; + let paths = vec![vec![vec![(0, 0), (10, 0)]], vec![vec![(20, 0), (20, 10)]]]; + assert_eq!(write_hpgl2(&pens, &paths), b"IN;NP4;PC1,1,2,3;PC2,4,5,6;PU;SP1;PE<=\xbf\xbf\xd3\xbf;PU;SP2;PE<\xd3\xbf\xbf\xd3;PU;SP0;"); + } + + #[test] + fn large_relative_move_uses_absolute_coordinates() { + let path = [(-MAX_COORD, 0), (MAX_COORD, 0)]; + let result = encode_pe(&[&path]); + assert_eq!(result.iter().filter(|&&b| b == b'=').count(), 2); + } + + #[test] + fn empty_plot_and_sparse_pen_number_are_preserved() { + assert_eq!(write_hpgl2(&[], &[]), b"IN;PU;SP0;"); + assert_eq!(write_hpgl2(&[Pen { number: 255, rgb: [0, 0, 0] }], &[]), b"IN;NP256;PC255,0,0,0;PU;SP0;"); + } + + #[test] + fn multibyte_pe_numbers_are_not_utf8() { + assert_eq!(encode_pe(&[&[(32, -32)]]), b"PE<=?\xc0@\xc0;"); + } + + #[test] + fn invalid_pens_keep_the_original_path_indices() { + let pens = [Pen { number: 0, rgb: [1, 2, 3] }, Pen { number: 2, rgb: [4, 5, 6] }]; + let paths = vec![vec![vec![(100, 100)]], vec![vec![(0, 0), (10, 0)]]]; + assert_eq!(write_hpgl2(&pens, &paths), b"IN;NP4;PC2,4,5,6;PU;SP2;PE<=\xbf\xbf\xd3\xbf;PU;SP0;"); + assert_eq!(write_hpgl2(&[Pen { number: 256, rgb: [0, 0, 0] }], &paths), b"IN;PU;SP0;"); + } + + #[test] + fn palette_cap_also_caps_drawn_paths() { + let mut pens = vec![Pen { number: 0, rgb: [0, 0, 0] }; MAX_PENS + 1]; + pens[MAX_PENS - 1] = Pen { number: 255, rgb: [1, 2, 3] }; + pens[MAX_PENS] = Pen { number: 1, rgb: [4, 5, 6] }; + let paths = vec![vec![vec![(0, 0), (10, 0)]]; MAX_PENS + 1]; + assert_eq!(write_hpgl2(&pens, &paths), b"IN;NP256;PC255,1,2,3;PU;SP255;PE<=\xbf\xbf\xd3\xbf;PU;SP0;"); + } + + #[test] + fn extreme_coordinates_do_not_overflow() { + let path = [(i64::MIN, i64::MAX), (i64::MAX, i64::MIN)]; + let output = encode_pe(&[&path]); + assert!(output.starts_with(b"PE<=")); + assert!(output.ends_with(b";")); } } From 50b0ee7bf811e363b5f238382b5c77318cf33e46 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:36:51 +0700 Subject: [PATCH 35/79] Expose structured palette errors for localized consumers (#2377) [skip ci] Co-authored-by: Codex --- crates/cms/src/palette.rs | 183 ++++++++++++++++++++++++++++++++------ 1 file changed, 154 insertions(+), 29 deletions(-) diff --git a/crates/cms/src/palette.rs b/crates/cms/src/palette.rs index eb2c2fcdac..8aabb70d85 100644 --- a/crates/cms/src/palette.rs +++ b/crates/cms/src/palette.rs @@ -148,8 +148,58 @@ const ACB_SIGNATURE: &[u8] = b"8BCB"; const ACB_CUT_SHORT: &str = "the color book is cut short"; const ACB_MAX_NAME_BYTES: usize = 64 << 20; +/// Structured palette failure for callers that supply localized messages. +/// +/// The existing string-returning entry points retain their English diagnostics. +/// Match these variants rather than parsing those strings when translating errors. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PaletteError { + UnsupportedFormat, + TruncatedAse, + TruncatedAcb, + AseWriteEntryLimit { limit: usize, entries: usize }, + AseReadEntryLimit { limit: usize }, + AseBlockCount, + AseBlockLength, + AseNameLength, + AseVersion { major: u16, minor: u16 }, + AcbVersion { version: u16 }, + AcbEntryLimit { limit: usize }, + AcbColorSpace { space: u16 }, + AcbNameBytes { limit: usize }, +} + +impl std::fmt::Display for PaletteError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::UnsupportedFormat => f.write_str("not a supported palette (.gpl, .ase, or .acb)"), + Self::TruncatedAse => f.write_str(ASE_CUT_SHORT), + Self::TruncatedAcb => f.write_str(ACB_CUT_SHORT), + Self::AseWriteEntryLimit { limit, entries } => { + write!(f, "at most {limit} colors and groups are supported in a swatch exchange file, and this library has {entries}") + } + Self::AseReadEntryLimit { limit } => write!(f, "the swatch exchange file holds more than {limit} colors and groups"), + Self::AseBlockCount => f.write_str("too many swatch exchange blocks"), + Self::AseBlockLength => f.write_str("a swatch exchange block is too long"), + Self::AseNameLength => f.write_str("a swatch exchange name is too long"), + Self::AseVersion { major, minor } => write!(f, "swatch exchange version {major}.{minor} isn't supported (only 1.x)"), + Self::AcbVersion { version } => write!(f, "color book version {version} isn't supported (only 1)"), + Self::AcbEntryLimit { limit } => write!(f, "the color book holds more than {limit} colors"), + Self::AcbColorSpace { space } => write!(f, "color books in color space {space} aren't supported (only RGB, CMYK and Lab)"), + Self::AcbNameBytes { limit } => write!(f, "the color book's names take more than {} MB", limit >> 20), + } + } +} + +impl std::error::Error for PaletteError {} + /// Write `palette` in `format`. pub fn write_palette(palette: &Palette, format: PaletteFormat) -> Result, String> { + write_palette_typed(palette, format).map_err(|error| error.to_string()) +} + +/// Write a palette, returning structured errors for caller-localized diagnostics. +pub fn write_palette_typed(palette: &Palette, format: PaletteFormat) -> Result, PaletteError> { match format { PaletteFormat::Gpl => Ok(write_gpl(palette).into_bytes()), PaletteFormat::Ase => write_ase(palette), @@ -160,18 +210,24 @@ pub fn write_palette(palette: &Palette, format: PaletteFormat) -> Result /// Read a palette from `bytes` (`.ase`, `.acb`, or `.gpl`, detected from content). /// `fallback_name` is used when the file does not specify a library name. pub fn read_palette(bytes: &[u8], fallback_name: &str) -> Result { + read_palette_typed(bytes, fallback_name).map_err(|error| error.to_string()) +} + +/// Read a palette, returning structured errors for caller-localized diagnostics. +/// Detection and fallback naming match [`read_palette`]. +pub fn read_palette_typed(bytes: &[u8], fallback_name: &str) -> Result { if bytes.starts_with(ASE_SIGNATURE) { return read_ase(bytes, fallback_name); } if bytes.starts_with(ACB_SIGNATURE) { - return read_acb(bytes, fallback_name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e }); + return read_acb(bytes, fallback_name).map_err(|e| if e == PaletteError::TruncatedAse { PaletteError::TruncatedAcb } else { e }); } let text = String::from_utf8_lossy(bytes); let text = text.trim_start_matches('\u{feff}').trim_start(); if text.starts_with(GPL_HEADER) { return Ok(read_gpl(text, fallback_name)); } - Err("not a supported palette (.gpl, .ase, or .acb)".into()) + Err(PaletteError::UnsupportedFormat) } /// Returns `true` if `bytes` looks like a `.gpl`, `.ase`, or `.acb` palette. @@ -267,10 +323,10 @@ fn write_css(lib: &Palette) -> String { out } -fn write_ase(lib: &Palette) -> Result, String> { +fn write_ase(lib: &Palette) -> Result, PaletteError> { let entries = lib.swatches.len() + lib.groups.iter().map(|g| 1 + g.swatches.len()).sum::(); if entries > ASE_MAX_ENTRIES { - return Err(format!("at most {ASE_MAX_ENTRIES} colors and groups are supported in a swatch exchange file, and this library has {entries}")); + return Err(PaletteError::AseWriteEntryLimit { limit: ASE_MAX_ENTRIES, entries }); } let mut body = vec![]; let mut blocks = put_ase_colors(&mut body, &lib.swatches)?; @@ -281,7 +337,7 @@ fn write_ase(lib: &Palette) -> Result, String> { blocks += 2 + put_ase_colors(&mut body, &g.swatches)?; put_ase_block(&mut body, ASE_GROUP_END, &[])?; } - let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?; + let blocks = u32::try_from(blocks).map_err(|_| PaletteError::AseBlockCount)?; let mut out = ASE_SIGNATURE.to_vec(); out.extend(1u16.to_be_bytes()); out.extend(0u16.to_be_bytes()); @@ -290,7 +346,7 @@ fn write_ase(lib: &Palette) -> Result, String> { Ok(out) } -fn put_ase_colors(out: &mut Vec, list: &[PaletteSwatch]) -> Result { +fn put_ase_colors(out: &mut Vec, list: &[PaletteSwatch]) -> Result { let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 }; let mut n = 0; @@ -319,15 +375,15 @@ fn put_ase_colors(out: &mut Vec, list: &[PaletteSwatch]) -> Result, kind: u16, body: &[u8]) -> Result<(), String> { - let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?; +fn put_ase_block(out: &mut Vec, kind: u16, body: &[u8]) -> Result<(), PaletteError> { + let len = u32::try_from(body.len()).map_err(|_| PaletteError::AseBlockLength)?; out.extend(kind.to_be_bytes()); out.extend(len.to_be_bytes()); out.extend_from_slice(body); Ok(()) } -fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), String> { +fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), PaletteError> { let mut units: Vec = vec![]; for c in name.chars().filter(|&c| c != '\0') { let mut buf = [0; 2]; @@ -338,7 +394,7 @@ fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), String> { units.extend_from_slice(encoded); } units.push(0); - let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?; + let count = u16::try_from(units.len()).map_err(|_| PaletteError::AseNameLength)?; out.extend(count.to_be_bytes()); out.extend(units.iter().flat_map(|u| u.to_be_bytes())); Ok(()) @@ -373,12 +429,12 @@ fn read_gpl(text: &str, fallback: &str) -> Palette { lib } -fn read_ase(bytes: &[u8], fallback: &str) -> Result { +fn read_ase(bytes: &[u8], fallback: &str) -> Result { let mut data = AseData(bytes); data.bytes(ASE_SIGNATURE.len())?; let (major, minor) = (data.u16()?, data.u16()?); if major != 1 { - return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)")); + return Err(PaletteError::AseVersion { major, minor }); } let blocks = data.u32()?; let mut lib = Palette { name: fallback.into(), ..Default::default() }; @@ -391,7 +447,7 @@ fn read_ase(bytes: &[u8], fallback: &str) -> Result { if matches!(kind, ASE_GROUP_START | ASE_COLOR) { entries += 1; if entries > ASE_MAX_ENTRIES { - return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups")); + return Err(PaletteError::AseReadEntryLimit { limit: ASE_MAX_ENTRIES }); } } match kind { @@ -414,18 +470,18 @@ fn read_ase(bytes: &[u8], fallback: &str) -> Result { Ok(lib) } -fn read_acb(bytes: &[u8], fallback: &str) -> Result { +fn read_acb(bytes: &[u8], fallback: &str) -> Result { let mut data = AseData(bytes); data.bytes(ACB_SIGNATURE.len())?; let version = data.u16()?; if version != 1 { - return Err(format!("color book version {version} isn't supported (only 1)")); + return Err(PaletteError::AcbVersion { version }); } let _book_id = data.u16()?; let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?]; let count = usize::from(data.u16()?); if count > ASE_MAX_ENTRIES { - return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors")); + return Err(PaletteError::AcbEntryLimit { limit: ASE_MAX_ENTRIES }); } let (_page_size, _page_offset) = (data.u16()?, data.u16()?); let space = data.u16()?; @@ -447,7 +503,7 @@ fn read_acb(bytes: &[u8], fallback: &str) -> Result { let [l, a, b] = data.array::<3>()?; PaletteColor::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0) } - other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")), + other => return Err(PaletteError::AcbColorSpace { space: other }), }; colors.push((name, color)); } @@ -458,7 +514,7 @@ fn read_acb(bytes: &[u8], fallback: &str) -> Result { for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) { kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len())); if kept > ACB_MAX_NAME_BYTES { - return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20)); + return Err(PaletteError::AcbNameBytes { limit: ACB_MAX_NAME_BYTES }); } let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string()); lib.swatches.push(PaletteSwatch { name, color, global: spot, spot }); @@ -466,7 +522,7 @@ fn read_acb(bytes: &[u8], fallback: &str) -> Result { Ok(lib) } -fn ase_swatch(body: &mut AseData) -> Result, String> { +fn ase_swatch(body: &mut AseData) -> Result, PaletteError> { let name = body.name()?; let unit = |v: f32| v.clamp(0.0, 1.0); let color = match &body.array::<4>()? { @@ -510,29 +566,29 @@ fn value_name(c: PaletteColor) -> String { struct AseData<'a>(&'a [u8]); impl<'a> AseData<'a> { - fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> { - let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?; + fn bytes(&mut self, n: usize) -> Result<&'a [u8], PaletteError> { + let (head, rest) = self.0.split_at_checked(n).ok_or(PaletteError::TruncatedAse)?; self.0 = rest; Ok(head) } - fn array(&mut self) -> Result<[u8; N], String> { - let (head, rest) = self.0.split_first_chunk::().ok_or(ASE_CUT_SHORT)?; + fn array(&mut self) -> Result<[u8; N], PaletteError> { + let (head, rest) = self.0.split_first_chunk::().ok_or(PaletteError::TruncatedAse)?; self.0 = rest; Ok(*head) } - fn u16(&mut self) -> Result { + fn u16(&mut self) -> Result { self.array().map(u16::from_be_bytes) } - fn u32(&mut self) -> Result { + fn u32(&mut self) -> Result { self.array().map(u32::from_be_bytes) } - fn f32(&mut self) -> Result { + fn f32(&mut self) -> Result { let v = f32::from_be_bytes(self.array()?); Ok(if v.is_finite() { v } else { 0.0 }) } - fn acb_string(&mut self) -> Result { + fn acb_string(&mut self) -> Result { let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX); - let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>(); + let (units, _) = self.bytes(n.checked_mul(2).ok_or(PaletteError::TruncatedAse)?)?.as_chunks::<2>(); let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); let s = String::from_utf16_lossy(&units); let s = match s.strip_prefix("$$$/") { @@ -541,7 +597,7 @@ impl<'a> AseData<'a> { }; Ok(s.replace("^R", "®").replace("^C", "©")) } - fn name(&mut self) -> Result { + fn name(&mut self) -> Result { if self.0.is_empty() { return Ok(String::new()); } @@ -604,6 +660,75 @@ mod tests { assert_eq!(parsed.groups[0].swatches[0].name, "Navy"); } + #[test] + fn typed_errors_distinguish_formats_and_preserve_legacy_messages() { + for (bytes, expected) in [ + (b"no palette".as_slice(), PaletteError::UnsupportedFormat), + (b"ASEF".as_slice(), PaletteError::TruncatedAse), + (b"8BCB".as_slice(), PaletteError::TruncatedAcb), + (b"8BCB\0\x01\0\0\0\0\0\x03\0x".as_slice(), PaletteError::TruncatedAcb), + (b"ASEF\0\x02\0\x03".as_slice(), PaletteError::AseVersion { major: 2, minor: 3 }), + (b"8BCB\0\x02".as_slice(), PaletteError::AcbVersion { version: 2 }), + ] { + assert_eq!(read_palette_typed(bytes, "fallback"), Err(expected)); + assert_eq!(read_palette(bytes, "fallback"), Err(expected.to_string())); + } + assert_eq!(read_palette(b"8BCB", "fallback"), Err("the color book is cut short".into())); + } + + #[test] + fn structured_error_display_preserves_legacy_wording() { + let cases = [ + (PaletteError::UnsupportedFormat, "not a supported palette (.gpl, .ase, or .acb)"), + (PaletteError::TruncatedAse, "the swatch exchange file is cut short"), + (PaletteError::TruncatedAcb, "the color book is cut short"), + ( + PaletteError::AseWriteEntryLimit { limit: 3, entries: 4 }, + "at most 3 colors and groups are supported in a swatch exchange file, and this library has 4", + ), + (PaletteError::AseReadEntryLimit { limit: 3 }, "the swatch exchange file holds more than 3 colors and groups"), + (PaletteError::AseBlockCount, "too many swatch exchange blocks"), + (PaletteError::AseBlockLength, "a swatch exchange block is too long"), + (PaletteError::AseNameLength, "a swatch exchange name is too long"), + (PaletteError::AseVersion { major: 2, minor: 3 }, "swatch exchange version 2.3 isn't supported (only 1.x)"), + (PaletteError::AcbVersion { version: 2 }, "color book version 2 isn't supported (only 1)"), + (PaletteError::AcbEntryLimit { limit: 3 }, "the color book holds more than 3 colors"), + (PaletteError::AcbColorSpace { space: 5 }, "color books in color space 5 aren't supported (only RGB, CMYK and Lab)"), + (PaletteError::AcbNameBytes { limit: 64 << 20 }, "the color book's names take more than 64 MB"), + ]; + for (error, expected) in cases { + assert_eq!(error.to_string(), expected); + } + } + + #[test] + fn typed_write_limit_exposes_counts_without_parsing_english() { + let palette = Palette { groups: vec![PaletteGroup::default(); ASE_MAX_ENTRIES + 1], ..Default::default() }; + let error = PaletteError::AseWriteEntryLimit { limit: ASE_MAX_ENTRIES, entries: ASE_MAX_ENTRIES + 1 }; + assert_eq!(write_palette_typed(&palette, PaletteFormat::Ase), Err(error)); + assert_eq!(write_palette(&palette, PaletteFormat::Ase), Err(error.to_string())); + } + + #[test] + fn typed_success_keeps_legacy_bytes_and_palette() { + let palette = Palette { + name: "typed".into(), + swatches: vec![PaletteSwatch { name: "red".into(), color: PaletteColor::rgb8(255, 0, 0), global: false, spot: false }], + groups: vec![], + }; + assert_eq!( + write_palette_typed(&palette, PaletteFormat::Ase).expect("ASE golden"), + b"ASEF\0\x01\0\0\0\0\0\x01\0\x01\0\0\0\x1c\0\x04\0r\0e\0d\0\0RGB \x3f\x80\0\0\0\0\0\0\0\0\0\0\0\x02" + ); + for format in PaletteFormat::ALL { + let typed = write_palette_typed(&palette, format).expect("typed write"); + assert_eq!(write_palette(&palette, format), Ok(typed.clone())); + if format.readable() { + assert_eq!(read_palette(&typed, "typed"), read_palette_typed(&typed, "typed").map_err(|error| error.to_string())); + } + } + } + #[test] fn ase_roundtrip() { let pal = Palette { From 30a568b97fa2927d2217f98ba9c799bc76102144 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:26:09 +0700 Subject: [PATCH 36/79] image-codecs: expose raw BMP density probe (#2354) [skip ci] Co-authored-by: FredApps --- crates/image-codecs/src/bmp_probe.rs | 46 +++++++++++++++++++++++++++ crates/image-codecs/src/codecs/bmp.rs | 17 ++++++++-- 2 files changed, 60 insertions(+), 3 deletions(-) diff --git a/crates/image-codecs/src/bmp_probe.rs b/crates/image-codecs/src/bmp_probe.rs index 89f6a3b977..8bd2c64352 100644 --- a/crates/image-codecs/src/bmp_probe.rs +++ b/crates/image-codecs/src/bmp_probe.rs @@ -2,6 +2,8 @@ use crate::error::CodecError; +pub use crate::codecs::bmp::pixels_per_meter; + /// Recognize a BMP file header with a supported DIB header kind. /// /// This is a format-routing check, not full validation: dimensions and pixel data may still @@ -617,3 +619,47 @@ mod tests { assert_eq!(dib_layout(odd.clone()), odd); } } + +#[cfg(test)] +mod density_tests { + use super::pixels_per_meter; + + fn header(dib: u32, x: i32, y: i32) -> [u8; 46] { + let mut b = [0; 46]; + b[..2].copy_from_slice(b"BM"); + b[14..18].copy_from_slice(&dib.to_le_bytes()); + b[38..42].copy_from_slice(&x.to_le_bytes()); + b[42..46].copy_from_slice(&y.to_le_bytes()); + b + } + + #[test] + fn raw_density_preserves_axes_and_integer_extremes() { + for dib in [40, 41, 52, 56, 64, 108, 124, u32::MAX] { + assert_eq!(pixels_per_meter(&header(dib, 10000, 20000)), Some((10000, 20000))); + } + assert_eq!(pixels_per_meter(&header(40, i32::MAX, 1)), Some((i32::MAX, 1))); + assert_eq!(pixels_per_meter(&header(40, 11811, 11811)), Some((11811, 11811))); + } + + #[test] + fn raw_density_rejects_missing_or_nonpositive_fields() { + let valid = header(40, 10000, 20000); + for len in 0..valid.len() { + assert_eq!(pixels_per_meter(&valid[..len]), None, "prefix {len}"); + } + for dib in [0, 12, 16, 39] { + assert_eq!(pixels_per_meter(&header(dib, 10000, 20000)), None); + } + for bad in [0, -1, i32::MIN] { + assert_eq!(pixels_per_meter(&header(40, bad, 20000)), None); + assert_eq!(pixels_per_meter(&header(40, 10000, bad)), None); + } + let mut wrong = valid; + wrong[0] = b'X'; + assert_eq!(pixels_per_meter(&wrong), None); + let mut trailing = valid.to_vec(); + trailing.extend_from_slice(&[1, 2, 3]); + assert_eq!(pixels_per_meter(&trailing), Some((10000, 20000))); + } +} diff --git a/crates/image-codecs/src/codecs/bmp.rs b/crates/image-codecs/src/codecs/bmp.rs index 239794a2c6..a574dd840e 100644 --- a/crates/image-codecs/src/codecs/bmp.rs +++ b/crates/image-codecs/src/codecs/bmp.rs @@ -27,12 +27,23 @@ fn has_resolution_fields(bytes: &[u8]) -> bool { /// or either is 0 or negative (most writers leave them 0). A whole number of ppi stored rounded to /// whole pixels per metre (300 ppi = 11811) reads back whole, as a PNG's `pHYs` does. pub(crate) fn resolution(bytes: &[u8]) -> Option<(f32, f32)> { + let (x, y) = pixels_per_meter(bytes)?; + Some((dpi_of_ppm(x as u32), dpi_of_ppm(y as u32))) +} + +/// Positive signed pixels per metre from a BMP's header, without rounding to DPI. +/// +/// Requires a `BM` signature, at least 46 bytes and a DIB header size of at least 40. +/// Zero or negative density on either axis gives `None`. This is a bounded header +/// probe, not full BMP validation: pixel data and other header fields are not checked. +/// Callers retain their own unit conversion, precision and density sanity policy. +pub fn pixels_per_meter(bytes: &[u8]) -> Option<(i32, i32)> { if !has_resolution_fields(bytes) { return None; } - let field = |at: usize| le4(bytes, at).map(i32::from_le_bytes).and_then(|v| u32::try_from(v).ok()); - let (x, y) = (field(X_PPM)?, field(Y_PPM)?); - (x > 0 && y > 0).then(|| (dpi_of_ppm(x), dpi_of_ppm(y))) + let x = i32::from_le_bytes(le4(bytes, X_PPM)?); + let y = i32::from_le_bytes(le4(bytes, Y_PPM)?); + (x > 0 && y > 0).then_some((x, y)) } /// Pixels per metre for `ppi`, rounded as Photoshop and the PNG `pHYs` writer do (300 ppi = 11811), From cfadb66dbf75fdeec8c50d6e6f389046b2c12695 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 10:00:27 -0500 Subject: [PATCH 37/79] midi: add live MIDI 1.0 channel-voice message decoder (#2392) --- crates/midi/src/lib.rs | 2 + crates/midi/src/live.rs | 85 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 crates/midi/src/live.rs diff --git a/crates/midi/src/lib.rs b/crates/midi/src/lib.rs index 0eabbc70d2..b2464dce87 100644 --- a/crates/midi/src/lib.rs +++ b/crates/midi/src/lib.rs @@ -10,6 +10,8 @@ //! Written from the public Standard MIDI Files 1.0 specification. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +/// Live MIDI 1.0 channel-voice message decoding. +pub mod live; mod sequence; mod smf; /// Source-timed SMF compatibility model, including tolerant and SMPTE reading. diff --git a/crates/midi/src/live.rs b/crates/midi/src/live.rs new file mode 100644 index 0000000000..f4ac1fae7c --- /dev/null +++ b/crates/midi/src/live.rs @@ -0,0 +1,85 @@ +//! Live MIDI 1.0 channel-voice message decoding. + +/// Decoded MIDI 1.0 channel-voice message. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChannelMessage { + /// Note Off (`0x8n`, key, release velocity). + NoteOff { channel: u8, key: u8, velocity: u8 }, + /// Note On (`0x9n`, key, velocity). + NoteOn { channel: u8, key: u8, velocity: u8 }, + /// Polyphonic key pressure / aftertouch (`0xAn`, key, pressure). + PolyPressure { channel: u8, key: u8, pressure: u8 }, + /// Control Change (`0xBn`, controller `0..=127`, value `0..=127`). + ControlChange { channel: u8, controller: u8, value: u8 }, + /// Channel pressure / aftertouch (`0xDn`, pressure `0..=127`). + ChannelPressure { channel: u8, pressure: u8 }, + /// 14-bit Pitch Bend (`0xEn`, value `0..=16383`). + PitchBend { channel: u8, value: u16 }, +} + +impl ChannelMessage { + /// Parses one MIDI 1.0 channel-voice message from raw wire bytes. + /// + /// Returns `None` for truncated messages, out-of-range data bytes (`> 127`), + /// system messages (`0xF0..=0xFF`), or Program Change (`0xCn`). + #[must_use] + pub fn parse(message: &[u8]) -> Option { + let &status = message.first()?; + let channel = status & 0x0F; + let &a = message.get(1)?; + if a > 127 { + return None; + } + match status & 0xF0 { + 0x80 => { + let &b = message.get(2)?; + (b <= 127).then_some(Self::NoteOff { channel, key: a, velocity: b }) + } + 0x90 => { + let &b = message.get(2)?; + (b <= 127).then_some(Self::NoteOn { channel, key: a, velocity: b }) + } + 0xA0 => { + let &b = message.get(2)?; + (b <= 127).then_some(Self::PolyPressure { channel, key: a, pressure: b }) + } + 0xB0 => { + let &b = message.get(2)?; + (b <= 127).then_some(Self::ControlChange { channel, controller: a, value: b }) + } + 0xD0 => Some(Self::ChannelPressure { channel, pressure: a }), + 0xE0 => { + let &b = message.get(2)?; + (b <= 127).then_some(Self::PitchBend { channel, value: (u16::from(b) << 7) | u16::from(a) }) + } + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::ChannelMessage; + + #[test] + fn parses_channel_voice_messages() { + assert_eq!(ChannelMessage::parse(&[0x92, 60, 100]), Some(ChannelMessage::NoteOn { channel: 2, key: 60, velocity: 100 })); + assert_eq!(ChannelMessage::parse(&[0x82, 60, 64]), Some(ChannelMessage::NoteOff { channel: 2, key: 60, velocity: 64 })); + assert_eq!(ChannelMessage::parse(&[0xA5, 64, 90]), Some(ChannelMessage::PolyPressure { channel: 5, key: 64, pressure: 90 })); + assert_eq!(ChannelMessage::parse(&[0xB1, 74, 127]), Some(ChannelMessage::ControlChange { channel: 1, controller: 74, value: 127 })); + assert_eq!(ChannelMessage::parse(&[0xD3, 55]), Some(ChannelMessage::ChannelPressure { channel: 3, pressure: 55 })); + assert_eq!(ChannelMessage::parse(&[0xE0, 0x00, 0x40]), Some(ChannelMessage::PitchBend { channel: 0, value: 8192 })); + assert_eq!(ChannelMessage::parse(&[0xEF, 0x7F, 0x7F]), Some(ChannelMessage::PitchBend { channel: 15, value: 16383 })); + } + + #[test] + fn rejects_invalid_and_truncated_messages() { + assert_eq!(ChannelMessage::parse(&[]), None); + assert_eq!(ChannelMessage::parse(&[0x90, 60]), None); + assert_eq!(ChannelMessage::parse(&[0x90, 128, 64]), None); + assert_eq!(ChannelMessage::parse(&[0x90, 60, 128]), None); + assert_eq!(ChannelMessage::parse(&[0xD0, 128]), None); + assert_eq!(ChannelMessage::parse(&[0xC0, 10]), None); + assert_eq!(ChannelMessage::parse(&[0xF8]), None); + } +} From 48c57b5fafa170eb9c77c1d9fef0be0f09876f1f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 10:00:32 -0500 Subject: [PATCH 38/79] http-url: add parse_content_range (#2395) --- crates/http-url/src/lib.rs | 41 +++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/http-url/src/lib.rs b/crates/http-url/src/lib.rs index 1e3e5875f7..bece12fc4b 100644 --- a/crates/http-url/src/lib.rs +++ b/crates/http-url/src/lib.rs @@ -177,10 +177,37 @@ impl Url { } } +/// Parses an HTTP `Content-Range` header value (`bytes a-b/total`) into `(a, total)`, +/// where `*` as the total length yields `None`. +#[must_use] +pub fn parse_content_range(v: &str) -> Option<(u64, Option)> { + let v = v.trim().strip_prefix("bytes")?.trim(); + let (range, total) = v.split_once('/')?; + let (a, b) = range.split_once('-')?; + let (a, b) = (digits(a)?, digits(b)?); + if b < a { + return None; + } + let total = match total.trim() { + "*" => None, + t => Some(digits(t)?), + }; + Some((a, total)) +} + +/// A non-empty run of ASCII digits as a `u64` (no sign, unlike `str::parse`). +fn digits(s: &str) -> Option { + let s = s.trim(); + if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + s.parse().ok() +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] - use super::{Url, UrlError}; + use super::{Url, UrlError, parse_content_range}; #[test] fn fragment_only_or_empty_location_keeps_file_name_and_query() { @@ -274,4 +301,16 @@ mod tests { assert!(!plain.join("http://127.0.0.1:9/b").unwrap().tls); assert!(plain.join("https://b.example/z").unwrap().tls); } + + #[test] + fn parses_content_ranges() { + assert_eq!(parse_content_range("bytes 100-299/300"), Some((100, Some(300)))); + assert_eq!(parse_content_range("bytes 0-0/*"), Some((0, None))); + assert_eq!(parse_content_range("bytes 9-1/300"), None); + assert_eq!(parse_content_range("items 1-2/3"), None); + assert_eq!(parse_content_range("bytes +100-+299/+300"), None); + assert_eq!(parse_content_range("bytes 100-+299/300"), None); + assert_eq!(parse_content_range("bytes 100-299/+300"), None); + assert_eq!(parse_content_range("bytes 1-/3"), None); + } } From d7c9632bfb3040cf45db394e7500cc93c81c49e0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 10:53:18 -0500 Subject: [PATCH 39/79] image-codecs: add jpeg_with_icc and jpeg_without_icc to jpeg_inks (#2400) --- crates/image-codecs/src/jpeg_inks.rs | 101 +++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/crates/image-codecs/src/jpeg_inks.rs b/crates/image-codecs/src/jpeg_inks.rs index 2267036430..977133ac0b 100644 --- a/crates/image-codecs/src/jpeg_inks.rs +++ b/crates/image-codecs/src/jpeg_inks.rs @@ -96,3 +96,104 @@ pub fn decode_jpeg_inks(bytes: &[u8], limits: &Limits) -> Result Option> { + // A segment's length counts itself (2 bytes) and the name, number and count (14). + const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2; + let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect(); + let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?; + let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len()); + for (i, chunk) in chunks.iter().enumerate() { + let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?; + segments.extend_from_slice(&[0xFF, 0xE2]); + segments.extend_from_slice(&len.to_be_bytes()); + segments.extend_from_slice(ICC_SEGMENT); + segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]); + segments.extend_from_slice(chunk); + } + with_icc_segments(bytes, &segments) +} + +/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the +/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose +/// segments before the scan can't be read. +pub fn jpeg_without_icc(bytes: &[u8]) -> Option> { + with_icc_segments(bytes, &[]) +} + +/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments` +/// written after the leading application segments; `None` when the bytes don't start a JPEG or +/// their segments before the scan can't be read. +fn with_icc_segments(bytes: &[u8], segments: &[u8]) -> Option> { + if !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } + let mut out = Vec::with_capacity(bytes.len() + segments.len()); + out.extend_from_slice(&[0xFF, 0xD8]); + let mut icc_segments = Some(segments); + let mut at = 2; + // The segments before the scan (SOS), each with its length; a marker without one ends them. + // Fill bytes (0xFF) before a marker are left out. + loop { + while bytes.get(at..at + 2) == Some(&[0xFF, 0xFF]) { + at += 1; + } + let (Some(&0xFF), Some(&marker)) = (bytes.get(at), bytes.get(at + 1)) else { return None }; + let app = (0xE0..=0xEF).contains(&marker); + if !app && let Some(s) = icc_segments.take() { + out.extend_from_slice(s); + } + if matches!(marker, 0xDA | 0xD8 | 0xD9 | 0x01 | 0xD0..=0xD7) { + break; + } + let len = usize::from(u16::from_be_bytes(bytes.get(at + 2..at + 4)?.try_into().ok()?)); + let segment = bytes.get(at..(at + 2).checked_add(len)?).filter(|_| len >= 2)?; + if !(marker == 0xE2 && segment.get(4..16) == Some(ICC_SEGMENT.as_slice())) { + out.extend_from_slice(segment); + } + at += segment.len(); + } + out.extend_from_slice(bytes.get(at..)?); + Some(out) +} + +#[cfg(test)] +mod tests { + use super::{jpeg_icc_profile, jpeg_with_icc, jpeg_without_icc}; + + fn minimal_jpeg() -> Vec { + let mut jpeg = Vec::new(); + jpeg.extend_from_slice(&[0xFF, 0xD8]); // SOI + jpeg.extend_from_slice(&[0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]); // APP0 + jpeg.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x0B, 8, 0, 1, 0, 1, 1, 1, 0x11, 0]); // SOF0 + jpeg.extend_from_slice(&[0xFF, 0xDA, 0x00, 0x08, 1, 1, 0, 0, 63, 0]); // SOS + jpeg.extend_from_slice(&[0x00, 0xFF, 0xD9]); // scan + EOI + jpeg + } + + #[test] + fn replaces_and_strips_jpeg_icc_segments() { + let base = minimal_jpeg(); + let icc_a = vec![0x11; 70_000]; + let with_a = jpeg_with_icc(&base, &icc_a).unwrap(); + assert_eq!(jpeg_icc_profile(&with_a), Some(icc_a)); + + let icc_b = b"short-profile"; + let with_b = jpeg_with_icc(&with_a, icc_b).unwrap(); + assert_eq!(jpeg_icc_profile(&with_b), Some(icc_b.to_vec())); + + let stripped = jpeg_without_icc(&with_b).unwrap(); + assert_eq!(jpeg_icc_profile(&stripped), None); + assert_eq!(stripped, base); + assert_eq!(jpeg_with_icc(&base, &[]), None); + } +} From 7a040c1f3bf5733f6526a7cf6b6e83b70f72c121 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 16:02:38 +0000 Subject: [PATCH 40/79] ci: the Workspace gate keeps compiled workspace crates on its Linux leg The Linux leg restores the newest rolling cache entry of the workspace crates (cache-workspace-crates), so a pull request rebuilds only the crates its change reaches. Each main run saves an entry of its own and cache-prune deletes the older ones; the midnight scheduled run builds from source and starts the entry afresh. gate.yml's cache-workspace-crates covers a whole call, so the macOS and Windows legs move to a call of their own with dependency-only entries. A select platforms job decides whether that call runs, since an empty leg list would fail it. To fit the 10 GB cache budget, the lint legs and the sonarcloud instrumented build keep no cache. --- .github/workflows/actions.lock | 10 ++- .github/workflows/sonarcloud.yml | 3 + .github/workflows/workspace.yml | 143 +++++++++++++++++++++++++------ scripts/test-workspace-tests.py | 15 +++- 4 files changed, 144 insertions(+), 27 deletions(-) diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index e78310f7f4..5996d0d2f7 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -108,7 +108,10 @@ workflows: - 'actions/checkout@v7.0.1' - 'step-security/dtolnay-rust-toolchain@v1.0.0' - 'step-security/harden-runner@v2.22.4' - '.github/workflows/workspace.yml': [] + '.github/workflows/workspace.yml': + - 'actions/checkout@v7.0.1' + - 'step-security/harden-runner@v2.22.4' + - 'storytold/craft-common-actions@d65d611f0ef67eaa94039351be5afce61102dbb0' dependencies: 'actions/cache@v6.1.0': ref: 'v6.1.0' @@ -150,3 +153,8 @@ dependencies: commit: 'sha1-76747d22a7567cc4438546a84f11bdf18e670ab8' owner_id: 88700172 repo_id: 1382753260 + 'storytold/craft-common-actions@d65d611f0ef67eaa94039351be5afce61102dbb0': + ref: 'main' + commit: 'sha1-d65d611f0ef67eaa94039351be5afce61102dbb0' + owner_id: 76897702 + repo_id: 1414429108 diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml index e40c1b4bc8..c03a3a0768 100644 --- a/.github/workflows/sonarcloud.yml +++ b/.github/workflows/sonarcloud.yml @@ -20,6 +20,9 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main with: pdf-test-fonts: true + # The instrumented build runs without a dependency cache: its 1.2 GB entry does not fit the + # repository's 10 GB cache budget beside the Workspace gate's. It runs on main only. + build-cache: false # The codec and format code behind features that are off by default. Without these the # coverage build never compiles it, and new code there reads as untested. cargo-features: >- diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index ff1d7ff5a6..e13d290a66 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -7,9 +7,10 @@ on: pull_request: workflow_dispatch: # A full run on main every 6 hours that is never cancelled, so the caches are saved while pushes - # to main cancel each other. + # to main cancel each other. The midnight run builds the Linux leg from source (`native`). schedule: - - cron: "17 */6 * * *" + - cron: "17 0 * * *" + - cron: "17 6,12,18 * * *" permissions: contents: read @@ -23,46 +24,73 @@ concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }} jobs: + # Whether this run needs the macOS and Windows legs. On a pull request they run only when it can + # change platform behaviour: a crate with platform cfg code or one that depends on it, the build + # setup, or a file outside the crates (craft-common-actions' select-platforms). The full-ci label + # runs them anyway from the next push or manual run; every other event runs them. + platforms: + name: select platforms + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + platform: ${{ steps.select.outputs.platform }} + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + # The merge commit and its first parent. + - uses: actions/checkout@v7.0.1 + if: github.event_name == 'pull_request' + with: + persist-credentials: false + fetch-depth: 2 + - id: select + uses: storytold/craft-common-actions/actions/select-platforms@d65d611f0ef67eaa94039351be5afce61102dbb0 + with: + os: '["ubuntu-latest","windows-latest","macos-latest"]' + select-os: '["windows-latest","macos-latest"]' + label: full-ci + + # The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each + # main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo + # rebuilds only the crates a change reaches. `cache-prune` keeps the newest entry. The midnight + # scheduled run builds from source (`cold-build`) and starts the entry afresh. The macOS and + # Windows legs keep a dependency-only entry: their workspace crates would not fit the 10 GB cache + # budget beside Linux's. The lint legs keep no cache (`lint-cache: false`) for the same reason; a + # cold lint leg is still shorter than its gate leg. native: name: Workspace uses: storytold/craft-common-actions/.github/workflows/gate.yml@main with: - os: '["ubuntu-latest","windows-latest","macos-latest"]' - # On a pull request, macOS and Windows run only when it can change platform behaviour: a - # crate with platform cfg code or one that depends on it, the build setup, or a file outside - # the crates (craft-common-actions' select-platforms). The full-ci label runs them anyway - # from the next push or manual run; pushes to main always run every leg. - select-os: '["windows-latest","macos-latest"]' - timeout-minutes: 120 + os: '["ubuntu-latest"]' + cache-workspace-crates: true + cold-build: ${{ github.event.schedule == '17 0 * * *' }} + lint-cache: false + timeout-minutes: &timeout 120 # Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml). - tools: cargo-nextest@0.9.150 + tools: &tools cargo-nextest@0.9.150 packages: mesa-vulkan-drivers libvulkan1 - craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + craft-fonts-ref: &craft-fonts b076417b5880bd4154bd22f00695b1d28c6bea83 linux-env: WGPU_BACKEND=vulkan # Test binaries without debug info or symbols: about a third of the size, and a panic still # names its file and line. dev-strip: true - # No debuginfo on Windows: writing PDBs for every test binary is a large part of its link - # time. A panic still names its file and line; only backtrace frames lose theirs, and the - # Linux and macOS legs keep line tables. - windows-env: | - CRAFT_PRINT_REQUIRE_QUEUE=1 - CARGO_PROFILE_DEV_DEBUG=0 # The fuzz-style tests run a fraction of their cases here: every hostile-input hammer and # sweep 1/8 (craft-testkit's CRAFT_HOSTILE_DIVISOR), every proptest without its own case # count 64 cases instead of 256. nightly.yml runs them all in full. - env: | + env: &env | CRAFT_PRINT_REQUIRE_QUEUE=0 CRAFT_HOSTILE_DIVISOR=8 PROPTEST_CASES=64 - setup-command: bash scripts/ci-test-inputs.sh + setup-command: &setup bash scripts/ci-test-inputs.sh # The PhotoCraft corpora, keyed on the script that pins them: a hit skips the PhotoCraft # checkout and its xtask build (1:51 on Windows). - cache-paths: .test-inputs/photocraft/corpus - cache-key: photocraft-corpus - cache-key-files: scripts/ci-test-inputs.sh + cache-paths: &cache-paths .test-inputs/photocraft/corpus + cache-key: &cache-key photocraft-corpus + cache-key-files: &cache-key-files scripts/ci-test-inputs.sh # A `lint ()` leg beside each `gate ()` leg, so clippy is off the tests' critical path. - lint-command: | + lint-command: &lint | if [ "$RUNNER_OS" = Linux ]; then python3 scripts/test-workspace-concurrency.py python3 scripts/test-workspace-tests.py @@ -75,7 +103,7 @@ jobs: fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - command: | + command: &command | # The tests run once, with every feature, in parallel across test binaries; nextest skips # doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose # tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's @@ -85,6 +113,34 @@ jobs: cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci --example stubicc --example h264_h264enc_bench cargo test --workspace --doc --all-features --locked cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests + + # The macOS and Windows legs, when `platforms` says this run needs them, with the Linux leg's + # inputs. + native-platforms: + name: Workspace + needs: platforms + if: needs.platforms.outputs.platform == 'true' + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["windows-latest","macos-latest"]' + lint-cache: false + timeout-minutes: *timeout + tools: *tools + craft-fonts-ref: *craft-fonts + dev-strip: true + # No debuginfo on Windows: writing PDBs for every test binary is a large part of its link + # time. A panic still names its file and line; only backtrace frames lose theirs, and the + # Linux and macOS legs keep line tables. + windows-env: | + CRAFT_PRINT_REQUIRE_QUEUE=1 + CARGO_PROFILE_DEV_DEBUG=0 + env: *env + setup-command: *setup + cache-paths: *cache-paths + cache-key: *cache-key + cache-key-files: *cache-key-files + lint-command: *lint + command: *command windows-command: | powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' cargo nextest run --workspace --all-features --locked --profile ci --lib --bins --tests @@ -92,6 +148,45 @@ jobs: cargo test --workspace --doc --all-features --locked cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci --lib --bins --tests + # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), and + # every run restores only the newest. This deletes the older ones as soon as the Linux leg is + # done, instead of leaving them to the 10 GB budget's eviction, which would evict other entries + # too. The only job with `actions: write`; it checks out and runs nothing from the repository. + cache-prune: + name: cache prune + needs: native + if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@v2.22.4 + with: + egress-policy: audit + - name: Delete all but the newest rolling entry of each job and runner + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + # `-rust---crates-----...`, newest first. + gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \ + --jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches" + declare -A kept + while read -r id key; do + [[ "$key" =~ ^.+-rust-[0-9a-f]{64}-(.+-crates-[A-Za-z_]+-[a-z0-9]+)-[0-9]+-[0-9]+- ]] || continue + entry=${BASH_REMATCH[1]} + if [ -n "${kept[$entry]:-}" ]; then + echo "delete $key" + gh cache delete "$id" --repo "$REPO" + else + kept[$entry]=1 + echo "keep $key" + fi + done < "$RUNNER_TEMP/caches" + msrv: name: Rust 1.95 uses: storytold/craft-common-actions/.github/workflows/gate.yml@main diff --git a/scripts/test-workspace-tests.py b/scripts/test-workspace-tests.py index a50d2370cf..711c8f1cd6 100644 --- a/scripts/test-workspace-tests.py +++ b/scripts/test-workspace-tests.py @@ -13,7 +13,9 @@ WORKFLOW = ROOT / ".github/workflows/workspace.yml" def block(text, name): - match = re.search(r"^ " + re.escape(name) + r": \|\n((?: .*\n|\n)+)", text, re.M) + # The Linux call names each shared block with a YAML anchor (`command: &command |`), and the + # macOS and Windows call refers to it, so this first block is the one every leg runs. + match = re.search(r"^ " + re.escape(name) + r": (?:&[\w-]+ )?\|\n((?: .*\n|\n)+)", text, re.M) if match is None: raise AssertionError(f"missing command block: {name}") return "\n".join(line[8:] for line in match[1].splitlines()) @@ -174,7 +176,16 @@ class WorkspaceTests(unittest.TestCase): def test_workflow_stays_shared_and_keeps_platform_gates(self): source = WORKFLOW.read_text() self.assertIn("uses: storytold/craft-common-actions/.github/workflows/gate.yml@main", source) - self.assertIn('os: \'["ubuntu-latest","windows-latest","macos-latest"]\'', source) + self.assertIn('os: \'["ubuntu-latest"]\'', source) + self.assertIn('os: \'["windows-latest","macos-latest"]\'', source) + self.assertIn("if: needs.platforms.outputs.platform == 'true'", source) + # The macOS and Windows legs run the Linux leg's blocks, not copies of them. + self.assertIn(" lint-command: &lint |\n", source) + self.assertIn(" command: &command |\n", source) + self.assertIn(" lint-command: *lint\n", source) + self.assertIn(" command: *command\n", source) + # Only the Linux leg keeps workspace crates; the cache budget has no room for the others. + self.assertEqual(source.count("cache-workspace-crates: true"), 1) self.assertIn(" msrv:", source) self.assertIn(" wasm:", source) self.assertIn("python3 scripts/test-workspace-tests.py", block(source, "lint-command")) From 45da77942bd69f8855d35111e8de01d388fb0681 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 11:52:55 -0500 Subject: [PATCH 41/79] svg: add parse_path_with_quads preserving quadratic segments --- crates/svg/src/path_data.rs | 95 +++++++++++++++++++++++++++++++------ 1 file changed, 81 insertions(+), 14 deletions(-) diff --git a/crates/svg/src/path_data.rs b/crates/svg/src/path_data.rs index 8db13faa28..16d2f3de5b 100644 --- a/crates/svg/src/path_data.rs +++ b/crates/svg/src/path_data.rs @@ -125,6 +125,26 @@ pub enum Segment { Arc { rx: f64, ry: f64, rot: f64, large: bool, sweep: bool, end: Point }, } +/// One `M …` run of a `d` attribute, preserving quadratic (`Q`/`T`) segments. +#[derive(Debug, Clone, PartialEq)] +pub struct QuadSubpath { + /// Start point. + pub start: Point, + /// Segments in drawing order. + pub segs: Vec, + /// Whether a close-path command closed this subpath. + pub closed: bool, +} + +/// A path segment that preserves quadratic Bézier curves alongside lines, cubics, and arcs. +#[derive(Debug, Clone, PartialEq)] +pub enum QuadSegment { + Line(Point), + Quad(Point, Point), + Cubic(Point, Point, Point), + Arc { rx: f64, ry: f64, rot: f64, large: bool, sweep: bool, end: Point }, +} + /// Tokens of a `d` attribute: command letters and numbers, in order. enum Tok { Cmd(u8), @@ -174,15 +194,51 @@ impl<'a> Tokenizer<'a> { } } -/// Split `d` into subpaths, resolving relative commands and the S/T control reflections. +/// Split `d` into subpaths, resolving relative commands and S/T control reflections while +/// raising quadratic (`Q`/`T`) segments to cubics. pub fn parse_path(d: &str) -> Result> { + Ok(parse_path_with_quads(d)? + .into_iter() + .map(|sub| { + let mut cur = sub.start; + let segs = sub + .segs + .into_iter() + .map(|seg| match seg { + QuadSegment::Line(p) => { + cur = p; + Segment::Line(p) + } + QuadSegment::Quad(q, p) => { + let out = Segment::Cubic(cur + (q - cur) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p); + cur = p; + out + } + QuadSegment::Cubic(c1, c2, p) => { + cur = p; + Segment::Cubic(c1, c2, p) + } + QuadSegment::Arc { rx, ry, rot, large, sweep, end } => { + cur = end; + Segment::Arc { rx, ry, rot, large, sweep, end } + } + }) + .collect(); + Subpath { start: sub.start, segs, closed: sub.closed } + }) + .collect()) +} + +/// Split `d` into subpaths, resolving relative commands and S/T control reflections while +/// preserving quadratic (`Q`/`T`) segments. +pub fn parse_path_with_quads(d: &str) -> Result> { let mut tk = Tokenizer::new(d); let mut lookahead: Option = None; let mut cmd = 0u8; let mut cur = Point::ZERO; let mut start = Point::ZERO; - let mut segs: Vec = Vec::new(); - let mut out: Vec = Vec::new(); + let mut segs: Vec = Vec::new(); + let mut out: Vec = Vec::new(); let closed = false; let mut prev_cubic: Option = None; let mut prev_quad: Option = None; @@ -214,7 +270,7 @@ pub fn parse_path(d: &str) -> Result> { Tok::Cmd(c) => { if c.eq_ignore_ascii_case(&b'z') { if !segs.is_empty() { - out.push(Subpath { start, segs, closed: true }); + out.push(QuadSubpath { start, segs, closed: true }); segs = Vec::new(); } cur = start; @@ -264,7 +320,7 @@ pub fn parse_path(d: &str) -> Result> { match abs { b'M' => { if !segs.is_empty() { - out.push(Subpath { start, segs, closed: false }); + out.push(QuadSubpath { start, segs, closed: false }); segs = Vec::new(); } cur = point(args[0], args[1]); @@ -275,25 +331,25 @@ pub fn parse_path(d: &str) -> Result> { } b'L' => { cur = point(args[0], args[1]); - segs.push(Segment::Line(cur)); + segs.push(QuadSegment::Line(cur)); prev_cubic = None; prev_quad = None; } b'H' => { cur = Point::new(if rel { cur.x + args[0] } else { args[0] }, cur.y); - segs.push(Segment::Line(cur)); + segs.push(QuadSegment::Line(cur)); prev_cubic = None; prev_quad = None; } b'V' => { cur = Point::new(cur.x, if rel { cur.y + args[0] } else { args[0] }); - segs.push(Segment::Line(cur)); + segs.push(QuadSegment::Line(cur)); prev_cubic = None; prev_quad = None; } b'C' => { let (c1, c2, p) = (point(args[0], args[1]), point(args[2], args[3]), point(args[4], args[5])); - segs.push(Segment::Cubic(c1, c2, p)); + segs.push(QuadSegment::Cubic(c1, c2, p)); prev_cubic = Some(c2); prev_quad = None; cur = p; @@ -301,14 +357,14 @@ pub fn parse_path(d: &str) -> Result> { b'S' => { let c1 = prev_cubic.map_or(cur, |c2| cur * 2.0 - c2); let (c2, p) = (point(args[0], args[1]), point(args[2], args[3])); - segs.push(Segment::Cubic(c1, c2, p)); + segs.push(QuadSegment::Cubic(c1, c2, p)); prev_cubic = Some(c2); prev_quad = None; cur = p; } b'Q' => { let (q, p) = (point(args[0], args[1]), point(args[2], args[3])); - segs.push(Segment::Cubic(cur + (q - cur) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p)); + segs.push(QuadSegment::Quad(q, p)); prev_quad = Some(q); prev_cubic = None; cur = p; @@ -316,14 +372,14 @@ pub fn parse_path(d: &str) -> Result> { b'T' => { let reflect = prev_quad.map_or(cur, |q| cur * 2.0 - q); let p = point(args[0], args[1]); - segs.push(Segment::Cubic(cur + (reflect - cur) * (2.0 / 3.0), p + (reflect - p) * (2.0 / 3.0), p)); + segs.push(QuadSegment::Quad(reflect, p)); prev_quad = Some(reflect); prev_cubic = None; cur = p; } b'A' => { let end = point(args[5], args[6]); - segs.push(Segment::Arc { rx: args[0].abs(), ry: args[1].abs(), rot: args[2], large: args[3] != 0.0, sweep: args[4] != 0.0, end }); + segs.push(QuadSegment::Arc { rx: args[0].abs(), ry: args[1].abs(), rot: args[2], large: args[3] != 0.0, sweep: args[4] != 0.0, end }); cur = end; prev_cubic = None; prev_quad = None; @@ -339,7 +395,7 @@ pub fn parse_path(d: &str) -> Result> { } } if !segs.is_empty() { - out.push(Subpath { start, segs, closed }); + out.push(QuadSubpath { start, segs, closed }); } Ok(out) } @@ -443,6 +499,17 @@ mod tests { assert_eq!(paths[0].segs[1], Segment::Cubic(Point::new(8.0, -2.0), Point::new(10.0, -2.0), Point::new(12.0, 0.0))); } + #[test] + fn parse_path_with_quads_preserves_quadratic_control_points() { + let paths = parse_path_with_quads("M0 10 Q5 20 10 10 T20 10 Z").unwrap(); + assert_eq!(paths.len(), 1); + assert!(paths[0].closed); + assert_eq!( + paths[0].segs, + vec![QuadSegment::Quad(Point::new(5.0, 20.0), Point::new(10.0, 10.0)), QuadSegment::Quad(Point::new(15.0, 0.0), Point::new(20.0, 10.0)),] + ); + } + #[test] fn close_resets_smooth_control_history() { // After Z, S must not reflect the preceding C's control (20,20) → (0,0). From 5c496f6e962fcccd8ba91704994c4c06c2fc6a6f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 12:27:57 -0500 Subject: [PATCH 42/79] zip: add SeekableArchive streaming reader and seekable entry-count guard (#2406) --- crates/zip/src/guard.rs | 97 +++++++++++- crates/zip/src/lib.rs | 4 +- crates/zip/src/seekable.rs | 296 ++++++++++++++++++++++++++++++++++++- 3 files changed, 392 insertions(+), 5 deletions(-) diff --git a/crates/zip/src/guard.rs b/crates/zip/src/guard.rs index 553e1532f4..312a3bbaf4 100644 --- a/crates/zip/src/guard.rs +++ b/crates/zip/src/guard.rs @@ -8,6 +8,8 @@ //! reader's limit is refused before `zip` parses anything. Anything else that is wrong is left for //! `zip` to report. +use std::io::{Read, Seek, SeekFrom}; + use crate::Error; const EOCD: &[u8; 4] = b"PK\x05\x06"; @@ -74,6 +76,86 @@ pub fn check_entry_count(bytes: &[u8], max_entries: u64) -> Result<(), Error> { Ok(()) } +/// Like [`check_entry_count`], but reads only the trailing end records and any referenced ZIP64 +/// end record from a seekable stream without buffering the archive in memory. +pub fn check_entry_count_seekable(reader: &mut R, max_entries: u64) -> Result<(), Error> { + let io_err = |e: std::io::Error| Error::NotZip(e.to_string()); + let len = reader.seek(SeekFrom::End(0)).map_err(io_err)?; + let tail_len = len.min(22 + u64::from(u16::MAX)); + let tail_start = len - tail_len; + let tail_len_usize = usize::try_from(tail_len).map_err(|_| Error::NotZip("tail too large".into()))?; + reader.seek(SeekFrom::Start(tail_start)).map_err(io_err)?; + let mut tail = vec![0u8; tail_len_usize]; + reader.read_exact(&mut tail).map_err(io_err)?; + + let u16_at = |b: &[u8], at: usize| b.get(at..at.checked_add(2)?).map(|s| u16::from_le_bytes([s[0], s[1]])); + let u32_at = |b: &[u8], at: usize| b.get(at..at.checked_add(4)?).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])); + let u64_at = |b: &[u8], at: usize| b.get(at..at.checked_add(8)?).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(u64::from_le_bytes); + let refuse = + |n: u64| -> Result<(), Error> { if n > max_entries { Err(Error::TooManyEntries { declared: n, limit: max_entries }) } else { Ok(()) } }; + + let mut end = tail.len(); + let mut seen = 0; + while let Some(at) = tail.get(..end).and_then(|b| b.windows(4).rposition(|w| w == EOCD)) { + end = at; + seen += 1; + if seen > MAX_END_RECORDS { + return Err(Error::TooManyEndRecords(MAX_END_RECORDS)); + } + let Some(comment) = u16_at(&tail, at + 20) else { continue }; + if at + 22 + usize::from(comment) > tail.len() { + continue; + } + let (Some(on_disk), Some(total), Some(cd_offset)) = (u16_at(&tail, at + 8), u16_at(&tail, at + 10), u32_at(&tail, at + 16)) else { + continue; + }; + let zip64 = total == u16::MAX || u32_at(&tail, at + 12) == Some(u32::MAX) || cd_offset == u32::MAX; + if zip64 + && let Some(locator) = at.checked_sub(20) + && tail.get(locator..locator + 4) == Some(EOCD64_LOCATOR.as_slice()) + { + let (Some(eocd64), Some(disks)) = (u64_at(&tail, locator + 8), u32_at(&tail, locator + 16)) else { continue }; + let locator_pos = tail_start + locator as u64; + if eocd64 >= locator_pos || disks > 1 { + continue; + } + let span = (locator_pos - eocd64).min(65_536); + let mut buf; + let slice = if let Some(in_tail) = eocd64.checked_sub(tail_start).and_then(|o| usize::try_from(o).ok()) { + tail.get(in_tail..locator).unwrap_or_default() + } else { + let span_usize = usize::try_from(span).unwrap_or(65_536); + reader.seek(SeekFrom::Start(eocd64)).map_err(io_err)?; + buf = vec![0u8; span_usize]; + reader.read_exact(&mut buf).map_err(io_err)?; + &buf + }; + for (i, _) in slice.windows(4).enumerate().filter(|(_, w)| *w == EOCD64) { + refuse(u64_at(slice, i + 24).unwrap_or(0).max(u64_at(slice, i + 32).unwrap_or(0)))?; + } + continue; + } + if total == 0 { + return Ok(()); + } + let cd = u64::from(cd_offset); + let at_pos = tail_start + at as u64; + if cd < at_pos { + let has_cd = if let Some(in_tail) = cd.checked_sub(tail_start).and_then(|o| usize::try_from(o).ok()) { + tail.get(in_tail..at).is_some_and(|b| b.windows(4).any(|w| w == CENTRAL_HEADER)) + } else { + let mut sig = [0u8; 4]; + reader.seek(SeekFrom::Start(cd)).map_err(io_err)?; + reader.read_exact(&mut sig).is_ok() && &sig == CENTRAL_HEADER + }; + if has_cd { + return refuse(u64::from(on_disk.max(total))); + } + } + } + Ok(()) +} + /// A package of one empty stored file, `a`, whose central directory lists it `entries` times (at /// most as many as fit in 64 MiB) under a ZIP64 end record that declares them all: `zip` /// parses and keeps every one of them before its caller can count them. Regression input for the @@ -125,7 +207,8 @@ pub fn zip64_entry_count_sample(entries: u64) -> Vec { #[cfg(test)] mod tests { - use super::{CENTRAL_HEADER, EOCD, check_entry_count as check, zip64_entry_count_sample}; + use super::{CENTRAL_HEADER, EOCD, check_entry_count as check, check_entry_count_seekable, zip64_entry_count_sample}; + use crate::Error; /// A plain package's tail: one central header at 0, then an end record declaring `entries`. @@ -200,4 +283,16 @@ mod tests { let f: Vec = (0..20).flat_map(|_| EOCD.iter().copied().chain(record)).collect(); assert_eq!(check(&f, 20_000), Err(Error::TooManyEndRecords(16))); } + + #[test] + fn seekable_entry_count_matches_in_memory_guard() { + use std::io::Cursor; + + let sample = zip64_entry_count_sample(20_001); + assert_eq!(check_entry_count_seekable(&mut Cursor::new(&sample), 20_000), Err(Error::TooManyEntries { declared: 20_001, limit: 20_000 })); + assert!(check_entry_count_seekable(&mut Cursor::new(zip64_entry_count_sample(5)), 20_000).is_ok()); + + let padded = plain(30_000, &vec![b'c'; 65_000]); + assert_eq!(check_entry_count_seekable(&mut Cursor::new(&padded), 20_000), Err(Error::TooManyEntries { declared: 30_000, limit: 20_000 })); + } } diff --git a/crates/zip/src/lib.rs b/crates/zip/src/lib.rs index ff8ce17a63..e8f8764dea 100644 --- a/crates/zip/src/lib.rs +++ b/crates/zip/src/lib.rs @@ -34,11 +34,11 @@ mod seekable; mod write; pub use archive::{Archive, Limits}; -pub use guard::check_entry_count; #[cfg(any(test, feature = "test-support"))] pub use guard::zip64_entry_count_sample; +pub use guard::{check_entry_count, check_entry_count_seekable}; pub use metadata_reader::{Indexing, MetadataReader}; -pub use seekable::{InspectError, inspect_seekable}; +pub use seekable::{EntryReader, InspectError, SeekableArchive, SeekableLimits, inspect_seekable}; pub use write::{Compression, Writer}; /// The payload of a ZIP's first entry when it is a stored file named `mimetype` of at most 256 diff --git a/crates/zip/src/seekable.rs b/crates/zip/src/seekable.rs index 2750a0123d..dfed9d643b 100644 --- a/crates/zip/src/seekable.rs +++ b/crates/zip/src/seekable.rs @@ -1,6 +1,9 @@ -//! Checks for an already indexed, seekable ZIP archive. +//! Checks and streaming reader for seekable ZIP archives. -use std::io::{Read, Seek}; +use std::borrow::Cow; +use std::io::{self, Read, Seek}; + +use crate::{Budget, Error, MetadataReader, check_entry_count_seekable}; /// Why an indexed seekable archive exceeded its caller's limits. #[derive(Debug, thiserror::Error)] @@ -33,6 +36,222 @@ pub fn inspect_seekable(archive: &mut zip::ZipArchive, max_en Ok(()) } +/// What a [`SeekableArchive`] refuses to exceed. All numbers are the caller's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SeekableLimits { + /// Most entries the archive may declare. + pub max_entries: u64, + /// Most bytes of trailing metadata (central directory and end records) read while indexing. + pub max_metadata_bytes: u64, + /// Most bytes all the entries read from the archive may expand to together. + pub max_total_bytes: u64, +} + +/// A seekable ZIP archive that indexes only the trailing metadata and streams entry payloads +/// without buffering the archive or large entries in memory. +pub struct SeekableArchive { + zip: zip::ZipArchive>, + budget: Budget, +} + +impl SeekableArchive { + /// Indexes the trailing metadata of `reader`. The declared entry count is checked before `zip` + /// allocates for the central directory, and indexing is bounded by + /// [`SeekableLimits::max_metadata_bytes`]. + pub fn open(mut reader: R, limits: SeekableLimits) -> Result { + check_entry_count_seekable(&mut reader, limits.max_entries)?; + let (meta_reader, indexing) = MetadataReader::new(reader, limits.max_metadata_bytes).map_err(|e| Error::NotZip(e.to_string()))?; + let zip = zip::ZipArchive::new(meta_reader).map_err(|e| Error::NotZip(e.to_string()))?; + indexing.finish(); + let found = zip.len() as u64; + if found > limits.max_entries { + return Err(Error::TooManyEntries { declared: found, limit: limits.max_entries }); + } + Ok(Self { zip, budget: Budget::new("archive", limits.max_total_bytes) }) + } + + /// The number of distinct entry names. + pub fn len(&self) -> usize { + self.zip.len() + } + + pub fn is_empty(&self) -> bool { + self.zip.is_empty() + } + + /// The name at `index`, copied on demand. + pub fn entry_name(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + let name = file.name().map_err(|error| Error::NotZip(error.to_string()))?; + Ok(Some(name.into_owned())) + } + + /// Whether the entry at `index` is a directory according to ZIP filename conventions. + pub fn entry_is_dir(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + Ok(Some(file.is_dir())) + } + + /// Declared decoded and compressed sizes at `index`, without name lookup. + pub fn entry_sizes(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|e| Error::NotZip(e.to_string()))?; + Ok(Some((file.size(), file.compressed_size()))) + } + + /// Do two entries' compressed data ranges overlap? + pub fn has_overlapping_files(&mut self) -> Result { + self.zip.has_overlapping_files().map_err(|e| Error::NotZip(e.to_string())) + } + + /// The entry names in the archive's order, folders included. Non-UTF-8 names are omitted. + pub fn names(&self) -> impl Iterator> { + self.zip.file_names().filter_map(Result::ok) + } + + /// Is there an entry `name` (exactly as stored)? + pub fn contains(&self, name: &str) -> bool { + self.zip.index_for_name(name).is_some() + } + + /// The size entry `name` declares. It is a claim, not a measurement. + pub fn declared_size(&mut self, name: &str) -> Option { + let index = self.zip.index_for_name(name)?; + self.zip.by_index_raw(index).ok().map(|f| f.size()) + } + + /// The size entry `name` takes in the archive, compressed. + pub fn compressed_size(&mut self, name: &str) -> Option { + let index = self.zip.index_for_name(name)?; + self.zip.by_index_raw(index).ok().map(|f| f.compressed_size()) + } + + /// Is `name` stored without compression? + pub fn is_stored(&mut self, name: &str) -> Option { + let index = self.zip.index_for_name(name)?; + self.zip.by_index_raw(index).ok().map(|f| f.compression() == zip::CompressionMethod::Stored) + } + + /// Open entry `name` for streaming reads, or `None` when there is no such entry. + /// + /// The entry may declare and expand to at most `max` bytes, and at most what is left of + /// [`SeekableLimits::max_total_bytes`]. The returned [`EntryReader`] enforces the size cap and + /// verifies the CRC-32 on EOF, charging [`Self::budget`] only when the full entry is read. + pub fn open_entry(&mut self, name: &str, max: u64) -> Result>, Error> { + let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; + self.open_entry_index_named(index, name, max) + } + + /// Open the entry at `index` for streaming reads under the same rules as [`Self::open_entry`]. + pub fn open_entry_index(&mut self, index: usize, max: u64) -> Result>, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let name = self.entry_name(index)?.unwrap_or_default(); + self.open_entry_index_named(index, &name, max) + } + + fn open_entry_index_named(&mut self, index: usize, name: &str, max: u64) -> Result>, Error> { + let file = self.zip.by_index(index).map_err(|e| Error::Entry { name: name.to_string(), msg: e.to_string() })?; + let declared = file.size(); + if declared > max { + return Err(Error::EntryTooLarge { name: name.to_string(), limit: max }); + } + if declared > self.budget.remaining() { + return Err(Error::BudgetSpent { name: name.to_string(), limit: self.budget.limit() }); + } + Ok(Some(EntryReader { file, budget: &mut self.budget, declared, limit: declared, read: 0, finished: false })) + } + + /// Read all bytes of entry `name` into memory, or `None` when there is no such entry. + pub fn read(&mut self, name: &str, max: u64) -> Result>, Error> { + let Some(index) = self.zip.index_for_name(name) else { return Ok(None) }; + self.read_index_named(index, name, max) + } + + /// Read all bytes of the entry at `index` into memory. + pub fn read_index(&mut self, index: usize, max: u64) -> Result>, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let name = self.entry_name(index)?.unwrap_or_default(); + self.read_index_named(index, &name, max) + } + + fn read_index_named(&mut self, index: usize, name: &str, max: u64) -> Result>, Error> { + let Some(mut reader) = self.open_entry_index_named(index, name, max)? else { return Ok(None) }; + let mut out = Vec::with_capacity(usize::try_from(reader.declared).unwrap_or(64 * 1024).min(64 * 1024)); + reader.read_to_end(&mut out).map_err(|e| Error::Entry { name: name.to_string(), msg: e.to_string() })?; + Ok(Some(out)) + } + + /// The total budget: what the entries read so far have used, and what is left. + pub fn budget(&self) -> &Budget { + &self.budget + } + + /// The total budget, for a caller with its own charging rule. + pub fn budget_mut(&mut self) -> &mut Budget { + &mut self.budget + } +} + +/// Streaming reader for a single entry opened from [`SeekableArchive`]. +/// +/// Enforces the declared and caller-provided byte limits and charges the archive's [`Budget`] +/// once the full entry has been read and its CRC-32 verified. +pub struct EntryReader<'a, R: Read> { + file: zip::read::ZipFile<'a, MetadataReader>, + budget: &'a mut Budget, + declared: u64, + limit: u64, + read: u64, + finished: bool, +} + +impl EntryReader<'_, R> { + /// The uncompressed size declared by the entry header. + pub fn declared_size(&self) -> u64 { + self.declared + } +} + +impl Read for EntryReader<'_, R> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + if self.finished || buf.is_empty() { + return Ok(0); + } + let remaining = self.limit.saturating_sub(self.read); + let max_read = usize::try_from(remaining.saturating_add(1)).unwrap_or(usize::MAX).min(buf.len()); + let n = self.file.read(&mut buf[..max_read])?; + if n == 0 { + if self.read < self.declared { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + format!("entry ended after {} bytes, declared {}", self.read, self.declared), + )); + } + self.budget.charge(self.read).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?; + self.finished = true; + return Ok(0); + } + let next = self.read.saturating_add(n as u64); + if next > self.limit { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("entry exceeds declared size of {} bytes", self.limit))); + } + self.read = next; + Ok(n) + } +} + #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { @@ -72,4 +291,77 @@ mod tests { let empty = zip::ZipWriter::new(Cursor::new(Vec::new())).finish().unwrap().into_inner(); assert!(inspect_seekable(&mut zip::ZipArchive::new(Cursor::new(empty)).unwrap(), 0, 0).is_ok()); } + + #[test] + fn seekable_archive_streams_stored_and_deflated_entries_within_limits() { + let mut writer = crate::Writer::new(); + let big: Vec = (0..50_000u32).flat_map(|i| (i % 251).to_le_bytes()).collect(); + writer.add("a.bin", &big, crate::Compression::Deflated).unwrap(); + writer.add("b.bin", b"hello stored", crate::Compression::Stored).unwrap(); + let bytes = writer.finish().unwrap(); + + let limits = SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 250_000 }; + let mut archive = SeekableArchive::open(Cursor::new(bytes), limits).unwrap(); + assert_eq!(archive.len(), 2); + assert!(archive.contains("a.bin")); + assert_eq!(archive.declared_size("a.bin"), Some(big.len() as u64)); + + // Stream in small chunks without loading via Vec in one shot. + let mut reader = archive.open_entry("a.bin", big.len() as u64).unwrap().unwrap(); + let mut out = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + let n = reader.read(&mut chunk).unwrap(); + if n == 0 { + break; + } + out.extend_from_slice(&chunk[..n]); + } + assert_eq!(out, big); + drop(reader); + assert_eq!(archive.budget().used(), big.len() as u64); + + let b = archive.read("b.bin", 100).unwrap().unwrap(); + assert_eq!(b, b"hello stored"); + assert_eq!(archive.budget().used(), big.len() as u64 + 12); + } + + #[test] + fn seekable_archive_enforces_entry_count_size_budget_and_crc() { + let sample = crate::zip64_entry_count_sample(20_001); + let err = SeekableArchive::open( + Cursor::new(sample), + SeekableLimits { max_entries: 20_000, max_metadata_bytes: 16 << 20, max_total_bytes: 1 << 20 }, + ) + .err() + .unwrap(); + assert!(matches!(err, Error::TooManyEntries { declared: 20_001, limit: 20_000 }), "{err:?}"); + + let mut writer = crate::Writer::new(); + writer.add("cat.lrcat", &[7u8; 1024], crate::Compression::Deflated).unwrap(); + let bytes = writer.finish().unwrap(); + + // Entry larger than per-entry max is refused before reading. + let mut archive = + SeekableArchive::open(Cursor::new(&bytes), SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 2048 }) + .unwrap(); + assert!(matches!(archive.open_entry("cat.lrcat", 1023), Err(Error::EntryTooLarge { limit: 1023, .. }))); + assert_eq!(archive.budget().used(), 0); + + // Entry larger than remaining budget is refused. + let mut tight = + SeekableArchive::open(Cursor::new(&bytes), SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 512 }).unwrap(); + assert!(matches!(tight.open_entry("cat.lrcat", 2048), Err(Error::BudgetSpent { limit: 512, .. }))); + + // Corrupted payload fails CRC check and does not charge budget. + let mut bad = bytes.clone(); + bad[45] ^= 0xFF; + let mut bad_archive = + SeekableArchive::open(Cursor::new(&bad), SeekableLimits { max_entries: 10, max_metadata_bytes: 16_384, max_total_bytes: 2048 }).unwrap(); + let mut reader = bad_archive.open_entry("cat.lrcat", 2048).unwrap().unwrap(); + let mut sink = Vec::new(); + assert!(reader.read_to_end(&mut sink).is_err()); + drop(reader); + assert_eq!(bad_archive.budget().used(), 0); + } } From 41a9edd001aae1ad497628a4109ad733ce68c587 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 13:11:14 -0500 Subject: [PATCH 43/79] image-codecs: keep resolution probe fallback and container-only WebP EXIF scan (#2409) --- crates/image-codecs/src/codecs/jpeg.rs | 7 ++-- crates/image-codecs/src/resolution_probe.rs | 26 +++++++++++-- .../src/resolution_probe_tests.rs | 39 ++++++++++++++++++- 3 files changed, 64 insertions(+), 8 deletions(-) diff --git a/crates/image-codecs/src/codecs/jpeg.rs b/crates/image-codecs/src/codecs/jpeg.rs index 989956182d..7ab5ad9cf6 100644 --- a/crates/image-codecs/src/codecs/jpeg.rs +++ b/crates/image-codecs/src/codecs/jpeg.rs @@ -278,9 +278,10 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { } m.held_coefficients = sof.map_or(0, |(marker, seg)| held_coefficients(marker, seg, scan_components)); m.dpi = photoshop_resolution(&photoshop) - .or_else(|| m.xmp.as_deref().and_then(xmp_resolution)) - .or_else(|| m.exif.as_deref().and_then(exif_resolution)) - .or(jfif_dpi); + .filter(|&d| crate::resolution_probe::usable(d)) + .or_else(|| m.xmp.as_deref().and_then(xmp_resolution).filter(|&d| crate::resolution_probe::usable(d))) + .or_else(|| m.exif.as_deref().and_then(exif_resolution).filter(|&d| crate::resolution_probe::usable(d))) + .or_else(|| jfif_dpi.filter(|&d| crate::resolution_probe::usable(d))); m.photoshop = Some(photoshop).filter(|p| !p.is_empty()); if !icc_parts.is_empty() { icc_parts.sort_by_key(|p| p.0); diff --git a/crates/image-codecs/src/resolution_probe.rs b/crates/image-codecs/src/resolution_probe.rs index f7b9aff83f..87729f18ec 100644 --- a/crates/image-codecs/src/resolution_probe.rs +++ b/crates/image-codecs/src/resolution_probe.rs @@ -17,7 +17,7 @@ //! non-positive or past [`MAX_PPI`] gives `None`, so the caller keeps its own default. use crate::Limits; -use crate::codecs::{jpeg, png, webp}; +use crate::codecs::{jpeg, png}; use crate::resolution::exif_resolution; /// Resolutions above this many pixels per inch are treated as corrupt. @@ -102,10 +102,28 @@ fn png_exif(bytes: &[u8]) -> Option<(f32, f32)> { exif_resolution(&exif?) } -/// The resolution of a WebP's `EXIF` chunk, read by the decoder's own container probe. +/// The resolution of a WebP's `EXIF` chunk, read from the RIFF container within its declared size. fn webp_exif(bytes: &[u8]) -> Option<(f32, f32)> { - let (_, _, exif) = webp::probe(bytes, &Limits::default()).ok()?; - exif_resolution(&exif?) + let riff = usize::try_from(le_u32(bytes, 4)?).ok()?; + let end = 8usize.checked_add(riff)?.min(bytes.len()); + let mut pos = 12usize; + for _ in 0..MAX_CHUNKS { + let kind = bytes.get(pos..pos.checked_add(4)?)?; + let size = usize::try_from(le_u32(bytes, pos.checked_add(4)?)?).ok()?; + let data = pos.checked_add(8)?; + if data.checked_add(size)? > end { + return None; + } + if kind == b"EXIF" { + let exif = bytes.get(data..data + size)?; + let tiff = exif.strip_prefix(b"Exif\0\0").unwrap_or(exif); + if let Some(dpi) = exif_resolution(tiff).filter(|&d| usable(d)) { + return Some(dpi); + } + } + pos = data.checked_add(size.checked_add(size & 1)?)?; + } + None } /// BMP: the info header size at 14 (40 or more for a header with resolution fields), then the diff --git a/crates/image-codecs/src/resolution_probe_tests.rs b/crates/image-codecs/src/resolution_probe_tests.rs index 65a7978539..1a650ec3f3 100644 --- a/crates/image-codecs/src/resolution_probe_tests.rs +++ b/crates/image-codecs/src/resolution_probe_tests.rs @@ -124,7 +124,15 @@ fn jpeg_exif_wins_over_jfif_and_non_exif_app1_is_skipped() { assert_eq!(file_resolution(&jpeg(&[jfif(1, 72, 72), xmp.clone(), exif])), Some((600.0, 600.0))); // An unusable EXIF value falls back to JFIF. let zero = exif_app1(&tiff(true, 0, 0, None)); - assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), xmp, zero])), Some((96.0, 96.0))); + assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), xmp.clone(), zero])), Some((96.0, 96.0))); + let huge = exif_app1(&tiff(true, 1_000_000, 1_000_000, None)); + assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), huge])), Some((96.0, 96.0))); + // Sub-1.0 EXIF rational also falls back to JFIF. + let mut sub = tiff(true, 1, 1, None); + let len = sub.len(); + sub[len - 12..len - 8].copy_from_slice(&4u32.to_le_bytes()); + sub[len - 4..len].copy_from_slice(&4u32.to_le_bytes()); + assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), xmp, exif_app1(&sub)])), Some((96.0, 96.0))); } #[test] @@ -166,6 +174,35 @@ fn webp_without_exif_has_none() { assert_eq!(file_resolution(b"RIFF\x04\0\0\0WEBP"), None); } +#[test] +fn webp_exif_after_many_frames_and_riff_bounds() { + let chunk = |out: &mut Vec, kind: &[u8; 4], data: &[u8]| { + out.extend_from_slice(kind); + out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_le_bytes()); + out.extend_from_slice(data); + if data.len() % 2 == 1 { + out.push(0); + } + }; + let mut body = b"WEBP".to_vec(); + chunk(&mut body, b"VP8X", &[0; 10]); + chunk(&mut body, b"ANIM", &[0; 6]); + for _ in 0..100 { + chunk(&mut body, b"ANMF", &[0; 17]); + } + chunk(&mut body, b"EXIF", &tiff(true, 300, 300, Some(2))); + let riff = |size: usize, trailing: usize| { + let mut webp = b"RIFF".to_vec(); + webp.extend_from_slice(&u32::try_from(size).unwrap().to_le_bytes()); + webp.extend_from_slice(&body); + webp.extend_from_slice(&vec![0xAA; trailing]); + webp + }; + assert_eq!(file_resolution(&riff(body.len(), 0)), Some((300.0, 300.0))); + assert_eq!(file_resolution(&riff(body.len(), 4)), Some((300.0, 300.0))); + assert_eq!(file_resolution(&riff(body.len() - 4, 4)), None); +} + #[test] fn bmp_pixels_per_metre() { close(file_resolution(&bmp(40, 3_780, 7_559)), (96.0, 192.0)); From 5d422c4f9dbd84cdbc23347195ba657f0e5a2929 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 13:11:18 -0500 Subject: [PATCH 44/79] zip: add symlink detection and streaming writer destinations (#2411) * zip: add symlink detection and streaming writer destinations * Reject legacy UTF-8 mode from generic ZIP finish_into --- crates/zip/src/archive.rs | 35 +++++++++++++++++ crates/zip/src/write.rs | 80 ++++++++++++++++++++++++++++++++------- 2 files changed, 101 insertions(+), 14 deletions(-) diff --git a/crates/zip/src/archive.rs b/crates/zip/src/archive.rs index b9b3b3d802..0f26267c12 100644 --- a/crates/zip/src/archive.rs +++ b/crates/zip/src/archive.rs @@ -108,6 +108,15 @@ impl<'a> Archive<'a> { Ok(Some(file.is_dir())) } + /// Whether the entry at `index` is a symbolic link according to its Unix mode bits. + pub fn entry_is_symlink(&mut self, index: usize) -> Result, Error> { + if index >= self.zip.len() { + return Ok(None); + } + let file = self.zip.by_index_raw(index).map_err(|error| Error::NotZip(error.to_string()))?; + Ok(Some(file.unix_mode().is_some_and(|mode| mode & 0o170000 == 0o120000))) + } + /// Declared decoded and compressed sizes at `index`, without name lookup. pub fn entry_sizes(&mut self, index: usize) -> Result, Error> { if index >= self.zip.len() { @@ -274,4 +283,30 @@ mod ownership_tests { drop(clone); assert!(weak.upgrade().is_none()); } + + #[test] + fn entry_is_symlink_reports_unix_symlink_entries() { + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + zip.add_symlink("link", "/outside", zip::write::SimpleFileOptions::default()).unwrap(); + zip.start_file("file.txt", zip::write::SimpleFileOptions::default()).unwrap(); + std::io::Write::write_all(&mut zip, b"ok").unwrap(); + let bytes = zip.finish().unwrap().into_inner(); + let mut archive = Archive::open(&bytes, Limits { max_entries: 4, max_total_bytes: 16 }).unwrap(); + assert_eq!(archive.entry_is_symlink(0).unwrap(), Some(true)); + assert_eq!(archive.entry_is_symlink(1).unwrap(), Some(false)); + assert_eq!(archive.entry_is_symlink(2).unwrap(), None); + } + + #[test] + fn streaming_writer_supports_directories_and_custom_destinations() { + let mut writer = crate::Writer::to_writer(Cursor::new(Vec::new())); + writer.add_directory("resources/").unwrap(); + writer.add("resources/data.bin", b"1234", crate::Compression::Stored).unwrap(); + let bytes = writer.finish_into().unwrap().into_inner(); + let mut archive = Archive::open(&bytes, Limits { max_entries: 4, max_total_bytes: 16 }).unwrap(); + assert_eq!(archive.len(), 2); + assert_eq!(archive.entry_is_dir(0).unwrap(), Some(true)); + assert_eq!(archive.entry_is_dir(1).unwrap(), Some(false)); + assert_eq!(archive.read("resources/data.bin", 16).unwrap().unwrap(), b"1234"); + } } diff --git a/crates/zip/src/write.rs b/crates/zip/src/write.rs index 4517297591..76bf753a62 100644 --- a/crates/zip/src/write.rs +++ b/crates/zip/src/write.rs @@ -1,6 +1,6 @@ //! A ZIP archive being written. -use std::io::{Cursor, Write}; +use std::io::{Cursor, Seek, Write}; use crate::Error; @@ -16,21 +16,21 @@ pub enum Compression { Level(u8), } -/// A ZIP archive being written into memory. The output is deterministic: the same (1980) +/// A ZIP archive being written. The output is deterministic: the same (1980) /// timestamp on every entry. Entries are written in the order they are added. -pub struct Writer { - zip: zip::ZipWriter>>, +pub struct Writer>> { + zip: zip::ZipWriter, legacy_utf8: bool, } -impl Default for Writer { - fn default() -> Writer { +impl Default for Writer>> { + fn default() -> Writer>> { Writer { zip: zip::ZipWriter::new(Cursor::new(Vec::new())), legacy_utf8: false } } } -impl Writer { - pub fn new() -> Writer { +impl Writer>> { + pub fn new() -> Writer>> { Writer::default() } @@ -38,10 +38,33 @@ impl Writer { /// /// This keeps stored archives byte-for-byte stable for existing users while still using the /// shared writer for entry encoding and validation. - pub fn legacy_utf8() -> Writer { + pub fn legacy_utf8() -> Writer>> { Writer { legacy_utf8: true, ..Writer::default() } } + /// The finished archive. + pub fn finish(self) -> Result, Error> { + let mut bytes = self.zip.finish().map(Cursor::into_inner).map_err(|e| Error::Write(e.to_string()))?; + if self.legacy_utf8 { + patch_legacy_utf8_headers(&mut bytes)?; + } + Ok(bytes) + } +} + +impl Writer { + /// Starts writing an archive directly to a seekable destination without buffering the whole + /// archive in memory. + pub fn to_writer(destination: W) -> Self { + Self { zip: zip::ZipWriter::new(destination), legacy_utf8: false } + } + + /// Adds a directory entry with the deterministic 1980 timestamp. + pub fn add_directory(&mut self, name: &str) -> Result<(), Error> { + let options = zip::write::SimpleFileOptions::default().last_modified_time(zip::DateTime::default()); + self.zip.add_directory(name, options).map_err(|e| Error::Write(format!("{name}: {e}"))) + } + /// Adds an entry from a byte slice. A name the archive already has is an error. pub fn add(&mut self, name: &str, data: &[u8], compression: Compression) -> Result<(), Error> { self.add_entry(name, data, compression, 1, data.len() as u64 >= u64::from(u32::MAX) / 2) @@ -98,13 +121,18 @@ impl Writer { write(&mut self.zip).map_err(|e| fail(&e)) } - /// The finished archive. - pub fn finish(self) -> Result, Error> { - let mut bytes = self.zip.finish().map(Cursor::into_inner).map_err(|e| Error::Write(e.to_string()))?; + /// Finishes writing and returns the underlying destination. + /// + /// Legacy UTF-8 mode requires [`Writer::finish`] to apply its in-memory header patch. + /// Calling this method in legacy mode consumes the writer and returns [`Error::Write`]; + /// use `finish` instead when constructing a writer with [`Writer::legacy_utf8`]. + pub fn finish_into(self) -> Result { + // A generic destination need not support reads or header patching. Never silently + // return an archive that omits the byte-compatibility contract of legacy mode. if self.legacy_utf8 { - patch_legacy_utf8_headers(&mut bytes)?; + return Err(Error::Write("legacy UTF-8 output requires Writer::finish".into())); } - Ok(bytes) + self.zip.finish().map_err(|e| Error::Write(e.to_string())) } } @@ -184,3 +212,27 @@ fn patch_legacy_utf8_headers(bytes: &mut [u8]) -> Result<(), Error> { } Ok(()) } + +#[cfg(test)] +mod finish_tests { + use super::*; + + #[test] + fn legacy_ascii_output_requires_the_header_patching_finish_path() { + let mut legacy = Writer::legacy_utf8(); + legacy.add("a.txt", b"ordinary text", Compression::Stored).unwrap(); + assert!(matches!(legacy.finish_into(), Err(Error::Write(message)) + if message == "legacy UTF-8 output requires Writer::finish")); + + let mut legacy = Writer::legacy_utf8(); + legacy.add("a.txt", b"ordinary text", Compression::Stored).unwrap(); + let bytes = legacy.finish().unwrap(); + assert_eq!(get_u16(&bytes, 6).unwrap() & 0x0800, 0x0800); + + let mut ordinary = Writer::to_writer(Cursor::new(Vec::new())); + ordinary.add("a.txt", b"ordinary text", Compression::Stored).unwrap(); + let bytes = ordinary.finish_into().unwrap().into_inner(); + let mut archive = crate::Archive::open(&bytes, crate::Limits { max_entries: 1, max_total_bytes: 32 }).unwrap(); + assert_eq!(archive.read("a.txt", 32).unwrap().unwrap(), b"ordinary text"); + } +} From 8dbe9705ffd23002c97f31a7727b1027ecd5c3fd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 13:11:21 -0500 Subject: [PATCH 45/79] psd: detect Lr16/Lr32 and Mt* merged transparency in Merged::open (#2412) --- crates/psd/src/merged.rs | 72 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 70 insertions(+), 2 deletions(-) diff --git a/crates/psd/src/merged.rs b/crates/psd/src/merged.rs index 467fb89043..08ed8f95bd 100644 --- a/crates/psd/src/merged.rs +++ b/crates/psd/src/merged.rs @@ -40,6 +40,48 @@ fn u64_at(bytes: &[u8], at: &mut usize) -> Result { Ok(u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])) } +fn has_merged_transparency(layer: &[u8], version: crate::Version) -> bool { + let mut at = 0usize; + let info_len = if version.is_psb() { u64_at(layer, &mut at).ok() } else { u32_at(layer, &mut at).ok().map(u64::from) }; + let Some(info_len) = info_len else { return false }; + if info_len >= 2 { + return layer.get(at..at + 2).is_some_and(|b| i16::from_be_bytes([b[0], b[1]]) < 0); + } + let Ok(info_len) = usize::try_from(info_len) else { return false }; + let Some(next) = at.checked_add(info_len) else { return false }; + at = next; + let Ok(mask_len) = u32_at(layer, &mut at) else { return false }; + let Some(next) = at.checked_add(mask_len as usize) else { return false }; + at = next; + while let Some(head) = at.checked_add(12).and_then(|end| layer.get(at..end)) { + let sig = &head[..4]; + let key = &head[4..8]; + if sig != b"8BIM" && sig != b"8B64" { + return false; + } + let Ok(key_arr): std::result::Result<&[u8; 4], _> = key.try_into() else { return false }; + let len = if crate::tagged::uses_long_length(version, key_arr) { + let Ok(l) = u64_at(layer, &mut { at + 8 }) else { return false }; + let Ok(l) = usize::try_from(l) else { return false }; + at += 16; + l + } else { + at += 12; + u32::from_be_bytes([head[8], head[9], head[10], head[11]]) as usize + }; + if (key == b"Lr16" || key == b"Lr32") && layer.get(at..at + 2).is_some_and(|b| i16::from_be_bytes([b[0], b[1]]) < 0) { + return true; + } + if matches!(key, b"Mtrn" | b"MTrn" | b"Mt16" | b"Mt32") { + return true; + } + // Global tagged blocks pad their data to 4 bytes (per psd-tools and craft-psd). + let Some(next) = len.checked_add(3).map(|v| v & !3).and_then(|p| at.checked_add(p)) else { return false }; + at = next; + } + false +} + impl<'a> Merged<'a> { /// Open the merged section with a pixel limit. This skips layer records, preserving the ability /// to read a composite when its layer data is not understood. No image planes are allocated. @@ -59,8 +101,7 @@ impl<'a> Merged<'a> { let mut at = usize::try_from(head.layer_section_offset).map_err(|_| PsdError::LimitExceeded("offset"))?; let len = if psb { u64_at(bytes, &mut at)? } else { u64::from(u32_at(bytes, &mut at)?) }; let layer = take(bytes, &mut at, usize::try_from(len).map_err(|_| PsdError::LimitExceeded("layer section"))?)?; - let offset = if psb { 8 } else { 4 }; - let transparency = layer.get(offset..offset + 2).is_some_and(|b| i16::from_be_bytes([b[0], b[1]]) < 0); + let transparency = has_merged_transparency(layer, h.version); let compression = u16_at(bytes, &mut at)?; Ok(Self { head, transparency, compression, bytes, data_offset: at }) } @@ -248,4 +289,31 @@ mod tests { assert_eq!(row, [7, 8, 0, 0]); assert!(unpackbits(&[0x81, 1], &mut row).is_err()); } + + #[test] + fn detects_lr16_and_mt16_merged_transparency() { + let with_layer = |layer: &[u8]| { + let mut b = head(2, 0); + b.splice(34..38, (layer.len() as u32).to_be_bytes().iter().copied().chain(layer.iter().copied())); + b + }; + let mut lr16 = Vec::new(); + lr16.extend_from_slice(&0u32.to_be_bytes()); + lr16.extend_from_slice(&0u32.to_be_bytes()); + lr16.extend_from_slice(b"8BIMPatt"); + lr16.extend_from_slice(&6u32.to_be_bytes()); + lr16.extend_from_slice(&[1, 2, 3, 4, 5, 6, 0, 0]); + lr16.extend_from_slice(b"8BIMLr16"); + lr16.extend_from_slice(&2u32.to_be_bytes()); + lr16.extend_from_slice(&(-1i16).to_be_bytes()); + assert!(Merged::open(&with_layer(&lr16), 4).unwrap().transparency); + + let n = lr16.len(); + lr16[n - 2..].copy_from_slice(&1i16.to_be_bytes()); + assert!(!Merged::open(&with_layer(&lr16), 4).unwrap().transparency); + + let mut mt16 = vec![0; 8]; + mt16.extend_from_slice(b"8BIMMt16\0\0\0\0"); + assert!(Merged::open(&with_layer(&mt16), 4).unwrap().transparency); + } } From 08da5e1486ee640de1d2cccd8fe8dd32b1d3b62c Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 14:00:33 -0500 Subject: [PATCH 46/79] anicraft-format: add write_version for explicit envelope version (#2420) --- crates/anicraft-format/src/lib.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/anicraft-format/src/lib.rs b/crates/anicraft-format/src/lib.rs index 7cc5dc2617..6ff5d81e19 100644 --- a/crates/anicraft-format/src/lib.rs +++ b/crates/anicraft-format/src/lib.rs @@ -34,7 +34,12 @@ struct EnvelopeOut<'a, P, T> { /// Serializes the envelope in its stable wire order and uses AniCraft's compact/pretty threshold. pub fn write(generator: &str, paths: &[P], document: &T) -> Result { - let envelope = EnvelopeOut { format: FORMAT_NAME, version: FORMAT_VERSION, generator, paths, document }; + write_version(FORMAT_VERSION, generator, paths, document) +} + +/// Serializes the envelope with an explicit format version and AniCraft's compact/pretty threshold. +pub fn write_version(version: u32, generator: &str, paths: &[P], document: &T) -> Result { + let envelope = EnvelopeOut { format: FORMAT_NAME, version, generator, paths, document }; let compact = serde_json::to_string(&envelope)?; if compact.len() < PRETTY_LIMIT { serde_json::to_string_pretty(&envelope) } else { Ok(compact) } } From a524687f93ac12b1683f0fccbd37987c3a0011c2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 10:49:57 -0800 Subject: [PATCH 47/79] file-formats: register JPEG-LS and tell it from JPEG craft-image-codecs reads and writes JPEG-LS since #1576, but the format registry had no entry for it. A `.jls` name resolved to no format, and a JPEG-LS file was reported as JPEG because both start with `FF D8 FF`. `Format::JpegLs` now has the `jls` extension, the `image/jls` media type and the codec mapping, so its capabilities come from the codec. A file that starts with `FF D8 FF` is JPEG-LS when its marker segments lead to an SOF55 frame header (`FF F7`). The walk follows `jpeg_frame_from` in craft-image-codecs, which a build without the `raster-codecs` feature does not link, and reads at most the first 1 MiB. When the bytes end before any frame header, a `.jls` name gives JPEG-LS and any other name gives JPEG. craft-file-import routes `JpegLs` to its raster reader and lists `jls` and `image/jls`, so a JPEG-LS file still imports as it did when it was detected as JPEG. Follows #1576. --- Cargo.lock | 1 + crates/file-formats/src/lib.rs | 69 +++++++++++++++++++++++++++++--- crates/file-formats/src/tests.rs | 66 ++++++++++++++++++++++++++++++ crates/file-import/Cargo.toml | 3 ++ crates/file-import/src/lib.rs | 30 ++++++++++++-- 5 files changed, 161 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index de69d0765c..9f5cd71c72 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2089,6 +2089,7 @@ dependencies = [ "craft-dxf", "craft-eps", "craft-file-formats", + "craft-image-codecs", "craft-pdf 0.1.0", "craft-raster-codecs", "craft-svg", diff --git a/crates/file-formats/src/lib.rs b/crates/file-formats/src/lib.rs index 38619075ff..0c290d93d4 100644 --- a/crates/file-formats/src/lib.rs +++ b/crates/file-formats/src/lib.rs @@ -39,6 +39,8 @@ pub enum Format { Cineon, Dicom, Iff, + /// JPEG-LS (ITU-T T.87). Its files start with the same `FF D8 FF` bytes as JPEG files. + JpegLs, Ase, Psd, Affinity, @@ -108,7 +110,7 @@ const fn availability(feature: bool, supported: bool) -> Availability { impl Format { /// Every known format, including formats whose reader or writer is not enabled in this build. - pub const ALL: [Format; 56] = [ + pub const ALL: [Format; 57] = [ Self::Pdf, Self::Eps, Self::PostScript, @@ -139,6 +141,7 @@ impl Format { Self::Cineon, Self::Dicom, Self::Iff, + Self::JpegLs, Self::Ase, Self::Psd, Self::Affinity, @@ -200,6 +203,7 @@ impl Format { Self::Cineon => &["cin"], Self::Dicom => &["dcm", "dicom", "dc3"], Self::Iff => &["iff", "lbm", "ilbm"], + Self::JpegLs => &["jls"], Self::Ase => &["ase"], Self::Psd => &["psd", "psb", "psdt"], Self::Affinity => &["afdesign", "afphoto", "afpub", "af"], @@ -270,6 +274,7 @@ impl Format { Self::Cineon => "image/x-cineon", Self::Dicom => "application/dicom", Self::Iff => "image/ilbm", + Self::JpegLs => "image/jls", Self::Ase => "application/x-adobe-swatch-exchange", Self::Psd => "image/vnd.adobe.photoshop", Self::Affinity => "application/x-affinity", @@ -327,6 +332,7 @@ impl Format { Self::Cineon => Codec::Cineon, Self::Dicom => Codec::Dicom, Self::Iff => Codec::Iff, + Self::JpegLs => Codec::JpegLs, _ => return None, }) } @@ -381,7 +387,8 @@ impl Format { | Self::Fits | Self::Dpx | Self::Cineon - | Self::Iff => capability(raster, true, true, false, false), + | Self::Iff + | Self::JpegLs => capability(raster, true, true, false, false), Self::Pdf => capability(cfg!(feature = "pdf"), true, true, false, false), Self::Eps | Self::PostScript | Self::Illustrator => capability(cfg!(feature = "pdf"), true, false, false, false), Self::Svg | Self::Svgz => capability(cfg!(feature = "svg"), true, false, false, false), @@ -483,7 +490,7 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option { if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("af")) { return Some(Format::Affinity); } - if let Some(raster) = raster_signature(bytes) { + if let Some(raster) = raster_signature(name, bytes) { return Some(raster); } if bytes.starts_with(b"silhouette04;") || bytes.starts_with(b"silhouette05;") { @@ -598,13 +605,18 @@ fn dxf_ascii_prefix(bytes: &[u8]) -> bool { matches!((lines.next(), lines.next(), lines.next(), lines.next()), (Some("0"), Some("SECTION"), Some("2"), Some(section)) if matches!(section, "HEADER" | "CLASSES" | "TABLES" | "BLOCKS" | "ENTITIES" | "OBJECTS")) } -fn raster_signature(bytes: &[u8]) -> Option { +fn raster_signature(name: &str, bytes: &[u8]) -> Option { let head = bytes.get(..16).unwrap_or(bytes); if head.starts_with(b"\x89PNG\r\n\x1a\n") { return Some(Format::Png); } if head.starts_with(b"\xff\xd8\xff") { - return Some(Format::Jpeg); + return Some(match jpeg_frame(bytes) { + JpegFrame::Ls => Format::JpegLs, + JpegFrame::Other => Format::Jpeg, + JpegFrame::Unknown if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("jls")) => Format::JpegLs, + JpegFrame::Unknown => Format::Jpeg, + }); } if head.starts_with(b"BM") { return Some(Format::Bmp); @@ -620,3 +632,50 @@ fn raster_signature(bytes: &[u8]) -> Option { } None } + +/// What the marker segments after a JPEG start-of-image marker lead to. +#[derive(Debug, PartialEq, Eq)] +enum JpegFrame { + /// An SOF55 frame header (`FF F7`, ITU-T T.87): JPEG-LS. + Ls, + /// Another frame header, a scan header, an end-of-image marker, or a byte that is not a + /// marker where one should be. + Other, + /// The bytes, or the probe's first 1 MiB, end before a frame or scan header. + Unknown, +} + +/// Walk the marker segments from the start-of-image marker to the first frame or scan header. +/// Only the first 1 MiB is read, and each step moves forward at least one byte. The walk follows +/// `jpeg_frame_from` in craft-image-codecs, which a build without the `raster-codecs` feature does +/// not link. +fn jpeg_frame(bytes: &[u8]) -> JpegFrame { + const LIMIT: usize = 1 << 20; + let bytes = bytes.get(..bytes.len().min(LIMIT)).unwrap_or(bytes); + let mut pos = 2; + loop { + let (Some(&prefix), Some(&marker)) = (bytes.get(pos), bytes.get(pos + 1)) else { + return if bytes.get(pos).is_none_or(|&prefix| prefix == 0xFF) { JpegFrame::Unknown } else { JpegFrame::Other }; + }; + if prefix != 0xFF { + return JpegFrame::Other; + } + match marker { + 0xF7 => return JpegFrame::Ls, + // `FF 00` is a stuffed zero, not a marker. + 0x00 | 0xDA | 0xD9 => return JpegFrame::Other, + // A DRI segment (`FF DD`) may come before an SOF55 frame header, so it is skipped + // by its length below. + 0xC0..=0xCF | 0xDB | 0xDC | 0xDE | 0xDF => return JpegFrame::Other, + // A fill byte, or a marker without a length. + 0xFF => pos += 1, + 0x01 | 0xD0..=0xD7 => pos += 2, + _ => { + let Some(length) = bytes.get(pos + 2..pos + 4).map(|length| usize::from(u16::from_be_bytes([length[0], length[1]]))) else { + return JpegFrame::Unknown; + }; + pos += 2 + length; + } + } + } +} diff --git a/crates/file-formats/src/tests.rs b/crates/file-formats/src/tests.rs index 399f884acf..504eba727a 100644 --- a/crates/file-formats/src/tests.rs +++ b/crates/file-formats/src/tests.rs @@ -57,6 +57,72 @@ fn bounded_probes_prefer_signatures_and_resolve_extensions() { assert_eq!(super::detect("unknown", b""), None); } +#[test] +fn jpeg_ls_is_told_from_jpeg_and_resolves_its_extension() { + assert_eq!(super::from_extension("JLS"), Some(Format::JpegLs)); + assert_eq!(Format::JpegLs.mime_type(), Some("image/jls")); + assert_eq!(super::detect("scan.jls", b""), Some(Format::JpegLs)); + // SOI followed by an SOF55 frame header. + assert_eq!(super::detect("scan.jpg", b"\xff\xd8\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0"), Some(Format::JpegLs)); + assert_eq!(super::detect("photo.jls", b"\xff\xd8\xff\xe0\0\x10JFIF\0\x01\x01\0\0\x01\0\x01\0\0\xff\xc0"), Some(Format::Jpeg)); + // An APP0 segment, a fill byte and a DRI segment before the SOF55 frame header. + let with_segments = b"\xff\xd8\xff\xe0\0\x04\0\0\xff\xff\xdd\0\x04\0\0\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0"; + assert_eq!(super::detect("scan.jpg", with_segments), Some(Format::JpegLs)); + assert_eq!(super::detect("", with_segments), Some(Format::JpegLs)); + // Bytes that end before any frame header: the name decides. + assert_eq!(super::detect("scan.jls", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::JpegLs)); + assert_eq!(super::detect("photo.jpg", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::Jpeg)); + assert_eq!(super::detect("", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::Jpeg)); +} + +#[test] +fn jpeg_marker_walk_reads_only_the_first_mebibyte() { + let mut bytes = vec![0xFF; (1 << 20) + 64]; + bytes[1] = 0xD8; + let len = bytes.len(); + bytes[len - 2] = 0xF7; + assert_eq!(super::detect("scan.jpg", &bytes), Some(Format::Jpeg)); + assert_eq!(super::detect("scan.jls", &bytes), Some(Format::JpegLs)); + bytes[1 << 19] = 0xF7; + assert_eq!(super::detect("scan.jpg", &bytes), Some(Format::JpegLs)); +} + +#[cfg(feature = "raster-codecs")] +#[test] +fn jpeg_marker_walk_matches_the_codec_detection() { + let cases: [&[u8]; 6] = [ + b"\xff\xd8\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0", + b"\xff\xd8\xff\xe0\0\x04\0\0\xff\xff\xdd\0\x04\0\0\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0", + b"\xff\xd8\xff\xe0\0\x10JFIF\0\x01\x01\0\0\x01\0\x01\0\0\xff\xc0", + b"\xff\xd8\xff\xd0\xff\x01\xff\xf7\0\x0b", + b"\xff\xd8\xff\xe0\0\x04\0\0\x12\x34", + b"\xff\xd8\xff\xda\0\x08", + ]; + for bytes in cases { + let expected = match craft_image_codecs::detect(bytes) { + Some(craft_image_codecs::Format::JpegLs) => Format::JpegLs, + _ => Format::Jpeg, + }; + assert_eq!(super::detect("", bytes), Some(expected), "{bytes:02x?}"); + } +} + +#[test] +fn jpeg_ls_capabilities_follow_the_codec() { + #[cfg(feature = "raster-codecs")] + { + assert_eq!(Format::JpegLs.raster_codec(), Some(craft_image_codecs::Format::JpegLs)); + assert_eq!(Format::JpegLs.extensions(), craft_image_codecs::Format::JpegLs.extensions()); + assert_eq!(Format::JpegLs.capabilities().read, Availability::Available); + assert_eq!(Format::JpegLs.capabilities().write, Availability::Available); + } + #[cfg(not(feature = "raster-codecs"))] + { + assert_eq!(Format::JpegLs.capabilities().read, Availability::BuildDisabled); + assert_eq!(Format::JpegLs.capabilities().write, Availability::BuildDisabled); + } +} + #[test] fn registered_mime_and_preferred_extensions_remain_distinct() { assert_eq!(Format::Svg.mime_type(), Format::Svgz.mime_type()); diff --git a/crates/file-import/Cargo.toml b/crates/file-import/Cargo.toml index 0119435210..ab4eb9c6f6 100644 --- a/crates/file-import/Cargo.toml +++ b/crates/file-import/Cargo.toml @@ -18,5 +18,8 @@ kurbo = { workspace = true } thiserror = { workspace = true } vectorcraft-geom = { workspace = true } +[dev-dependencies] +craft-image-codecs = { workspace = true } + [lints] workspace = true diff --git a/crates/file-import/src/lib.rs b/crates/file-import/src/lib.rs index 195363da06..ebf5dc3d09 100644 --- a/crates/file-import/src/lib.rs +++ b/crates/file-import/src/lib.rs @@ -89,14 +89,15 @@ pub const CAPABILITIES: &[Capability] = &[ detected_formats: &[ craft_file_formats::Format::Png, craft_file_formats::Format::Jpeg, + craft_file_formats::Format::JpegLs, craft_file_formats::Format::Bmp, craft_file_formats::Format::Gif, craft_file_formats::Format::Tiff, craft_file_formats::Format::WebP, ], - extensions: &["png", "jpg", "jpeg", "bmp", "gif", "tif", "tiff", "webp"], + extensions: &["png", "jpg", "jpeg", "jls", "bmp", "gif", "tif", "tiff", "webp"], write_extensions: &["png", "jpg", "jpeg"], - mime_types: &["image/png", "image/jpeg", "image/bmp", "image/gif", "image/tiff", "image/webp"], + mime_types: &["image/png", "image/jpeg", "image/jls", "image/bmp", "image/gif", "image/tiff", "image/webp"], raster: true, vector: false, }, @@ -197,7 +198,7 @@ pub fn format_for(name: &str, bytes: &[u8]) -> Option { F::Pdf => Some(ImportFormat::Pdf), F::Illustrator if bytes.starts_with(b"%PDF-") => Some(ImportFormat::Pdf), F::Eps | F::PostScript | F::Illustrator => Some(ImportFormat::Eps), - F::Png | F::Jpeg | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster), + F::Png | F::Jpeg | F::JpegLs | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster), _ => None, } } @@ -402,4 +403,27 @@ mod format_tests { let bytes = b"%PDF-1.7\n/AIPrivateData"; assert_eq!(format_for("illustration.ai", bytes), Some(ImportFormat::Pdf)); } + + #[test] + fn jpeg_ls_is_routed_to_the_raster_reader() { + use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, encode}; + let gray: Vec = (0..6).map(|value| value * 40).collect(); + let Ok(image) = Image::from_u8(3, 2, ChannelLayout::Gray, gray.clone()) else { + panic!("a 3 by 2 gray image"); + }; + let Ok(bytes) = encode(&image, Format::JpegLs, &EncodeOptions::default()) else { + panic!("JPEG-LS encodes"); + }; + for name in ["scan.jls", "scan.jpg", "scan"] { + assert_eq!(format_for(name, &bytes), Some(ImportFormat::Raster), "{name}"); + let Ok(Imported::Raster(raster)) = import(name, &bytes, Limits::default()) else { + panic!("{name} imports as a raster image"); + }; + assert_eq!((raster.width, raster.height), (3, 2)); + let red: Vec = raster.rgba.as_chunks::<4>().0.iter().map(|pixel| pixel[0]).collect(); + assert_eq!(red, gray, "{name}"); + } + assert!(supported_formats(ImportFormat::Raster).contains(&craft_file_formats::Format::JpegLs)); + assert!(supported_extensions().contains(&"jls")); + } } From bc186ca719958fcce3b6ee24794277eabed14609 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 14:51:45 -0500 Subject: [PATCH 48/79] image-codecs: keep first JFIF APP0 density in scan_metadata (#2422) --- crates/image-codecs/src/codecs/jpeg.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/image-codecs/src/codecs/jpeg.rs b/crates/image-codecs/src/codecs/jpeg.rs index 7ab5ad9cf6..13c1903018 100644 --- a/crates/image-codecs/src/codecs/jpeg.rs +++ b/crates/image-codecs/src/codecs/jpeg.rs @@ -236,7 +236,7 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta { } let seg = &b[i + 4..i + 2 + len]; match marker { - 0xE0 if seg.len() >= 12 && seg.starts_with(b"JFIF\0") => { + 0xE0 if seg.len() >= 12 && seg.starts_with(b"JFIF\0") && jfif_dpi.is_none() => { let unit = seg[7]; let x = u16::from_be_bytes([seg[8], seg[9]]) as f32; let y = u16::from_be_bytes([seg[10], seg[11]]) as f32; From bf6054c96dda08773b2056c8a7e6db684b159d86 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 20:24:41 +0000 Subject: [PATCH 49/79] craft-update tests: retry hdiutil create and attach while the disk-image helper is busy --- crates/update/src/install.rs | 49 +++++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/crates/update/src/install.rs b/crates/update/src/install.rs index 6cf91868a2..690df3f385 100644 --- a/crates/update/src/install.rs +++ b/crates/update/src/install.rs @@ -4326,6 +4326,22 @@ exit 0 app } + /// Runs `hdiutil` with `args` (the caller holds its [`macos::disk_image_turn`]). The disk-image + /// helper can turn a request away with EAGAIN ("Resource temporarily unavailable") while it + /// is busy elsewhere, as on shared CI runners; that reply alone is retried, up to five + /// attempts over about eight seconds. Any other result returns at once. + fn hdiutil(args: &[&std::ffi::OsStr]) -> std::process::Output { + let mut output = std::process::Command::new("hdiutil").args(args).output().unwrap(); + for wait_ms in [500, 1000, 2000, 4000] { + if output.status.success() || !String::from_utf8_lossy(&output.stderr).contains("Resource temporarily unavailable") { + break; + } + std::thread::sleep(Duration::from_millis(wait_ms)); + output = std::process::Command::new("hdiutil").args(args).output().unwrap(); + } + output + } + /// A release-style disk image holding a `PhotoCraft.app` that reports `version`. The tests, /// in this process and in others, ask the disk-image helper one at a time; when a program /// that is not one of these tests keeps it busy, the test fails with what `hdiutil create` @@ -4335,12 +4351,17 @@ exit 0 bundle(&src, version); let dmg = dir.join(format!("photocraft-{version}-macos-universal.dmg")); let _one_at_a_time = macos::disk_image_turn(); - let output = std::process::Command::new("hdiutil") - .args(["create", "-quiet", "-format", "UDZO", "-volname", "PhotoCraft", "-srcfolder"]) - .arg(&src) - .arg(&dmg) - .output() - .unwrap(); + let output = hdiutil(&[ + "create".as_ref(), + "-quiet".as_ref(), + "-format".as_ref(), + "UDZO".as_ref(), + "-volname".as_ref(), + "PhotoCraft".as_ref(), + "-srcfolder".as_ref(), + src.as_os_str(), + dmg.as_os_str(), + ]); assert!(output.status.success(), "hdiutil create failed: {}", String::from_utf8_lossy(&output.stderr).trim()); dmg } @@ -4722,12 +4743,16 @@ exit 0 // One request at a time, as in `dmg`. let output = { let _one_at_a_time = macos::disk_image_turn(); - std::process::Command::new("hdiutil") - .args(["attach", "-nobrowse", "-readonly", "-noautoopen", "-noverify", "-mountpoint"]) - .arg(&mount) - .arg(&image) - .output() - .unwrap() + hdiutil(&[ + "attach".as_ref(), + "-nobrowse".as_ref(), + "-readonly".as_ref(), + "-noautoopen".as_ref(), + "-noverify".as_ref(), + "-mountpoint".as_ref(), + mount.as_os_str(), + image.as_os_str(), + ]) }; let _attached = Attached(mount.clone()); assert!(output.status.success(), "hdiutil attach failed: {}", String::from_utf8_lossy(&output.stderr).trim()); From 6ec20913b0c4b1355c23f52431bbb6d4898d79cd Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 20:29:34 +0000 Subject: [PATCH 50/79] craft-update: name std::time::Duration in the macOS test helper --- crates/update/src/install.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/update/src/install.rs b/crates/update/src/install.rs index 690df3f385..984797d677 100644 --- a/crates/update/src/install.rs +++ b/crates/update/src/install.rs @@ -4336,7 +4336,7 @@ exit 0 if output.status.success() || !String::from_utf8_lossy(&output.stderr).contains("Resource temporarily unavailable") { break; } - std::thread::sleep(Duration::from_millis(wait_ms)); + std::thread::sleep(std::time::Duration::from_millis(wait_ms)); output = std::process::Command::new("hdiutil").args(args).output().unwrap(); } output From dc6adc3fbd9cf39e4a8210f94106a5b0c3e26e17 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:22:22 +0700 Subject: [PATCH 51/79] psd: expose bounded encoded composite rows [skip ci] (#2442) --- crates/psd/src/merged.rs | 3 + crates/psd/src/merged/rows.rs | 284 ++++++++++++++++++++++++++++++++++ 2 files changed, 287 insertions(+) create mode 100644 crates/psd/src/merged/rows.rs diff --git a/crates/psd/src/merged.rs b/crates/psd/src/merged.rs index 08ed8f95bd..25392819c0 100644 --- a/crates/psd/src/merged.rs +++ b/crates/psd/src/merged.rs @@ -1,6 +1,9 @@ //! Borrowed, merged-only PSD reader that skips layer records and decodes selected planes. use crate::{Head, PsdError, Result}; +mod rows; +pub use rows::{ChannelRows, EncodedRow, EncodedRows}; + /// Dimensions in the fixed header fields, for reporting a preflight limit error. /// This does not validate the PSD signature or remaining header. pub fn declared_dimensions(bytes: &[u8]) -> Option<(u32, u32)> { diff --git a/crates/psd/src/merged/rows.rs b/crates/psd/src/merged/rows.rs new file mode 100644 index 0000000000..279368b905 --- /dev/null +++ b/crates/psd/src/merged/rows.rs @@ -0,0 +1,284 @@ +//! Allocation-free access to the selected composite channels, one encoded row at a time. + +use super::{Merged, take}; +use crate::{PsdError, Result}; + +/// Validated locations of the first requested composite channels. +/// +/// This view allocates no plane or row index. Unselected channel payloads need not be present. +pub struct EncodedRows<'a> { + table: &'a [u8], + payload: &'a [u8], + entry_bytes: usize, + row_bytes: usize, + height: usize, + used: usize, +} + +/// A sequential cursor over one selected channel, without a decoded plane allocation. +pub struct ChannelRows<'a> { + table: &'a [u8], + payload: &'a [u8], + entry_bytes: usize, + row_bytes: usize, + remaining: usize, +} + +/// A borrowed raw or PackBits row with its declared decoded length. +pub struct EncodedRow<'a> { + bytes: &'a [u8], + row_bytes: usize, + rle: bool, +} + +fn row_length(entry: &[u8]) -> Result { + match *entry { + [a, b] => Ok(usize::from(u16::from_be_bytes([a, b]))), + [a, b, c, d] => usize::try_from(u32::from_be_bytes([a, b, c, d])).map_err(|_| PsdError::LimitExceeded("RLE row size")), + _ => Err(PsdError::invalid("RLE row table entry")), + } +} + +impl<'a> Merged<'a> { + /// Borrow the first `used` raw or PackBits channels for row-at-a-time decoding. + /// + /// Checks the full declared row table and the selected payload extents before returning, + /// without allocating. Eight-, sixteen- and thirty-two-bit samples remain big-endian. + /// `max_row_bytes` limits one decoded row. RLE packet contents are checked on decoding; + /// a short or malformed row is an error, not zero-padded recovery. Existing + /// [`read_planes`](Self::read_planes) keeps its tolerant recovery behaviour. + pub fn encoded_rows(&self, used: usize, max_row_bytes: usize) -> Result> { + let h = &self.head.header; + let channels = usize::from(h.channels); + if used > channels { + return Err(PsdError::invalid("too few channels")); + } + let bpc = match h.depth { + 8 => 1usize, + 16 => 2, + 32 => 4, + _ => return Err(PsdError::Unsupported("merged depth".into())), + }; + let width = usize::try_from(h.width).map_err(|_| PsdError::LimitExceeded("row size"))?; + let height = usize::try_from(h.height).map_err(|_| PsdError::LimitExceeded("row count"))?; + let row_bytes = width.checked_mul(bpc).ok_or(PsdError::LimitExceeded("row size"))?; + if row_bytes > max_row_bytes || row_bytes as u64 > crate::compression::MAX_DECODED_BYTES { + return Err(PsdError::LimitExceeded("merged row size")); + } + let mut at = self.data_offset; + let (table, entry_bytes, payload_bytes) = match self.compression { + 0 => { + let len = used.checked_mul(height).and_then(|n| n.checked_mul(row_bytes)).ok_or(PsdError::LimitExceeded("merged data"))?; + (&[][..], 0, len) + } + 1 => { + let entry = if h.version.is_psb() { 4 } else { 2 }; + // Even when only the first channel is requested, every declared row-length + // entry precedes the payload. Skipping only selected entries reads table bytes. + let table_len = channels.checked_mul(height).and_then(|n| n.checked_mul(entry)).ok_or(PsdError::LimitExceeded("row table"))?; + let full_table = take(self.bytes, &mut at, table_len)?; + let selected_len = used.checked_mul(height).and_then(|n| n.checked_mul(entry)).ok_or(PsdError::LimitExceeded("row table"))?; + let table = full_table.get(..selected_len).ok_or_else(|| PsdError::invalid("row table"))?; + let minimum = row_bytes.div_ceil(128).checked_mul(2).ok_or(PsdError::LimitExceeded("row size"))?; + let mut total = 0usize; + for entry in table.chunks_exact(entry) { + let len = row_length(entry)?; + // Reject impossible expansion before callers allocate the final image. + if len < minimum { + return Err(PsdError::invalid("RLE row too short for its width")); + } + total = total.checked_add(len).ok_or(PsdError::LimitExceeded("merged data"))?; + } + (table, entry, total) + } + _ => return Err(PsdError::Unsupported("merged compression".into())), + }; + let payload = take(self.bytes, &mut at, payload_bytes)?; + Ok(EncodedRows { table, payload, entry_bytes, row_bytes, height, used }) + } +} + +impl<'a> EncodedRows<'a> { + /// Number of decoded bytes in each row. + pub fn row_bytes(&self) -> usize { + self.row_bytes + } + + /// Cursor for a selected channel. RLE setup scans preceding row lengths, without allocating. + pub fn channel(&self, channel: usize) -> Result> { + if channel >= self.used { + return Err(PsdError::invalid("channel was not selected")); + } + let first = channel.checked_mul(self.height).ok_or(PsdError::LimitExceeded("row count"))?; + let (table, offset) = if self.entry_bytes == 0 { + (&[][..], first.checked_mul(self.row_bytes).ok_or(PsdError::LimitExceeded("channel offset"))?) + } else { + let start = first.checked_mul(self.entry_bytes).ok_or(PsdError::LimitExceeded("row table"))?; + let before = self.table.get(..start).ok_or_else(|| PsdError::invalid("row table"))?; + let mut offset = 0usize; + for entry in before.chunks_exact(self.entry_bytes) { + offset = offset.checked_add(row_length(entry)?).ok_or(PsdError::LimitExceeded("channel offset"))?; + } + (self.table.get(start..).ok_or_else(|| PsdError::invalid("row table"))?, offset) + }; + let payload = self.payload.get(offset..).ok_or_else(|| PsdError::invalid("channel offset"))?; + Ok(ChannelRows { table, payload, entry_bytes: self.entry_bytes, row_bytes: self.row_bytes, remaining: self.height }) + } +} + +impl<'a> ChannelRows<'a> { + /// Read the next encoded row, or `None` after the declared channel height. + pub fn next_row(&mut self) -> Result>> { + if self.remaining == 0 { + return Ok(None); + } + let len = if self.entry_bytes == 0 { + self.row_bytes + } else { + let entry = self.table.get(..self.entry_bytes).ok_or_else(|| PsdError::invalid("row table"))?; + row_length(entry)? + }; + let bytes = self.payload.get(..len).ok_or_else(|| PsdError::invalid("truncated row"))?; + self.payload = self.payload.get(len..).ok_or_else(|| PsdError::invalid("truncated row"))?; + if self.entry_bytes != 0 { + self.table = self.table.get(self.entry_bytes..).ok_or_else(|| PsdError::invalid("row table"))?; + } + self.remaining -= 1; + Ok(Some(EncodedRow { bytes, row_bytes: self.row_bytes, rle: self.entry_bytes != 0 })) + } +} + +impl EncodedRow<'_> { + /// Decode into exactly one row of caller-owned storage, without allocating. + /// + /// Truncated PackBits packets and underfilled/overfilled rows are errors. Bytes after a + /// complete row remain tolerated, matching [`crate::compression::packbits::decode_to_slice`]. + /// On error, the output may contain a partially decoded prefix. + pub fn decode_to_slice(&self, output: &mut [u8]) -> Result<()> { + if output.len() != self.row_bytes { + return Err(PsdError::invalid("decoded row has wrong length")); + } + if self.rle { + crate::compression::packbits::decode_to_slice(self.bytes, output) + } else { + output.copy_from_slice(self.bytes); + Ok(()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file(psb: bool, depth: u16, channels: u16, height: u32, compression: u16) -> Vec { + let mut b = b"8BPS".to_vec(); + b.extend_from_slice(&(if psb { 2u16 } else { 1 }).to_be_bytes()); + b.extend_from_slice(&[0; 6]); + b.extend_from_slice(&channels.to_be_bytes()); + b.extend_from_slice(&height.to_be_bytes()); + b.extend_from_slice(&2u32.to_be_bytes()); + b.extend_from_slice(&depth.to_be_bytes()); + b.extend_from_slice(&1u16.to_be_bytes()); + b.extend_from_slice(&[0; 8]); + b.extend(std::iter::repeat_n(0, if psb { 8 } else { 4 })); + b.extend_from_slice(&compression.to_be_bytes()); + b + } + + #[test] + fn selected_rows_skip_full_table_and_allow_missing_spot_payload() { + for psb in [false, true] { + for depth in [8, 16, 32] { + let row_bytes = 2 * usize::from(depth / 8); + let mut b = file(psb, depth, 3, 2, 1); + for _ in 0..6 { + if psb { + b.extend_from_slice(&2u32.to_be_bytes()); + } else { + b.extend_from_slice(&2u16.to_be_bytes()); + } + } + for value in 1..=4 { + b.extend_from_slice(&[(1i16 - row_bytes as i16) as u8, value]); + } + let merged = Merged::open(&b, 4).unwrap(); + let rows = merged.encoded_rows(2, row_bytes).unwrap(); + assert_eq!(rows.row_bytes(), row_bytes); + assert!(rows.channel(2).is_err()); + for c in 0..2 { + let mut channel = rows.channel(c).unwrap(); + for y in 0..2 { + let mut out = vec![0; row_bytes]; + channel.next_row().unwrap().unwrap().decode_to_slice(&mut out).unwrap(); + assert_eq!(out, vec![(c * 2 + y + 1) as u8; row_bytes]); + } + assert!(channel.next_row().unwrap().is_none()); + } + assert!(merged.encoded_rows(3, row_bytes).is_err()); + assert!(merged.encoded_rows(2, row_bytes - 1).is_err()); + assert!(merged.encoded_rows(4, row_bytes).is_err()); + } + } + } + + #[test] + fn raw_rows_are_borrowed_and_require_exact_output_length() { + let mut b = file(false, 16, 2, 2, 0); + b.extend(0..16); + let merged = Merged::open(&b, 4).unwrap(); + let rows = merged.encoded_rows(2, 4).unwrap(); + let mut channel = rows.channel(1).unwrap(); + let row = channel.next_row().unwrap().unwrap(); + assert!(row.decode_to_slice(&mut [0; 3]).is_err()); + let mut out = [0; 4]; + row.decode_to_slice(&mut out).unwrap(); + assert_eq!(out, [8, 9, 10, 11]); + channel.next_row().unwrap().unwrap().decode_to_slice(&mut out).unwrap(); + assert_eq!(out, [12, 13, 14, 15]); + assert!(channel.next_row().unwrap().is_none()); + b.pop(); + assert!(Merged::open(&b, 4).unwrap().encoded_rows(2, 4).is_err()); + } + + #[test] + fn strict_rows_reject_short_packets_but_keep_trailing_bytes_and_recovery() { + for encoded in [&[3, 7, 8][..], &[0, 7, 128], &[255, 7, 255], &[252, 7]] { + let mut b = file(false, 16, 1, 1, 1); + b.extend_from_slice(&(encoded.len() as u16).to_be_bytes()); + b.extend_from_slice(encoded); + let merged = Merged::open(&b, 2).unwrap(); + let rows = merged.encoded_rows(1, 4).unwrap(); + let row = rows.channel(0).unwrap().next_row().unwrap().unwrap(); + assert!(row.decode_to_slice(&mut [0; 4]).is_err(), "{encoded:?}"); + } + let mut b = file(false, 16, 1, 1, 1); + b.extend_from_slice(&3u16.to_be_bytes()); + b.extend_from_slice(&[253, 7, 127]); + let merged = Merged::open(&b, 2).unwrap(); + let rows = merged.encoded_rows(1, 4).unwrap(); + let mut out = [0; 4]; + rows.channel(0).unwrap().next_row().unwrap().unwrap().decode_to_slice(&mut out).unwrap(); + assert_eq!(out, [7; 4]); + b.truncate(b.len() - 3); + b.extend_from_slice(&[3, 7, 8]); + let merged = Merged::open(&b, 2).unwrap(); + assert_eq!(merged.read_planes(1).unwrap(), vec![vec![7, 8, 0, 0]]); + } + + #[test] + fn rejects_incomplete_table_payload_and_impossible_expansion_before_output() { + let mut b = file(false, 16, 2, 1, 1); + b.extend_from_slice(&2u16.to_be_bytes()); + assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_err()); + b.extend_from_slice(&2u16.to_be_bytes()); + b.extend_from_slice(&[253]); + assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_err()); + b.push(7); + assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_ok()); + let mut b = file(false, 16, 1, 1, 1); + b.extend_from_slice(&1u16.to_be_bytes()); + b.push(128); + assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_err()); + } +} From 9d5c9cce6947344cdcbe3d5dd731f11b0d2cb2ac Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 16:25:53 -0500 Subject: [PATCH 52/79] psd: add resource writers for alpha names and clipping path (2999) (#2429) --- crates/psd/src/channel_resources.rs | 19 +++++++++++++++++++ crates/psd/src/path.rs | 27 +++++++++++++++++++++++++++ crates/psd/src/resources.rs | 14 ++++++++++++++ crates/psd/src/unicode_names.rs | 23 +++++++++++++++++++++++ 4 files changed, 83 insertions(+) diff --git a/crates/psd/src/channel_resources.rs b/crates/psd/src/channel_resources.rs index 204d36eb03..2dc77b454c 100644 --- a/crates/psd/src/channel_resources.rs +++ b/crates/psd/src/channel_resources.rs @@ -68,6 +68,19 @@ pub fn alternate_spot_colors(data: &[u8]) -> impl ExactSizeIterator(names: impl IntoIterator) -> Vec { + let mut out = Vec::new(); + for name in names { + let legacy = crate::io::encode_legacy_name(name); + crate::io::write_pascal(&mut out, &legacy, 1); + } + out +} + #[cfg(test)] mod tests { use super::*; @@ -108,4 +121,10 @@ mod tests { bytes[2..4].copy_from_slice(&0u16.to_be_bytes()); assert_eq!(alternate_spot_colors(&bytes).len(), 0); } + + #[test] + fn pascal_names_encodes_unpadded_legacy_strings() { + assert_eq!(pascal_names(["Spot Color 1"]), b"\x0cSpot Color 1"); + assert_eq!(pascal_names(["café", "A\nB"]), b"\x04caf?\x03A?B"); + } } diff --git a/crates/psd/src/path.rs b/crates/psd/src/path.rs index 3520a71d81..abfebe9fdb 100644 --- a/crates/psd/src/path.rs +++ b/crates/psd/src/path.rs @@ -252,6 +252,24 @@ impl VectorMaskBlock { } } +/// Extract the raw Pascal-string path name bytes from a Clipping Path Name resource (2999). +/// +/// Returns `None` if the resource is empty or truncated before the declared name length. +pub fn clipping_path_name(data: &[u8]) -> Option<&[u8]> { + let len = usize::from(*data.first()?); + data.get(1..1 + len) +} + +/// Encode a Clipping Path Name resource (2999): legacy Pascal name followed by 16.16 unsigned +/// fixed-point flatness. +pub fn clipping_path_resource(name: &str, flatness: f32) -> Vec { + let legacy = crate::io::encode_legacy_name(name); + let mut out = Vec::with_capacity(1 + legacy.len() + 4); + crate::io::write_pascal(&mut out, &legacy, 1); + out.extend_from_slice(&((flatness.max(0.0) * 65536.0) as u32).to_be_bytes()); + out +} + #[cfg(test)] mod tests { use super::*; @@ -339,4 +357,13 @@ mod tests { assert_eq!(s.len(), 2); assert_eq!(s[0].knots.len(), 3); } + + #[test] + fn clipping_path_resource_roundtrip_and_truncation() { + let bytes = clipping_path_resource("Outline", 1.5); + assert_eq!(bytes, b"\x07Outline\x00\x01\x80\x00"); + assert_eq!(clipping_path_name(&bytes), Some(b"Outline".as_slice())); + assert_eq!(clipping_path_name(&[]), None); + assert_eq!(clipping_path_name(&[5, b'a', b'b']), None); + } } diff --git a/crates/psd/src/resources.rs b/crates/psd/src/resources.rs index d0ac3e83f4..8eefaf25a3 100644 --- a/crates/psd/src/resources.rs +++ b/crates/psd/src/resources.rs @@ -8,10 +8,14 @@ use crate::io::{Reader, WriteExt, write_pascal}; pub mod ids { /// Resolution info (`ResolutionInfo` structure). pub const RESOLUTION_INFO: u16 = 1005; + /// Alpha channel names as unpadded Pascal strings. + pub const ALPHA_NAMES: u16 = 1006; /// Target layer index. pub const LAYER_STATE: u16 = 1024; /// Layer group ids (one u16 per layer). pub const LAYER_GROUP_INFO: u16 = 1026; + /// Grid and guides (legacy v1). + pub const GUIDES: u16 = 1032; /// Legacy (Photoshop 4) thumbnail, BGR. pub const THUMBNAIL_PS4: u16 = 1033; /// Thumbnail (JFIF). @@ -20,6 +24,8 @@ pub mod ids { pub const GLOBAL_ANGLE: u16 = 1037; /// ICC profile. pub const ICC_PROFILE: u16 = 1039; + /// Unicode alpha channel names. + pub const UNICODE_ALPHA_NAMES: u16 = 1045; /// Global altitude. pub const GLOBAL_ALTITUDE: u16 = 1049; /// Version info (has real merged data flag). @@ -32,6 +38,14 @@ pub mod ids { pub const TIMELINE_INFO: u16 = 1075; /// Selected layer ids (`u16` count followed by `u32` ids). pub const LAYER_SELECTION_IDS: u16 = 1069; + /// Clipping path name and flatness. + pub const CLIPPING_PATH: u16 = 2999; +} + +/// Encode a name for a legacy Pascal field: printable ASCII up to 255 bytes, with other +/// characters replaced by `?`. +pub fn encode_legacy_name(s: &str) -> Vec { + crate::io::encode_legacy_name(s) } /// One image resource block. diff --git a/crates/psd/src/unicode_names.rs b/crates/psd/src/unicode_names.rs index c4547243b2..f4a01829a5 100644 --- a/crates/psd/src/unicode_names.rs +++ b/crates/psd/src/unicode_names.rs @@ -24,6 +24,20 @@ pub fn records(mut data: &[u8]) -> impl Iterator { }) } +/// Encode counted NUL-terminated big-endian UTF-16 name records (resource 1045). +pub fn write<'a>(names: impl IntoIterator) -> Vec { + let mut out = Vec::new(); + for name in names { + let count = name.encode_utf16().count().saturating_add(1); + let count_u32 = u32::try_from(count).unwrap_or(u32::MAX); + out.extend_from_slice(&count_u32.to_be_bytes()); + for unit in name.encode_utf16().take(count_u32 as usize - 1).chain(std::iter::once(0)) { + out.extend_from_slice(&unit.to_be_bytes()); + } + } + out +} + #[cfg(test)] mod tests { use super::*; @@ -51,4 +65,13 @@ mod tests { assert_eq!(records(&first[..end]).count(), 0); } } + + #[test] + fn write_roundtrips_with_nul_terminator() { + let bytes = write(["Alpha 1", "café"]); + let decoded: Vec<_> = records(&bytes).collect(); + assert_eq!(decoded.len(), 2); + assert_eq!(decoded[0], [0, b'A', 0, b'l', 0, b'p', 0, b'h', 0, b'a', 0, b' ', 0, b'1', 0, 0]); + assert_eq!(decoded[1], [0, b'c', 0, b'a', 0, b'f', 0, 0xe9, 0, 0]); + } } From 219c1d0b14177af6f291395d6587f61a5e09043a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 16:25:57 -0500 Subject: [PATCH 53/79] dxf: add shared .lin and .pat text parsers (#2434) --- crates/dxf/src/lib.rs | 1 + crates/dxf/src/lin_pat.rs | 391 ++++++++++++++++++++++++++++++++++++ crates/dxf/tests/lin_pat.rs | 180 +++++++++++++++++ 3 files changed, 572 insertions(+) create mode 100644 crates/dxf/src/lin_pat.rs create mode 100644 crates/dxf/tests/lin_pat.rs diff --git a/crates/dxf/src/lib.rs b/crates/dxf/src/lib.rs index c4595bef9f..dcffaf3962 100644 --- a/crates/dxf/src/lib.rs +++ b/crates/dxf/src/lib.rs @@ -12,6 +12,7 @@ use std::io::Write as _; pub mod drawing; +pub mod lin_pat; pub mod model; pub mod mtext; pub mod mtext_tokens; diff --git a/crates/dxf/src/lin_pat.rs b/crates/dxf/src/lin_pat.rs new file mode 100644 index 0000000000..309f0567aa --- /dev/null +++ b/crates/dxf/src/lin_pat.rs @@ -0,0 +1,391 @@ +//! Readers for AutoCAD-compatible linetype (`.lin`) and hatch pattern (`.pat`) text files. +//! +//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then +//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for +//! a pattern), with `;` starting a comment. Everything here treats the text as hostile: lines, +//! definitions, dashes, families and warnings are capped, numbers must be finite and reasonable, +//! and nothing panics. Problems become warnings and the definitions that can be read are kept. + +/// Longest line read; longer lines are skipped with a warning. +pub const MAX_LINE_CHARS: usize = 4096; +/// Most definitions (linetypes or patterns) read from one file. +pub const MAX_DEFINITIONS: usize = 4096; +/// Most elements in one linetype. +pub const MAX_LINETYPE_ELEMENTS: usize = 256; +/// Most line families in one hatch pattern. +pub const MAX_PATTERN_FAMILIES: usize = 1024; +/// Most dashes in one pattern line family. +pub const MAX_PATTERN_DASHES: usize = 256; +/// Largest magnitude accepted for a length, offset or scale. +pub const MAX_VALUE: f64 = 1.0e6; +/// Longest name or description kept. +const MAX_NAME_CHARS: usize = 255; +/// Most warnings collected; the rest are counted in a last line. +const MAX_WARNINGS: usize = 100; + +/// One element of a linetype parsed from a `.lin` file. +#[derive(Clone, Debug, PartialEq)] +pub struct LinDashElement { + /// Dash (`> 0`), gap (`< 0`), or dot (`0`) length in drawing units. + pub length: f64, + /// Embedded text string, if any. + pub text: Option, + /// Text style name for embedded text, if any. + pub style: Option, + /// Text scale factor (`S=`, default `1.0`). + pub scale: f64, + /// Text rotation in radians (`R=`, `A=`, or `U=`, default `0.0`). + pub rotation: f64, + /// Text X/Y offset (`X=`, `Y=`, default `[0.0, 0.0]`). + pub offset: [f64; 2], + /// Whether rotation is absolute (`A=`) rather than relative to the line (`R=` or `U=`). + pub absolute: bool, +} + +impl LinDashElement { + /// A simple dash, gap, or dot element with no embedded text. + #[must_use] + pub fn dash(length: f64) -> Self { + Self { length, text: None, style: None, scale: 1.0, rotation: 0.0, offset: [0.0, 0.0], absolute: false } + } +} + +/// A linetype definition parsed from a `.lin` file. +#[derive(Clone, Debug, PartialEq)] +pub struct LinDefinition { + pub name: String, + pub description: String, + pub pattern: Vec, +} + +/// One line family of a hatch pattern parsed from a `.pat` file. +/// +/// Values are in pattern-definition coordinates as written: `angle` in degrees, `origin` as +/// `[x, y]`, `delta` as `[delta_x, delta_y]` along/perpendicular to the line direction, and +/// `dashes` as dash (`> 0`), gap (`< 0`), and dot (`0`) lengths. +#[derive(Clone, Debug, PartialEq)] +pub struct PatLineFamily { + pub angle: f64, + pub origin: [f64; 2], + pub delta: [f64; 2], + pub dashes: Vec, +} + +/// A hatch pattern definition parsed from a `.pat` file. +#[derive(Clone, Debug, PartialEq)] +pub struct PatDefinition { + pub name: String, + pub description: String, + pub lines: Vec, +} + +/// What a file held: the definitions that could be read, and why anything else was skipped. +#[derive(Clone, Debug, PartialEq)] +pub struct Parsed { + pub items: Vec, + pub warnings: Vec, +} + +impl Default for Parsed { + fn default() -> Self { + Self { items: Vec::new(), warnings: Vec::new() } + } +} + +impl Parsed { + fn warn(&mut self, line: usize, msg: impl Into) { + match self.warnings.len() { + n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())), + MAX_WARNINGS => self.warnings.push("more problems not listed".into()), + _ => {} + } + } +} + +/// A header line `*NAME[,description]`: the name and description, or why it can't be used. +fn header(rest: &str) -> std::result::Result<(String, String), String> { + let (name, desc) = rest.split_once(',').unwrap_or((rest, "")); + let name = name.trim(); + if name.is_empty() { + return Err("a definition without a name".into()); + } + if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) { + return Err("a definition name that is too long or has control characters".into()); + } + let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect(); + Ok((name.to_string(), desc)) +} + +/// A finite number within ±[`MAX_VALUE`]. +fn number(t: &str) -> Option { + t.trim().parse::().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE) +} + +/// The file's text lines with 1-based numbers, without a leading byte-order mark. +fn lines(text: &str) -> impl Iterator { + text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim())) +} + +// ---------- LIN ---------- + +/// Read the linetypes of a `.lin` file. +/// +/// Simple linetypes and complex ones with embedded text +/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`) +/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept. +/// Lengths are in drawing units as written: a user's file is never rescaled. +#[must_use] +pub fn parse_lin(text: &str) -> Parsed { + let mut out = Parsed::default(); + // The definition being read: name, description, header line. + let mut pending: Option<(String, String, usize)> = None; + for (no, line) in lines(text) { + if line.is_empty() || line.starts_with(';') { + continue; + } + if line.chars().count() > MAX_LINE_CHARS { + out.warn(no, "line too long; skipped"); + continue; + } + if let Some(rest) = line.strip_prefix('*') { + if let Some((name, _, at)) = pending.take() { + out.warn(at, format!("linetype {name} has no pattern line; skipped")); + } + match header(rest) { + Ok((name, desc)) => pending = Some((name, desc, no)), + Err(e) => out.warn(no, format!("{e}; skipped")), + } + continue; + } + let Some((name, description, _)) = pending.take() else { + out.warn(no, "pattern line without a *NAME line before it; skipped"); + continue; + }; + if out.items.len() >= MAX_DEFINITIONS { + out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped")); + break; + } + if out.items.iter().any(|l: &LinDefinition| l.name.eq_ignore_ascii_case(&name)) { + out.warn(no, format!("linetype {name} is defined twice; the first definition is kept")); + continue; + } + match lin_pattern(line, no, &name, &mut out) { + Ok(pattern) => out.items.push(LinDefinition { name, description, pattern }), + Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")), + } + } + if let Some((name, _, at)) = pending { + out.warn(at, format!("linetype {name} has no pattern line; skipped")); + } + out +} + +/// Split a pattern line at commas outside `[…]` and `"…"`. +fn lin_fields(line: &str) -> std::result::Result, String> { + let mut out = Vec::new(); + let (mut depth, mut quoted, mut start) = (0usize, false, 0usize); + for (i, c) in line.char_indices() { + match c { + '"' => quoted = !quoted, + '[' if !quoted => depth = depth.saturating_add(1), + ']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?, + ',' if !quoted && depth == 0 => { + out.push(line.get(start..i).unwrap_or("").trim()); + start = i.saturating_add(1); + } + _ => {} + } + if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) { + return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements")); + } + } + if quoted || depth != 0 { + return Err("an unclosed [ or \"".into()); + } + out.push(line.get(start..).unwrap_or("").trim()); + Ok(out) +} + +/// The elements of a pattern line `A,dash,gap,[…],…`. +fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed) -> std::result::Result, String> { + let mut fields = lin_fields(line)?; + // The alignment field ("A") comes first; a line of plain numbers is read as well. + if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) { + fields.remove(0); + } else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) { + return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or(""))); + } + let mut pattern: Vec = Vec::new(); + for f in fields.into_iter().filter(|f| !f.is_empty()) { + if pattern.len() >= MAX_LINETYPE_ELEMENTS { + return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements")); + } + let Some(inner) = f.strip_prefix('[') else { + let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?; + pattern.push(LinDashElement::dash(len)); + continue; + }; + let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?; + match lin_text(inner)? { + Some(text) => { + // The text sits at the end of the element before it (a zero-length one if none). + if pattern.last().is_none_or(|e| e.text.is_some()) { + pattern.push(LinDashElement::dash(0.0)); + } + if let Some(last) = pattern.last_mut() { + *last = LinDashElement { length: last.length, ..text }; + } + } + None => { + let shape = inner.split(',').next().unwrap_or("").trim(); + out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which is not supported here; left out")); + } + } + } + if pattern.is_empty() { + return Err("no dashes".into()); + } + if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) { + return Err("every element has zero length".into()); + } + Ok(pattern) +} + +/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element. +fn lin_text(inner: &str) -> std::result::Result, String> { + let inner = inner.trim(); + let Some(after) = inner.strip_prefix('"') else { return Ok(None) }; + let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?; + if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) { + return Err("embedded text that is too long or has control characters".into()); + } + let mut parts = rest.split(',').map(str::trim); + if !parts.next().unwrap_or("").is_empty() { + return Err("text element: expected a comma after the text".into()); + } + let style = parts.next().unwrap_or("").trim(); + if style.is_empty() || style.contains('=') { + return Err("text element: the text style is missing".into()); + } + let mut e = LinDashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..LinDashElement::dash(0.0) }; + for kv in parts.filter(|p| !p.is_empty()) { + let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?; + match k.trim().to_ascii_uppercase().as_str() { + "S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?, + "X" => e.offset[0] = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?, + "Y" => e.offset[1] = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?, + // Upright text keeps a rotation relative to the line, like R. + k @ ("R" | "A" | "U") => { + e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?; + e.absolute = k == "A"; + } + other => return Err(format!("text element: unknown option `{other}`")), + } + } + Ok(Some(e)) +} + +/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out. +fn angle(t: &str) -> Option { + let t = t.trim().to_ascii_lowercase(); + let (num, unit) = match t.char_indices().last() { + Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c), + _ => (t.as_str(), 'd'), + }; + let v = num.trim().parse::().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?; + Some(match unit { + 'r' => v, + 'g' => v * std::f64::consts::PI / 200.0, + _ => v.to_radians(), + }) +} + +// ---------- PAT ---------- + +/// Read the hatch patterns of a `.pat` file. +/// +/// Values are used as written (an inch file for inch drawings, a millimetre file for metric ones). +#[must_use] +pub fn parse_pat(text: &str) -> Parsed { + let mut out: Parsed = Parsed::default(); + // The pattern being read, its header line, and whether it already failed. + let mut cur: Option<(PatDefinition, usize, bool)> = None; + for (no, line) in lines(text) { + // A comment runs to the end of the line. + let line = line.split(';').next().unwrap_or("").trim(); + if line.is_empty() { + continue; + } + if line.chars().count() > MAX_LINE_CHARS { + out.warn(no, "line too long; skipped"); + continue; + } + if let Some(rest) = line.strip_prefix('*') { + finish_pat(cur.take(), &mut out); + match header(rest) { + Ok((name, description)) => cur = Some((PatDefinition { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)), + Err(e) => out.warn(no, format!("{e}; skipped")), + } + continue; + } + let Some((p, _, failed)) = cur.as_mut() else { + out.warn(no, "line family without a *NAME line before it; skipped"); + continue; + }; + if *failed { + continue; + } + if p.lines.len() >= MAX_PATTERN_FAMILIES { + out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name)); + *failed = true; + continue; + } + match pat_family(line) { + Ok(l) => p.lines.push(l), + Err(e) => { + out.warn(no, format!("pattern {}: {e}; skipped", p.name)); + *failed = true; + } + } + } + finish_pat(cur, &mut out); + out +} + +fn finish_pat(cur: Option<(PatDefinition, usize, bool)>, out: &mut Parsed) { + let Some((p, at, failed)) = cur else { return }; + if failed { + return; + } + if p.lines.is_empty() { + out.warn(at, format!("pattern {} has no line families; skipped", p.name)); + } else if out.items.len() >= MAX_DEFINITIONS { + out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name)); + } else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) { + out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name)); + } else { + out.items.push(p); + } +} + +/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`. +fn pat_family(line: &str) -> std::result::Result { + let mut v = Vec::new(); + for f in line.split(',') { + if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) { + return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family")); + } + let f = f.trim(); + if f.is_empty() && v.len() >= 5 { + continue; + } + v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?); + } + let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else { + return Err("a line family needs angle, x, y, delta-x and delta-y".into()); + }; + if dy.abs() < 1e-9 { + return Err("a line family with zero spacing (delta-y)".into()); + } + Ok(PatLineFamily { angle, origin: [x, y], delta: [dx, dy], dashes: v.get(5..).unwrap_or(&[]).to_vec() }) +} diff --git a/crates/dxf/tests/lin_pat.rs b/crates/dxf/tests/lin_pat.rs new file mode 100644 index 0000000000..afe45d056d --- /dev/null +++ b/crates/dxf/tests/lin_pat.rs @@ -0,0 +1,180 @@ +//! Tests for `.lin` and `.pat` text resource parsing. + +use craft_dxf::lin_pat::{MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, parse_lin, parse_pat}; + +const LIN: &str = "\ +;; my own linetypes +*MYDASH,My dash __ __ __ +A,.5,-.25 + +*MYDOTS +A,0,-.1,0,-.2 +*MYTEXT,Text line --MY--MY-- +A,.5,-.2,[\"MY\",STANDARD,S=.1,R=0.0,X=-0.1,Y=-.05],-.2 +*MYSHAPE,Shape line +A,.25,-.1,[MYBOX,myshapes.shx,S=.1],-.1,1 +"; + +#[test] +fn simple_and_text_linetypes_are_read() { + let r = parse_lin(LIN); + let names: Vec<&str> = r.items.iter().map(|l| l.name.as_str()).collect(); + assert_eq!(names, ["MYDASH", "MYDOTS", "MYTEXT", "MYSHAPE"]); + let dash = &r.items[0]; + assert_eq!(dash.description, "My dash __ __ __"); + assert_eq!(dash.pattern.iter().map(|e| e.length).collect::>(), [0.5, -0.25]); + assert_eq!(r.items[1].description, ""); + assert_eq!(r.items[1].pattern.len(), 4); + + // The text belongs to the gap before it: drawn at that gap's end. + let text = &r.items[2].pattern; + assert_eq!(text.len(), 3); + assert_eq!(text[1].length, -0.2); + assert_eq!(text[1].text.as_deref(), Some("MY")); + assert_eq!(text[1].style.as_deref(), Some("STANDARD")); + assert!((text[1].scale - 0.1).abs() < 1e-12); + assert!((text[1].offset[0] + 0.1).abs() < 1e-12 && (text[1].offset[1] + 0.05).abs() < 1e-12); + assert!(!text[1].absolute); + assert!(text[2].text.is_none()); + + // Shapes need SHX files: left out with a note, the dashes kept. + let shape = &r.items[3].pattern; + assert_eq!(shape.iter().map(|e| e.length).collect::>(), [0.25, -0.1, -0.1, 1.0]); + assert!(shape.iter().all(|e| e.text.is_none())); + assert!(r.warnings.iter().any(|w| w.contains("MYBOX")), "{:?}", r.warnings); +} + +#[test] +fn text_rotation_units_and_absolute_angles() { + let r = parse_lin("*R1\nA,1,[\"x\",S1,A=90,S=1],-1\n*R2\nA,1,[\"x\",S1,R=1.5r],-1\n*R3\nA,1,[\"a,b]\",S1,U=100g],-1\n"); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + let rot = |i: usize| r.items[i].pattern[0].rotation; + assert!((rot(0) - std::f64::consts::FRAC_PI_2).abs() < 1e-12 && r.items[0].pattern[0].absolute); + assert!((rot(1) - 1.5).abs() < 1e-12); + assert!((rot(2) - std::f64::consts::FRAC_PI_2).abs() < 1e-12); + // Commas and brackets inside the quoted text are text. + assert_eq!(r.items[2].pattern[0].text.as_deref(), Some("a,b]")); +} + +#[test] +fn broken_linetypes_are_skipped_with_warnings() { + let text = "\ +*NOPATTERN +*BADNUM +A,.5,abc +*BADALIGN +B,.5,-.5 +*UNCLOSED +A,.5,[\"x\",S1 +* +A,1,-1 +A,1,-1 +*GOOD +A,1,-1 +*GOOD +A,2,-2 +*ZERO +A,0,0 +*NOSTYLE +A,1,[\"x\"],-1 +"; + let r = parse_lin(text); + assert_eq!(r.items.iter().map(|l| l.name.as_str()).collect::>(), ["GOOD"]); + assert_eq!(r.items[0].pattern[0].length, 1.0, "the first definition is kept"); + for what in ["NOPATTERN", "BADNUM", "BADALIGN", "UNCLOSED", "without a name", "without a *NAME", "defined twice", "ZERO", "NOSTYLE"] { + assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings); + } +} + +#[test] +fn hostile_linetype_files_never_panic_and_stay_capped() { + let long_line = format!("*LONG\nA,{}", vec!["1"; 5000].join(",")); + let many = format!("*MANY\nA,{}", vec!["1,-1"; MAX_LINETYPE_ELEMENTS].join(",")); + let defs: String = (0..5000).map(|i| format!("*L{i}\nA,1,-1\n")).collect(); + let huge = "*HUGE\nA,1e300,-1\n*NAN\nA,NaN,-1\n*INF\nA,inf,-1\n"; + for text in [long_line.as_str(), many.as_str(), defs.as_str(), huge, "", "\u{feff}", "]]][[[\"", "*\u{0}\nA,1", "A,1,-1\n*X,", "*X\nA,[[[[\"]]]"] + { + let r = parse_lin(text); + assert!(r.items.len() <= 4096); + assert!(r.items.iter().all(|l| l.pattern.len() <= MAX_LINETYPE_ELEMENTS && l.pattern.iter().all(|e| e.length.is_finite()))); + assert!(r.warnings.len() <= 101); + } + assert!(parse_lin(huge).items.is_empty()); + assert_eq!(parse_lin(&defs).items.len(), 4096); +} + +const PAT: &str = "\ +; my own patterns +*MYGRID, My grid +0, 0,0, 0,.5 +90, 0,0, 0,.5 +*MYBRICK,My brick ; trailing comment +0, 0,0, 0,.25 +90, 0,0, .25,.25, .25,-.25 +"; + +#[test] +fn hatch_patterns_are_read() { + let r = parse_pat(PAT); + assert!(r.warnings.is_empty(), "{:?}", r.warnings); + assert_eq!(r.items.len(), 2); + let grid = &r.items[0]; + assert_eq!((grid.name.as_str(), grid.description.as_str()), ("MYGRID", "My grid")); + assert_eq!(grid.lines.len(), 2); + assert_eq!(grid.lines[1].angle, 90.0); + assert_eq!(grid.lines[1].delta, [0.0, 0.5]); + let brick = &r.items[1]; + assert_eq!(brick.description, "My brick"); + assert_eq!(brick.lines[1].origin, [0.0, 0.0]); + assert_eq!(brick.lines[1].dashes, [0.25, -0.25]); +} + +#[test] +fn lowercase_pattern_names_are_upper_cased() { + let r = parse_pat("*mypat\n45,0,0,0,.125\n"); + assert_eq!(r.items[0].name, "MYPAT"); +} + +#[test] +fn broken_patterns_are_skipped_with_warnings() { + let text = "\ +0,0,0,0,1 +*EMPTY +*SHORT +0,0,0 +*ZEROGAP +0,0,0,1,0 +*BADNUM +0,0,0,0,x +*OK +0,0,0,0,1 +*OK +45,0,0,0,1 +"; + let r = parse_pat(text); + assert_eq!(r.items.iter().map(|p| p.name.as_str()).collect::>(), ["OK"]); + assert_eq!(r.items[0].lines[0].angle, 0.0, "the first definition is kept"); + for what in ["without a *NAME", "EMPTY", "SHORT", "ZEROGAP", "BADNUM", "defined twice"] { + assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings); + } +} + +#[test] +fn hostile_pattern_files_never_panic_and_stay_capped() { + let families = format!("*FAM\n{}", "0,0,0,0,1\n".repeat(MAX_PATTERN_FAMILIES + 5)); + let dashes = format!("*DASH\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES + 1].join(",")); + let ok_dashes = format!("*DASHOK\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES].join(",")); + let defs: String = (0..5000).map(|i| format!("*P{i}\n0,0,0,0,1\n")).collect(); + let big = "*BIG\n1e300,0,0,0,1\n*NAN\nNaN,0,0,0,1\n"; + for text in [families.as_str(), dashes.as_str(), ok_dashes.as_str(), defs.as_str(), big, "", "*", "***\n,,,,,", "*X\n,,,,,,,,,,"] { + let r = parse_pat(text); + assert!(r.items.len() <= 4096); + assert!(r.items.iter().all(|p| p.lines.len() <= MAX_PATTERN_FAMILIES && p.lines.iter().all(|l| l.dashes.len() <= MAX_PATTERN_DASHES))); + assert!(r.warnings.len() <= 101); + } + assert!(parse_pat(&families).items.is_empty()); + assert!(parse_pat(&dashes).items.is_empty()); + assert_eq!(parse_pat(&ok_dashes).items.len(), 1); + assert!(parse_pat(big).items.is_empty()); + assert_eq!(parse_pat(&defs).items.len(), 4096); +} From 6a5ff3d4fdd1051b0609b3a05265e52fa2c3a826 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Fri, 20 Nov 2026 06:07:30 +0800 Subject: [PATCH 54/79] psd: open merged composites without image resources (#2426) --- crates/psd/src/merged.rs | 178 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 176 insertions(+), 2 deletions(-) diff --git a/crates/psd/src/merged.rs b/crates/psd/src/merged.rs index 25392819c0..4741d738cf 100644 --- a/crates/psd/src/merged.rs +++ b/crates/psd/src/merged.rs @@ -1,5 +1,5 @@ //! Borrowed, merged-only PSD reader that skips layer records and decodes selected planes. -use crate::{Head, PsdError, Result}; +use crate::{Head, HeadView, PsdError, Result}; mod rows; pub use rows::{ChannelRows, EncodedRow, EncodedRows}; @@ -89,13 +89,37 @@ impl<'a> Merged<'a> { /// Open the merged section with a pixel limit. This skips layer records, preserving the ability /// to read a composite when its layer data is not understood. No image planes are allocated. pub fn open(bytes: &'a [u8], max_pixels: u64) -> Result { + Self::check_pixel_limit(bytes, max_pixels)?; + Self::from_head(bytes, Head::from_bytes(bytes)?, max_pixels) + } + + /// Open the merged section while omitting all image resources, including valid records. + /// + /// This validates the header and declared section boundaries but skips the resource records. + /// Callers choose when to use it, for example after detecting damaged resources during a strict + /// open. The returned reader borrows the original file and only copies its color-mode data; + /// no resource payloads or image planes are allocated. + pub fn open_without_resources(bytes: &'a [u8], max_pixels: u64) -> Result { + Self::check_pixel_limit(bytes, max_pixels)?; + let view = HeadView::from_bytes(bytes)?; + let mut color_mode_data = Vec::new(); + color_mode_data.try_reserve_exact(view.color_mode_data.len()).map_err(|_| PsdError::OutOfMemory("color-mode data"))?; + color_mode_data.extend_from_slice(view.color_mode_data); + let head = Head { header: view.header, color_mode_data, resources: Vec::new(), layer_section_offset: view.layer_section_offset }; + Self::from_head(bytes, head, max_pixels) + } + + fn check_pixel_limit(bytes: &[u8], max_pixels: u64) -> Result<()> { // Refuse a declared oversized canvas before copying color-mode data or resources. if let Some((w, h)) = declared_dimensions(bytes) && u64::from(w) * u64::from(h) > max_pixels { return Err(PsdError::LimitExceeded("pixel count")); } - let head = Head::from_bytes(bytes)?; + Ok(()) + } + + fn from_head(bytes: &'a [u8], head: Head, max_pixels: u64) -> Result { let h = &head.header; if u64::from(h.width) * u64::from(h.height) > max_pixels { return Err(PsdError::LimitExceeded("pixel count")); @@ -319,4 +343,154 @@ mod tests { mt16.extend_from_slice(b"8BIMMt16\0\0\0\0"); assert!(Merged::open(&with_layer(&mt16), 4).unwrap().transparency); } + + #[test] + fn resource_skipping_open_reads_psd_raw_and_psb_packbits_from_original_bytes() { + for (version, compression) in [(1, 0), (2, 1)] { + let valid_resources = recovery_resource(); + let mut damaged_resources = valid_resources.clone(); + damaged_resources.extend_from_slice(b"BAD!"); + let (bytes, data_offset) = recovery_file(version, compression, &damaged_resources); + let (control_bytes, _) = recovery_file(version, compression, &[]); + let control = Merged::open(&control_bytes, 4).unwrap(); + + assert!(Head::from_bytes(&bytes).is_err()); + assert!(Merged::open(&bytes, 4).is_err()); + let recovered = Merged::open_without_resources(&bytes, 4).unwrap(); + assert!(std::ptr::eq(recovered.bytes, bytes.as_slice())); + assert_eq!(recovered.data_offset, data_offset); + assert_eq!(recovered.head.header, control.head.header); + assert_eq!(recovered.head.color_mode_data, [9, 8]); + assert!(recovered.head.resources.is_empty()); + assert_eq!(recovered.compression, compression); + assert!(recovered.transparency); + assert_eq!(recovered.transparency, control.transparency); + assert_eq!(recovered.read_planes(2).unwrap(), vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]]); + assert_eq!(recovered.read_planes(2).unwrap(), control.read_planes(2).unwrap()); + recovered.validate_all().unwrap(); + + let (valid_bytes, _) = recovery_file(version, compression, &valid_resources); + let strict = Merged::open(&valid_bytes, 4).unwrap(); + assert_eq!(strict.head.resources.len(), 1); + assert_eq!(strict.head.resources[0].id, 1039); + assert_eq!(strict.head.resources[0].data, [7, 6]); + let skipped = Merged::open_without_resources(&valid_bytes, 4).unwrap(); + assert!(skipped.head.resources.is_empty()); + assert_eq!(skipped.read_planes(2).unwrap(), strict.read_planes(2).unwrap()); + } + } + + #[test] + fn resource_skipping_open_ignores_truncated_resource_payload() { + for version in [1, 2] { + let mut resources = recovery_resource(); + resources[8..12].copy_from_slice(&100u32.to_be_bytes()); + let (bytes, _) = recovery_file(version, 0, &resources); + assert!(Merged::open(&bytes, 4).is_err()); + let recovered = Merged::open_without_resources(&bytes, 4).unwrap(); + assert!(recovered.head.resources.is_empty()); + assert_eq!(recovered.read_planes(1).unwrap(), vec![vec![1, 2, 3, 4]]); + } + } + + #[test] + fn resource_skipping_open_checks_pixel_limit_before_malformed_head() { + let (mut bytes, _) = recovery_file(1, 0, b"BAD!"); + bytes.truncate(22); + bytes[..4].copy_from_slice(b"BAD!"); + assert!(matches!(Merged::open_without_resources(&bytes, 3), Err(PsdError::LimitExceeded("pixel count")))); + assert!(matches!(Merged::open(&bytes, 3), Err(PsdError::LimitExceeded("pixel count")))); + } + + #[test] + fn resource_skipping_open_rejects_out_of_bounds_sections_and_tail_framing() { + for version in [1, 2] { + let (bytes, data_offset) = recovery_file(version, 0, b"BAD!"); + let mut invalid_header = bytes.clone(); + invalid_header[..4].copy_from_slice(b"BAD!"); + assert!(Merged::open_without_resources(&invalid_header, 4).is_err()); + + let mut color_outside_file = bytes.clone(); + color_outside_file[26..30].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(Merged::open_without_resources(&color_outside_file, 4).is_err()); + let mut resources_outside_file = bytes.clone(); + resources_outside_file[32..36].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(Merged::open_without_resources(&resources_outside_file, 4).is_err()); + + let layer_offset = crate::HeadView::from_bytes(&bytes).unwrap().layer_section_offset as usize; + let length_width = if version == 2 { 8 } else { 4 }; + assert!(Merged::open_without_resources(&bytes[..layer_offset + length_width - 1], 4).is_err()); + let mut layer_outside_file = bytes.clone(); + layer_outside_file[layer_offset..layer_offset + length_width].fill(0xff); + assert!(Merged::open_without_resources(&layer_outside_file, 4).is_err()); + assert!(Merged::open_without_resources(&bytes[..data_offset - 1], 4).is_err()); + } + } + + #[test] + fn resource_skipping_open_preserves_selected_plane_and_full_validation_distinction() { + for (version, compression) in [(1, 0), (2, 1)] { + let (mut bytes, _) = recovery_file(version, compression, b"BAD!"); + bytes.truncate(bytes.len() - if compression == 0 { 4 } else { 6 }); + let recovered = Merged::open_without_resources(&bytes, 4).unwrap(); + assert_eq!(recovered.read_planes(1).unwrap(), vec![vec![1, 2, 3, 4]]); + assert!(recovered.read_planes(2).is_err()); + assert!(recovered.validate_all().is_err()); + } + } + + fn recovery_resource() -> Vec { + let mut bytes = b"8BIM".to_vec(); + bytes.extend_from_slice(&1039u16.to_be_bytes()); + bytes.extend_from_slice(&[0, 0]); + bytes.extend_from_slice(&2u32.to_be_bytes()); + bytes.extend_from_slice(&[7, 6]); + bytes + } + + fn recovery_file(version: u16, compression: u16, resources: &[u8]) -> (Vec, usize) { + let mut bytes = b"8BPS".to_vec(); + bytes.extend_from_slice(&version.to_be_bytes()); + bytes.extend_from_slice(&[0; 6]); + bytes.extend_from_slice(&2u16.to_be_bytes()); + bytes.extend_from_slice(&2u32.to_be_bytes()); + bytes.extend_from_slice(&2u32.to_be_bytes()); + bytes.extend_from_slice(&8u16.to_be_bytes()); + bytes.extend_from_slice(&1u16.to_be_bytes()); + bytes.extend_from_slice(&2u32.to_be_bytes()); + bytes.extend_from_slice(&[9, 8]); + bytes.extend_from_slice(&(resources.len() as u32).to_be_bytes()); + bytes.extend_from_slice(resources); + let mut layer = Vec::new(); + if version == 2 { + layer.extend_from_slice(&2u64.to_be_bytes()); + } else { + layer.extend_from_slice(&2u32.to_be_bytes()); + } + layer.extend_from_slice(&(-1i16).to_be_bytes()); + if version == 2 { + bytes.extend_from_slice(&(layer.len() as u64).to_be_bytes()); + } else { + bytes.extend_from_slice(&(layer.len() as u32).to_be_bytes()); + } + bytes.extend_from_slice(&layer); + bytes.extend_from_slice(&compression.to_be_bytes()); + let data_offset = bytes.len(); + if compression == 0 { + bytes.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]); + } else { + for _ in 0..4 { + if version == 2 { + bytes.extend_from_slice(&3u32.to_be_bytes()); + } else { + bytes.extend_from_slice(&3u16.to_be_bytes()); + } + } + for row in [[1, 2], [3, 4], [5, 6], [7, 8]] { + bytes.push(1); + bytes.extend_from_slice(&row); + } + } + (bytes, data_offset) + } } From a559fd3abc3801d970770d8b719bad596f771bb9 Mon Sep 17 00:00:00 2001 From: Mex <44814932+MMexicann@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:41:52 +0100 Subject: [PATCH 55/79] fix(mcp-server): reject invalid JSON-RPC versions before dispatch (#2444) * fix(mcp): validate JSON-RPC versions before dispatch Reject malformed request envelopes before tool or lifecycle effects. Companion to storytold/gridcraft#4210 after the shared-server migration. * test(mcp): cover invalid version markers across transports Actual shared crate: baseline 18 passed and 3 new regressions failed; fixed 21 passed. Repository formatting and strict production Clippy pass. --- crates/mcp-server/src/server.rs | 4 +++ crates/mcp-server/src/tests.rs | 57 +++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/crates/mcp-server/src/server.rs b/crates/mcp-server/src/server.rs index e0d064da5e..17f04fe636 100644 --- a/crates/mcp-server/src/server.rs +++ b/crates/mcp-server/src/server.rs @@ -243,6 +243,10 @@ impl Server { }; return Some(error(echoed, INVALID_REQUEST, "missing `method`")); }; + // A malformed envelope must not dispatch a tool or change notification state. + if o.get("jsonrpc").and_then(Value::as_str) != Some("2.0") { + return Some(error(Value::Null, INVALID_REQUEST, "`jsonrpc` must be \"2.0\"")); + } let params = o.get("params").cloned().unwrap_or(Value::Null); let Some(id) = id else { if method == "notifications/initialized" { diff --git a/crates/mcp-server/src/tests.rs b/crates/mcp-server/src/tests.rs index 3f8f8d315f..bf273c81ef 100644 --- a/crates/mcp-server/src/tests.rs +++ b/crates/mcp-server/src/tests.rs @@ -48,6 +48,63 @@ fn serve_with(tools: T, lines: &[Value]) -> (Server, Vec) { (s, replies) } +fn malformed_version_messages() -> Vec { + let mut messages = Vec::new(); + for version in [None, Some(Value::Null), Some(json!("1.0")), Some(json!(2.0)), Some(json!(true)), Some(json!([])), Some(json!({}))] { + for mut message in [ + json!({"id": 1, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "changed"}}}), + json!({"method": "notifications/initialized"}), + ] { + if let Some(version) = &version { + message["jsonrpc"] = version.clone(); + } + messages.push(message); + } + } + messages +} + +fn invalid_version_reply() -> Value { + json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32600, "message": "`jsonrpc` must be \"2.0\""}}) +} + +/// Invalid envelopes are refused before listing or calling tools or changing lifecycle state. +#[test] +fn invalid_jsonrpc_versions_never_dispatch() { + for message in malformed_version_messages() { + let mut s = Server::new(info(), Echo::default()); + let response = s.handle(message.clone()).unwrap(); + assert_eq!(response, invalid_version_reply(), "{message}"); + assert!(s.tools().log.is_empty(), "{message}"); + assert!(!s.is_initialized(), "{message}"); + } +} + +/// The stdio entry point validates every envelope and still leaves valid notifications unanswered. +#[test] +fn stdio_refuses_invalid_jsonrpc_versions() { + let messages = malformed_version_messages(); + let (mut s, replies) = serve(&messages); + assert_eq!(replies, vec![invalid_version_reply(); messages.len()]); + assert!(s.tools().log.is_empty()); + assert!(!s.is_initialized()); + assert_eq!(reply(&mut s, &json!({"jsonrpc": "2.0", "method": "notifications/initialized"})), None); + assert!(s.is_initialized()); +} + +/// Batch dispatch uses the same validation while continuing to answer valid requests. +#[test] +fn batches_refuse_invalid_jsonrpc_versions() { + let mut messages = malformed_version_messages(); + let mut expected = vec![invalid_version_reply(); messages.len()]; + messages.push(ping(9)); + expected.push(json!({"jsonrpc": "2.0", "id": 9, "result": {}})); + let mut s = Server::new(info(), Echo::default()); + assert_eq!(reply(&mut s, &Value::Array(messages)), Some(Value::Array(expected))); + assert!(s.tools().log.is_empty()); + assert!(!s.is_initialized()); +} + /// A registered tool is listed and called over the stdio transport, with no engine behind it. #[test] fn a_registered_tool_is_served_over_stdio() { From 352c589d89c136d29858769ee5ee5c94aa655001 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 19 Nov 2026 23:45:24 +0100 Subject: [PATCH 56/79] RAW-DNG: gate JPEG XL tests on the codec feature (#2381) The DNG integration target also runs when JPEG XL decoding is disabled. Gate the five JPEG XL cases and their fixture helpers on the jxl feature so a DNG-only test run checks the codecs available in that build. The full JPEG XL regressions remain enabled when jxl is selected. Co-authored-by: pancake --- crates/raw/tests/it/dng.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/raw/tests/it/dng.rs b/crates/raw/tests/it/dng.rs index 21074a8288..e4c41b1566 100644 --- a/crates/raw/tests/it/dng.rs +++ b/crates/raw/tests/it/dng.rs @@ -749,6 +749,7 @@ fn malformed_profile_look_tags_are_ignored() { } /// Lossless JPEG XL codestream of `px` (`w × h × cpp` interleaved), 16-bit unless `eight`. +#[cfg(feature = "jxl")] fn jxl_encode(px: &[u16], w: usize, h: usize, cpp: usize, eight: bool) -> Vec { use zune_core::bit_depth::BitDepth; use zune_core::colorspace::ColorSpace; @@ -765,6 +766,7 @@ fn jxl_encode(px: &[u16], w: usize, h: usize, cpp: usize, eight: bool) -> Vec Vec { let mut b = vec![0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a, 0, 0, 0, 0x14]; b.extend_from_slice(b"ftypjxl \0\0\0\0jxl "); @@ -777,6 +779,7 @@ fn jxl_container(cs: &[u8]) -> Vec { /// A tiled JPEG XL raw IFD of `px`. Edge tiles alternate between being coded at their in-image size /// and padded to the nominal tile size (with junk the decoder must drop); tiles alternate between bare /// codestreams and containers. +#[cfg(feature = "jxl")] fn jxl_tiled(px: &[u16], w: usize, h: usize, cpp: usize, bits: u16, cfa: bool, tile: (usize, usize)) -> IfdBuilder { let (tw, th) = tile; let mut tiles = Vec::new(); @@ -804,6 +807,7 @@ fn jxl_tiled(px: &[u16], w: usize, h: usize, cpp: usize, bits: u16, cfa: bool, t } #[test] +#[cfg(feature = "jxl")] fn jpeg_xl_tiles_decode_bit_exactly() { let (w, h) = (37, 29); // LinearRaw 3 × 16-bit, the full code range @@ -831,6 +835,7 @@ fn jpeg_xl_tiles_decode_bit_exactly() { } #[test] +#[cfg(feature = "jxl")] fn malformed_jpeg_xl_tiles_are_errors() { use craft_raw::RawError; let (w, h) = (16, 16); @@ -868,6 +873,7 @@ fn malformed_jpeg_xl_tiles_are_errors() { /// One undecodable tile makes the whole image an error: it is never returned with a black tile. #[test] +#[cfg(feature = "jxl")] fn a_jpeg_xl_tile_that_fails_is_an_error_for_the_image() { use craft_raw::RawError; let (w, h) = (32, 16); @@ -890,6 +896,7 @@ fn a_jpeg_xl_tile_that_fails_is_an_error_for_the_image() { /// about twice what one plane may use, and is an error rather than an allocation the header asks /// for. The same samples without the alpha channel decode. #[test] +#[cfg(feature = "jxl")] fn jpeg_xl_tiles_beyond_their_decode_budget_are_errors() { use craft_raw::RawError; use zune_core::bit_depth::BitDepth; @@ -911,6 +918,7 @@ fn jpeg_xl_tiles_beyond_their_decode_budget_are_errors() { } #[test] +#[cfg(feature = "jxl")] fn jpeg_xl_preview_ifd_is_offered() { let raw = synthetic(16, 16, Some(Cfa::bayer("RGGB").unwrap()), 1); let RawData::U16(px) = &raw.data else { unreachable!() }; From 42e0bd548246c4d34637b2b75945c9ce8ec9f98b Mon Sep 17 00:00:00 2001 From: Terra854 Date: Fri, 20 Nov 2026 06:50:06 +0800 Subject: [PATCH 57/79] Add a craft-raw decoder comparison example (#2417) * Add a craft-raw decoder comparison example * Clean up RAW decoder report test fixtures * craft-raw: say the report hashes decoded samples and which revisions build it The digest covers RawImage::data, after any decoder linearization, so the README now says "decoded samples" and explains that two stored codes that map to the same value give the same digest. The copy-into-an-older-checkout instructions now name the first main revision the example builds on (ecee6933, #1171): older revisions have no Cfa origin fields. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: FredApps Co-authored-by: Claude Opus 5.5 --- crates/raw/README.md | 56 +++++ crates/raw/examples/decode_report/main.rs | 35 ++++ crates/raw/examples/decode_report/report.rs | 154 ++++++++++++++ crates/raw/tests/it/decode_report.rs | 217 ++++++++++++++++++++ crates/raw/tests/it/main.rs | 2 + 5 files changed, 464 insertions(+) create mode 100644 crates/raw/examples/decode_report/main.rs create mode 100644 crates/raw/examples/decode_report/report.rs create mode 100644 crates/raw/tests/it/decode_report.rs diff --git a/crates/raw/README.md b/crates/raw/README.md index d17dd62d74..d709e7047e 100644 --- a/crates/raw/README.md +++ b/crates/raw/README.md @@ -216,3 +216,59 @@ decode bit-exactly; lossy tiles are made with `jpeg-encoder`, JPEG XL tiles with (tests only). Hostile input: every truncation of each sample, byte mutations across the header, 400 random mutations per property, random TIFF-like, lossless-JPEG, opcode-list and CIFF bytes, and a test per limit. + +## Decoder comparison reports + +The native `decode_report` example records the decoded sensor samples and selected metadata for an +explicit, ordered list of local files. It reads one regular file at a time, accepts at most 512 MiB +of encoded bytes per file, and uses `Limits::default()` for decoding. + +```sh +cargo run --quiet --locked --release -p craft-raw --example decode_report -- fixture-a.dng fixture-b.nef > report.tsv +``` + +Use shell redirection that preserves native stdout bytes. The report is UTF-8 TSV with LF line +endings, a header, and one row per argument, indexed from 1. Schema version 1 has these columns in +this order. + +```text +schema input status format sample_type sample_count sensor_sha256 width height cpp bits cfa active_area crop orientation baseline_exposure_bits +``` + +`format` is a fixed lowercase decoder label, such as `dng` or `cfa_tiff`. `sample_type` is `u16` or +`f32`. `sensor_sha256` hashes the complete decoded sample sequence (`RawImage::data`), encoding +each integer as two little-endian bytes and each float's IEEE 754 bits as four little-endian bytes. +The digest is 64 lowercase hexadecimal digits. It reflects any mapping the decoder has already +applied, such as a DNG `LinearizationTable`, so two stored codes that map to the same value give the +same digest. Shape and metadata have their own columns, so an orientation change +can be distinguished from a sample change. + +`cfa` is `width,height,origin_x,origin_y:pattern`, where the pattern is a comma-separated row-major +sequence. It is empty for images without a CFA. Active area and crop are `x,y,width,height`, with +crop coordinates relative to the active area. Orientation is the Exif integer code, and baseline +exposure is the `f64` bit pattern as 16 lowercase hexadecimal digits. + +Each row's status is `ok`, `read_error`, `input_limit`, `not_raw`, `unsupported`, `corrupt`, +`decode_limit`, or `tiff_error`. `input_limit` means the encoded-byte cap was exceeded. +`decode_limit` covers RAW and TIFF decoder limits. A failed input has empty fields after `status`, +and processing continues. The report contains input ordinals, with paths and free-form diagnostics +omitted. A completed batch exits successfully even when inputs fail. No arguments or a report +write or flush failure produces a nonzero exit and a concise diagnostic on stderr. + +To compare two pinned decoder revisions, use separate clean checkouts and keep the example source, +enabled features, and ordered fixture list identical. If a revision predates the example, copy both +`examples/decode_report/main.rs` and `examples/decode_report/report.rs` at the same relative paths +under that checkout's `crates/raw/` directory. The example uses the crate's existing `sha2` dev +dependency. It builds on `main` from +[`ecee6933`](https://github.com/storytold/craft-libs/commit/ecee693322c27acdbcafed4b57066356404e8378) +(#1171, 2026-11-13) onwards, the first revision whose `Cfa` has `origin_x` and `origin_y`. Older +revisions fail to build it. Build and save one report from each checkout, then compare them. + +```sh +git diff --no-index -- before.tsv after.tsv +``` + +Repeat on the same revision to check deterministic output. Record both decoder revisions, the +example source revision, enabled features, fixture checksums and order with the reports. A diff +exit status of 1 indicates differing reports. Inspect the status, sample digest, shape and metadata +columns to identify the change. diff --git a/crates/raw/examples/decode_report/main.rs b/crates/raw/examples/decode_report/main.rs new file mode 100644 index 0000000000..94b7225623 --- /dev/null +++ b/crates/raw/examples/decode_report/main.rs @@ -0,0 +1,35 @@ +//! Report the decoded samples and selected metadata of explicitly supplied RAW files. +//! `cargo run --locked -p craft-raw --example decode_report -- [ ...]` +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +#[cfg(not(target_arch = "wasm32"))] +mod report; + +#[cfg(not(target_arch = "wasm32"))] +fn main() -> std::process::ExitCode { + use std::io::{self, Write}; + use std::process::ExitCode; + + let stdout = io::stdout(); + let mut out = stdout.lock(); + match report::run(std::env::args_os().skip(1), &mut out, report::MAX_INPUT_BYTES, &craft_raw::Limits::default()) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + let stderr = io::stderr(); + let mut err = stderr.lock(); + match error { + report::RunError::Usage => { + let _ = writeln!(err, "usage: decode_report [ ...]"); + } + report::RunError::Output(error) => { + let _ = writeln!(err, "decode_report: report output failed ({:?})", error.kind()); + } + } + ExitCode::FAILURE + } + } +} + +#[cfg(target_arch = "wasm32")] +fn main() {} diff --git a/crates/raw/examples/decode_report/report.rs b/crates/raw/examples/decode_report/report.rs new file mode 100644 index 0000000000..2d0c14dc05 --- /dev/null +++ b/crates/raw/examples/decode_report/report.rs @@ -0,0 +1,154 @@ +use std::ffi::OsString; +use std::fs::{self, File}; +use std::io::{self, Read, Write}; +use std::path::Path; + +use craft_raw::{Limits, RawData, RawError, RawFormat, RawImage, Rect}; +use craft_tiff::TiffError; +use sha2::{Digest, Sha256}; + +pub(super) const MAX_INPUT_BYTES: u64 = 512 * 1024 * 1024; +const SCHEMA: u8 = 1; +const HEADER: &str = "schema\tinput\tstatus\tformat\tsample_type\tsample_count\tsensor_sha256\twidth\theight\tcpp\tbits\tcfa\tactive_area\tcrop\torientation\tbaseline_exposure_bits"; + +#[derive(Debug)] +pub(super) enum RunError { + Usage, + Output(io::Error), +} + +pub(super) fn run(paths: impl IntoIterator, out: &mut impl Write, max_input_bytes: u64, limits: &Limits) -> Result<(), RunError> { + let mut paths = paths.into_iter().peekable(); + if paths.peek().is_none() { + return Err(RunError::Usage); + } + writeln!(out, "{HEADER}").map_err(RunError::Output)?; + for (index, path) in paths.enumerate() { + let input = index + 1; + let result = read_input(Path::new(&path), max_input_bytes) + .map_err(|failure| match failure { + InputFailure::Read => "read_error", + InputFailure::Limit => "input_limit", + }) + .and_then(|bytes| craft_raw::decode_with(&bytes, limits).map_err(decode_status)); + match result { + Ok(raw) => write_success(out, input, &raw), + Err(status) => write_failure(out, input, status), + } + .map_err(RunError::Output)?; + } + out.flush().map_err(RunError::Output) +} + +enum InputFailure { + Read, + Limit, +} + +fn read_input(path: &Path, max_input_bytes: u64) -> Result, InputFailure> { + // Reject non-regular paths before opening, and check the opened file again. + check_input(&fs::metadata(path).map_err(|_| InputFailure::Read)?, max_input_bytes)?; + let file = File::open(path).map_err(|_| InputFailure::Read)?; + check_input(&file.metadata().map_err(|_| InputFailure::Read)?, max_input_bytes)?; + let mut bytes = Vec::new(); + // A file may grow after the metadata check. Read at most one extra byte to detect it. + file.take(max_input_bytes.saturating_add(1)).read_to_end(&mut bytes).map_err(|_| InputFailure::Read)?; + if bytes.len() as u64 > max_input_bytes { + return Err(InputFailure::Limit); + } + Ok(bytes) +} + +fn check_input(metadata: &fs::Metadata, max_input_bytes: u64) -> Result<(), InputFailure> { + if !metadata.is_file() { + return Err(InputFailure::Read); + } + if metadata.len() > max_input_bytes { + return Err(InputFailure::Limit); + } + Ok(()) +} + +fn decode_status(error: RawError) -> &'static str { + match error { + RawError::NotRaw => "not_raw", + RawError::Unsupported(_) => "unsupported", + RawError::Corrupt(_) => "corrupt", + RawError::Limit(_) | RawError::Tiff(TiffError::Limit(_)) => "decode_limit", + RawError::Tiff(_) => "tiff_error", + } +} + +fn write_failure(out: &mut impl Write, input: usize, status: &str) -> io::Result<()> { + // Keep all 13 success-only fields present and empty. + writeln!(out, "{SCHEMA}\t{input}\t{status}\t\t\t\t\t\t\t\t\t\t\t\t\t") +} + +fn write_success(out: &mut impl Write, input: usize, raw: &RawImage) -> io::Result<()> { + let mut hash = Sha256::new(); + let (sample_type, count) = match &raw.data { + RawData::U16(samples) => { + for sample in samples { + hash.update(sample.to_le_bytes()); + } + ("u16", samples.len()) + } + RawData::F32(samples) => { + for sample in samples { + hash.update(sample.to_bits().to_le_bytes()); + } + ("f32", samples.len()) + } + }; + let digest = hash.finalize(); + write!( + out, + "{SCHEMA}\t{input}\tok\t{}\t{sample_type}\t{count}\t{digest:x}\t{}\t{}\t{}\t{}\t", + format_label(raw.format), + raw.width, + raw.height, + raw.cpp, + raw.bits, + )?; + if let Some(cfa) = &raw.cfa { + write!(out, "{},{},{},{}:", cfa.width, cfa.height, cfa.origin_x, cfa.origin_y)?; + let mut pattern = cfa.pattern.iter(); + if let Some(first) = pattern.next() { + write!(out, "{first}")?; + for channel in pattern { + write!(out, ",{channel}")?; + } + } + } + write_rect(out, raw.active_area)?; + write_rect(out, raw.crop)?; + writeln!(out, "\t{}\t{:016x}", raw.orientation.to_exif(), raw.color.baseline_exposure.to_bits()) +} + +fn write_rect(out: &mut impl Write, rect: Rect) -> io::Result<()> { + write!(out, "\t{},{},{},{}", rect.x, rect.y, rect.width, rect.height) +} + +fn format_label(format: RawFormat) -> &'static str { + match format { + RawFormat::Dng => "dng", + RawFormat::Cr2 => "cr2", + RawFormat::Cr3 => "cr3", + RawFormat::Nef => "nef", + RawFormat::Nrw => "nrw", + RawFormat::Arw => "arw", + RawFormat::Raf => "raf", + RawFormat::Orf => "orf", + RawFormat::Rw2 => "rw2", + RawFormat::Pef => "pef", + RawFormat::Srw => "srw", + RawFormat::Crw => "crw", + RawFormat::Mrw => "mrw", + RawFormat::X3f => "x3f", + RawFormat::CfaTiff => "cfa_tiff", + RawFormat::KodakDcs => "kodak_dcs", + RawFormat::Erf => "erf", + RawFormat::Mef => "mef", + RawFormat::OtherTiff => "other_tiff", + } +} diff --git a/crates/raw/tests/it/decode_report.rs b/crates/raw/tests/it/decode_report.rs new file mode 100644 index 0000000000..89c800ce69 --- /dev/null +++ b/crates/raw/tests/it/decode_report.rs @@ -0,0 +1,217 @@ +use super::dng::{base_ifd, dng, synthetic}; +use craft_raw::{BlackLevel, Cfa, DngCompression, DngWriteOptions, Limits, Orientation, RawData, RawImage, write_dng}; +use craft_tiff::{ByteOrder, ImageData, Value, tags}; +use std::ffi::OsString; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; + +#[path = "../../examples/decode_report/report.rs"] +mod report; + +const HEADER: &str = concat!( + "schema\tinput\tstatus\tformat\tsample_type\tsample_count\tsensor_sha256\twidth\theight\tcpp\tbits\tcfa\t", + "active_area\tcrop\torientation\tbaseline_exposure_bits\n", +); + +struct FixtureDir(PathBuf); + +impl FixtureDir { + fn new(test: &str) -> Self { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")); + for attempt in 0..1000 { + let path = root.join(format!("decode-report-{test}-{}-{attempt}", std::process::id())); + // Only clean up a directory this test created, even if a process ID was reused. + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("create fixture directory {}: {error}", path.display()), + } + } + panic!("no free fixture directory for {test}"); + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for FixtureDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn integer_raw() -> RawImage { + let mut raw = synthetic(16, 16, Some(Cfa::bayer("RGGB").unwrap()), 1); + raw.data = RawData::U16((256..512).collect()); + raw.color.baseline_exposure = 0.5; + raw +} + +fn float_raw() -> RawImage { + let mut raw = synthetic(16, 16, None, 3); + raw.data = RawData::F32((0..16 * 16 * 3).map(|i| (i % 16) as f32 / 16.0).collect()); + raw.black = BlackLevel::uniform(0.0); + raw.white = vec![1.0]; + raw.color.baseline_exposure = 0.5; + raw +} + +fn write_fixture(dir: &Path, name: &str, raw: &RawImage, order: ByteOrder) -> OsString { + let bytes = write_dng(raw, &DngWriteOptions { compression: DngCompression::Uncompressed, order, ..Default::default() }).unwrap(); + write_bytes(dir, name, &bytes) +} + +fn write_bytes(dir: &Path, name: &str, bytes: &[u8]) -> OsString { + let path = dir.join(name); + std::fs::write(&path, bytes).unwrap(); + path.into_os_string() +} + +fn run_report(paths: &[OsString], max_input_bytes: u64, limits: &Limits) -> Vec { + let mut output = Vec::new(); + assert!(report::run(paths.iter().cloned(), &mut output, max_input_bytes, limits).is_ok()); + output +} + +#[test] +fn reports_exact_samples_shape_and_metadata_in_argument_order() { + let fixtures = FixtureDir::new("success"); + let dir = fixtures.path(); + let original = integer_raw(); + let integer = write_fixture(dir, "integer.dng", &original, ByteOrder::Little); + let float = write_fixture(dir, "float.dng", &float_raw(), ByteOrder::Big); + + let mut changed_sample = original.clone(); + let RawData::U16(samples) = &mut changed_sample.data else { + panic!("integer fixture must contain integer samples"); + }; + samples[127] += 1; + let changed_sample = write_fixture(dir, "changed-sample.dng", &changed_sample, ByteOrder::Little); + + let mut rotated = original; + rotated.orientation = Orientation::Normal; + let rotated = write_fixture(dir, "changed-orientation.dng", &rotated, ByteOrder::Little); + + let paths = [integer.clone(), float, changed_sample, rotated, integer]; + let limits = Limits::default(); + let first = run_report(&paths, report::MAX_INPUT_BYTES, &limits); + assert_eq!(first, run_report(&paths, report::MAX_INPUT_BYTES, &limits)); + + // The digests were generated independently from the known little-endian u16 and f32 bytes. + let rows = concat!( + "1\t1\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + "1\t2\tok\tdng\tf32\t768\tc50a4d270d6140ad9988fd8002c5b5de4a78b0b8d598b4db1a5a5385bd4119fd\t16\t16\t3\t32\t\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + "1\t3\tok\tdng\tu16\t256\t3ebf95a27aa36848dc2fc39f537625913e29fd1d390c41b50a527f27f1d5ce91\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + "1\t4\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t1\t3fe0000000000000\n", + "1\t5\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n", + ); + assert_eq!(String::from_utf8(first).unwrap(), format!("{HEADER}{rows}")); +} + +fn report_rows(text: &str) -> Vec> { + text.strip_prefix(HEADER) + .unwrap() + .lines() + .map(|line| { + let fields: Vec<_> = line.split('\t').collect(); + assert_eq!(fields.len(), 16); + fields + }) + .collect() +} + +#[test] +fn reports_mixed_failures_and_keeps_the_last_success() { + let fixtures = FixtureDir::new("mixed"); + let dir = fixtures.path(); + let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little); + let unreadable = dir.join("missing.dng").into_os_string(); + let text = write_bytes(dir, "private-fixture-name.txt", b"not a recognized RAW header"); + + let mut unsupported = base_ifd(8, 6, 16, 2, false); + unsupported.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![vec![0; 8 * 6 * 2 * 2]] }); + let unsupported = write_bytes(dir, "unsupported.dng", &dng(unsupported, ByteOrder::Little)); + + let mut corrupt = base_ifd(8, 6, 16, 1, true); + corrupt.set(tags::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 2])); + corrupt.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![vec![0; 8 * 6 * 2]] }); + let corrupt = write_bytes(dir, "corrupt.dng", &dng(corrupt, ByteOrder::Little)); + + let missing_strips = dng(base_ifd(8, 6, 16, 1, true), ByteOrder::Little); + let tiff_error = write_bytes(dir, "missing-strips.dng", &missing_strips); + let paths = [integer.clone(), unreadable, text, unsupported, corrupt, tiff_error, integer]; + let limits = Limits::default(); + let first = run_report(&paths, report::MAX_INPUT_BYTES, &limits); + assert_eq!(first, run_report(&paths, report::MAX_INPUT_BYTES, &limits)); + + let text = String::from_utf8(first).unwrap(); + assert!(!text.contains("private-fixture-name")); + assert!(!text.contains("CFAPattern size mismatch")); + let rows = report_rows(&text); + let statuses = ["ok", "read_error", "not_raw", "unsupported", "corrupt", "tiff_error", "ok"]; + assert_eq!(rows.len(), statuses.len()); + for (index, (row, status)) in rows.iter().zip(statuses).enumerate() { + assert_eq!(row[0], "1"); + assert_eq!(row[1], (index + 1).to_string()); + assert_eq!(row[2], status); + if status != "ok" { + assert!(row[3..].iter().all(|field| field.is_empty())); + } + } + assert_eq!(rows[0][2..], rows[6][2..]); +} + +#[test] +fn separates_encoded_file_and_shared_decoder_limits() { + let fixtures = FixtureDir::new("limits"); + let dir = fixtures.path(); + let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little); + let size = std::fs::metadata(Path::new(&integer)).unwrap().len(); + let paths = [integer]; + for (max_input_bytes, max_samples, status) in [(size, 256, "ok"), (size - 1, 256, "input_limit"), (size, 255, "decode_limit")] { + let mut limits = Limits::default(); + limits.max_samples = max_samples; + let output = String::from_utf8(run_report(&paths, max_input_bytes, &limits)).unwrap(); + let rows = report_rows(&output); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0][..3], ["1", "1", status]); + if status != "ok" { + assert!(rows[0][3..].iter().all(|field| field.is_empty())); + } + } +} + +#[test] +fn empty_arguments_report_usage_without_writing_a_header() { + let mut output = Vec::new(); + let result = report::run([], &mut output, report::MAX_INPUT_BYTES, &Limits::default()); + assert!(matches!(result, Err(report::RunError::Usage))); + assert!(output.is_empty()); +} + +struct BrokenOutput { + write_error: bool, +} + +impl Write for BrokenOutput { + fn write(&mut self, bytes: &[u8]) -> io::Result { + if self.write_error { Err(io::Error::from(io::ErrorKind::BrokenPipe)) } else { Ok(bytes.len()) } + } + + fn flush(&mut self) -> io::Result<()> { + Err(io::Error::from(io::ErrorKind::WriteZero)) + } +} + +#[test] +fn write_and_flush_errors_fail_the_invocation() { + let fixtures = FixtureDir::new("output-error"); + let dir = fixtures.path(); + let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little); + for (write_error, kind) in [(true, io::ErrorKind::BrokenPipe), (false, io::ErrorKind::WriteZero)] { + let mut out = BrokenOutput { write_error }; + let result = report::run([integer.clone()], &mut out, report::MAX_INPUT_BYTES, &Limits::default()); + assert!(matches!(result, Err(report::RunError::Output(error)) if error.kind() == kind)); + } +} diff --git a/crates/raw/tests/it/main.rs b/crates/raw/tests/it/main.rs index 30f3312630..a13bdf29f5 100644 --- a/crates/raw/tests/it/main.rs +++ b/crates/raw/tests/it/main.rs @@ -1,5 +1,7 @@ //! The integration tests, one module per file, linked into one test binary. +#[cfg(all(feature = "dng", not(target_arch = "wasm32")))] +mod decode_report; #[cfg(feature = "dng")] mod dng; #[cfg(feature = "line-dng")] From ea9407b3500488bd8af71eb0f1b950306315bf7e Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:06:57 +0700 Subject: [PATCH 58/79] svg: share compact path command formatting (#778) [skip ci] (#2453) --- crates/svg/src/write.rs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/write.rs b/crates/svg/src/write.rs index af3eec992b..7fb4986914 100644 --- a/crates/svg/src/write.rs +++ b/crates/svg/src/write.rs @@ -229,12 +229,22 @@ pub fn path_data(path: &BezPath) -> String { /// Path data with `decimals` decimals per coordinate, written compactly: `M1.00 2.00L3.50 2.00Z`. /// Coordinates that are not finite are written as zero. pub fn path_data_fixed(path: &BezPath, decimals: usize) -> String { + path_data_with_format(path, |value| num(value, decimals)) +} + +/// Compact absolute path commands with caller-owned coordinate formatting. +/// +/// The formatter is called once per coordinate, in path order. It must produce a valid SVG +/// number (including handling nonfinite inputs); it controls rounding and negative zero. +/// Command letters and separators are shared, while the application's precision policy stays +/// with the caller. No intermediate geometry or coordinate collection is allocated. +pub fn path_data_with_format(path: &BezPath, mut format: impl FnMut(f64) -> T) -> String { let mut d = String::new(); let mut command = |letter: char, points: &[Point]| { d.push(letter); for (i, p) in points.iter().enumerate() { let sep = if i == 0 { "" } else { " " }; - let _ = write!(d, "{sep}{} {}", num(p.x, decimals), num(p.y, decimals)); + let _ = write!(d, "{sep}{} {}", format(p.x), format(p.y)); } }; for el in path.elements() { @@ -400,6 +410,25 @@ mod tests { p } + #[test] + fn custom_path_format_keeps_commands_and_coordinate_order() { + let mut path = BezPath::new(); + path.move_to((1.0, 2.0)); + path.line_to((3.0, 4.0)); + path.quad_to((5.0, 6.0), (7.0, 8.0)); + path.curve_to((9.0, 10.0), (11.0, 12.0), (13.0, 14.0)); + path.close_path(); + let mut seen = Vec::new(); + let output = path_data_with_format(&path, |v| { + seen.push(v); + v + }); + assert_eq!(output, "M1 2L3 4Q5 6 7 8C9 10 11 12 13 14Z"); + assert_eq!(seen, (1..=14).map(f64::from).collect::>()); + assert_eq!(BezPath::from_svg(&output).unwrap(), path); + assert_eq!(path_data_with_format(&BezPath::new(), |_: f64| -> String { panic!("empty path") }), ""); + } + #[test] fn scene_can_keep_fixed_view_box_without_changing_default_output() { let scene = Scene { width_mm: 100.0, height_mm: 150.0, view_box: [0.0, 0.0, 100.0, 150.0], elements: vec![] }; From 01c89f9a23a401ab1bc16357b2e5b1007a7dd685 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 18:32:24 -0500 Subject: [PATCH 59/79] idml: add reusable designmap schema emission (#778) (#2455) * idml: separate reusable designmap schema emission (#778) * test(idml): split designmap schema roundtrip test for clippy --- crates/idml/src/model/document.rs | 332 +++++++++++++++++++++++++++++- crates/idml/src/model/mod.rs | 6 +- crates/idml/tests/model.rs | 129 ++++++++++++ 3 files changed, 464 insertions(+), 3 deletions(-) diff --git a/crates/idml/src/model/document.rs b/crates/idml/src/model/document.rs index 830b95a3f3..c66840a153 100644 --- a/crates/idml/src/model/document.rs +++ b/crates/idml/src/model/document.rs @@ -2,7 +2,13 @@ use craft_xml::El; -use super::{AlternatingFillValues, AlternatingStrokeValues, Spread, Story, StrokeValues, Values}; +use super::{AlternatingFillValues, AlternatingStrokeValues, MojikumiRow, Spread, Story, StrokeValues, Values}; +use crate::value::{escape_id, num}; +use crate::{prop, with_props}; + +fn bool_str(value: bool) -> &'static str { + if value { "true" } else { "false" } +} /// One IDML table-of-contents style entry before document style names are resolved. #[derive(Clone, Debug, Default, PartialEq)] @@ -190,6 +196,20 @@ impl ConditionValues { visible: values.get("Visible") != Some("false"), } } + + /// Emits a `Condition` element from these metadata values. + pub fn to_el(&self) -> El { + let name = self.name.as_deref().unwrap_or(""); + let self_id = self.self_id.clone().unwrap_or_else(|| format!("Condition/{}", escape_id(name))); + let rgb = self.indicator_rgb.unwrap_or([0, 0, 0]); + El::new("Condition") + .with_attr("Self", self_id) + .with_attr("Name", name) + .with_attr("IndicatorColor", format!("{} {} {}", rgb[0], rgb[1], rgb[2])) + .with_attr("IndicatorMethod", "UseUnderline") + .with_attr("UnderlineIndicatorAppearance", "Solid") + .with_attr("Visible", bool_str(self.visible)) + } } /// Parsed IDML numbering-list metadata. @@ -292,6 +312,11 @@ impl TableStyleValues { } impl NumberingListValues { + /// The default IDML numbering list (`$ID/[Default]`). + pub fn default_list() -> Self { + Self { name: "$ID/[Default]".into(), continue_across_stories: false } + } + /// Reads a `NumberingList` element. pub fn from_el(el: &El) -> Self { let values = Values::of(el); @@ -300,6 +325,15 @@ impl NumberingListValues { continue_across_stories: values.boolean("ContinueNumbersAcrossStories") == Some(true), } } + + /// Emits a `NumberingList` element. + pub fn to_el(&self) -> El { + El::new("NumberingList") + .with_attr("Self", format!("NumberingList/{}", escape_id(&self.name))) + .with_attr("Name", &self.name) + .with_attr("ContinueNumbersAcrossStories", bool_str(self.continue_across_stories)) + .with_attr("ContinueNumbersAcrossDocuments", "false") + } } impl EpubSplitValues { @@ -355,6 +389,302 @@ impl TextVariableValues { kind, } } + + /// Emits a `TextVariable` element with its type-specific preference child. + pub fn to_el(&self) -> El { + let pref = |name: &str| El::new(name).with_attr("TextBefore", &self.before); + let (ty, settings) = match &self.kind { + TextVariableKind::CustomText { text } => ("CustomTextType", Some(pref("CustomTextVariablePreference").with_attr("Contents", text))), + TextVariableKind::LastPageNumber { section } => ( + "LastPageNumberType", + Some( + pref("PageNumberVariablePreference") + .with_attr("Format", "Current") + .with_attr("Scope", if *section { "SectionScope" } else { "DocumentScope" }), + ), + ), + TextVariableKind::ChapterNumber => ("ChapterNumberType", Some(pref("ChapterNumberVariablePreference").with_attr("Format", "Current"))), + TextVariableKind::FileName { extension } => ( + "FileNameType", + Some(pref("FileNameVariablePreference").with_attr("IncludePath", "false").with_attr("IncludeExtension", bool_str(*extension))), + ), + TextVariableKind::Date { kind, format } => { + let ty = match kind { + TextDateKind::Creation => "CreationDateType", + TextDateKind::Modification => "ModificationDateType", + TextDateKind::Output => "OutputDateType", + }; + (ty, Some(pref("DateVariablePreference").with_attr("Format", format))) + } + TextVariableKind::RunningHeader { style, character, last_on_page } => { + let (ty, el, key) = if *character { + ("MatchCharacterStyleType", "MatchCharacterStylePreference", "AppliedCharacterStyle") + } else { + ("MatchParagraphStyleType", "MatchParagraphStylePreference", "AppliedParagraphStyle") + }; + let strategy = if *last_on_page { "LastOnPage" } else { "FirstOnPage" }; + ( + ty, + Some( + pref(el) + .with_attr(key, style) + .with_attr("SearchStrategy", strategy) + .with_attr("ChangeCase", "None") + .with_attr("DeleteEndPunctuation", "false"), + ), + ) + } + TextVariableKind::CrossReference { page_number } => (if *page_number { "XrefPageNumberType" } else { "XrefChapterNumberType" }, None), + TextVariableKind::Imported { variable_type, settings_element, settings } => { + let el = (!settings_element.is_empty()).then(|| El { name: settings_element.clone(), attrs: settings.clone(), children: Vec::new() }); + (variable_type.as_str(), el) + } + }; + let self_id = self.self_id.clone().unwrap_or_else(|| format!("dTextVariablen{}", self.name)); + let mut el = El::new("TextVariable").with_attr("Self", self_id).with_attr("Name", &self.name).with_attr("VariableType", ty); + if let Some(mut s) = settings { + if !matches!(self.kind, TextVariableKind::Imported { .. }) { + s.set_attr("TextAfter", &self.after); + } + el.push(s); + } + el + } +} + +/// The standard `[No Language]` and `English: USA` `Language` elements emitted in `designmap.xml`. +pub fn default_languages() -> [El; 2] { + [ + El::new("Language") + .with_attr("Self", "Language/$ID/[No Language]") + .with_attr("Name", "$ID/[No Language]") + .with_attr("SingleQuotes", "''") + .with_attr("DoubleQuotes", "\"\"") + .with_attr("PrimaryLanguageName", "$ID/[No Language]") + .with_attr("SublanguageName", "$ID/[No Language]") + .with_attr("Id", "0") + .with_attr("HyphenationVendor", "$ID/") + .with_attr("SpellingVendor", "$ID/"), + El::new("Language") + .with_attr("Self", "Language/$ID/English%3a USA") + .with_attr("Name", "$ID/English: USA") + .with_attr("SingleQuotes", "\u{2018}\u{2019}") + .with_attr("DoubleQuotes", "\u{201C}\u{201D}") + .with_attr("PrimaryLanguageName", "$ID/English") + .with_attr("SublanguageName", "$ID/USA") + .with_attr("Id", "269") + .with_attr("HyphenationVendor", "Hunspell") + .with_attr("SpellingVendor", "Hunspell"), + ] +} + +/// The built-in cross-reference chapter/page number `TextVariable` elements. +pub fn default_xref_text_variables() -> [El; 2] { + [("XRefChapterNumber", "XrefChapterNumberType"), ("XRefPageNumber", "XrefPageNumberType")].map(|(name, ty)| { + let full_name = format!("TV {name}"); + El::new("TextVariable").with_attr("Self", format!("dTextVariablen{full_name}")).with_attr("Name", &full_name).with_attr("VariableType", ty) + }) +} + +/// Reusable IDML `KinsokuTable` schema values. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct KinsokuTableValues { + pub name: String, + pub cant_begin_line_chars: String, + pub cant_end_line_chars: String, + pub cant_be_separated_chars: String, + pub hanging_punctuation_chars: String, +} + +impl KinsokuTableValues { + /// Emits a `KinsokuTable` element. + pub fn to_el(&self) -> El { + El::new("KinsokuTable") + .with_attr("Self", format!("KinsokuTable/{}", escape_id(&self.name))) + .with_attr("Name", &self.name) + .with_attr("CantBeginLineChars", &self.cant_begin_line_chars) + .with_attr("CantEndLineChars", &self.cant_end_line_chars) + .with_attr("CantBeSeparatedChars", &self.cant_be_separated_chars) + .with_attr("HangingPunctuationChars", &self.hanging_punctuation_chars) + } +} + +/// Reusable IDML `MojikumiTable` schema values. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MojikumiTableValues { + pub name: String, + pub based_on: String, + pub overrides: Vec, +} + +impl MojikumiTableValues { + /// Emits a `MojikumiTable` element with optional spacing overrides. + pub fn to_el(&self) -> El { + let mut el = El::new("MojikumiTable").with_attr("Self", format!("MojikumiTable/{}", escape_id(&self.name))).with_attr("Name", &self.name); + if !self.based_on.is_empty() { + el.set_attr("BasedOnMojikumiSet", &self.based_on); + } + if !self.overrides.is_empty() { + let mut list = El::new("OverrideMojikumiAkiList"); + for r in &self.overrides { + list.push( + El::new("OverrideMojikumiAkiType") + .with_attr("TargetMojikumiClass", r.target_class.to_string()) + .with_attr("SideMojikumiClass", r.side_class.to_string()) + .with_attr("SideIsAfterTarget", bool_str(r.after)) + .with_attr("Minimum", num(r.minimum)) + .with_attr("Desired", num(r.desired)) + .with_attr("Maximum", num(r.maximum)) + .with_attr("CompressionPriority", r.priority.to_string()) + .with_attr("AkiDoesNotFloat", bool_str(r.does_not_float)), + ); + } + let mut props = El::new("Properties"); + props.push(list); + el.push(props); + } + el + } +} + +/// IDML `LayerColor` property value: either a named enumeration or an RGB triplet. +#[derive(Clone, Debug, PartialEq)] +pub enum LayerColorValue { + Named(String), + Rgb([f64; 3]), +} + +/// Reusable IDML `Layer` schema values. +#[derive(Clone, Debug, PartialEq)] +pub struct LayerValues { + pub self_id: String, + pub name: String, + pub visible: bool, + pub locked: bool, + pub ignore_wrap: bool, + pub show_guides: bool, + pub lock_guides: bool, + pub printable: bool, + pub color: LayerColorValue, +} + +impl LayerValues { + /// Emits a `Layer` element with its `` child. + pub fn to_el(&self) -> El { + let color = match &self.color { + LayerColorValue::Named(name) => prop("LayerColor", "enumeration", name), + LayerColorValue::Rgb(rgb) => { + let mut el = El::new("LayerColor").with_attr("type", "list"); + for c in rgb { + el.push(prop("ListItem", "double", num(*c))); + } + el + } + }; + let el = El::new("Layer") + .with_attr("Self", &self.self_id) + .with_attr("Name", &self.name) + .with_attr("Visible", bool_str(self.visible)) + .with_attr("Locked", bool_str(self.locked)) + .with_attr("IgnoreWrap", bool_str(self.ignore_wrap)) + .with_attr("ShowGuides", bool_str(self.show_guides)) + .with_attr("LockGuides", bool_str(self.lock_guides)) + .with_attr("UI", "true") + .with_attr("Expendable", "true") + .with_attr("Printable", bool_str(self.printable)); + with_props(el, vec![color]) + } +} + +/// Reusable IDML `Section` schema values. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SectionValues { + pub self_id: String, + pub length: usize, + pub name: String, + pub continue_numbering: bool, + pub include_section_prefix: bool, + pub page_number_start: Option, + pub marker: String, + pub page_start: String, + pub section_prefix: String, + pub alternate_layout: Option<(String, usize)>, + pub page_number_style: String, +} + +impl SectionValues { + /// Emits a `Section` element with its `` child. + pub fn to_el(&self) -> El { + let mut el = El::new("Section") + .with_attr("Self", &self.self_id) + .with_attr("Length", self.length.to_string()) + .with_attr("Name", &self.name) + .with_attr("ContinueNumbering", bool_str(self.continue_numbering)) + .with_attr("IncludeSectionPrefix", bool_str(self.include_section_prefix)); + if let Some(n) = self.page_number_start { + el.set_attr("PageNumberStart", n.to_string()); + } + el = el.with_attr("Marker", &self.marker).with_attr("PageStart", &self.page_start).with_attr("SectionPrefix", &self.section_prefix); + if let Some((layout, layout_len)) = &self.alternate_layout { + el = el.with_attr("AlternateLayout", layout).with_attr("AlternateLayoutLength", layout_len.to_string()); + } + with_props(el, vec![prop("PageNumberStyle", "enumeration", &self.page_number_style)]) + } +} + +/// Emits a `HyperlinkURLDestination` element. +pub fn hyperlink_url_destination_el(self_id: &str, name: &str, url: &str) -> El { + El::new("HyperlinkURLDestination") + .with_attr("Self", self_id) + .with_attr("Name", name) + .with_attr("DestinationURL", url) + .with_attr("Hidden", "false") +} + +/// Emits a `HyperlinkPageDestination` element. +pub fn hyperlink_page_destination_el(self_id: &str, name: &str, destination_page: &str) -> El { + El::new("HyperlinkPageDestination") + .with_attr("Self", self_id) + .with_attr("Name", name) + .with_attr("DestinationPage", destination_page) + .with_attr("ViewSetting", "FitPage") + .with_attr("Hidden", "false") +} + +/// Emits a `HyperlinkPageItemSource` element. +pub fn hyperlink_page_item_source_el(self_id: &str, name: &str, source_page_item: &str) -> El { + El::new("HyperlinkPageItemSource") + .with_attr("Self", self_id) + .with_attr("Name", name) + .with_attr("SourcePageItem", source_page_item) + .with_attr("Hidden", "false") +} + +/// Emits a `Hyperlink` element joining `source` and `destination`. +pub fn hyperlink_el(self_id: &str, name: &str, source: &str, destination: &str, visible: bool, destination_unique_key: u64) -> El { + let el = El::new("Hyperlink") + .with_attr("Self", self_id) + .with_attr("Name", name) + .with_attr("Source", source) + .with_attr("Visible", bool_str(visible)) + .with_attr("Highlight", "None") + .with_attr("Width", "Thin") + .with_attr("BorderStyle", "Solid") + .with_attr("Hidden", "false") + .with_attr("DestinationUniqueKey", (destination_unique_key & 0xFFFF_FFFF).to_string()); + with_props(el, vec![prop("Destination", "object", destination)]) +} + +/// Emits the root `ColorGroup` (`ColorGroup/[Root Color Group]`) with `ColorGroupSwatch` children. +pub fn root_color_group_el(swatch_ids: &[String], swatch_id_prefix: &str) -> El { + let mut cg = El::new("ColorGroup") + .with_attr("Self", "ColorGroup/[Root Color Group]") + .with_attr("Name", "[Root Color Group]") + .with_attr("IsRootColorGroup", "true"); + for (n, id) in swatch_ids.iter().enumerate() { + cg.push(El::new("ColorGroupSwatch").with_attr("Self", format!("{swatch_id_prefix}ColorGroupSwatch{n:x}")).with_attr("SwatchItemRef", id)); + } + cg } impl TocStyleValues { diff --git a/crates/idml/src/model/mod.rs b/crates/idml/src/model/mod.rs index a4560b22e8..99fb8a12fb 100644 --- a/crates/idml/src/model/mod.rs +++ b/crates/idml/src/model/mod.rs @@ -22,8 +22,10 @@ mod story; use craft_xml::{El, Local, Node}; pub use document::{ - CellStyleValues, ConditionValues, CrossReferenceBuildingBlock, CrossReferenceFormatValues, EpubSplitValues, ModelDocument, NumberingListValues, - TableStyleValues, TextDateKind, TextVariableKind, TextVariableValues, TocStyleEntryValues, TocStyleValues, TopLevelKind, TopLevelNode, + CellStyleValues, ConditionValues, CrossReferenceBuildingBlock, CrossReferenceFormatValues, EpubSplitValues, KinsokuTableValues, LayerColorValue, + LayerValues, ModelDocument, MojikumiTableValues, NumberingListValues, SectionValues, TableStyleValues, TextDateKind, TextVariableKind, + TextVariableValues, TocStyleEntryValues, TocStyleValues, TopLevelKind, TopLevelNode, default_languages, default_xref_text_variables, + hyperlink_el, hyperlink_page_destination_el, hyperlink_page_item_source_el, hyperlink_url_destination_el, root_color_group_el, }; pub use effects::{ DirectionalFeatherValues, DropShadowValues, FeatherValues, GradientFeatherValues, ObjectStyleStack, OpacityStopValues, TransparencySetting, diff --git a/crates/idml/tests/model.rs b/crates/idml/tests/model.rs index 075a77c821..33d5e3df4c 100644 --- a/crates/idml/tests/model.rs +++ b/crates/idml/tests/model.rs @@ -280,3 +280,132 @@ fn text_variable_decoration_uses_preference_and_falls_back_to_legacy_root_values let variable = craft_idml::model::TextVariableValues::from_el(&legacy); assert_eq!((variable.before.as_str(), variable.after.as_str()), ("of ", " pages")); } + +#[test] +fn designmap_schema_elements_roundtrip_expected_attributes() { + use craft_idml::model::{ + ConditionValues, KinsokuTableValues, LayerColorValue, LayerValues, MojikumiRow, MojikumiTableValues, NumberingListValues, SectionValues, + TextDateKind, TextVariableKind, TextVariableValues, default_languages, default_xref_text_variables, hyperlink_el, + hyperlink_page_destination_el, hyperlink_page_item_source_el, hyperlink_url_destination_el, root_color_group_el, + }; + + let langs = default_languages(); + assert_eq!(langs[0].attr("Self"), Some("Language/$ID/[No Language]")); + assert_eq!(langs[1].attr("Self"), Some("Language/$ID/English%3a USA")); + assert_eq!(langs[1].attr("Id"), Some("269")); + + let num_list = NumberingListValues::default_list().to_el(); + assert_eq!(num_list.attr("Self"), Some("NumberingList/$ID/[Default]")); + assert_eq!(num_list.attr("ContinueNumbersAcrossDocuments"), Some("false")); + + let kinsoku = KinsokuTableValues { + name: "My:Kinsoku".into(), + cant_begin_line_chars: "。".into(), + cant_end_line_chars: "「".into(), + cant_be_separated_chars: "…".into(), + hanging_punctuation_chars: "、".into(), + } + .to_el(); + assert_eq!(kinsoku.attr("Self"), Some("KinsokuTable/My%3aKinsoku")); + assert_eq!(kinsoku.attr("CantBeginLineChars"), Some("。")); + + let mojikumi = MojikumiTableValues { + name: "Custom%1".into(), + based_on: "Base".into(), + overrides: vec![MojikumiRow { + target_class: 1, + side_class: 2, + after: true, + minimum: 0.0, + desired: 0.25, + maximum: 0.5, + priority: 3, + does_not_float: false, + }], + } + .to_el(); + assert_eq!(mojikumi.attr("Self"), Some("MojikumiTable/Custom%251")); + assert_eq!(mojikumi.attr("BasedOnMojikumiSet"), Some("Base")); + let row = mojikumi.child("Properties").and_then(|p| p.child("OverrideMojikumiAkiList")).and_then(|l| l.child("OverrideMojikumiAkiType")).unwrap(); + assert_eq!(row.attr("TargetMojikumiClass"), Some("1")); + assert_eq!(row.attr("SideIsAfterTarget"), Some("true")); + + let cond = ConditionValues { self_id: None, name: Some("A:B".into()), indicator_rgb: Some([10, 20, 30]), visible: true }.to_el(); + assert_eq!(cond.attr("Self"), Some("Condition/A%3aB")); + assert_eq!(cond.attr("IndicatorColor"), Some("10 20 30")); + assert_eq!(cond.attr("Visible"), Some("true")); + + let xrefs = default_xref_text_variables(); + assert_eq!(xrefs[0].attr("VariableType"), Some("XrefChapterNumberType")); + assert_eq!(xrefs[1].attr("VariableType"), Some("XrefPageNumberType")); + + let tv = TextVariableValues { + self_id: None, + name: "Mod".into(), + before: "Updated ".into(), + after: "!".into(), + kind: TextVariableKind::Date { kind: TextDateKind::Modification, format: "yyyy-MM-dd".into() }, + } + .to_el(); + assert_eq!(tv.attr("VariableType"), Some("ModificationDateType")); + let pref = tv.child("DateVariablePreference").unwrap(); + assert_eq!(pref.attr("TextBefore"), Some("Updated ")); + assert_eq!(pref.attr("TextAfter"), Some("!")); + assert_eq!(pref.attr("Format"), Some("yyyy-MM-dd")); +} + +#[test] +fn designmap_layers_sections_and_hyperlinks_roundtrip_expected_attributes() { + use craft_idml::model::{ + LayerColorValue, LayerValues, SectionValues, hyperlink_el, hyperlink_page_destination_el, hyperlink_page_item_source_el, + hyperlink_url_destination_el, root_color_group_el, + }; + + let layer = LayerValues { + self_id: "u1".into(), + name: "Layer 1".into(), + visible: true, + locked: false, + ignore_wrap: false, + show_guides: true, + lock_guides: false, + printable: true, + color: LayerColorValue::Rgb([128.0, 64.0, 0.0]), + } + .to_el(); + assert_eq!(layer.attr("Self"), Some("u1")); + assert_eq!(layer.attr("UI"), Some("true")); + let list_items: Vec<_> = + layer.child("Properties").and_then(|p| p.child("LayerColor")).map(|lc| lc.elements().map(|e| e.deep_text()).collect()).unwrap(); + assert_eq!(list_items, ["128", "64", "0"]); + + let section = SectionValues { + self_id: "u2".into(), + length: 4, + name: "A".into(), + continue_numbering: false, + include_section_prefix: true, + page_number_start: Some(1), + marker: "M".into(), + page_start: "u3".into(), + section_prefix: "A".into(), + alternate_layout: Some(("Phone".into(), 4)), + page_number_style: "Arabic".into(), + } + .to_el(); + assert_eq!(section.attr("PageNumberStart"), Some("1")); + assert_eq!(section.attr("AlternateLayout"), Some("Phone")); + + let url_dest = hyperlink_url_destination_el("HyperlinkURLDestination/u1", "Site", "https://example.com"); + assert_eq!(url_dest.attr("DestinationURL"), Some("https://example.com")); + let page_dest = hyperlink_page_destination_el("HyperlinkPageDestination/p1", "Page", "u3"); + assert_eq!(page_dest.attr("ViewSetting"), Some("FitPage")); + let item_src = hyperlink_page_item_source_el("HyperlinkPageItemSource/i1k0", "Link", "u4"); + assert_eq!(item_src.attr("SourcePageItem"), Some("u4")); + let link = hyperlink_el("u5", "Link", "HyperlinkPageItemSource/i1k0", "HyperlinkURLDestination/u1", true, 0x1_0000_0007); + assert_eq!(link.attr("DestinationUniqueKey"), Some("7")); + + let cg = root_color_group_el(&["Color/Black".into(), "Color/Paper".into()], "u10"); + assert_eq!(cg.attr("IsRootColorGroup"), Some("true")); + assert_eq!(cg.elements().count(), 2); +} From f428c3d36e0faf3924b76956a01334c051543527 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Fri, 20 Nov 2026 07:34:01 +0800 Subject: [PATCH 60/79] sqlite: add bounded wire decoding helpers (#2446) --- Cargo.lock | 4 ++ Cargo.toml | 1 + crates/sqlite/Cargo.toml | 11 +++++ crates/sqlite/src/lib.rs | 87 +++++++++++++++++++++++++++++++++++++ crates/sqlite/tests/wire.rs | 71 ++++++++++++++++++++++++++++++ 5 files changed, 174 insertions(+) create mode 100644 crates/sqlite/Cargo.toml create mode 100644 crates/sqlite/src/lib.rs create mode 100644 crates/sqlite/tests/wire.rs diff --git a/Cargo.lock b/Cargo.lock index 9f5cd71c72..90f18fada2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3274,6 +3274,10 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-sqlite" +version = "0.1.0" + [[package]] name = "craft-ssip" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index a278beb414..7ef038f990 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ craft-xfdf = { path = "crates/xfdf" } craft-jsonc = { path = "crates/jsonc" } craft-palette = { path = "crates/palette" } craft-score = { path = "crates/score" } +craft-sqlite = { path = "crates/sqlite" } craft-shx = { path = "crates/shx" } craft-http-url = { path = "crates/http-url" } craft-usd = { path = "crates/usd" } diff --git a/crates/sqlite/Cargo.toml b/crates/sqlite/Cargo.toml new file mode 100644 index 0000000000..45b255b0d8 --- /dev/null +++ b/crates/sqlite/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "craft-sqlite" +description = "Bounded wire-format helpers for SQLite database readers." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true diff --git a/crates/sqlite/src/lib.rs b/crates/sqlite/src/lib.rs new file mode 100644 index 0000000000..a86c4bcbb9 --- /dev/null +++ b/crates/sqlite/src/lib.rs @@ -0,0 +1,87 @@ +#![no_std] +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +//! Wire helpers for the [SQLite database file format](https://www.sqlite.org/fileformat.html). +//! +//! The caller owns cursor advancement, field bounds, and interpretation of stored values. + +use core::fmt; + +const MAX_VARINT_BYTES: usize = 9; + +/// A failure to decode part of a SQLite record or page. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + /// Input ended before the integer was complete. + TruncatedVarint, + /// The serial type is reserved and has no defined field width. + ReservedSerialType(u64), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TruncatedVarint => f.write_str("truncated SQLite varint"), + Self::ReservedSerialType(code) => write!(f, "reserved SQLite serial type {code}"), + } + } +} + +impl core::error::Error for Error {} + +/// Decode the leading SQLite varint and return its raw bit pattern and byte count. +/// +/// The first eight bytes each contribute seven bits. If all eight have the high bit set, +/// the ninth contributes all eight bits. The caller interprets the bits as signed when needed. +/// Decoding ends at the first complete representation, including non-minimal encodings. +/// +/// # Errors +/// +/// Returns [`Error::TruncatedVarint`] if the slice ends before the integer is complete. +/// +/// ``` +/// use craft_sqlite::read_varint; +/// +/// assert_eq!(read_varint(&[0x81, 0x00, 0xff]), Ok((128, 2))); +/// ``` +pub fn read_varint(input: &[u8]) -> Result<(u64, usize), Error> { + let mut value = 0; + for (index, &byte) in input.iter().take(MAX_VARINT_BYTES).enumerate() { + if index == MAX_VARINT_BYTES - 1 { + return Ok(((value << 8) | u64::from(byte), MAX_VARINT_BYTES)); + } + value = (value << 7) | u64::from(byte & 0x7f); + if byte & 0x80 == 0 { + return Ok((value, index + 1)); + } + } + Err(Error::TruncatedVarint) +} + +/// Return the encoded body width in bytes for a SQLite record serial type. +/// +/// The width is independent of the host's pointer size. The caller checks it against the +/// available body bytes before reading a field. +/// +/// # Errors +/// +/// Returns [`Error::ReservedSerialType`] for codes 10 and 11. +/// +/// ``` +/// use craft_sqlite::serial_type_len; +/// +/// assert_eq!(serial_type_len(3), Ok(3)); +/// assert_eq!(serial_type_len(17), Ok(2)); +/// ``` +pub const fn serial_type_len(serial_type: u64) -> Result { + match serial_type { + 0 | 8 | 9 => Ok(0), + 1..=4 => Ok(serial_type), + 5 => Ok(6), + 6 | 7 => Ok(8), + 10 | 11 => Err(Error::ReservedSerialType(serial_type)), + // Integer division accounts for the one-code difference between BLOB and text. + _ => Ok((serial_type - 12) / 2), + } +} diff --git a/crates/sqlite/tests/wire.rs b/crates/sqlite/tests/wire.rs new file mode 100644 index 0000000000..9ef7bb278a --- /dev/null +++ b/crates/sqlite/tests/wire.rs @@ -0,0 +1,71 @@ +use craft_sqlite::{Error, read_varint, serial_type_len}; + +#[test] +fn varints_decode_at_each_width() { + let cases: &[(&[u8], u64)] = &[ + (&[0x7f], 127), + (&[0x81, 0], 1 << 7), + (&[0x81, 0x80, 0], 1 << 14), + (&[0x81, 0x80, 0x80, 0], 1 << 21), + (&[0x81, 0x80, 0x80, 0x80, 0], 1 << 28), + (&[0x81, 0x80, 0x80, 0x80, 0x80, 0], 1 << 35), + (&[0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0], 1 << 42), + (&[0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0], 1 << 49), + (&[0x80, 0xc0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0], 1 << 56), + ]; + for &(bytes, expected) in cases { + assert_eq!(read_varint(bytes), Ok((expected, bytes.len())), "{bytes:x?}"); + } +} + +#[test] +fn ninth_byte_keeps_all_bits_and_leaves_trailing_bytes() { + let bytes = [0xc0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x42]; + assert_eq!(read_varint(&bytes), Ok((0x8000_0000_0000_0080, 9))); + assert_eq!(read_varint(&[0xff; 9]), Ok((u64::MAX, 9))); +} + +#[test] +fn leading_varint_preserves_following_bytes_and_accepts_padding() { + assert_eq!(read_varint(&[0, 0xff]), Ok((0, 1))); + assert_eq!(read_varint(&[0x81, 0, 0xff]), Ok((128, 2))); + assert_eq!(read_varint(&[0x80, 1, 0xff]), Ok((1, 2))); +} + +#[test] +fn varint_refuses_every_incomplete_prefix() { + let bytes = [0xff; 9]; + for len in 0..bytes.len() { + assert_eq!(read_varint(&bytes[..len]), Err(Error::TruncatedVarint), "length {len}"); + } +} + +#[test] +fn fixed_serial_types_have_exact_widths() { + for (serial_type, width) in (0..).zip([0, 1, 2, 3, 4, 6, 8, 8, 0, 0]) { + assert_eq!(serial_type_len(serial_type), Ok(width), "code {serial_type}"); + } +} + +#[test] +fn reserved_serial_types_are_refused() { + for serial_type in [10, 11] { + assert_eq!(serial_type_len(serial_type), Err(Error::ReservedSerialType(serial_type))); + } +} + +#[test] +fn variable_serial_type_widths_are_portable() { + for (serial_type, width) in [ + (12, 0), + (13, 0), + (14, 1), + (15, 1), + (12_012, 6_000), + (12_013, 6_000), + (u64::MAX - 1, 9_223_372_036_854_775_801), + (u64::MAX, 9_223_372_036_854_775_801), + ] { + assert_eq!(serial_type_len(serial_type), Ok(width), "code {serial_type}"); + } +} From ff98d8b93ce716084ecb84e26657c675d3939cf0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 19:07:33 -0500 Subject: [PATCH 61/79] fix(idml): remove unused imports in model test (#2467) --- crates/idml/tests/model.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/idml/tests/model.rs b/crates/idml/tests/model.rs index 33d5e3df4c..e6fcc8f3f3 100644 --- a/crates/idml/tests/model.rs +++ b/crates/idml/tests/model.rs @@ -284,9 +284,8 @@ fn text_variable_decoration_uses_preference_and_falls_back_to_legacy_root_values #[test] fn designmap_schema_elements_roundtrip_expected_attributes() { use craft_idml::model::{ - ConditionValues, KinsokuTableValues, LayerColorValue, LayerValues, MojikumiRow, MojikumiTableValues, NumberingListValues, SectionValues, - TextDateKind, TextVariableKind, TextVariableValues, default_languages, default_xref_text_variables, hyperlink_el, - hyperlink_page_destination_el, hyperlink_page_item_source_el, hyperlink_url_destination_el, root_color_group_el, + ConditionValues, KinsokuTableValues, MojikumiRow, MojikumiTableValues, NumberingListValues, TextDateKind, TextVariableKind, + TextVariableValues, default_languages, default_xref_text_variables, }; let langs = default_languages(); From 6719b207fac3f0c13d844ab12a100cafb5ea026d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 19:14:36 -0500 Subject: [PATCH 62/79] craft-pdf: add fonts feature with PDF encodings and Standard-14 metrics (#2454) * craft-pdf: add fonts feature with ISO 32000-2 Annex D encodings and Standard-14 metrics * pdf(fonts): call crate::fonts::win_ansi in std14 --- crates/pdf/Cargo.toml | 2 + crates/pdf/src/fonts.rs | 180 ++++++++++++++++ crates/pdf/src/fonts/encodings.rs | 275 +++++++++++++++++++++++ crates/pdf/src/fonts/std14.rs | 260 ++++++++++++++++++++++ crates/pdf/src/fonts/std14_metrics.rs | 300 ++++++++++++++++++++++++++ crates/pdf/src/lib.rs | 3 + 6 files changed, 1020 insertions(+) create mode 100644 crates/pdf/src/fonts.rs create mode 100644 crates/pdf/src/fonts/encodings.rs create mode 100644 crates/pdf/src/fonts/std14.rs create mode 100644 crates/pdf/src/fonts/std14_metrics.rs diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index f4c2d0b23c..82b9a294c0 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -29,6 +29,8 @@ content = ["cos", "dep:hayro-syntax"] crypt = ["dep:aes", "dep:md-5", "dep:sha2", "dep:stringprep", "dep:zeroize", "dep:thiserror"] # `testing`: a builder of small synthetic PDF files, for the tests of crates that read them. test-support = ["cos"] +# Standard-14 font metrics and ISO 32000-2 Annex D single-byte encodings. +fonts = [] [dependencies] hayro-syntax = { workspace = true, optional = true } diff --git a/crates/pdf/src/fonts.rs b/crates/pdf/src/fonts.rs new file mode 100644 index 0000000000..4a880d180e --- /dev/null +++ b/crates/pdf/src/fonts.rs @@ -0,0 +1,180 @@ +//! PDF single-byte encodings (ISO 32000-2 Annex D), WinAnsi/Unicode CMap encoding helpers, +//! and Standard-14 font metrics. + +pub mod encodings; +mod std14; +mod std14_metrics; + +pub use std14::{Match as Std14Match, Std14}; + +/// The WinAnsiEncoding (ISO 32000-2 Annex D) code for `c`, if the encoding has one. +/// +/// Codes 0x80–0x9F come from the same table the text extractor decodes with, so encoding and +/// decoding agree (Š š Ž ž Œ œ Ÿ ƒ † ‡ ˆ ˜ ‰ ‹ › as well as quotes, dashes, € and ™). +pub fn win_ansi_byte(c: char) -> Option { + match c { + '\u{20}'..='\u{7e}' | '\u{a0}'..='\u{ff}' => u8::try_from(u32::from(c)).ok(), + _ => { + let high = encodings::WIN_ANSI.get(0x80..0xa0)?; + let i = high.iter().position(|&u| u != 0 && u == u32::from(c))?; + u8::try_from(0x80 + i).ok() + } + } +} + +/// Encode text in WinAnsiEncoding (ISO 32000-2 Annex D); tabs become spaces and unmappable +/// characters become `?`. +pub fn win_ansi(s: &str) -> Vec { + s.chars().map(|c| if c == '\t' { b' ' } else { win_ansi_byte(c).unwrap_or(b'?') }).collect() +} + +/// The byte used by Unicode text plans, from the shared WinAnsi table (tabs become spaces). +pub fn win_ansi_char(c: char) -> Option { + if c == '\t' { Some(b' ') } else { win_ansi_byte(c) } +} + +/// Whether [`win_ansi`] keeps `c` rather than writing `?` (a tab becomes a space). +pub fn win_ansi_encodable(c: char) -> bool { + c == '\t' || win_ansi_byte(c).is_some() +} + +/// The first character of `s` that [`win_ansi`] can't encode and would write as `?`. +pub fn first_non_win_ansi(s: &str) -> Option { + s.chars().find(|c| !win_ansi_encodable(*c)) +} + +/// Whether every character can be represented without substitution in WinAnsi. +pub fn fits_win_ansi(s: &str) -> bool { + s.chars().all(win_ansi_encodable) +} + +/// The character encoding of a predefined Unicode CMap (`UniJIS-UTF16-H`, `UniGB-UCS2-H`, …; +/// ISO 32000-2 §9.7.5.2), which maps Unicode text straight to codes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UnicodeCMap { + Ucs2, + Utf16, + Utf8, + Utf32, +} + +impl UnicodeCMap { + /// The encoding of the predefined CMap `name`, if it is a horizontal Unicode one. Vertical + /// (`-V`) CMaps are refused: field appearances are laid out horizontally, so their glyphs + /// would be drawn stacked down the field instead of across it. + pub fn from_name(name: &[u8]) -> Option { + let name = std::str::from_utf8(name).ok()?; + if !name.starts_with("Uni") || !name.ends_with("-H") { + return None; + } + name.split('-').find_map(|part| match part { + "UCS2" => Some(Self::Ucs2), + "UTF16" => Some(Self::Utf16), + "UTF8" => Some(Self::Utf8), + "UTF32" => Some(Self::Utf32), + _ => None, + }) + } + + /// The first character of `s` this encoding can't hold, which [`Self::encode`] would write as + /// `?`: a character beyond U+FFFF in UCS-2 (`𠀋`). UTF-16, UTF-8 and UTF-32 hold every one. + pub fn first_unencodable(self, s: &str) -> Option { + match self { + Self::Ucs2 => s.chars().find(|c| u16::try_from(u32::from(*c)).is_err()), + Self::Utf16 | Self::Utf8 | Self::Utf32 => None, + } + } + + /// Encode `s`; tabs become spaces, and characters UCS-2 can't hold become `?` (check them + /// first with [`Self::first_unencodable`]: callers should refuse such text rather than write `?`). + pub fn encode(self, s: &str) -> Vec { + let mut out = Vec::with_capacity(s.len().saturating_mul(2)); + let mut units = [0u16; 2]; + let mut buf = [0u8; 4]; + for c in s.chars() { + let c = if c == '\t' { ' ' } else { c }; + match self { + Self::Ucs2 => { + let unit = u16::try_from(u32::from(c)).unwrap_or(u16::from(b'?')); + out.extend_from_slice(&unit.to_be_bytes()); + } + Self::Utf16 => { + for unit in c.encode_utf16(&mut units) { + out.extend_from_slice(&unit.to_be_bytes()); + } + } + Self::Utf8 => out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()), + Self::Utf32 => out.extend_from_slice(&u32::from(c).to_be_bytes()), + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_alias_codes_read_as_the_glyph_they_draw() { + assert_eq!(encodings::WIN_ANSI.get(0xAD), Some(&u32::from('-'))); + assert_eq!(encodings::WIN_ANSI.get(0x2D), Some(&u32::from('-'))); + assert_eq!(encodings::WIN_ANSI.get(0xA0), Some(&u32::from(' '))); + assert_eq!(encodings::WIN_ANSI.get(0x20), Some(&u32::from(' '))); + assert_eq!(encodings::MAC_ROMAN.get(0xCA), Some(&u32::from(' '))); + assert_eq!(encodings::MAC_ROMAN.get(0x20), Some(&u32::from(' '))); + // MacRoman has no soft hyphen; 0xAD there is `notequal`, and keeps it. + assert_eq!(encodings::MAC_ROMAN.get(0xAD), Some(&0x2260)); + // Writing is unaffected: '-' and ' ' take the canonical low codes, and a caller holding a + // literal U+00AD or U+00A0 still writes the high byte, which is the one that draws them. + assert_eq!(win_ansi_byte('-'), Some(0x2D)); + assert_eq!(win_ansi_byte(' '), Some(0x20)); + assert_eq!(win_ansi_byte('\u{00ad}'), Some(0xAD)); + assert_eq!(win_ansi_byte('\u{00a0}'), Some(0xA0)); + assert_eq!(win_ansi("a-b c"), b"a-b c"); + } + + #[test] + fn win_ansi_covers_the_0x80_to_0x9f_glyphs() { + const ALIASES: &[u8] = &[0xA0, 0xAD]; + for (code, &u) in encodings::WIN_ANSI.iter().enumerate() { + let Some(c) = char::from_u32(u).filter(|_| u != 0) else { continue }; + if ALIASES.contains(&(code as u8)) { + let canonical = win_ansi_byte(c).expect("an aliased glyph still encodes"); + assert!(canonical < code as u8, "{c:?}: the canonical code is the lower one"); + assert_eq!(encodings::WIN_ANSI.get(usize::from(canonical)), Some(&u), "both codes mean the same character"); + continue; + } + assert_eq!(win_ansi_byte(c), Some(code as u8), "{c:?} (U+{u:04X})"); + assert_eq!(win_ansi(&c.to_string()), [code as u8]); + } + assert_eq!( + win_ansi("Šta? žaba, œuvre — „ok“ ‰ ƒ † ‡ ˆ ˜ ‹›Ÿ"), + b"\x8ata? \x9eaba, \x9cuvre \x97 \x84ok\x93 \x89 \x83 \x86 \x87 \x88 \x98 \x8b\x9b\x9f" + ); + assert_eq!(win_ansi("čć\u{81}\u{8d}\t"), b"???? "); + assert_eq!(win_ansi_byte('\0'), None); + } + + #[test] + fn unicode_cmaps_encode_cjk_text() { + assert_eq!(UnicodeCMap::from_name(b"UniJIS-UTF16-H"), Some(UnicodeCMap::Utf16)); + assert_eq!(UnicodeCMap::from_name(b"UniGB-UCS2-V"), None); + assert_eq!(UnicodeCMap::from_name(b"UniJIS-UCS2-HW-H"), Some(UnicodeCMap::Ucs2)); + assert_eq!(UnicodeCMap::from_name(b"UniKS-UTF8-H"), Some(UnicodeCMap::Utf8)); + assert_eq!(UnicodeCMap::from_name(b"UniJIS2004-UTF32-H"), Some(UnicodeCMap::Utf32)); + assert_eq!(UnicodeCMap::from_name(b"Identity-H"), None); + assert_eq!(UnicodeCMap::from_name(b"90ms-RKSJ-H"), None); + assert_eq!(UnicodeCMap::from_name(b"\xff\xfe"), None); + assert_eq!(UnicodeCMap::Utf16.encode("令A"), [0x4e, 0xe4, 0x00, 0x41]); + assert_eq!(UnicodeCMap::Utf16.encode("𠀋"), [0xd8, 0x40, 0xdc, 0x0b]); + assert_eq!(UnicodeCMap::Ucs2.encode("𠀋\t"), [0x00, b'?', 0x00, b' ']); + assert_eq!(UnicodeCMap::Ucs2.first_unencodable("令和𠀋"), Some('𠀋')); + assert_eq!(UnicodeCMap::Ucs2.first_unencodable("令和"), None); + for cmap in [UnicodeCMap::Utf16, UnicodeCMap::Utf8, UnicodeCMap::Utf32] { + assert_eq!(cmap.first_unencodable("令和𠀋"), None, "{cmap:?}"); + } + assert_eq!(UnicodeCMap::Utf8.encode("令"), "令".as_bytes()); + assert_eq!(UnicodeCMap::Utf32.encode("令"), [0, 0, 0x4e, 0xe4]); + } +} diff --git a/crates/pdf/src/fonts/encodings.rs b/crates/pdf/src/fonts/encodings.rs new file mode 100644 index 0000000000..676d573ab6 --- /dev/null +++ b/crates/pdf/src/fonts/encodings.rs @@ -0,0 +1,275 @@ +//! Single-byte encodings (ISO 32000-2 Annex D) as code → Unicode tables (0 = undefined). + +pub static WIN_ANSI: [u32; 256] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 8364, 0, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, + // 0xA0 is `space` and 0xAD is `hyphen`, not U+00A0 and U+00AD: WinAnsiEncoding's table + // (Annex D.2) gives those codes the same glyph names as 0x20 and 0x2D, so the bytes a Windows + // codepage calls a non-breaking space and a soft hyphen draw, and extract as, an ordinary + // space and hyphen. Emitting the formatting characters instead hides them from search and + // from redaction's pattern matching: a soft hyphen is invisible and matches nothing, and a + // non-breaking space does not match the space a reader typed. + 0, 381, 0, 0, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 0, 382, 376, 32, 161, 162, 163, 164, 165, 166, 167, 168, 169, + 170, 171, 172, 45, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, + 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, + 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, +]; +pub static MAC_ROMAN: [u32; 256] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, + 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 196, 197, 199, 201, 209, 214, 220, 225, 224, 226, 228, 227, 229, 231, + 233, 232, 234, 235, 237, 236, 238, 239, 241, 243, 242, 244, 246, 245, 250, 249, 251, 252, 8224, 176, 162, 163, 167, 8226, 182, 223, 174, 169, + 8482, 180, 168, 8800, 198, 216, 8734, 177, 8804, 8805, 165, 181, 8706, 8721, 8719, 960, 8747, 170, 186, 937, 230, 248, 191, 161, 172, 8730, 402, + // 0xCA is `space`, the same glyph name Annex D.2 gives 0x20, for the reason WinAnsi 0xA0 is. + 8776, 8710, 171, 187, 8230, 32, 192, 195, 213, 338, 339, 8211, 8212, 8220, 8221, 8216, 8217, 247, 9674, 255, 376, 8260, 8364, 8249, 8250, 64257, + 64258, 8225, 183, 8218, 8222, 8240, 194, 202, 193, 203, 200, 205, 206, 207, 204, 211, 212, 63743, 210, 218, 219, 217, 305, 710, 732, 175, 728, + 729, 730, 184, 733, 731, 711, +]; +pub static STANDARD: [u32; 256] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 8217, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 8216, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 161, 162, 163, 8260, 165, 402, 167, 164, 39, 8220, 171, 8249, 8250, 64257, 64258, 0, 8211, 8224, 8225, 183, 0, + 182, 8226, 8218, 8222, 8221, 187, 8230, 8240, 0, 191, 0, 96, 180, 710, 732, 175, 728, 729, 168, 0, 730, 184, 0, 733, 731, 711, 8212, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 0, 170, 0, 0, 0, 0, 321, 216, 338, 186, 0, 0, 0, 0, 0, 230, 0, 0, 0, 305, 0, 0, 322, 248, 339, 223, 0, + 0, 0, 0, +]; + +/// Glyph names of the Latin character set (Annex D) → Unicode. +pub static NAMES: &[(&str, u32)] = &[ + ("A", 0x41), + ("AE", 0xc6), + ("Aacute", 0xc1), + ("Acircumflex", 0xc2), + ("Adieresis", 0xc4), + ("Agrave", 0xc0), + ("Aring", 0xc5), + ("Atilde", 0xc3), + ("B", 0x42), + ("C", 0x43), + ("Ccedilla", 0xc7), + ("D", 0x44), + ("E", 0x45), + ("Eacute", 0xc9), + ("Ecircumflex", 0xca), + ("Edieresis", 0xcb), + ("Egrave", 0xc8), + ("Eth", 0xd0), + ("Euro", 0x20ac), + ("F", 0x46), + ("G", 0x47), + ("H", 0x48), + ("I", 0x49), + ("Iacute", 0xcd), + ("Icircumflex", 0xce), + ("Idieresis", 0xcf), + ("Igrave", 0xcc), + ("J", 0x4a), + ("K", 0x4b), + ("L", 0x4c), + ("Lslash", 0x141), + ("M", 0x4d), + ("N", 0x4e), + ("Ntilde", 0xd1), + ("O", 0x4f), + ("OE", 0x152), + ("Oacute", 0xd3), + ("Ocircumflex", 0xd4), + ("Odieresis", 0xd6), + ("Ograve", 0xd2), + ("Oslash", 0xd8), + ("Otilde", 0xd5), + ("P", 0x50), + ("Q", 0x51), + ("R", 0x52), + ("S", 0x53), + ("Scaron", 0x160), + ("T", 0x54), + ("Thorn", 0xde), + ("U", 0x55), + ("Uacute", 0xda), + ("Ucircumflex", 0xdb), + ("Udieresis", 0xdc), + ("Ugrave", 0xd9), + ("V", 0x56), + ("W", 0x57), + ("X", 0x58), + ("Y", 0x59), + ("Yacute", 0xdd), + ("Ydieresis", 0x178), + ("Z", 0x5a), + ("Zcaron", 0x17d), + ("a", 0x61), + ("aacute", 0xe1), + ("acircumflex", 0xe2), + ("acute", 0xb4), + ("adieresis", 0xe4), + ("ae", 0xe6), + ("agrave", 0xe0), + ("ampersand", 0x26), + ("aring", 0xe5), + ("asciicircum", 0x5e), + ("asciitilde", 0x7e), + ("asterisk", 0x2a), + ("at", 0x40), + ("atilde", 0xe3), + ("b", 0x62), + ("backslash", 0x5c), + ("bar", 0x7c), + ("braceleft", 0x7b), + ("braceright", 0x7d), + ("bracketleft", 0x5b), + ("bracketright", 0x5d), + ("breve", 0x2d8), + ("brokenbar", 0xa6), + ("bullet", 0x2022), + ("c", 0x63), + ("caron", 0x2c7), + ("ccedilla", 0xe7), + ("cedilla", 0xb8), + ("cent", 0xa2), + ("circumflex", 0x2c6), + ("colon", 0x3a), + ("comma", 0x2c), + ("copyright", 0xa9), + ("currency", 0xa4), + ("d", 0x64), + ("dagger", 0x2020), + ("daggerdbl", 0x2021), + ("degree", 0xb0), + ("dieresis", 0xa8), + ("divide", 0xf7), + ("dollar", 0x24), + ("dotaccent", 0x2d9), + ("dotlessi", 0x131), + ("e", 0x65), + ("eacute", 0xe9), + ("ecircumflex", 0xea), + ("edieresis", 0xeb), + ("egrave", 0xe8), + ("eight", 0x38), + ("ellipsis", 0x2026), + ("emdash", 0x2014), + ("endash", 0x2013), + ("equal", 0x3d), + ("eth", 0xf0), + ("exclam", 0x21), + ("exclamdown", 0xa1), + ("f", 0x66), + ("fi", 0xfb01), + ("five", 0x35), + ("fl", 0xfb02), + ("florin", 0x192), + ("four", 0x34), + ("fraction", 0x2044), + ("g", 0x67), + ("germandbls", 0xdf), + ("grave", 0x60), + ("greater", 0x3e), + ("guillemotleft", 0xab), + ("guillemotright", 0xbb), + ("guilsinglleft", 0x2039), + ("guilsinglright", 0x203a), + ("h", 0x68), + ("hungarumlaut", 0x2dd), + ("hyphen", 0x2d), + ("i", 0x69), + ("iacute", 0xed), + ("icircumflex", 0xee), + ("idieresis", 0xef), + ("igrave", 0xec), + ("j", 0x6a), + ("k", 0x6b), + ("l", 0x6c), + ("less", 0x3c), + ("logicalnot", 0xac), + ("lslash", 0x142), + ("m", 0x6d), + ("macron", 0xaf), + ("minus", 0x2212), + ("mu", 0xb5), + ("multiply", 0xd7), + ("n", 0x6e), + ("nbspace", 0xa0), + ("nine", 0x39), + ("ntilde", 0xf1), + ("numbersign", 0x23), + ("o", 0x6f), + ("oacute", 0xf3), + ("ocircumflex", 0xf4), + ("odieresis", 0xf6), + ("oe", 0x153), + ("ogonek", 0x2db), + ("ograve", 0xf2), + ("one", 0x31), + ("onehalf", 0xbd), + ("onequarter", 0xbc), + ("onesuperior", 0xb9), + ("ordfeminine", 0xaa), + ("ordmasculine", 0xba), + ("oslash", 0xf8), + ("otilde", 0xf5), + ("p", 0x70), + ("paragraph", 0xb6), + ("parenleft", 0x28), + ("parenright", 0x29), + ("percent", 0x25), + ("period", 0x2e), + ("periodcentered", 0xb7), + ("perthousand", 0x2030), + ("plus", 0x2b), + ("plusminus", 0xb1), + ("q", 0x71), + ("question", 0x3f), + ("questiondown", 0xbf), + ("quotedbl", 0x22), + ("quotedblbase", 0x201e), + ("quotedblleft", 0x201c), + ("quotedblright", 0x201d), + ("quoteleft", 0x2018), + ("quoteright", 0x2019), + ("quotesinglbase", 0x201a), + ("quotesingle", 0x27), + ("r", 0x72), + ("registered", 0xae), + ("ring", 0x2da), + ("s", 0x73), + ("scaron", 0x161), + ("section", 0xa7), + ("semicolon", 0x3b), + ("seven", 0x37), + ("sfthyphen", 0xad), + ("six", 0x36), + ("slash", 0x2f), + ("space", 0x20), + ("sterling", 0xa3), + ("t", 0x74), + ("thorn", 0xfe), + ("three", 0x33), + ("threequarters", 0xbe), + ("threesuperior", 0xb3), + ("tilde", 0x2dc), + ("trademark", 0x2122), + ("two", 0x32), + ("twosuperior", 0xb2), + ("u", 0x75), + ("uacute", 0xfa), + ("ucircumflex", 0xfb), + ("udieresis", 0xfc), + ("ugrave", 0xf9), + ("underscore", 0x5f), + ("v", 0x76), + ("w", 0x77), + ("x", 0x78), + ("y", 0x79), + ("yacute", 0xfd), + ("ydieresis", 0xff), + ("yen", 0xa5), + ("z", 0x7a), + ("zcaron", 0x17e), + ("zero", 0x30), +]; diff --git a/crates/pdf/src/fonts/std14.rs b/crates/pdf/src/fonts/std14.rs new file mode 100644 index 0000000000..ac68c95c6a --- /dev/null +++ b/crates/pdf/src/fonts/std14.rs @@ -0,0 +1,260 @@ +//! Standard-14 font metrics (ISO 32000-2 Annex D; the Adobe Core14 AFM metrics), as advance +//! widths in glyph space — thousandths of an em. +//! +//! A PDF may name any of the fourteen standard fonts without embedding a program, and the viewer +//! has to supply the metrics. These are those metrics, exactly, replacing the character-class +//! estimate that generated appearances used before: that estimate had Times at 0.9 x Helvetica, +//! which makes a capital A 600 where the specification says 722. +//! +//! **Generated.** The tables are data, not typefaces, and are the item AGENTS.md §1.1 permits as +//! Adobe-authored non-visual technical data; `ATTRIBUTION.toml` carries the entry with +//! `adobe_data = true`. Each row is indexed by character **code**, not by Unicode: the twelve text +//! fonts are indexed by WinAnsiEncoding, which is what PdfCraft writes into the appearance streams +//! it generates, and Symbol and ZapfDingbats by their own built-in encodings. A zero means the +//! encoding leaves that code undefined. + +/// One of the fourteen standard fonts (ISO 32000-2 §9.6.2.2). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Std14 { + Helvetica, + HelveticaBold, + HelveticaOblique, + HelveticaBoldOblique, + TimesRoman, + TimesBold, + TimesItalic, + TimesBoldItalic, + Courier, + CourierBold, + CourierOblique, + CourierBoldOblique, + Symbol, + ZapfDingbats, +} + +/// How [`Std14::recognise`] matched a `/BaseFont` name. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Match { + /// A standard-14 face or a well-known alias of one (Arial for Helvetica, CourierNew for + /// Courier). The document is asking for this face. + Alias, + /// Only a family hint matched -- "Serif", "Roman" or "Mono" in an otherwise unknown name. + /// The face is a guess from the name, not the one the document asked for. + FamilyHint, +} + +impl Std14 { + /// The font a `/BaseFont` name selects, by the spec's names and the common aliases viewers + /// accept (`Arial` for `Helvetica`, `TimesNewRoman` for `Times`, `CourierNew` for `Courier`). + /// A subset prefix such as `ABCDEF+Helvetica` is ignored. + pub fn from_base_font(base: &str) -> Option { + Self::recognise(base).map(|(face, _)| face) + } + + /// [`Std14::from_base_font`], also saying *how* the name matched. + /// + /// Reporting needs the difference. "Arial" really is a request for Helvetica, but + /// "SomeHouseSerif" is a house font whose name merely contains "Serif"; choosing Times for it + /// is a reasonable guess from the name, not the face the document asked for, and a substitution + /// report that called it a standard-14 name would be telling the reader something untrue. + pub fn recognise(base: &str) -> Option<(Self, Match)> { + let base = base.rsplit('+').next().unwrap_or(base); + let flat: String = base.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect(); + let has = |w: &str| flat.contains(w); + let (bold, italic) = (has("bold"), has("italic") || has("oblique")); + // Two bools index a four-element array, so the subscript is provably 0..=3. + let styled = |faces: [Self; 4]| faces[usize::from(bold) | usize::from(italic) << 1]; + let courier = || styled([Self::Courier, Self::CourierBold, Self::CourierOblique, Self::CourierBoldOblique]); + let times = || styled([Self::TimesRoman, Self::TimesBold, Self::TimesItalic, Self::TimesBoldItalic]); + if has("symbol") { + return Some((Self::Symbol, Match::Alias)); + } + if has("zapf") || has("dingbat") { + return Some((Self::ZapfDingbats, Match::Alias)); + } + if has("courier") { + return Some((courier(), Match::Alias)); + } + if has("mono") { + return Some((courier(), Match::FamilyHint)); + } + if has("times") { + return Some((times(), Match::Alias)); + } + if (has("serif") && !has("sans")) || has("roman") { + return Some((times(), Match::FamilyHint)); + } + if has("helvetica") || has("arial") { + return Some((styled([Self::Helvetica, Self::HelveticaBold, Self::HelveticaOblique, Self::HelveticaBoldOblique]), Match::Alias)); + } + None + } + + /// The advance of one character `code`, in thousandths of an em. Zero where the font's + /// encoding leaves the code undefined. + pub fn width(self, code: u8) -> f64 { + f64::from(super::std14_metrics::WIDTHS[self as usize][code as usize]) + } + + /// The advance of `code` at `size` points. + pub fn advance(self, code: u8, size: f64) -> f64 { + self.width(code) * size / 1000.0 + } + + /// The advance of `text` at `size` points, encoded as the twelve text fonts are written: + /// WinAnsiEncoding, with characters it cannot represent replaced as `win_ansi` replaces them. + /// + /// Symbol and ZapfDingbats have their own built-in encodings and are not WinAnsi, so this + /// measures them as if they were; pass codes to [`Std14::width`] for those. + pub fn text_width(self, text: &str, size: f64) -> f64 { + super::win_ansi(text).iter().map(|&c| self.width(c)).sum::() * size / 1000.0 + } + + /// Courier is the only fixed-pitch family of the fourteen. + pub fn is_fixed_pitch(self) -> bool { + matches!(self, Self::Courier | Self::CourierBold | Self::CourierOblique | Self::CourierBoldOblique) + } + + /// The `/BaseFont` name for this font, as it is written into a PDF. + pub fn base_font(self) -> &'static str { + super::std14_metrics::BASE_FONTS[self as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sans_serif_names_are_not_mapped_to_times() { + assert!(!matches!(Std14::recognise("SansSerif"), Some((Std14::TimesRoman, _)))); + assert_eq!(Std14::recognise("Arial-SansSerif"), Some((Std14::Helvetica, Match::Alias))); + } + + /// Widths from the published Core14 metrics, typed in here by hand so the table is checked + /// against the specification rather than against whatever produced it. + #[test] + fn widths_match_the_published_metrics() { + let cases: &[(Std14, char, u16)] = &[ + // Helvetica + (Std14::Helvetica, ' ', 278), + (Std14::Helvetica, 'A', 667), + (Std14::Helvetica, 'W', 944), + (Std14::Helvetica, 'i', 222), + (Std14::Helvetica, 'm', 833), + (Std14::Helvetica, '0', 556), + (Std14::Helvetica, '@', 1015), + (Std14::HelveticaBold, 'A', 722), + (Std14::HelveticaBold, 'i', 278), + // Times: not Helvetica scaled by 0.9, which is what the old estimate assumed. + (Std14::TimesRoman, ' ', 250), + (Std14::TimesRoman, 'A', 722), + (Std14::TimesRoman, 'W', 944), + (Std14::TimesRoman, 'i', 278), + (Std14::TimesRoman, 'm', 778), + (Std14::TimesBold, 'A', 722), + (Std14::TimesItalic, 'A', 611), + // Courier is fixed pitch at 600 for every glyph. + (Std14::Courier, ' ', 600), + (Std14::Courier, 'A', 600), + (Std14::Courier, 'm', 600), + (Std14::CourierBoldOblique, 'W', 600), + ]; + for &(font, ch, want) in cases { + let code = crate::fonts::win_ansi(&ch.to_string()); + assert_eq!(code.len(), 1, "{ch:?} is one WinAnsi byte"); + assert_eq!(font.width(code[0]) as u16, want, "{font:?} {ch:?}"); + } + } + + #[test] + fn courier_is_fixed_pitch_everywhere_it_is_defined() { + for font in [Std14::Courier, Std14::CourierBold, Std14::CourierOblique, Std14::CourierBoldOblique] { + assert!(font.is_fixed_pitch()); + for code in 0..=255u8 { + let w = font.width(code); + assert!(w == 0.0 || w == 600.0, "{font:?} code {code} has width {w}"); + } + } + assert!(!Std14::Helvetica.is_fixed_pitch()); + } + + #[test] + fn every_text_font_covers_printable_ascii_and_latin1() { + for font in [Std14::Helvetica, Std14::TimesRoman, Std14::Courier, Std14::TimesBoldItalic] { + for code in 0x20..=0x7Eu8 { + assert!(font.width(code) > 0.0, "{font:?} has no width for ASCII {code}"); + } + for code in 0xA0..=0xFFu8 { + assert!(font.width(code) > 0.0, "{font:?} has no width for Latin-1 {code}"); + } + } + } + + #[test] + fn symbol_and_dingbats_have_their_own_encodings() { + // Symbol's code 0x61 is alpha, not 'a'; ZapfDingbats' is a scissors glyph. + assert!(Std14::Symbol.width(0x61) > 0.0); + assert!(Std14::ZapfDingbats.width(0x61) > 0.0); + // Neither defines the Latin-1 upper half the text fonts do. + assert_eq!(Std14::Symbol.width(0xFF), 0.0); + } + + #[test] + fn base_font_names_round_trip() { + for i in 0..14usize { + let font = [ + Std14::Helvetica, + Std14::HelveticaBold, + Std14::HelveticaOblique, + Std14::HelveticaBoldOblique, + Std14::TimesRoman, + Std14::TimesBold, + Std14::TimesItalic, + Std14::TimesBoldItalic, + Std14::Courier, + Std14::CourierBold, + Std14::CourierOblique, + Std14::CourierBoldOblique, + Std14::Symbol, + Std14::ZapfDingbats, + ][i]; + assert_eq!(Std14::from_base_font(font.base_font()), Some(font), "{}", font.base_font()); + } + } + + #[test] + fn base_font_aliases_and_subset_prefixes_resolve() { + assert_eq!(Std14::from_base_font("ABCDEF+Helvetica-Bold"), Some(Std14::HelveticaBold)); + assert_eq!(Std14::from_base_font("Arial"), Some(Std14::Helvetica)); + assert_eq!(Std14::from_base_font("Arial,BoldItalic"), Some(Std14::HelveticaBoldOblique)); + assert_eq!(Std14::from_base_font("TimesNewRoman,Bold"), Some(Std14::TimesBold)); + assert_eq!(Std14::from_base_font("CourierNew-Oblique"), Some(Std14::CourierOblique)); + assert_eq!(Std14::from_base_font("ZapfDingbats"), Some(Std14::ZapfDingbats)); + assert_eq!(Std14::from_base_font("Wingdings"), None); + assert_eq!(Std14::from_base_font(""), None); + } + + #[test] + fn text_width_sums_the_glyphs_and_scales_with_size() { + let h = Std14::Helvetica; + // "AW" = 667 + 944 = 1611 thousandths of an em. + assert!((h.text_width("AW", 1000.0) - 1611.0).abs() < 1e-9); + assert!((h.text_width("AW", 12.0) - 1611.0 * 12.0 / 1000.0).abs() < 1e-9); + assert_eq!(h.text_width("", 12.0), 0.0); + // Courier: every character is 600, so the width is purely a count. + assert!((Std14::Courier.text_width("hello", 10.0) - 5.0 * 6.0).abs() < 1e-9); + } + + #[test] + fn hostile_text_does_not_panic_and_stays_finite() { + for font in [Std14::Helvetica, Std14::Symbol, Std14::Courier] { + for s in ["", "\0", "\u{202E}", "💥", &"a".repeat(10_000), "\u{FFFD}"] { + let w = font.text_width(s, 12.0); + assert!(w.is_finite() && w >= 0.0, "{font:?} {s:?} -> {w}"); + } + assert!(font.advance(0, 12.0).is_finite()); + assert!(font.advance(255, 0.0).is_finite()); + } + } +} diff --git a/crates/pdf/src/fonts/std14_metrics.rs b/crates/pdf/src/fonts/std14_metrics.rs new file mode 100644 index 0000000000..05ba41c711 --- /dev/null +++ b/crates/pdf/src/fonts/std14_metrics.rs @@ -0,0 +1,300 @@ +//! The generated standard-14 tables: the fourteen base font names and their per-code advance +//! widths. **Data only, no logic** -- see `std14.rs` for everything that interprets it. +//! +//! This file is the closed-list item in AGENTS.md 1.1 and carries a SHA-256 in `ATTRIBUTION.toml`, +//! so `cargo xtask assets` fails until a change to it is re-attested. It is kept separate from the +//! code that reads it for exactly that reason: if ordinary edits churned the hash, re-attesting +//! would become reflexive and the check would stop meaning anything. +//! +//! Widths are in thousandths of an em, indexed by character code in each face's own encoding -- +//! WinAnsi for the twelve text faces, and their built-in encodings for Symbol and ZapfDingbats. +//! A zero means the encoding leaves that code undefined. Verified against the published +//! specification by the tests in `std14.rs`, which type the expected values in by hand. + +pub(crate) static BASE_FONTS: [&str; 14] = [ + "Helvetica", + "Helvetica-Bold", + "Helvetica-Oblique", + "Helvetica-BoldOblique", + "Times-Roman", + "Times-Bold", + "Times-Italic", + "Times-BoldItalic", + "Courier", + "Courier-Bold", + "Courier-Oblique", + "Courier-BoldOblique", + "Symbol", + "ZapfDingbats", +]; + +/// Advance widths by code, one row per [`Std14`] variant in declaration order. +#[rustfmt::skip] +pub(crate) static WIDTHS: [[u16; 256]; 14] = [ + // Helvetica + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, + 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, + 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, + 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 0, + 556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, + 0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 667, + 278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333, + 400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, + 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, + 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500, + ], + // HelveticaBold + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, + 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, + 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, + 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 0, + 556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, + 0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 667, + 278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333, + 400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, + 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, + 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, + 611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556, + ], + // HelveticaOblique + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, + 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, + 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, + 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 0, + 556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, + 0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 667, + 278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333, + 400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611, + 667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, + 556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500, + ], + // HelveticaBoldOblique + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278, + 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, + 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, + 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, + 333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, + 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 0, + 556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0, + 0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 667, + 278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333, + 400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611, + 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278, + 722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611, + 556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278, + 611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556, + ], + // TimesRoman + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444, + 921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, 722, 722, + 556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333, 469, 500, + 333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, 500, 500, + 500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541, 0, + 500, 0, 333, 500, 444, 1000, 500, 500, 333, 1000, 556, 333, 889, 0, 611, 0, + 0, 333, 333, 444, 444, 350, 500, 1000, 333, 980, 389, 333, 722, 0, 444, 722, + 250, 333, 500, 500, 500, 500, 200, 500, 333, 760, 276, 500, 564, 333, 760, 333, + 400, 564, 300, 300, 333, 500, 453, 250, 333, 300, 310, 500, 750, 750, 750, 444, + 722, 722, 722, 722, 722, 722, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333, + 722, 722, 722, 722, 722, 722, 722, 564, 722, 722, 722, 722, 722, 722, 556, 500, + 444, 444, 444, 444, 444, 444, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278, + 500, 500, 500, 500, 500, 500, 500, 564, 500, 500, 500, 500, 500, 500, 500, 500, + ], + // TimesBold + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 250, 333, 555, 500, 500, 1000, 833, 278, 333, 333, 500, 570, 250, 333, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, + 930, 722, 667, 722, 722, 667, 611, 778, 778, 389, 500, 778, 667, 944, 722, 778, + 611, 778, 722, 556, 667, 722, 722, 1000, 722, 722, 667, 333, 278, 333, 581, 500, + 333, 500, 556, 444, 556, 444, 333, 500, 556, 278, 333, 556, 278, 833, 556, 500, + 556, 556, 444, 389, 333, 556, 500, 722, 500, 500, 444, 394, 220, 394, 520, 0, + 500, 0, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 1000, 0, 667, 0, + 0, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 0, 444, 722, + 250, 333, 500, 500, 500, 500, 220, 500, 333, 747, 300, 500, 570, 333, 747, 333, + 400, 570, 300, 300, 333, 556, 540, 250, 333, 300, 330, 500, 750, 750, 750, 500, + 722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 389, 389, 389, 389, + 722, 722, 778, 778, 778, 778, 778, 570, 778, 722, 722, 722, 722, 722, 611, 556, + 500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278, 278, 278, + 500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 500, 556, 500, + ], + // TimesItalic + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 250, 333, 420, 500, 500, 833, 778, 214, 333, 333, 500, 675, 250, 333, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 675, 675, 675, 500, + 920, 611, 611, 667, 722, 611, 611, 722, 722, 333, 444, 667, 556, 833, 667, 722, + 611, 722, 611, 500, 556, 722, 611, 833, 611, 556, 556, 389, 278, 389, 422, 500, + 333, 500, 500, 444, 500, 444, 278, 500, 500, 278, 278, 444, 278, 722, 500, 500, + 500, 500, 389, 389, 278, 500, 444, 667, 444, 444, 389, 400, 275, 400, 541, 0, + 500, 0, 333, 500, 556, 889, 500, 500, 333, 1000, 500, 333, 944, 0, 556, 0, + 0, 333, 333, 556, 556, 350, 500, 889, 333, 980, 389, 333, 667, 0, 389, 556, + 250, 389, 500, 500, 500, 500, 275, 500, 333, 760, 276, 500, 675, 333, 760, 333, + 400, 675, 300, 300, 333, 500, 523, 250, 333, 300, 310, 500, 750, 750, 750, 500, + 611, 611, 611, 611, 611, 611, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333, + 722, 667, 722, 722, 722, 722, 722, 675, 722, 722, 722, 722, 722, 556, 611, 500, + 500, 500, 500, 500, 500, 500, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278, + 500, 500, 500, 500, 500, 500, 500, 675, 500, 500, 500, 500, 500, 444, 500, 444, + ], + // TimesBoldItalic + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 250, 389, 555, 500, 500, 833, 778, 278, 333, 333, 500, 570, 250, 333, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, + 832, 667, 667, 667, 722, 667, 667, 722, 778, 389, 500, 667, 611, 889, 722, 722, + 611, 722, 667, 556, 611, 722, 667, 889, 667, 611, 611, 333, 278, 333, 570, 500, + 333, 500, 500, 444, 500, 444, 333, 500, 556, 278, 278, 500, 278, 778, 556, 500, + 500, 500, 389, 389, 278, 556, 444, 667, 500, 444, 389, 348, 220, 348, 570, 0, + 500, 0, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 944, 0, 611, 0, + 0, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 0, 389, 611, + 250, 389, 500, 500, 500, 500, 220, 500, 333, 747, 266, 500, 606, 333, 747, 333, + 400, 570, 300, 300, 333, 576, 500, 250, 333, 300, 300, 500, 750, 750, 750, 500, + 667, 667, 667, 667, 667, 667, 944, 667, 667, 667, 667, 667, 389, 389, 389, 389, + 722, 722, 722, 722, 722, 722, 722, 570, 722, 722, 722, 722, 722, 611, 611, 500, + 500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278, 278, 278, + 500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 444, 500, 444, + ], + // Courier + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, + 600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, + 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + ], + // CourierBold + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, + 600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, + 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + ], + // CourierOblique + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, + 600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, + 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + ], + // CourierBoldOblique + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, + 600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0, + 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, + ], + // Symbol + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 250, 333, 713, 500, 549, 833, 778, 439, 333, 333, 500, 549, 250, 549, 250, 278, + 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 549, 549, 549, 444, + 549, 722, 667, 722, 612, 611, 763, 603, 722, 333, 631, 722, 686, 889, 722, 722, + 768, 741, 556, 592, 611, 690, 439, 768, 645, 795, 611, 333, 863, 333, 658, 500, + 500, 631, 549, 549, 494, 439, 521, 411, 603, 329, 603, 549, 549, 576, 521, 549, + 549, 521, 549, 603, 439, 576, 713, 686, 493, 686, 494, 480, 200, 480, 549, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 750, 620, 247, 549, 167, 713, 500, 753, 753, 753, 753, 1042, 987, 603, 987, 603, + 400, 549, 411, 549, 549, 713, 494, 460, 549, 549, 549, 549, 1000, 603, 1000, 658, + 823, 686, 795, 987, 768, 768, 823, 768, 768, 713, 713, 713, 713, 713, 713, 713, + 768, 713, 790, 790, 890, 823, 549, 250, 713, 603, 603, 1042, 987, 603, 987, 603, + 494, 329, 790, 790, 786, 713, 384, 384, 384, 384, 384, 384, 494, 494, 494, 494, + 0, 329, 274, 686, 686, 686, 384, 384, 384, 384, 384, 384, 494, 494, 494, 0, + ], + // ZapfDingbats + [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 278, 974, 961, 974, 980, 719, 789, 790, 791, 690, 960, 939, 549, 855, 911, 933, + 911, 945, 974, 755, 846, 762, 761, 571, 677, 763, 760, 759, 754, 494, 552, 537, + 577, 692, 786, 788, 788, 790, 793, 794, 816, 823, 789, 841, 823, 833, 816, 831, + 923, 744, 723, 749, 790, 792, 695, 776, 768, 792, 759, 707, 708, 682, 701, 826, + 815, 789, 789, 707, 687, 696, 689, 786, 787, 713, 791, 785, 791, 873, 761, 762, + 762, 759, 759, 892, 892, 788, 784, 438, 138, 277, 415, 392, 392, 668, 668, 0, + 390, 390, 317, 317, 276, 276, 509, 509, 410, 410, 234, 234, 334, 334, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 732, 544, 544, 910, 667, 760, 760, 776, 595, 694, 626, 788, 788, 788, 788, + 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, + 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, + 788, 788, 788, 788, 894, 838, 1016, 458, 748, 924, 748, 918, 927, 928, 928, 834, + 873, 828, 924, 924, 917, 930, 931, 463, 883, 836, 836, 867, 867, 696, 696, 874, + 0, 874, 760, 946, 771, 865, 771, 888, 967, 888, 831, 873, 927, 970, 918, 0, + ], +]; diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 8893a84b05..61e2cd43ad 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -35,3 +35,6 @@ pub mod write_raster; /// Low-level, direct-to-output framing of new classic-xref PDF files. pub mod classic; +/// PDF single-byte encodings (ISO 32000-2 Annex D), WinAnsi/Unicode CMap helpers, and Standard-14 metrics. +#[cfg(feature = "fonts")] +pub mod fonts; From 0275c0b1070fd9814d67a00f0b1a65ce2d4ab43e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 19:38:35 -0500 Subject: [PATCH 63/79] html, xfdf: extract standalone HTML writer and XFDF annotation/FDF grammar (#778) (#2457) * html, xfdf: add standalone HTML writer and XFDF annotation/FDF grammar (#778) * html, xfdf: escape image mime attribute and clarify rich_plain vs direct_text --- crates/html/Cargo.toml | 2 + crates/html/src/lib.rs | 2 + crates/html/src/standalone.rs | 194 +++++++++++++++ crates/xfdf/Cargo.toml | 2 +- crates/xfdf/src/grammar.rs | 443 ++++++++++++++++++++++++++++++++++ crates/xfdf/src/lib.rs | 5 +- 6 files changed, 646 insertions(+), 2 deletions(-) create mode 100644 crates/html/src/standalone.rs create mode 100644 crates/xfdf/src/grammar.rs diff --git a/crates/html/Cargo.toml b/crates/html/Cargo.toml index d4d1c4f0ea..9119b0545a 100644 --- a/crates/html/Cargo.toml +++ b/crates/html/Cargo.toml @@ -13,6 +13,8 @@ workspace = true [features] # HTML documents: read into and written from the craft-flow model and a craft-wordmodel Document. flow = ["dep:craft-codepage", "dep:craft-flow", "dep:craft-math", "dep:craft-mime", "dep:craft-wordmodel", "dep:encoding_rs"] +# Standalone portable HTML document writer. +standalone = ["dep:craft-mime"] [dependencies] craft-codepage = { workspace = true, optional = true } diff --git a/crates/html/src/lib.rs b/crates/html/src/lib.rs index 70f19746e4..fa504882a7 100644 --- a/crates/html/src/lib.rs +++ b/crates/html/src/lib.rs @@ -38,6 +38,8 @@ struct ReadmeExamples; pub mod doc; mod entity; mod lex; +#[cfg(feature = "standalone")] +pub mod standalone; pub use entity::{decode_entity, escape, escape_dq, reference, unescape, unescape_attr}; pub use lex::{Lexer, Limits, Options, Tag, Token}; diff --git a/crates/html/src/standalone.rs b/crates/html/src/standalone.rs new file mode 100644 index 0000000000..ac7f893164 --- /dev/null +++ b/crates/html/src/standalone.rs @@ -0,0 +1,194 @@ +//! Portable standalone HTML document writer (no PDF layout, reading order, or export policy). + +pub use craft_mime::transfer::base64; + +/// Whether a character may appear in the output. XML 1.0 forbids the C0 controls other than tab, +/// line feed and carriage return, and U+FFFE/U+FFFF. +pub fn allowed(c: char) -> bool { + matches!(c, '\t' | '\n' | '\r') || !(c.is_ascii_control() || c == '\u{FFFE}' || c == '\u{FFFF}') +} + +/// Escape text for HTML content and double-quoted attribute values, stripping disallowed characters. +pub fn esc(s: &str) -> String { + let mut o = String::with_capacity(s.len()); + for c in s.chars().filter(|c| allowed(*c)) { + match c { + '&' => o.push_str("&"), + '<' => o.push_str("<"), + '>' => o.push_str(">"), + '"' => o.push_str("""), + c => o.push(c), + } + } + o +} + +/// An inline run of text for portable HTML rendering. +pub struct HtmlRun<'a> { + pub text: &'a str, + pub bold: bool, + pub italic: bool, + pub color: [u8; 3], +} + +/// A single table cell for portable HTML rendering. +pub struct HtmlCell<'a> { + pub text: &'a str, + pub bold: bool, + pub italic: bool, + pub color: [u8; 3], + pub span: usize, +} + +/// A table of rows of cells for portable HTML rendering. +pub struct HtmlTable<'a> { + pub rows: Vec>>, +} + +/// A block-level element in a portable HTML document. +pub enum HtmlBlock<'a> { + Para { runs: Vec>, level: u8 }, + Table(HtmlTable<'a>), + Image { mime: &'a str, bytes: &'a [u8] }, + PageBreak, +} + +fn rgb_hex(rgb: [u8; 3]) -> Option { + let [r, g, b] = rgb; + (r | g | b != 0).then(|| format!("{r:02X}{g:02X}{b:02X}")) +} + +fn style_color(rgb: [u8; 3], simple: bool) -> String { + if simple { String::new() } else { rgb_hex(rgb).map_or(String::new(), |h| format!(" style=\"color:#{h}\"")) } +} + +/// Wrap escaped inline text in `` and/or `` when non-whitespace. +pub fn wrap_inline(mut text: String, bold: bool, italic: bool) -> String { + if text.trim().is_empty() { + return text; + } + if italic { + text = format!("{text}"); + } + if bold { + text = format!("{text}"); + } + text +} + +/// Render a paragraph or heading (`lvl` clamped to `1..=6`, or `0` for `

`). +pub fn render_para(runs: &[HtmlRun<'_>], lvl: u8, simple: bool) -> Option { + let non_empty: Vec<_> = runs.iter().map(|r| (r, esc(r.text))).filter(|(_, text)| !text.is_empty()).collect(); + let &(first, _) = non_empty.iter().find(|(_, text)| !text.trim().is_empty())?; + let mut t = String::new(); + for (run, text) in non_empty { + if text.trim().is_empty() { + t.push_str(&text); + continue; + } + let mut out = wrap_inline(text, run.bold && lvl == 0, run.italic); + // The paragraph has its first visible run's colour; a run in another colour says so. + if !simple && run.color != first.color { + let [red, green, blue] = run.color; + out = format!("{out}"); + } + t.push_str(&out); + } + let style = style_color(first.color, simple); + Some(match lvl.min(6) { + 0 => format!("{t}

\n"), + l => format!("{t}\n"), + }) +} + +/// Render a table into an HTML `` element. +pub fn render_table(t: &HtmlTable<'_>, simple: bool) -> String { + let mut s = String::from("
\n"); + for row in &t.rows { + s.push_str(""); + for c in row { + let body = wrap_inline(esc(c.text), c.bold, c.italic); + let span = if c.span > 1 { format!(" colspan=\"{}\"", c.span) } else { String::new() }; + let style = style_color(c.color, simple); + s.push_str(&format!("{body}")); + } + s.push_str("\n"); + } + s.push_str("
\n"); + s +} + +/// Render a sequence of portable HTML blocks into a standalone HTML5 document. +pub fn render(blocks: &[HtmlBlock<'_>], title: &str, simple: bool, language: Option<&str>) -> String { + let lang = language.map(|tag| format!(" lang=\"{}\"", esc(tag))).unwrap_or_default(); + let mut s = format!( + "\n\n\n\n{}\n{}\n\n\n", + esc(title), + if simple { + "" + } else { + "" + } + ); + for block in blocks { + match block { + HtmlBlock::Para { runs, level } => { + if let Some(p) = render_para(runs, *level, simple) { + s.push_str(&p); + } + } + HtmlBlock::Table(t) => s.push_str(&render_table(t, simple)), + HtmlBlock::Image { mime, bytes } => { + s.push_str(&format!("

\"\"

\n", esc(mime), base64(bytes))); + } + HtmlBlock::PageBreak => s.push_str("
\n"), + } + } + s.push_str("\n\n"); + s +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn renders_standalone_document_and_omits_empty_runs() { + let blocks = [ + HtmlBlock::Para { + runs: vec![ + HtmlRun { text: "\u{1}\u{FFFF}", bold: true, italic: true, color: [255, 0, 0] }, + HtmlRun { text: "Hello", bold: false, italic: false, color: [0, 128, 0] }, + ], + level: 0, + }, + HtmlBlock::PageBreak, + HtmlBlock::Table(HtmlTable { + rows: vec![vec![ + HtmlCell { text: "\u{1}", bold: true, italic: true, color: [0, 0, 0], span: 1 }, + HtmlCell { text: "Val", bold: true, italic: false, color: [0, 0, 0], span: 2 }, + ]], + }), + ]; + let out = render(&blocks, "Clean ", false, Some("en-US")); + assert!(out.starts_with("<!DOCTYPE html>\n<html lang=\"en-US\">\n"), "{out}"); + assert!(out.contains("<title>Clean <Title>"), "{out}"); + assert!(out.contains("

Hello

"), "{out}"); + assert!(out.contains("
\n"), "{out}"); + assert!(out.contains("Val"), "{out}"); + } + + #[test] + fn heading_level_clamps_to_h6() { + let runs = [HtmlRun { text: "Deep", bold: true, italic: false, color: [0, 0, 0] }]; + assert_eq!(render_para(&runs, 9, true).as_deref(), Some("
Deep
\n")); + } + + #[test] + fn image_mime_is_attribute_escaped() { + let blocks = [HtmlBlock::Image { mime: "image/png\" onerror=\"alert(1)", bytes: b"abc" }]; + let out = render(&blocks, "Img", true, None); + assert!(out.contains("src=\"data:image/png" onerror="alert(1);base64,YWJj\""), "{out}"); + assert!(!out.contains("onerror=\"alert(1)\""), "{out}"); + } +} diff --git a/crates/xfdf/Cargo.toml b/crates/xfdf/Cargo.toml index 9b1304d899..1807a96f97 100644 --- a/crates/xfdf/Cargo.toml +++ b/crates/xfdf/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-xfdf" -description = "Bounded XFDF field-value reader without PDF or form policy" +description = "Bounded XFDF field-value reader and annotation/FDF grammar without PDF or form policy" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/xfdf/src/grammar.rs b/crates/xfdf/src/grammar.rs new file mode 100644 index 0000000000..d757e85580 --- /dev/null +++ b/crates/xfdf/src/grammar.rs @@ -0,0 +1,443 @@ +//! Portable XFDF annotation and FDF grammar (no PDF COS document or annotation models). + +use std::fmt::Write as _; + +use craft_xml::esc_attr as esc; + +use crate::{check_form_xml_depth, el_text, parse_form_xml, xml_nesting_depth}; + +/// XFDF's own namespace (ISO 19444-1). +pub const XFDF_NS: &str = "http://ns.adobe.com/xfdf/"; + +/// Rich text deeper than this is written as text rather than as markup, so the XFDF it goes into +/// stays well inside the nesting the reader accepts (`MAX_XML_DEPTH`). +const MAX_RICH_DEPTH: usize = 512; + +/// PDF annotation `/Subtype` names paired with their XFDF element names. +pub const SUBTYPES: [(&str, &str); 17] = [ + ("Text", "text"), + ("FreeText", "freetext"), + ("Line", "line"), + ("Square", "square"), + ("Circle", "circle"), + ("Polygon", "polygon"), + ("PolyLine", "polyline"), + ("Highlight", "highlight"), + ("Underline", "underline"), + ("Squiggly", "squiggly"), + ("StrikeOut", "strikeout"), + ("Stamp", "stamp"), + ("Caret", "caret"), + ("Ink", "ink"), + ("FileAttachment", "fileattachment"), + ("Sound", "sound"), + ("Redact", "redact"), +]; + +/// PDF annotation `/F` bitflags paired with their XFDF `flags` attribute tokens. +pub const FLAGS: [(i64, &str); 9] = [ + (1, "invisible"), + (2, "hidden"), + (4, "print"), + (8, "nozoom"), + (16, "norotate"), + (32, "noview"), + (64, "readonly"), + (128, "locked"), + (256, "togglenoview"), +]; + +/// PDF annotation border style (`/BS /S`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BorderStyle { + Solid, + Dash, + Bevelled, + Inset, + Underline, +} + +impl BorderStyle { + /// Return the PDF `/BS /S` name for this border style. + pub fn as_pdf_name(self) -> &'static str { + match self { + Self::Solid => "S", + Self::Dash => "D", + Self::Bevelled => "B", + Self::Inset => "I", + Self::Underline => "U", + } + } + + fn as_xfdf_attr(self) -> Option<&'static str> { + match self { + Self::Dash => Some("dash"), + Self::Bevelled => Some("bevelled"), + Self::Inset => Some("inset"), + Self::Underline => Some("underline"), + Self::Solid => None, + } + } +} + +/// PDF Caret annotation `/Sy` symbol. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CaretSymbol { + Paragraph, + None, +} + +impl CaretSymbol { + /// Return the PDF `/Sy` name for this caret symbol. + pub fn as_pdf_name(self) -> &'static str { + match self { + Self::Paragraph => "P", + Self::None => "None", + } + } +} + +/// Portable XFDF 3.0 annotation formatting attributes. +#[derive(Default, Debug, PartialEq)] +pub struct AnnotFormat { + pub width: Option, + pub border_style: Option, + pub dashes: Option>, + pub cloudy_intensity: Option>, + pub rotation: Option, + pub justification: Option, + pub fringe: Option<[f64; 4]>, + pub leader_length: Option, + pub leader_extend: Option, + pub leader_offset: Option, + pub caption: Option, + pub caption_style: Option, + pub caption_offset: Option<[f64; 2]>, + pub symbol: Option, + pub overlay_text: Option, + pub overlay_text_repeat: Option, +} + +fn format_num(v: f64) -> String { + let s = format!("{v:.4}"); + let s = s.trim_end_matches('0').trim_end_matches('.'); + if s == "-0" { "0".into() } else { s.into() } +} + +fn parse_csv(list: &str) -> Vec { + let v: Vec = list.split([',', ';', ' ']).filter(|t| !t.is_empty()).filter_map(|t| t.trim().parse().ok()).collect(); + if v.iter().all(|x| x.is_finite()) { v } else { Vec::new() } +} + +fn hex_color(c: &[f64]) -> Option { + let rgb = match c.len() { + 1 => [c[0]; 3], + 3 => [c[0], c[1], c[2]], + 4 => [(1.0 - c[0]) * (1.0 - c[3]), (1.0 - c[1]) * (1.0 - c[3]), (1.0 - c[2]) * (1.0 - c[3])], + _ => return None, + }; + Some(format!( + "#{:02X}{:02X}{:02X}", + (rgb[0].clamp(0.0, 1.0) * 255.0).round() as u8, + (rgb[1].clamp(0.0, 1.0) * 255.0).round() as u8, + (rgb[2].clamp(0.0, 1.0) * 255.0).round() as u8 + )) +} + +/// Format XFDF 3.0 annotation formatting attributes into `attrs`. +pub fn write_format_attrs(fmt: &AnnotFormat, is_free_text: bool, attrs: &mut String) { + let list = |v: &[f64]| v.iter().map(|x| format_num(*x)).collect::>().join(","); + if let Some(w) = fmt.width.filter(|w| w.is_finite()) { + let _ = write!(attrs, " width=\"{}\"", format_num(w)); + } + if let Some(intensity) = fmt.cloudy_intensity { + attrs.push_str(" style=\"cloudy\""); + if let Some(i) = intensity.filter(|i| i.is_finite()) { + let _ = write!(attrs, " intensity=\"{}\"", format_num(i)); + } + } else if let Some(s) = fmt.border_style.and_then(BorderStyle::as_xfdf_attr) { + let _ = write!(attrs, " style=\"{s}\""); + } + if let Some(dashes) = &fmt.dashes + && !dashes.is_empty() + && dashes.iter().all(|v| v.is_finite()) + { + let _ = write!(attrs, " dashes=\"{}\"", list(dashes)); + } + if let Some(r) = fmt.rotation { + let _ = write!(attrs, " rotation=\"{r}\""); + } + if let Some(q) = fmt.justification { + match (is_free_text, q) { + (true, 0) => attrs.push_str(" justification=\"left\""), + (true, 1) => attrs.push_str(" justification=\"centered\""), + (true, 2) => attrs.push_str(" justification=\"right\""), + (true, _) => {} + (false, q) => { + let _ = write!(attrs, " justification=\"{q}\""); + } + } + } + if let Some(rd) = fmt.fringe + && rd.iter().all(|v| v.is_finite()) + { + let _ = write!(attrs, " fringe=\"{}\"", list(&rd)); + } + if let Some(ll) = fmt.leader_length.filter(|v| v.is_finite()) { + let _ = write!(attrs, " leaderLength=\"{}\"", format_num(ll)); + } + if let Some(lle) = fmt.leader_extend.filter(|v| v.is_finite()) { + let _ = write!(attrs, " leaderExtend=\"{}\"", format_num(lle)); + } + if let Some(llo) = fmt.leader_offset.filter(|v| v.is_finite()) { + let _ = write!(attrs, " leader-offset=\"{}\"", format_num(llo)); + } + if let Some(cap) = fmt.caption { + let _ = write!(attrs, " caption=\"{}\"", if cap { "yes" } else { "no" }); + } + if let Some(cp) = &fmt.caption_style { + let _ = write!(attrs, " caption-style=\"{}\"", esc(cp)); + } + if let Some([h, v]) = fmt.caption_offset + && h.is_finite() + && v.is_finite() + { + let _ = write!(attrs, " caption-offset-h=\"{}\" caption-offset-v=\"{}\"", format_num(h), format_num(v)); + } + match fmt.symbol { + Some(CaretSymbol::Paragraph) => attrs.push_str(" symbol=\"paragraph\""), + Some(CaretSymbol::None) => attrs.push_str(" symbol=\"none\""), + None => {} + } + if let Some(t) = &fmt.overlay_text { + let _ = write!(attrs, " overlay-text=\"{}\"", esc(t)); + } + if let Some(repeat) = fmt.overlay_text_repeat { + let _ = write!(attrs, " overlay-text-repeat=\"{repeat}\""); + } +} + +/// Parse XFDF 3.0 annotation formatting attributes from an XML element. +pub fn parse_format_attrs(node: &craft_xml::El) -> AnnotFormat { + let num = |a: &str| node.attr(a).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()); + let style = node.attr("style").map(str::trim); + let dashes = node.attr("dashes").map(parse_csv).filter(|v| !v.is_empty() && v.iter().all(|x| *x >= 0.0) && v.iter().any(|x| *x > 0.0)); + let border_style = match style { + Some("dash") => Some(BorderStyle::Dash), + Some("bevelled" | "beveled") => Some(BorderStyle::Bevelled), + Some("inset") => Some(BorderStyle::Inset), + Some("underline") => Some(BorderStyle::Underline), + Some("solid") => Some(BorderStyle::Solid), + _ => None, + }; + let cloudy_intensity = (style == Some("cloudy")).then(|| Some(num("intensity").unwrap_or(1.0).clamp(0.0, 2.0))); + let (h, v) = (num("caption-offset-h"), num("caption-offset-v")); + AnnotFormat { + width: num("width"), + border_style, + dashes, + cloudy_intensity, + rotation: node.attr("rotation").and_then(|r| r.trim().parse::().ok()).map(i64::from), + justification: match node.attr("justification").map(str::trim) { + Some("left" | "0") => Some(0), + Some("centered" | "center" | "1") => Some(1), + Some("right" | "2") => Some(2), + _ => None, + }, + fringe: node.attr("fringe").map(parse_csv).and_then(|r| r.try_into().ok()), + leader_length: num("leaderLength"), + leader_extend: num("leaderExtend").filter(|v| *v >= 0.0), + leader_offset: num("leader-offset").filter(|v| *v >= 0.0), + caption: match node.attr("caption").map(str::trim) { + Some("yes" | "true") => Some(true), + Some("no" | "false") => Some(false), + _ => None, + }, + caption_style: node.attr("caption-style").map(str::trim).filter(|c| matches!(*c, "Inline" | "Top")).map(str::to_owned), + caption_offset: (h.is_some() || v.is_some()).then(|| [h.unwrap_or(0.0), v.unwrap_or(0.0)]), + symbol: match node.attr("symbol").map(str::trim) { + Some("paragraph" | "P") => Some(CaretSymbol::Paragraph), + Some("none" | "None") => Some(CaretSymbol::None), + _ => None, + }, + overlay_text: node.attr("overlay-text").map(str::to_owned), + overlay_text_repeat: match node.attr("overlay-text-repeat").map(str::trim) { + Some("true" | "yes") => Some(true), + Some("false" | "no") => Some(false), + _ => None, + }, + } +} + +/// Format PDF `/F` annotation bitflags as a comma-separated XFDF `flags` string. +pub fn format_flags(flags: i64) -> String { + FLAGS.iter().filter(|(b, _)| flags & b != 0).map(|(_, s)| *s).collect::>().join(",") +} + +/// Parse an XFDF `flags` attribute into PDF `/F` annotation bitflags. +pub fn parse_flags(attr: Option<&str>) -> i64 { + attr.unwrap_or("print") + .split(',') + .filter_map(|f| FLAGS.iter().find(|(_, s)| s.eq_ignore_ascii_case(f.trim())).map(|x| x.0)) + .fold(0, |bits, flag| bits | flag) +} + +/// Pairs `x,y;x,y;…` (XFDF vertices and ink gestures). +pub fn pairs(text: &str) -> Vec<[f64; 2]> { + text.split(';').filter_map(|p| if let [x, y] = parse_csv(p).as_slice() { Some([*x, *y]) } else { None }).collect() +} + +/// Format coordinate pairs as `x,y;x,y;…`. +pub fn format_pairs(pts: &[[f64; 2]]) -> String { + pts.iter().map(|p| format!("{},{}", format_num(p[0]), format_num(p[1]))).collect::>().join(";") +} + +/// Rich text (`/RC`) as `` holds it: its root element alone (no XML +/// declaration), when the text is well-formed XML; `None` otherwise. +pub fn rich_text_element(rc: &str) -> Option { + let t = rc.trim_start_matches('\u{feff}'); + if xml_nesting_depth(t) > MAX_RICH_DEPTH { + return None; + } + let parsed = parse_form_xml(t).ok()?; + Some(parsed.to_xml()) +} + +/// Recursively extract plain text from a `` element, a `\r`-separated line +/// per paragraph or `
` (what `/Contents` gets when `` comes without +/// ``). Unlike [`direct_text`], this walks descendant elements. +pub fn rich_plain(node: &craft_xml::El) -> String { + fn walk(node: &craft_xml::El, out: &mut String) { + for n in &node.children { + match n { + craft_xml::Node::El(el) => { + if el.local() == "br" || (matches!(el.local(), "p" | "div" | "li") && !out.is_empty() && !out.ends_with('\r')) { + out.push('\r'); + } + walk(el, out); + } + craft_xml::Node::Text(t) if !(t.trim().is_empty() && t.contains('\n')) => { + out.push_str(&t.replace("\r\n", "\r").replace('\n', "\r")); + } + _ => {} + } + } + } + let mut out = String::new(); + walk(node, &mut out); + out.trim_end_matches('\r').to_string() +} + +/// The one element `markup` (cut out of `rich`, a ``) as an XML +/// document of its own: the namespaces it inherits from the XFDF around it are declared on it. +pub fn standalone(el: &craft_xml::El, ns: &[(String, String)]) -> String { + let mut clone = (*el).clone(); + let markup = clone.to_xml(); + if let Some((_, uri)) = ns.iter().rfind(|(p, _)| p.is_empty()) + && !uri.is_empty() + && uri != XFDF_NS + && !clone.has_attr("xmlns") + { + clone.set_attr("xmlns", uri); + } + for (prefix, uri) in ns { + if prefix.is_empty() || prefix == "xml" { + continue; + } + let attr_name = format!("xmlns:{prefix}"); + if markup.contains(&format!("{prefix}:")) && !clone.has_attr(&attr_name) { + clone.set_attr(&attr_name, uri); + } + } + clone.to_xml() +} + +/// Whether `text` is XFDF with comments in it (what a paste of copied comments carries). +pub fn is_xfdf_comments(text: &str) -> bool { + let head: String = text.chars().take(400).collect(); + head.contains(" bool { + matches!(key, b"P" | b"Popup" | b"IRT" | b"Parent" | b"FS" | b"Sound") || (key == b"AP" && !is_stamp) +} + +/// Format a colour attribute (` name="#RRGGBB"`) when `color` is 1, 3, or 4 components. +pub fn format_color_attr(name: &str, color: &[f64], out: &mut String) { + if let Some(c) = hex_color(color) { + let _ = write!(out, " {name}=\"{c}\""); + } +} + +/// Concatenate only the direct text children of `node`, without recursing into child elements +/// (unlike [`rich_plain`]). +pub fn direct_text(node: &craft_xml::El) -> String { + el_text(node) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn format_attrs_round_trip() { + let fmt = AnnotFormat { + width: Some(2.5), + border_style: Some(BorderStyle::Dash), + dashes: Some(vec![3.0, 1.5]), + rotation: Some(90), + justification: Some(1), + caption: Some(true), + symbol: Some(CaretSymbol::Paragraph), + overlay_text: Some("REDACT".into()), + overlay_text_repeat: Some(true), + ..AnnotFormat::default() + }; + let mut attrs = String::new(); + write_format_attrs(&fmt, true, &mut attrs); + let xml = format!(""); + let parsed_xml = parse_form_xml(&xml); + assert!(parsed_xml.is_ok(), "failed to parse generated attributes: {xml}"); + if let Ok(el) = parsed_xml { + let parsed = parse_format_attrs(&el); + assert_eq!(parsed.width, Some(2.5)); + assert_eq!(parsed.border_style, Some(BorderStyle::Dash)); + assert_eq!(parsed.dashes.as_deref(), Some(&[3.0, 1.5][..])); + assert_eq!(parsed.rotation, Some(90)); + assert_eq!(parsed.justification, Some(1)); + assert_eq!(parsed.caption, Some(true)); + assert_eq!(parsed.symbol, Some(CaretSymbol::Paragraph)); + assert_eq!(parsed.overlay_text.as_deref(), Some("REDACT")); + assert_eq!(parsed.overlay_text_repeat, Some(true)); + } + } + + #[test] + fn flags_and_pairs_and_fdf_skip_keys() { + assert_eq!(format_flags(parse_flags(Some("print,locked"))), "print,locked"); + assert_eq!(pairs("1,2;3.5,4"), vec![[1.0, 2.0], [3.5, 4.0]]); + assert_eq!(format_pairs(&[[1.0, 2.0], [3.5, 4.0]]), "1,2;3.5,4"); + assert!(fdf_annot_skip_key(b"AP", false)); + assert!(!fdf_annot_skip_key(b"AP", true)); + assert!(fdf_annot_skip_key(b"Popup", true)); + assert!(is_xfdf_comments("")); + } +} diff --git a/crates/xfdf/src/lib.rs b/crates/xfdf/src/lib.rs index 0023761067..31188fd46c 100644 --- a/crates/xfdf/src/lib.rs +++ b/crates/xfdf/src/lib.rs @@ -1,6 +1,9 @@ -//! Bounded XFDF field values; PDF annotations and form application remain caller-owned. +//! Bounded XFDF field values and annotation/FDF grammar; PDF annotations and form application remain caller-owned. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] + +pub mod grammar; +pub use grammar::is_xfdf_comments; const MAX_NODES: u32 = 2_000_000; const MAX_DEPTH: usize = 64; const MAX_XML_DEPTH: usize = 1024; From 0ffb1a0abe8763f9fda3a2fb9ca0edc8fdcb7ec0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 19:39:15 -0500 Subject: [PATCH 64/79] xlsx, drawingml: track dropped cells and chart data tables/pivot source/first slice angle (#778) (#2465) * xlsx, drawingml: track dropped cells and chart data tables/pivot source/first slice angle (#778) * xlsx, drawingml: add unit tests for dropped_cells, ChartDataTable, first_slice_angle, pivot_source (#778) --- crates/drawingml/src/chart.rs | 32 ++++++++++++++++++++++ crates/drawingml/src/chart/read.rs | 41 ++++++++++++++++++++++++++++- crates/drawingml/src/chart/write.rs | 26 ++++++++++++++++-- crates/xlsx/src/package.rs | 12 +++++++-- crates/xlsx/src/sheet.rs | 22 +++++++++++++++- 5 files changed, 127 insertions(+), 6 deletions(-) diff --git a/crates/drawingml/src/chart.rs b/crates/drawingml/src/chart.rs index 9475d20548..5fcbfc9d45 100644 --- a/crates/drawingml/src/chart.rs +++ b/crates/drawingml/src/chart.rs @@ -344,6 +344,26 @@ impl ErrorBars { } } +/// A chart's data table (`c:dTable`), independent of the chart legend. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct ChartDataTable { + pub show_keys: bool, + pub horizontal_border: bool, + pub vertical_border: bool, + pub outline: bool, +} + +impl Default for ChartDataTable { + fn default() -> Self { + Self { show_keys: true, horizontal_border: true, vertical_border: true, outline: true } + } +} + +fn is_zero_u16(v: &u16) -> bool { + *v == 0 +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct Chart { @@ -423,6 +443,15 @@ pub struct Chart { /// A histogram's bin width (`cx:binSize`). #[serde(skip_serializing_if = "Option::is_none")] pub bin_size: Option, + /// A chart's data table (`c:dTable`). + #[serde(skip_serializing_if = "Option::is_none")] + pub data_table: Option, + /// Pie/doughnut first slice angle in degrees clockwise from 12 o'clock (0–359). + #[serde(skip_serializing_if = "is_zero_u16")] + pub first_slice_angle: u16, + /// A PivotChart's PivotTable reference (`c:pivotSource/c:name`). + #[serde(skip_serializing_if = "Option::is_none")] + pub pivot_source: Option, /// Original chart XML part kept for round-trip of unmodelled options. #[serde(skip_serializing_if = "Option::is_none")] pub raw: Option, @@ -537,6 +566,9 @@ impl Default for Chart { up_down_bars: false, bin_count: None, bin_size: None, + data_table: None, + first_slice_angle: 0, + pivot_source: None, raw: None, verbatim: false, kept: ChartKept::default(), diff --git a/crates/drawingml/src/chart/read.rs b/crates/drawingml/src/chart/read.rs index 3f2be736f8..735ceb8c89 100644 --- a/crates/drawingml/src/chart/read.rs +++ b/crates/drawingml/src/chart/read.rs @@ -1,6 +1,6 @@ //! Chart parts (`c:chartSpace`) → [`Chart`]. The original XML is kept in `Chart.raw`. -use crate::chart::{Chart, ChartType, ErrorBars, Series, Trendline, TrendlineType}; +use crate::chart::{Chart, ChartDataTable, ChartType, ErrorBars, Series, Trendline, TrendlineType}; use crate::style::Fill; use craft_xml::{El, Local, value}; @@ -194,6 +194,16 @@ fn chart_within(root: &El, mut budget: usize) -> Option { } } c.lang = root.child(Local("lang")).and_then(|c| c.attr_local("val")).map(str::to_string); + c.pivot_source = root.path(&[Local("pivotSource"), Local("name")]).map(|n| n.deep_text().trim().to_string()).filter(|n| !n.is_empty()); + c.data_table = pa.child(Local("dTable")).map(|t| { + let flag = |name: &str| t.child(Local(name)).is_some_and(|e| e.attr_local("val").and_then(value::to_bool).unwrap_or(true)); + ChartDataTable { + show_keys: flag("showKeys"), + horizontal_border: flag("showHorzBorder"), + vertical_border: flag("showVertBorder"), + outline: flag("showOutline"), + } + }); let (val_ax, cat_ax) = read_axes(&mut c, pa, &primary_val); read_text_styles(&mut c, root, ch, val_ax, cat_ax); Some(c) @@ -288,6 +298,9 @@ fn read_group_settings(g: &El, c: &mut Chart) -> Option { if let Some(v) = g.child(Local("holeSize")).and_then(|c| c.attr_local("val")).and_then(|v| v.parse::().ok()) { c.hole_size = (v / 100.0).clamp(0.0, 0.9); } + if let Some(v) = g.child(Local("firstSliceAng")).and_then(|c| c.attr_local("val")).and_then(|v| v.trim().parse::().ok()) { + c.first_slice_angle = v % 360; + } // `` without a val attribute means true, as in the schema's default. // The setting belongs to this plot group: a group that asks for no labels keeps them // off, even when another group of a combo chart asks for them (#868). @@ -902,4 +915,30 @@ mod tests { assert!(read_chart_xml(vary_xml(r#""#).as_bytes()).is_some_and(|c| !c.vary_colors)); assert!(read_chart_xml(vary_xml(r#""#).as_bytes()).is_some_and(|c| c.vary_colors)); } + + #[test] + fn data_table_first_slice_angle_and_pivot_source_roundtrip() { + let xml = format!( + r#"[Book.xlsx]Sheet1!PivotTable15"# + ); + let c = read_chart_xml(xml.as_bytes()).unwrap(); + assert_eq!(c.pivot_source.as_deref(), Some("[Book.xlsx]Sheet1!PivotTable1")); + assert_eq!(c.data_table, Some(ChartDataTable { show_keys: true, horizontal_border: true, vertical_border: false, outline: true })); + let mut edited = c.clone(); + edited.raw = None; + let (written, kept) = crate::chart::write::chart_xml(&edited); + assert!(!kept); + let back = read_chart_xml(&written).unwrap(); + assert_eq!(back.pivot_source, c.pivot_source); + assert_eq!(back.data_table, c.data_table); + + let pie_xml = format!( + r#"5"# + ); + let mut pie = read_chart_xml(pie_xml.as_bytes()).unwrap(); + assert_eq!(pie.first_slice_angle, 90); + pie.raw = None; + let (pie_written, _) = crate::chart::write::chart_xml(&pie); + assert_eq!(read_chart_xml(&pie_written).unwrap().first_slice_angle, 90); + } } diff --git a/crates/drawingml/src/chart/write.rs b/crates/drawingml/src/chart/write.rs index 6993a6d219..68e4028d44 100644 --- a/crates/drawingml/src/chart/write.rs +++ b/crates/drawingml/src/chart/write.rs @@ -645,9 +645,9 @@ fn plot_group(w: &mut Writer, c: &Chart, kind: ChartType, list: &[(usize, &Serie w.close(); } } - Group::Pie => w.tag("c:firstSliceAng").attr("val", 0).empty(), + Group::Pie => w.tag("c:firstSliceAng").attr("val", c.first_slice_angle % 360).empty(), Group::Doughnut => { - w.tag("c:firstSliceAng").attr("val", 0).empty(); + w.tag("c:firstSliceAng").attr("val", c.first_slice_angle % 360).empty(); w.tag("c:holeSize").attr("val", (c.hole_size.clamp(0.1, 0.9) * 100.0).round() as i64).empty(); } _ => {} @@ -733,6 +733,12 @@ pub fn chart_xml(c: &Chart) -> (Vec, bool) { w.tag("c:date1904").attr("val", 0).empty(); w.tag("c:roundedCorners").attr("val", 0).empty(); w.tag("c:style").attr("val", c.style.clamp(1, 48)).empty(); + if let Some(pivot) = c.pivot_source.as_deref().map(str::trim).filter(|s| !s.is_empty()) { + w.open("c:pivotSource", &[]); + w.tag("c:name").text(pivot); + w.tag("c:fmtId").attr("val", 0).empty(); + w.close(); + } w.open("c:chart", &[]); match &c.title { Some(t) => { @@ -802,6 +808,22 @@ pub fn chart_xml(c: &Chart) -> (Vec, bool) { axes(&mut w, c, g); } } + if let Some(dt) = &c.data_table { + w.open("c:dTable", &[]); + if dt.horizontal_border { + w.empty("c:showHorzBorder", &[]); + } + if dt.vertical_border { + w.empty("c:showVertBorder", &[]); + } + if dt.outline { + w.empty("c:showOutline", &[]); + } + if dt.show_keys { + w.empty("c:showKeys", &[]); + } + w.close(); + } if let Some(f) = &c.plot_fill { sp_pr(&mut w, Some(f), None); } diff --git a/crates/xlsx/src/package.rs b/crates/xlsx/src/package.rs index a75874e71b..44b0fbf22b 100644 --- a/crates/xlsx/src/package.rs +++ b/crates/xlsx/src/package.rs @@ -291,8 +291,16 @@ impl<'a> Package<'a> { if rows.dropped > 0 { self.warn(format!("sheet \"{}\": {} cells or rows outside the 1,048,576 × 16,384 grid were dropped", entry.name, rows.dropped)); } - let mut sheet = - SheetPart { part, root: root.unwrap_or_default(), rels, rows: rows.rows, dropped: rows.dropped, damaged, ..SheetPart::default() }; + let mut sheet = SheetPart { + part, + root: root.unwrap_or_default(), + rels, + rows: rows.rows, + dropped: rows.dropped, + dropped_cells: rows.dropped_cells, + damaged, + ..SheetPart::default() + }; sheet.lift(); Ok(sheet) } diff --git a/crates/xlsx/src/sheet.rs b/crates/xlsx/src/sheet.rs index 2691764d5c..16026c6a0d 100644 --- a/crates/xlsx/src/sheet.rs +++ b/crates/xlsx/src/sheet.rs @@ -190,6 +190,8 @@ pub struct SheetPart { pub rows: u64, /// Rows and cells dropped because their position was outside the grid or unreadable. pub dropped: u64, + /// Cell elements (``) inside dropped rows or dropped for an invalid/out-of-grid reference. + pub dropped_cells: u64, /// Why reading stopped early, when the part is damaged; the rows before the damage were /// handed out. pub damaged: Option, @@ -361,6 +363,7 @@ pub(crate) struct RowReader { next_row: u32, pub(crate) rows: u64, pub(crate) dropped: u64, + pub(crate) dropped_cells: u64, } impl RowReader { @@ -371,11 +374,13 @@ impl RowReader { Some(r) if (1..=MAX_ROWS).contains(&r) => r - 1, Some(_) => { self.dropped += 1; + self.dropped_cells += e.children("c").count() as u64; return None; } None if self.next_row < MAX_ROWS => self.next_row, None => { self.dropped += 1; + self.dropped_cells += e.children("c").count() as u64; return None; } }; @@ -398,12 +403,14 @@ impl RowReader { Some(p) => p, None => { self.dropped += 1; + self.dropped_cells += 1; continue; } }, None if next_col < MAX_COLS => CellRef::new(index, next_col), None => { self.dropped += 1; + self.dropped_cells += 1; continue; } }; @@ -569,7 +576,20 @@ mod tests { assert_eq!(next, Some(3)); assert!(r.row(&craft_xml::El::new("row").with_attr("r", "1048577")).is_none()); assert!(r.row(&craft_xml::El::new("row").with_attr("r", "0")).is_none()); - assert_eq!((r.rows, r.dropped), (4, 3)); + assert_eq!((r.rows, r.dropped, r.dropped_cells), (4, 3, 1)); + } + + #[test] + fn dropped_cells_counts_cells_in_dropped_rows_and_bad_refs() { + let mut r = RowReader::default(); + let bad_row_zero = craft_xml::Options::local().parse(br#"12"#).unwrap(); + let bad_row_high = craft_xml::Options::local().parse(br#"3"#).unwrap(); + let bad_cell = craft_xml::Options::local().parse(br#"45"#).unwrap(); + assert!(r.row(&bad_row_zero).is_none()); + assert!(r.row(&bad_row_high).is_none()); + let kept = r.row(&bad_cell).unwrap(); + assert_eq!(kept.cells.len(), 1); + assert_eq!((r.dropped, r.dropped_cells), (3, 4)); } #[test] From 512a1b8e8b59a7b325e7f69f6131aa8628470288 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 19:50:59 -0500 Subject: [PATCH 65/79] mesh, image-codecs: add clearcoat/sheen GLB, obj_with_mtl, and EXR chromaticities (#778) (#2466) * mesh, image-codecs: add clearcoat/sheen GLB, obj_with_mtl, and EXR chromaticities (#778) * fix(mesh): import Image and TextureRef in obj tests * fix(mesh): construct Mesh via struct literal in gltf test --- crates/image-codecs/src/codecs/exr.rs | 27 ++++++++++- crates/image-codecs/src/options.rs | 4 ++ crates/mesh/src/gltf.rs | 68 ++++++++++++++++++++++++--- crates/mesh/src/lib.rs | 30 +++++++++++- crates/mesh/src/obj.rs | 18 +++++-- crates/mesh/src/tests/gltf.rs | 37 ++++++++++++++- crates/mesh/src/tests/obj.rs | 13 ++++- 7 files changed, 183 insertions(+), 14 deletions(-) diff --git a/crates/image-codecs/src/codecs/exr.rs b/crates/image-codecs/src/codecs/exr.rs index 04019bcdcd..87c9617799 100644 --- a/crates/image-codecs/src/codecs/exr.rs +++ b/crates/image-codecs/src/codecs/exr.rs @@ -402,9 +402,21 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result, /// DPX bits per sample. `None` follows the image: 8 for 8-bit, 16 otherwise. pub dpx_bits: Option, /// DDS compression and mip chain. @@ -302,6 +305,7 @@ impl Default for EncodeOptions { tiff_bigtiff: false, tiff_pyramid: false, exr_compression: ExrCompression::Zip16, + exr_chromaticities: None, dpx_bits: None, dds: DdsOptions::default(), embed_icc: true, diff --git a/crates/mesh/src/gltf.rs b/crates/mesh/src/gltf.rs index d074f1ed12..5fde04b0ab 100644 --- a/crates/mesh/src/gltf.rs +++ b/crates/mesh/src/gltf.rs @@ -619,6 +619,8 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { let pbr = m.get("pbrMetallicRoughness").unwrap_or(&null); let ext = m.get("extensions"); let strength = ext.and_then(|e| e.get("KHR_materials_emissive_strength")).map_or(1.0, |e| num(e, "emissiveStrength", 1.0)); + let clearcoat = ext.and_then(|e| e.get("KHR_materials_clearcoat")); + let sheen = ext.and_then(|e| e.get("KHR_materials_sheen")); scene.materials.push(Material { name: name(m), base_color: nums(pbr, "baseColorFactor", [1.0; 4]).map(|v| v as f32), @@ -639,6 +641,14 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> { occlusion_texture: tref(m.get("occlusionTexture")), occlusion_strength: m.get("occlusionTexture").map_or(1.0, |n| num(n, "strength", 1.0)) as f32, emissive_texture: tref(m.get("emissiveTexture")), + clearcoat: clearcoat.map_or(0.0, |c| num(c, "clearcoatFactor", 0.0)) as f32, + clearcoat_roughness: clearcoat.map_or(0.0, |c| num(c, "clearcoatRoughnessFactor", 0.0)) as f32, + clearcoat_texture: clearcoat.and_then(|c| tref(c.get("clearcoatTexture"))), + clearcoat_roughness_texture: clearcoat.and_then(|c| tref(c.get("clearcoatRoughnessTexture"))), + sheen_color: sheen.map_or([0.0; 3], |s| nums(s, "sheenColorFactor", [0.0; 3]).map(|v| v as f32)), + sheen_roughness: sheen.map_or(0.0, |s| num(s, "sheenRoughnessFactor", 0.0)) as f32, + sheen_color_texture: sheen.and_then(|s| tref(s.get("sheenColorTexture"))), + sheen_roughness_texture: sheen.and_then(|s| tref(s.get("sheenRoughnessTexture"))), }); // The older specular-glossiness model, as the nearest metallic-roughness material: its // diffuse colour and texture, no metal, and roughness from the glossiness. @@ -816,12 +826,14 @@ fn uv_transform(t: &Value) -> UvTransform { /// the reader handles: the geometry reads without the others being understood. fn check_extensions(j: &Value, scene: &mut Scene) -> Result<()> { const LOOKS: [&str; 3] = ["KHR_texture_basisu", "MSFT_texture_dds", "KHR_lights_punctual"]; - const READ: [&str; 6] = [ + const READ: [&str; 8] = [ TEXTURE_TRANSFORM, "KHR_mesh_quantization", "KHR_materials_unlit", "KHR_materials_emissive_strength", "KHR_materials_pbrSpecularGlossiness", + "KHR_materials_clearcoat", + "KHR_materials_sheen", "EXT_texture_webp", ]; for e in arr(j, "extensionsRequired").iter().filter_map(Value::as_str) { @@ -1021,12 +1033,46 @@ fn material_json(m: &Material, textures: &mut Textures, extensions: &mut Vec<&'s if m.unlit { ext.insert("KHR_materials_unlit".into(), json!({})); } - for name in ["KHR_materials_emissive_strength", "KHR_materials_unlit"] { + if m.clearcoat > 0.0 || m.clearcoat_texture.is_some() || m.clearcoat_roughness_texture.is_some() { + let mut coat = Map::new(); + coat.insert("clearcoatFactor".into(), json!(m.clearcoat)); + if let Some(t) = textures.slot(m.clearcoat_texture) { + coat.insert("clearcoatTexture".into(), t); + } + coat.insert("clearcoatRoughnessFactor".into(), json!(m.clearcoat_roughness)); + if let Some(t) = textures.slot(m.clearcoat_roughness_texture) { + coat.insert("clearcoatRoughnessTexture".into(), t); + } + ext.insert("KHR_materials_clearcoat".into(), Value::Object(coat)); + } + if m.sheen_color != [0.0; 3] || m.sheen_color_texture.is_some() || m.sheen_roughness_texture.is_some() { + let mut sheen = Map::new(); + sheen.insert("sheenColorFactor".into(), json!(m.sheen_color)); + if let Some(t) = textures.slot(m.sheen_color_texture) { + sheen.insert("sheenColorTexture".into(), t); + } + sheen.insert("sheenRoughnessFactor".into(), json!(m.sheen_roughness)); + if let Some(t) = textures.slot(m.sheen_roughness_texture) { + sheen.insert("sheenRoughnessTexture".into(), t); + } + ext.insert("KHR_materials_sheen".into(), Value::Object(sheen)); + } + for name in ["KHR_materials_emissive_strength", "KHR_materials_unlit", "KHR_materials_clearcoat", "KHR_materials_sheen"] { if ext.contains_key(name) && !extensions.contains(&name) { extensions.push(name); } } - let slots = [m.base_color_texture, m.metallic_roughness_texture, m.normal_texture, m.occlusion_texture, m.emissive_texture]; + let slots = [ + m.base_color_texture, + m.metallic_roughness_texture, + m.normal_texture, + m.occlusion_texture, + m.emissive_texture, + m.clearcoat_texture, + m.clearcoat_roughness_texture, + m.sheen_color_texture, + m.sheen_roughness_texture, + ]; if slots.iter().flatten().any(|t| t.transform.is_some()) && !extensions.contains(&TEXTURE_TRANSFORM) { extensions.push(TEXTURE_TRANSFORM); } @@ -1067,15 +1113,25 @@ fn check_finite(scene: &Scene) -> Result<()> { let positions = scene.meshes.iter().flat_map(|m| m.positions.iter().flatten()).all(|x| (*x as f32).is_finite()); let nodes = scene.nodes.iter().flat_map(|n| n.transform.iter()).all(|x| x.is_finite()); let materials = scene.materials.iter().all(|m| { - let values = [m.metallic, m.roughness, m.normal_scale, m.occlusion_strength]; + let values = [m.metallic, m.roughness, m.normal_scale, m.occlusion_strength, m.clearcoat, m.clearcoat_roughness, m.sheen_roughness]; let cutoff = if let AlphaMode::Mask(c) = m.alpha_mode { c } else { 0.0 }; - let slots = [&m.base_color_texture, &m.metallic_roughness_texture, &m.normal_texture, &m.occlusion_texture, &m.emissive_texture]; + let slots = [ + &m.base_color_texture, + &m.metallic_roughness_texture, + &m.normal_texture, + &m.occlusion_texture, + &m.emissive_texture, + &m.clearcoat_texture, + &m.clearcoat_roughness_texture, + &m.sheen_color_texture, + &m.sheen_roughness_texture, + ]; let transforms = slots .into_iter() .flatten() .filter_map(|t| t.transform) .all(|t| t.offset.iter().chain(&t.scale).chain([&t.rotation]).all(|x| x.is_finite())); - m.base_color.iter().chain(&m.emissive).chain(&values).all(|x| x.is_finite()) && cutoff.is_finite() && transforms + m.base_color.iter().chain(&m.emissive).chain(&m.sheen_color).chain(&values).all(|x| x.is_finite()) && cutoff.is_finite() && transforms }); if positions && nodes && materials { Ok(()) } else { Err(malformed(KIND, "a position, transform or material value is not finite")) } } diff --git a/crates/mesh/src/lib.rs b/crates/mesh/src/lib.rs index 4808834fa4..f5368424d9 100644 --- a/crates/mesh/src/lib.rs +++ b/crates/mesh/src/lib.rs @@ -448,6 +448,16 @@ pub struct Material { pub occlusion_texture: Option, pub occlusion_strength: f32, pub emissive_texture: Option, + /// Clearcoat layer strength in `0..=1` (glTF `KHR_materials_clearcoat`). + pub clearcoat: f32, + pub clearcoat_roughness: f32, + pub clearcoat_texture: Option, + pub clearcoat_roughness_texture: Option, + /// Sheen colour factor (linear RGB) and roughness (glTF `KHR_materials_sheen`). + pub sheen_color: [f32; 3], + pub sheen_roughness: f32, + pub sheen_color_texture: Option, + pub sheen_roughness_texture: Option, } impl Default for Material { @@ -468,6 +478,14 @@ impl Default for Material { occlusion_texture: None, occlusion_strength: 1.0, emissive_texture: None, + clearcoat: 0.0, + clearcoat_roughness: 0.0, + clearcoat_texture: None, + clearcoat_roughness_texture: None, + sheen_color: [0.0; 3], + sheen_roughness: 0.0, + sheen_color_texture: None, + sheen_roughness_texture: None, } } } @@ -742,7 +760,17 @@ impl Scene { } } for m in &self.materials { - let slots = [m.base_color_texture, m.metallic_roughness_texture, m.normal_texture, m.occlusion_texture, m.emissive_texture]; + let slots = [ + m.base_color_texture, + m.metallic_roughness_texture, + m.normal_texture, + m.occlusion_texture, + m.emissive_texture, + m.clearcoat_texture, + m.clearcoat_roughness_texture, + m.sheen_color_texture, + m.sheen_roughness_texture, + ]; if slots.iter().flatten().any(|t| t.image >= self.images.len()) { return bad(format!("material `{}` names an image that does not exist", m.name)); } diff --git a/crates/mesh/src/obj.rs b/crates/mesh/src/obj.rs index 69428eb252..5f33cf902c 100644 --- a/crates/mesh/src/obj.rs +++ b/crates/mesh/src/obj.rs @@ -646,9 +646,15 @@ pub fn write(scene: &Scene, mtllib: Option<&str>, limits: &Limits) -> Result Result<(String, String)> { + Ok((write(scene, Some(mtllib), limits)?, write_mtl(scene))) +} + /// The scene's materials as an MTL library, named as [`write`] names them: `Kd`, `d`, `Ke`, -/// `Ns` (for readers without the PBR extension) with `Pr` and `Pm`, and `map_Kd`, `map_Ke` -/// and `norm` for images that have a [`Image::uri`]. +/// `Ns` (for readers without the PBR extension) with `Pr` and `Pm`, and `map_Kd`, `map_Ke`, +/// `norm`, `map_Pc`, and `map_Pcr` for images that have an [`Image::uri`]. pub fn write_mtl(scene: &Scene) -> String { let mut mtl = String::new(); for (m, name) in scene.materials.iter().zip(material_names(scene)) { @@ -661,7 +667,13 @@ pub fn write_mtl(scene: &Scene) -> String { "newmtl {name}\nKd {} {} {}\nd {}\nKe {} {} {}\nNs {ns}\nPr {r}\nPm {}", kd[0], kd[1], kd[2], m.base_color[3], ke[0], ke[1], ke[2], m.metallic ); - for (key, tex) in [("map_Kd", m.base_color_texture), ("map_Ke", m.emissive_texture), ("norm", m.normal_texture)] { + for (key, tex) in [ + ("map_Kd", m.base_color_texture), + ("map_Ke", m.emissive_texture), + ("norm", m.normal_texture), + ("map_Pc", m.clearcoat_texture), + ("map_Pcr", m.clearcoat_roughness_texture), + ] { if let Some(uri) = tex.and_then(|t| scene.images.get(t.image)).and_then(|i| i.uri.as_deref()) { let _ = writeln!(mtl, "{key} {}", uri.replace(['\n', '\r'], " ")); } diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index c47b911df8..5a60f28ebe 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -508,7 +508,7 @@ fn what_is_not_read_is_refused_or_named() { assert!(matches!(parse(&doc(json!({ "extensionsRequired": ["VENDOR_something_new"] }))), Err(Error::Unsupported(_)))); // Extensions that only change looks are named in a warning; the ones the reader handles are not. let s = parse(&doc( - json!({ "extensionsRequired": ["KHR_texture_transform", "KHR_materials_clearcoat", "KHR_mesh_quantization", "KHR_materials_unlit"] }), + json!({ "extensionsRequired": ["KHR_texture_transform", "KHR_materials_transmission", "KHR_mesh_quantization", "KHR_materials_unlit"] }), )) .unwrap(); assert_eq!(s.warnings.len(), 1, "texture transforms are read: {:?}", s.warnings); @@ -979,3 +979,38 @@ fn strict_uri_decoding_preserves_exact_names_and_rejects_invalid_utf8() { assert_eq!(decoded, "A%GG+é".repeat(100_000)); assert!(decoded.len() <= input.len()); } + +#[test] +fn clearcoat_and_sheen_round_trip_through_write_glb() { + let mut mesh = Mesh { name: "card".into(), ..Mesh::default() }; + mesh.positions = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]; + mesh.parts = vec![Part { material: Some(0), corners: [0, 1, 2].map(Corner::at).to_vec(), ..Part::default() }]; + let mat = Material { + name: "CoatedVelvet".into(), + clearcoat: 0.8, + clearcoat_roughness: 0.25, + clearcoat_texture: Some(TextureRef { image: 0, ..TextureRef::default() }), + clearcoat_roughness_texture: Some(TextureRef { image: 0, ..TextureRef::default() }), + sheen_color: [0.9, 0.2, 0.1], + sheen_roughness: 0.5, + sheen_color_texture: Some(TextureRef { image: 1, ..TextureRef::default() }), + sheen_roughness_texture: Some(TextureRef { image: 1, ..TextureRef::default() }), + ..Material::default() + }; + let mut scene = Scene::from_meshes(vec![mesh], vec![mat.clone()]); + scene.images = vec![ + Image { name: "coat".into(), data: Some(b"\x89PNG coat".to_vec()), ..Image::default() }, + Image { name: "sheen".into(), data: Some(b"\x89PNG sheen".to_vec()), ..Image::default() }, + ]; + let glb = write_glb(&scene, &Limits::default()).unwrap(); + let back = parse(&glb).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); + assert_eq!(back.materials[0].clearcoat, mat.clearcoat); + assert_eq!(back.materials[0].clearcoat_roughness, mat.clearcoat_roughness); + assert_eq!(back.materials[0].clearcoat_texture.map(|t| t.image), Some(0)); + assert_eq!(back.materials[0].clearcoat_roughness_texture.map(|t| t.image), Some(0)); + assert_eq!(back.materials[0].sheen_color, mat.sheen_color); + assert_eq!(back.materials[0].sheen_roughness, mat.sheen_roughness); + assert_eq!(back.materials[0].sheen_color_texture.map(|t| t.image), Some(1)); + assert_eq!(back.materials[0].sheen_roughness_texture.map(|t| t.image), Some(1)); +} diff --git a/crates/mesh/src/tests/obj.rs b/crates/mesh/src/tests/obj.rs index ed8a89755c..172137cc7b 100644 --- a/crates/mesh/src/tests/obj.rs +++ b/crates/mesh/src/tests/obj.rs @@ -1,6 +1,6 @@ use super::hammer; use crate::obj::{material_names, read, read_mtl, sibling_name, write, write_mtl}; -use crate::{AlphaMode, Corner, Error, Limits, Material, Mesh, NONE, Part, Scene, no_external}; +use crate::{AlphaMode, Corner, Error, Image, Limits, Material, Mesh, NONE, Part, Scene, TextureRef, no_external}; /// A unit cube with texture coordinates, normals, two materials and one face written with /// negative references. @@ -373,3 +373,14 @@ fn group_boundaries_keep_repeated_names_separate() { assert_eq!(scene.meshes.len(), 2); assert!(scene.meshes.iter().all(|m| m.name == "Same")); } + +#[test] +fn write_with_mtl_links_library_and_clearcoat_maps() { + let mut scene = cube(); + scene.images = vec![Image { uri: Some("coat.png".into()), ..Image::default() }]; + scene.materials[0].clearcoat_texture = Some(TextureRef { image: 0, ..TextureRef::default() }); + scene.materials[0].clearcoat_roughness_texture = Some(TextureRef { image: 0, ..TextureRef::default() }); + let (obj, mtl) = crate::obj::write_with_mtl(&scene, "cube.mtl", &Limits::default()).unwrap(); + assert!(obj.contains("mtllib cube.mtl\n")); + assert!(mtl.contains("map_Pc coat.png\n") && mtl.contains("map_Pcr coat.png\n"), "{mtl}"); +} From 7258e42d8dd909f2176fb08f09aae048611f3eaf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 19:55:29 -0500 Subject: [PATCH 66/79] ps: expose public PostScript token/lexer scanner (read::lex) (#2458) * ps: expose public PostScript token/lexer scanner (read::lex) * ps(lex): only mark stream fresh on Ok token * fix(ps): allow clippy::should_implement_trait on Lexer::next --- crates/ps/src/read/lex.rs | 432 ++++++++++++++++++++++++++++++++++++++ crates/ps/src/read/mod.rs | 1 + 2 files changed, 433 insertions(+) create mode 100644 crates/ps/src/read/lex.rs diff --git a/crates/ps/src/read/lex.rs b/crates/ps/src/read/lex.rs new file mode 100644 index 0000000000..c8f81add7c --- /dev/null +++ b/crates/ps/src/read/lex.rs @@ -0,0 +1,432 @@ +//! PostScript token scanner over an in-memory byte slice, tracking the unread whitespace +//! boundary for `currentfile` data reads (`read`, `readstring`, filters, `token`, `eexec`). + +use std::fmt; + +/// Deepest procedure nesting the scanner reads. +const MAX_NESTING: usize = 256; + +/// Most bytes an ASCII85 string literal may decode to. +const MAX_ASCII85: usize = 1 << 28; + +/// How an immediately evaluated name (`//name`) is prefixed in [`Token::Exec`], until the +/// interpreter replaces it. +pub const IMMEDIATE: &str = "//"; + +/// A scanned PostScript token. +#[derive(Clone, Debug, PartialEq)] +pub enum Token { + Int(i64), + Real(f64), + /// A literal name (`/name`). + Name(String), + /// An executable name (operator, `[`, `]`, `<<`, `>>`, or `//name` prefixed with [`IMMEDIATE`]). + Exec(String), + /// A byte string (`(...)`, `<...>`, or `<~...~>`). + Str(Vec), + /// A procedure (`{ ... }`). + Proc(Vec), +} + +/// A finite number parsed from a PostScript numeric token. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Number { + Int(i64), + Real(f64), +} + +/// An error returned by [`Lexer::next`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LexError { + Syntax(String), + Limit(&'static str), +} + +impl fmt::Display for LexError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Syntax(what) => write!(f, "syntaxerror: {what}"), + Self::Limit(msg) => f.write_str(msg), + } + } +} + +impl std::error::Error for LexError {} + +/// PostScript byte-slice scanner with `currentfile` data boundary tracking. +pub struct Lexer<'a> { + src: &'a [u8], + pos: usize, + /// The whitespace character that ended the last token is still unread (data the program + /// reads from itself starts after it). + fresh: bool, + /// The last object read has immediately evaluated names (`//name`) in it, read as executable + /// names starting with [`IMMEDIATE`] for the interpreter to replace by their values. + pub immediate: bool, +} + +/// Whether `b` is PostScript whitespace. +pub fn is_space(b: u8) -> bool { + matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0') +} + +/// Whether `b` is a PostScript delimiter. +pub fn is_delim(b: u8) -> bool { + matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') +} + +fn syntax(what: &str) -> Result { + Err(LexError::Syntax(what.to_string())) +} + +impl<'a> Lexer<'a> { + /// Create a scanner over `src`. + pub fn new(src: &'a [u8]) -> Self { + Self { src, pos: 0, fresh: false, immediate: false } + } + + /// What is left to read. + pub fn rest(&self) -> &'a [u8] { + self.src.get(self.pos..).unwrap_or_default() + } + + /// What is left to read as data: after the whitespace that ended the last token (a CR LF + /// pair counts as one). + pub fn data(&mut self) -> &'a [u8] { + if std::mem::take(&mut self.fresh) { + match self.peek() { + Some(b'\r') => { + self.pos += 1; + if self.peek() == Some(b'\n') { + self.pos += 1; + } + } + Some(b) if is_space(b) => self.pos += 1, + _ => {} + } + } + self.rest() + } + + /// Skip `n` bytes (the data a filter or `readstring` took). + pub fn advance(&mut self, n: usize) { + self.fresh = false; + self.pos = self.pos.saturating_add(n).min(self.src.len()); + } + + fn peek(&self) -> Option { + self.src.get(self.pos).copied() + } + + fn skip_space(&mut self) { + while let Some(b) = self.peek() { + if is_space(b) { + self.pos += 1; + } else if b == b'%' { + while let Some(c) = self.peek() { + if c == b'\n' || c == b'\r' { + break; + } + self.pos += 1; + } + } else { + break; + } + } + } + + /// The next token at the top level (`None` at the end of the file). + #[allow(clippy::should_implement_trait)] + pub fn next(&mut self) -> Result, LexError> { + self.immediate = false; + let t = self.token(0)?; + self.fresh = true; + Ok(t) + } + + fn token(&mut self, depth: usize) -> Result, LexError> { + self.skip_space(); + let Some(b) = self.peek() else { return Ok(None) }; + self.pos += 1; + Ok(Some(match b { + b'(' => Token::Str(self.string()?), + b'<' => self.angle_string()?, + b'>' => { + if self.peek() != Some(b'>') { + return syntax(">"); + } + self.pos += 1; + Token::Exec(">>".to_string()) + } + b'[' => Token::Exec("[".to_string()), + b']' => Token::Exec("]".to_string()), + b'{' => self.proc(depth)?, + b'}' | b')' => return syntax(&char::from(b).to_string()), + b'/' => self.name(), + _ => { + self.pos -= 1; + let w = self.word(); + match number(&w) { + Some(Number::Int(i)) => Token::Int(i), + Some(Number::Real(r)) => Token::Real(r), + None => Token::Exec(w), + } + } + })) + } + + fn angle_string(&mut self) -> Result { + match self.peek() { + Some(b'<') => { + self.pos += 1; + Ok(Token::Exec("<<".to_string())) + } + Some(b'~') => { + self.pos += 1; + Ok(Token::Str(self.ascii85()?)) + } + _ => Ok(Token::Str(self.hex()?)), + } + } + + fn proc(&mut self, depth: usize) -> Result { + if depth >= MAX_NESTING { + return Err(LexError::Limit("procedures nested too deeply")); + } + let mut items = vec![]; + loop { + self.skip_space(); + match self.peek() { + None => return syntax("{"), + Some(b'}') => { + self.pos += 1; + break; + } + _ => match self.token(depth + 1)? { + Some(o) => items.push(o), + None => return syntax("{"), + }, + } + } + Ok(Token::Proc(items)) + } + + fn name(&mut self) -> Token { + // `//name` stands for the name's value when it is read. + let immediate = self.peek() == Some(b'/'); + if immediate { + self.pos += 1; + self.immediate = true; + } + let name = self.word(); + if immediate { Token::Exec(format!("{IMMEDIATE}{name}")) } else { Token::Name(name) } + } + + /// A regular token's characters. + fn word(&mut self) -> String { + let start = self.pos; + while let Some(b) = self.peek() { + if is_space(b) || is_delim(b) { + break; + } + self.pos += 1; + } + String::from_utf8_lossy(self.src.get(start..self.pos).unwrap_or_default()).into_owned() + } + + /// A literal string after its `(`. + fn string(&mut self) -> Result, LexError> { + let mut out = vec![]; + let mut depth = 0usize; + loop { + let Some(b) = self.peek() else { return syntax("(") }; + self.pos += 1; + match b { + b'(' => { + depth += 1; + out.push(b); + } + b')' if depth == 0 => return Ok(out), + b')' => { + depth -= 1; + out.push(b); + } + b'\\' => self.string_escape(&mut out)?, + _ => out.push(b), + } + } + } + + fn string_escape(&mut self, out: &mut Vec) -> Result<(), LexError> { + let Some(e) = self.peek() else { return syntax("(") }; + self.pos += 1; + match e { + b'n' => out.push(b'\n'), + b'r' => out.push(b'\r'), + b't' => out.push(b'\t'), + b'b' => out.push(8), + b'f' => out.push(12), + b'\r' => { + if self.peek() == Some(b'\n') { + self.pos += 1; + } + } + b'\n' => {} + b'0'..=b'7' => { + let mut v = u32::from(e - b'0'); + for _ in 0..2 { + match self.peek() { + Some(d @ b'0'..=b'7') => { + v = v * 8 + u32::from(d - b'0'); + self.pos += 1; + } + _ => break, + } + } + out.push((v & 0xff) as u8); + } + other => out.push(other), + } + Ok(()) + } + + /// A hexadecimal string after its `<`. + fn hex(&mut self) -> Result, LexError> { + let Some(end) = self.rest().iter().position(|b| *b == b'>') else { + return syntax("<"); + }; + let body = self.rest().get(..end).unwrap_or_default(); + let Some(out) = hex_decode(body) else { + return syntax("<"); + }; + self.advance(end + 1); + Ok(out) + } + + /// An ASCII85 string after its `<~`. + fn ascii85(&mut self) -> Result, LexError> { + let Some(end) = find(self.rest(), b"~>") else { + return syntax("<~"); + }; + let text = String::from_utf8_lossy(self.rest().get(..end + 2).unwrap_or_default()).into_owned(); + self.advance(end + 2); + let Some(out) = craft_eps::ascii85::decode(text.as_bytes(), MAX_ASCII85) else { + return syntax("<~"); + }; + Ok(out) + } +} + +/// Where `needle` first starts in `hay`. +pub fn find(hay: &[u8], needle: &[u8]) -> Option { + if needle.is_empty() { + return Some(0); + } + hay.windows(needle.len()).position(|w| w == needle) +} + +/// Hexadecimal digits (whitespace ignored, an odd last digit padded with 0); `None` on others. +pub fn hex_decode(body: &[u8]) -> Option> { + let mut out = Vec::with_capacity(body.len() / 2); + let mut high: Option = None; + for &b in body { + if is_space(b) { + continue; + } + let v = char::from(b).to_digit(16)? as u8; + match high.take() { + Some(h) => out.push(h << 4 | v), + None => high = Some(v), + } + } + if let Some(h) = high { + out.push(h << 4); + } + Some(out) +} + +/// A number token (`12`, `-3.5`, `.5`, `1e-3`, `16#ff`), or `None`. +pub fn number(w: &str) -> Option { + let first = w.bytes().next()?; + if !(first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.')) { + return None; + } + if let Ok(i) = w.parse::() { + return Some(Number::Int(i)); + } + if let Some((base, digits)) = w.split_once('#') { + let base: u32 = base.parse().ok().filter(|b| (2..=36).contains(b))?; + // `from_str_radix` accepts a leading sign; a PostScript radix number has digits only. + if digits.starts_with(['+', '-']) { + return None; + } + return i64::from_str_radix(digits, base).ok().map(Number::Int); + } + // Rust reads `inf` and `nan`; PostScript doesn't. + if w.bytes().any(|b| b.is_ascii_alphabetic() && !matches!(b, b'e' | b'E')) { + return None; + } + let v: f64 = w.parse().ok()?; + v.is_finite().then_some(Number::Real(v)) +} + +#[cfg(test)] +mod tests { + use super::{LexError, Lexer, Number, Token, find, hex_decode, number}; + + #[test] + fn radix_number_with_sign_after_hash_is_not_a_number() { + assert!(number("16#+ff").is_none()); + assert!(number("16#-ff").is_none()); + assert_eq!(number("16#ff"), Some(Number::Int(255))); + } + + #[test] + fn currentfile_data_consumes_single_whitespace_or_crlf() { + let mut lex = Lexer::new(b"image\r\nDATA"); + assert_eq!(lex.next(), Ok(Some(Token::Exec("image".into())))); + assert_eq!(lex.rest(), b"\r\nDATA"); + assert_eq!(lex.data(), b"DATA"); + lex.advance(2); + assert_eq!(lex.rest(), b"TA"); + } + + #[test] + fn partial_lines_and_eof() { + let mut lex = Lexer::new(b"1 2 add"); + assert_eq!(lex.next(), Ok(Some(Token::Int(1)))); + assert_eq!(lex.next(), Ok(Some(Token::Int(2)))); + assert_eq!(lex.next(), Ok(Some(Token::Exec("add".into())))); + assert_eq!(lex.next(), Ok(None)); + assert_eq!(lex.data(), b""); + } + + #[test] + fn immediate_names_and_procedures() { + let mut lex = Lexer::new(b"{ //foo /bar }"); + assert_eq!(lex.next(), Ok(Some(Token::Proc(vec![Token::Exec("//foo".into()), Token::Name("bar".into())])))); + assert!(lex.immediate); + } + + #[test] + fn find_and_hex_decode() { + assert_eq!(find(b"abcdef", b"cd"), Some(2)); + assert_eq!(find(b"abcdef", b""), Some(0)); + assert_eq!(find(b"abcdef", b"xy"), None); + assert_eq!(hex_decode(b"41 4"), Some(vec![0x41, 0x40])); + assert_eq!(hex_decode(b"4g"), None); + } + + #[test] + fn unterminated_string_is_syntax_error() { + let mut lex = Lexer::new(b"(open"); + assert_eq!(lex.next(), Err(LexError::Syntax("(".into()))); + } + + #[test] + fn error_does_not_mark_fresh() { + let mut lex = Lexer::new(b") rest"); + assert_eq!(lex.next(), Err(LexError::Syntax(")".into()))); + assert_eq!(lex.data(), b" rest"); + } +} diff --git a/crates/ps/src/read/mod.rs b/crates/ps/src/read/mod.rs index 0fcc3b3634..2165547d7e 100644 --- a/crates/ps/src/read/mod.rs +++ b/crates/ps/src/read/mod.rs @@ -18,6 +18,7 @@ mod encodings; mod font; mod gstate; mod interp; +pub mod lex; mod obj; mod ops; mod pdf; From d0ca0cdb28404bc2c76e7370ba8b5955f8926172 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:01:05 -0500 Subject: [PATCH 67/79] craft-mesh: add COLLADA (.dae) and Alembic (.abc) readers (#2462) * craft-mesh: add COLLADA (.dae) and Alembic (.abc) readers * fix(mesh): use str::to_owned instead of into_owned in dae * craft-mesh: make dae and abc opt-in features * fix(mesh): remove unused Error import and use Entry API in abc --- crates/mesh/Cargo.toml | 4 +- crates/mesh/README.md | 4 +- crates/mesh/src/abc.rs | 709 +++++++++++++++++++++++++++++++++++ crates/mesh/src/dae.rs | 583 ++++++++++++++++++++++++++++ crates/mesh/src/lib.rs | 15 +- crates/mesh/src/tests.rs | 4 + crates/mesh/src/tests/abc.rs | 198 ++++++++++ crates/mesh/src/tests/dae.rs | 130 +++++++ 8 files changed, 1644 insertions(+), 3 deletions(-) create mode 100644 crates/mesh/src/abc.rs create mode 100644 crates/mesh/src/dae.rs create mode 100644 crates/mesh/src/tests/abc.rs create mode 100644 crates/mesh/src/tests/dae.rs diff --git a/crates/mesh/Cargo.toml b/crates/mesh/Cargo.toml index ef860114f0..6ba794aae6 100644 --- a/crates/mesh/Cargo.toml +++ b/crates/mesh/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-mesh" -description = "3D mesh file formats behind one neutral model: STL and Wavefront OBJ/MTL readers and writers, a glTF 2.0 / GLB reader and GLB writer, and PLY, FBX and 3MF readers, bounded on hostile input" +description = "3D mesh file formats behind one neutral model: STL and Wavefront OBJ/MTL readers and writers, a glTF 2.0 / GLB reader and GLB writer, and PLY, FBX, 3MF, COLLADA and Alembic readers, bounded on hostile input" version.workspace = true edition.workspace = true license.workspace = true @@ -18,6 +18,8 @@ ply = [] gltf = ["dep:serde_json"] fbx = ["dep:miniz_oxide", "dep:craft-zip"] threemf = ["dep:craft-opc", "dep:craft-xml"] +dae = ["dep:craft-xml"] +abc = [] [dependencies] serde_json = { workspace = true, optional = true } diff --git a/crates/mesh/README.md b/crates/mesh/README.md index df32e7a599..c8d335f449 100644 --- a/crates/mesh/README.md +++ b/crates/mesh/README.md @@ -11,8 +11,10 @@ a `Scene` into bytes. One Cargo feature per format, all on by default. | `gltf` | glTF 2.0 (`.gltf`) and GLB | yes | GLB | `serde_json` | | `threemf` | 3MF, core and materials extension | yes | no | `craft-opc`, `craft-xml` | | `fbx` | FBX 6.x and 7.x, binary and ASCII | yes | no | `miniz_oxide` | +| `dae` | COLLADA (`.dae`), scenes, transforms, cameras | yes | no | `craft-xml` | +| `abc` | Alembic (`.abc`), Ogawa container | yes | no | none | -USD, Alembic and COLLADA are not here yet. +USD is not here yet. ## The neutral model diff --git a/crates/mesh/src/abc.rs b/crates/mesh/src/abc.rs new file mode 100644 index 0000000000..b54374d064 --- /dev/null +++ b/crates/mesh/src/abc.rs @@ -0,0 +1,709 @@ +//! Alembic (`.abc`), read: the Ogawa container, `AbcGeom_Xform` hierarchy (matrix, translate, +//! rotate, scale ops; `.inherits`), `AbcGeom_PolyMesh` at its first sample (positions `P`, +//! polygons `.faceIndices` / `.faceCounts` turned counter-clockwise from Alembic's clockwise +//! winding, normals `N` and UVs `uv` at any geometry scope, indexed or not), and +//! `AbcGeom_FaceSet` children as materials. +//! +//! UVs are flipped to top-left origin (`1.0 - v`), matching the rest of this crate. HDF5-based +//! Alembic files are refused with [`Error::Unsupported`]. + +use std::collections::HashMap; + +use crate::{Corner, Error, IDENTITY, Limits, Mat4, Material, Mesh, Node, Part, Result, Scene, malformed, mat_mul, too_large}; + +const KIND: &str = "Alembic"; +const OGAWA_MAGIC: &[u8] = b"Ogawa"; +const HDF5_MAGIC: &[u8] = b"\x89HDF\r\n\x1a\n"; +const DATA_BIT: u64 = 1 << 63; +const KEY_BYTES: usize = 16; +const OBJECT_HASH_BYTES: usize = 32; +const MAX_INDEXED_META: usize = 255; + +/// Read an Alembic (`.abc` Ogawa) file into a [`Scene`]. +pub fn read(bytes: &[u8], limits: &Limits) -> Result { + if bytes.starts_with(HDF5_MAGIC) { + return Err(Error::Unsupported("HDF5-based Alembic (re-export the file as Alembic Ogawa, the default since Alembic 1.5)".into())); + } + if !bytes.starts_with(OGAWA_MAGIC) || bytes.len() < 16 { + return Err(malformed(KIND, "not an Alembic Ogawa file")); + } + let mut o = Ogawa { b: bytes, budget: limits.max_data_bytes, max_budget: limits.max_data_bytes, indexed_meta: vec![String::new()] }; + let root_ref = o.u64_at(8)?; + let root = o.group(root_ref)?; + let is_data = |i: usize| root.get(i).is_some_and(|r| r & DATA_BIT != 0); + if root.len() < 6 || !(0..6).all(|i| is_data(i) != (i == 2)) { + return Err(malformed(KIND, "the archive group does not have the Alembic layout")); + } + let block = o.data(root[5])?; + read_indexed_meta(block, &mut o.indexed_meta)?; + + let mut walk = Walk { o, limits, scene: Scene::default(), materials: HashMap::new(), visits: 0, triangles: 0, parts: 0 }; + walk.object(root[2], None, "", 0)?; + Ok(walk.scene) +} + +struct Ogawa<'a> { + b: &'a [u8], + budget: usize, + max_budget: usize, + indexed_meta: Vec, +} + +#[derive(Clone, Copy, PartialEq)] +enum PropKind { + Compound, + Scalar, + Array, +} + +struct Prop { + name: String, + meta: String, + kind: PropKind, + pod: u32, + extent: usize, + group: u64, +} + +fn meta_get<'m>(meta: &'m str, key: &str) -> Option<&'m str> { + meta.split(';').filter_map(|kv| kv.split_once('=')).find(|(k, _)| *k == key).map(|(_, v)| v) +} + +struct Cursor<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Cursor<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8]> { + let s = self.pos.checked_add(n).and_then(|end| self.b.get(self.pos..end)).ok_or_else(|| malformed(KIND, "header block ends early"))?; + self.pos += n; + Ok(s) + } + + fn u8(&mut self) -> Result { + Ok(self.take(1)?.first().copied().unwrap_or(0)) + } + + fn u32(&mut self) -> Result { + let s = self.take(4)?; + Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]])) + } + + fn hinted(&mut self, hint: u32) -> Result { + Ok(match hint { + 0 => self.u8()? as usize, + 1 => { + let s = self.take(2)?; + u16::from_le_bytes([s[0], s[1]]) as usize + } + 2 => self.u32()? as usize, + _ => return Err(malformed(KIND, format!("bad size hint {hint}"))), + }) + } + + fn string(&mut self, n: usize) -> Result { + Ok(String::from_utf8_lossy(self.take(n)?).into_owned()) + } +} + +fn f16_to_f64(bits: u16) -> f64 { + let sign = if bits & 0x8000 != 0 { -1.0_f64 } else { 1.0_f64 }; + let exp = (bits >> 10) & 0x1f; + let mant = bits & 0x03ff; + match exp { + 0 => sign * (f64::from(mant) * 2.0_f64.powi(-24)), + 31 => { + if mant == 0 { + sign * f64::INFINITY + } else { + f64::NAN + } + } + _ => sign * ((1.0 + f64::from(mant) / 1024.0) * 2.0_f64.powi(i32::from(exp) - 15)), + } +} + +impl<'a> Ogawa<'a> { + fn charge(&mut self, bytes: usize) -> Result<()> { + self.budget = self.budget.checked_sub(bytes).ok_or_else(|| too_large(KIND, format!("decodes to more than {} bytes", self.max_budget)))?; + Ok(()) + } + + fn u64_at(&self, pos: u64) -> Result { + let p = usize::try_from(pos).map_err(|_| malformed(KIND, "offset out of range"))?; + let s = + p.checked_add(8).and_then(|e| self.b.get(p..e)).ok_or_else(|| malformed(KIND, format!("offset {pos} is past the end of the file")))?; + let mut a = [0u8; 8]; + a.copy_from_slice(s); + Ok(u64::from_le_bytes(a)) + } + + fn group(&mut self, r: u64) -> Result> { + if r & DATA_BIT != 0 { + return Err(malformed(KIND, "expected a group, found a data block")); + } + if r == 0 { + return Ok(Vec::new()); + } + let n = self.u64_at(r)?; + let room = (self.b.len() as u64).saturating_sub(r.saturating_add(8)) / 8; + if n > room { + return Err(malformed(KIND, format!("group at {r} claims {n} children"))); + } + self.charge(n as usize * 8)?; + (0..n).map(|i| self.u64_at(r + 8 + 8 * i)).collect() + } + + fn data(&self, r: u64) -> Result<&'a [u8]> { + if r & DATA_BIT == 0 { + return Err(malformed(KIND, "expected a data block, found a group")); + } + let off = r & !DATA_BIT; + if off == 0 { + return Ok(&[]); + } + let size = self.u64_at(off)?; + let start = usize::try_from(off + 8).map_err(|_| malformed(KIND, "offset out of range"))?; + usize::try_from(size) + .ok() + .and_then(|s| start.checked_add(s)) + .and_then(|end| self.b.get(start..end)) + .ok_or_else(|| malformed(KIND, format!("data block at {off} ({size} bytes) overruns the file"))) + } + + fn meta_at(&self, index: u8) -> String { + self.indexed_meta.get(index as usize).cloned().unwrap_or_default() + } + + fn compound(&mut self, r: u64) -> Result> { + let children = self.group(r)?; + let Some(&last) = children.last().filter(|c| **c & DATA_BIT != 0) else { return Ok(Vec::new()) }; + let block = self.data(last)?; + self.charge(block.len())?; + let mut c = Cursor { b: block, pos: 0 }; + let mut out = Vec::new(); + while c.pos < block.len() { + let info = c.u32()?; + let hint = (info & 0xc) >> 2; + let kind = match info & 0x3 { + 0 => PropKind::Compound, + 1 => PropKind::Scalar, + _ => PropKind::Array, + }; + let (pod, extent) = ((info & 0xf0) >> 4, ((info & 0xff000) >> 12) as usize); + if kind != PropKind::Compound { + let _samples = c.hinted(hint)?; + if info & 0x200 != 0 { + c.hinted(hint)?; + c.hinted(hint)?; + } + if info & 0x100 != 0 { + c.hinted(hint)?; + } + } + let name_len = c.hinted(hint)?; + let name = c.string(name_len)?; + let meta_index = ((info & 0xff0_0000) >> 20) as u8; + let meta = if meta_index == 0xff { + let n = c.hinted(hint)?; + c.string(n)? + } else { + self.meta_at(meta_index) + }; + let group = children.get(out.len()).copied().ok_or_else(|| malformed(KIND, format!("property \"{name}\" has no group")))?; + out.push(Prop { name, meta, kind, pod, extent, group }); + } + Ok(out) + } + + fn values(&mut self, property: &Prop) -> Result> { + let samples = self.group(property.group)?; + let Some(&first) = samples.first() else { return Ok(Vec::new()) }; + + let raw = self.data(first)?; + let raw = if raw.is_empty() { + raw + } else { + raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", property.name)))? + }; + + let value_bytes = match property.pod { + 0..=2 => 1, + 3 | 4 | 9 => 2, + 5 | 6 | 10 => 4, + 7 | 8 | 11 => 8, + other => return Err(Error::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))), + }; + self.charge((raw.len() / value_bytes).saturating_mul(8))?; + + Ok(match property.pod { + 0 | 1 => raw.iter().map(|v| *v as f64).collect(), + 2 => raw.iter().map(|v| *v as i8 as f64).collect(), + 3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c) as f64).collect(), + 4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c) as f64).collect(), + 5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c) as f64).collect(), + 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), + 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(), + 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), + 9 => raw.as_chunks::<2>().0.iter().map(|c| f16_to_f64(u16::from_le_bytes(*c))).collect(), + 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), + _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), + }) + } + + fn object_headers(&mut self, children: &[u64]) -> Result> { + let Some(&last) = children.last().filter(|c| **c & DATA_BIT != 0) else { return Ok(Vec::new()) }; + let block = self.data(last)?; + self.charge(block.len())?; + let body = block.get(..block.len().saturating_sub(OBJECT_HASH_BYTES)).unwrap_or_default(); + let mut c = Cursor { b: body, pos: 0 }; + let mut out = Vec::new(); + while c.pos < body.len() { + let n = c.u32()? as usize; + let name = c.string(n)?; + let index = c.u8()?; + let meta = if index == 0xff { + let n = c.u32()? as usize; + c.string(n)? + } else { + self.meta_at(index) + }; + out.push((name, meta)); + } + Ok(out) + } +} + +fn read_indexed_meta(block: &[u8], out: &mut Vec) -> Result<()> { + let mut c = Cursor { b: block, pos: 0 }; + while c.pos < block.len() && out.len() < MAX_INDEXED_META { + let n = c.u8()? as usize; + out.push(c.string(n)?); + } + Ok(()) +} + +#[derive(Clone, Copy)] +enum Scope { + Constant, + Uniform, + Vertex, + FaceVarying, +} + +struct Param { + vals: Vec, + indices: Option>, + scope: Scope, +} + +impl Param { + fn get(&self, k: usize, p: usize, f: usize) -> Option<[f64; W]> { + let i = match self.scope { + Scope::Constant => 0, + Scope::Uniform => f, + Scope::Vertex => p, + Scope::FaceVarying => k, + }; + let i = match &self.indices { + Some(ix) => Some(*ix.get(i)?).filter(|v| *v >= 0.0)? as usize, + None => i, + }; + let start = i.checked_mul(W)?; + self.vals.get(start..start.checked_add(W)?)?.try_into().ok() + } +} + +fn find<'p>(props: &'p [Prop], name: &str) -> Option<&'p Prop> { + props.iter().find(|p| p.name == name) +} + +fn schema_compound<'p>(props: &'p [Prop], schema: &str, name: &str) -> Option<&'p Prop> { + let compounds = || props.iter().filter(|p| p.kind == PropKind::Compound); + compounds().find(|p| meta_get(&p.meta, "schema") == Some(schema)).or_else(|| compounds().find(|p| p.name == name)) +} + +struct Walk<'a> { + o: Ogawa<'a>, + limits: &'a Limits, + scene: Scene, + materials: HashMap, + visits: usize, + triangles: usize, + parts: usize, +} + +impl Walk<'_> { + fn warn(&mut self, msg: String) { + if !self.scene.warnings.contains(&msg) { + self.scene.warnings.push(msg); + } + } + + fn push_node(&mut self, node: Node, parent: Option) -> Result { + if self.scene.nodes.len() >= self.limits.max_nodes { + return Err(too_large(KIND, format!("more than {} nodes", self.limits.max_nodes))); + } + let idx = self.scene.nodes.len(); + self.scene.nodes.push(node); + match parent { + Some(p) => self.scene.nodes[p].children.push(idx), + None => self.scene.roots.push(idx), + } + Ok(idx) + } + + fn intern_material(&mut self, name: &str) -> Result { + if let Some(&idx) = self.materials.get(name) { + return Ok(idx); + } + if self.scene.materials.len() >= self.limits.max_materials { + return Err(too_large(KIND, format!("more than {} materials", self.limits.max_materials))); + } + let idx = self.scene.materials.len(); + self.scene.materials.push(Material { name: name.to_owned(), ..Material::default() }); + self.materials.insert(name.to_owned(), idx); + Ok(idx) + } + + fn object(&mut self, r: u64, parent_node: Option, xform_name: &str, depth: usize) -> Result<()> { + self.visits += 1; + if depth > self.limits.max_depth || self.visits > self.limits.max_nodes { + return Err(malformed(KIND, "objects are nested too deeply or shared too often")); + } + let children = self.o.group(r)?; + let headers = self.o.object_headers(&children)?; + for (i, (name, meta)) in headers.iter().enumerate() { + let group = children + .get(i + 1) + .copied() + .filter(|g| g & DATA_BIT == 0) + .ok_or_else(|| malformed(KIND, format!("object \"{name}\" has no group")))?; + let schema = meta_get(meta, "schema").unwrap_or_default(); + let kids = self.o.group(group)?; + let props = match kids.first() { + Some(&p) if p & DATA_BIT == 0 => self.o.compound(p)?, + _ => Vec::new(), + }; + + let mut next_parent = parent_node; + if schema.starts_with("AbcGeom_Xform") { + if let Some(xf) = schema_compound(&props, schema, ".xform") { + let (local, inherits) = self.xform(xf.group)?; + let attach_to = if inherits { parent_node } else { None }; + let node_idx = self.push_node(Node { name: name.clone(), transform: local, ..Node::default() }, attach_to)?; + next_parent = Some(node_idx); + } + } else if schema.starts_with("AbcGeom_PolyMesh") + && let Some(geom) = schema_compound(&props, schema, ".geom") + { + let part_name = if xform_name.is_empty() { name.clone() } else { xform_name.to_string() }; + let sets = self.face_sets(&kids)?; + let mesh = self.mesh(geom.group, &part_name, &sets)?; + if self.scene.meshes.len() >= self.limits.max_meshes { + return Err(too_large(KIND, format!("more than {} meshes", self.limits.max_meshes))); + } + let mesh_idx = self.scene.meshes.len(); + self.scene.meshes.push(mesh); + let node_idx = self.push_node(Node { name: part_name, mesh: Some(mesh_idx), ..Node::default() }, parent_node)?; + next_parent = Some(node_idx); + } + + if !schema.starts_with("AbcGeom_FaceSet") { + let owner = if schema.starts_with("AbcGeom_Xform") { name.as_str() } else { "" }; + self.object(group, next_parent, owner, depth + 1)?; + } + } + Ok(()) + } + + fn xform(&mut self, r: u64) -> Result<(Mat4, bool)> { + let props = self.o.compound(r)?; + let ops = match find(&props, ".ops") { + Some(p) => self.o.values(p)?, + None => Vec::new(), + }; + let vals = match find(&props, ".vals") { + Some(p) => self.o.values(p)?, + None => Vec::new(), + }; + let inherits = match find(&props, ".inherits") { + Some(p) => self.o.values(p)?.first().is_none_or(|v| *v != 0.0), + None => true, + }; + let mut m = IDENTITY; + let mut ch = 0usize; + for op in ops { + let kind = (op as u32) >> 4; + let n = match kind { + 0 | 1 => 3, + 2 => 4, + 3 => 16, + 4..=6 => 1, + _ => return Err(malformed(KIND, format!("unknown xform operation {kind}"))), + }; + let Some(v) = vals.get(ch..ch + n) else { return Err(malformed(KIND, "xform has fewer values than its operations need")) }; + ch += n; + let op_m = match kind { + 0 => [v[0], 0.0, 0.0, 0.0, 0.0, v[1], 0.0, 0.0, 0.0, 0.0, v[2], 0.0, 0.0, 0.0, 0.0, 1.0], + 1 => [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, v[0], v[1], v[2], 1.0], + 2 => axis_angle_matrix([v[0], v[1], v[2]], v[3].to_radians()), + 3 => { + let mut a = [0.0; 16]; + a.copy_from_slice(v); + a + } + 4 => rot_x(v[0].to_radians()), + 5 => rot_y(v[0].to_radians()), + _ => rot_z(v[0].to_radians()), + }; + m = mat_mul(&m, &op_m); + } + if !m.iter().all(|x| x.is_finite()) { + return Err(malformed(KIND, "xform has non-finite values")); + } + Ok((m, inherits)) + } + + fn face_sets(&mut self, kids: &[u64]) -> Result)>> { + let headers = self.o.object_headers(kids)?; + let mut out = Vec::new(); + for (i, (name, meta)) in headers.iter().enumerate() { + let schema = meta_get(meta, "schema").unwrap_or_default(); + if !schema.starts_with("AbcGeom_FaceSet") { + continue; + } + let Some(&g) = kids.get(i + 1).filter(|g| **g & DATA_BIT == 0) else { continue }; + let props = match self.o.group(g)?.first() { + Some(&p) if p & DATA_BIT == 0 => self.o.compound(p)?, + _ => continue, + }; + let Some(fs) = schema_compound(&props, schema, ".faceset") else { continue }; + let inner = self.o.compound(fs.group)?; + if let Some(faces) = find(&inner, ".faces") { + out.push((name.clone(), self.o.values(faces)?)); + } + } + Ok(out) + } + + fn param(&mut self, props: &[Prop], name: &str, counts: [usize; 3]) -> Result> { + let Some(p) = find(props, name) else { return Ok(None) }; + let (vals, indices) = match p.kind { + PropKind::Array => (self.o.values(p)?, None), + PropKind::Compound => { + let inner = self.o.compound(p.group)?; + let Some(v) = find(&inner, ".vals") else { return Ok(None) }; + let vals = self.o.values(v)?; + let indices = match find(&inner, ".indices") { + Some(ix) => Some(self.o.values(ix)?), + None => None, + }; + (vals, indices) + } + PropKind::Scalar => return Ok(None), + }; + let width = p.extent.max(1); + let items = indices.as_ref().map_or(vals.len() / width, Vec::len); + let [points, faces, corners] = counts; + let scope = match meta_get(&p.meta, "geoScope") { + Some("con") => Scope::Constant, + Some("uni") => Scope::Uniform, + Some("vtx" | "var") => Scope::Vertex, + Some("fvr") => Scope::FaceVarying, + _ if items == corners => Scope::FaceVarying, + _ if items == points => Scope::Vertex, + _ if items == faces => Scope::Uniform, + _ => Scope::Constant, + }; + Ok(Some(Param { vals, indices, scope })) + } + + fn mesh(&mut self, r: u64, name: &str, sets: &[(String, Vec)]) -> Result { + let properties = self.o.compound(r)?; + let get = |o: &mut Ogawa, prop_name: &str| -> Result> { + match find(&properties, prop_name) { + Some(p) => o.values(p), + None => Err(malformed(KIND, format!("PolyMesh has no {prop_name}"))), + } + }; + + let p = get(&mut self.o, "P")?; + let indices = get(&mut self.o, ".faceIndices")?; + let counts = get(&mut self.o, ".faceCounts")?; + let num_points = p.len() / 3; + if num_points > self.limits.max_vertices { + return Err(too_large(KIND, format!("more than {} vertices", self.limits.max_vertices))); + } + let positions: Vec<[f64; 3]> = p.as_chunks::<3>().0.to_vec(); + let n = [positions.len(), counts.len(), indices.len()]; + let normals_param = self.param(&properties, "N", n)?; + let uvs_param = self.param(&properties, "uv", n)?; + + let mut face_material = vec![None::; counts.len()]; + for (s, (_, faces)) in sets.iter().enumerate() { + for f in faces { + if let Some(m) = face_material.get_mut(*f as usize).filter(|m| m.is_none() && *f >= 0.0) { + *m = Some(s); + } + } + } + + let mut mesh = Mesh { name: name.to_string(), positions, ..Mesh::default() }; + let mut norm_ids: HashMap<[u64; 3], u32> = HashMap::new(); + let mut uv_ids: HashMap<[u32; 2], u32> = HashMap::new(); + let mut uv_pool: Vec<[f32; 2]> = Vec::new(); + let mut parts_by_mat: HashMap, Part> = HashMap::new(); + let mut part_order: Vec> = Vec::new(); + + let (mut k, mut face_corners, mut bad_uvs) = (0usize, Vec::new(), 0usize); + for (f, &count) in counts.iter().enumerate() { + let end = (count >= 0.0).then(|| k.checked_add(count as usize)).flatten().filter(|e| *e <= indices.len()); + let end = end.ok_or_else(|| malformed(KIND, format!("face {f} has {count} corners past the index list")))?; + let face_len = end - k; + if face_len > self.limits.max_face_corners { + return Err(too_large(KIND, format!("face {f} has more than {} corners", self.limits.max_face_corners))); + } + if face_len >= 3 { + self.triangles = self.triangles.saturating_add(face_len - 2); + if self.triangles > self.limits.max_triangles { + return Err(too_large(KIND, format!("more than {} triangles", self.limits.max_triangles))); + } + face_corners.clear(); + for (corner_index, &point_index) in indices.iter().enumerate().take(end).skip(k) { + if point_index < 0.0 || (point_index as usize) >= mesh.positions.len() { + return Err(malformed(KIND, format!("point index {point_index} out of range"))); + } + let pt = point_index as usize; + let norm_idx = match normals_param.as_ref().and_then(|l| l.get::<3>(corner_index, pt, f)) { + Some(norm) => intern_norm(&mut mesh.normals, &mut norm_ids, norm, self.limits.max_vertices)?, + None => crate::NONE, + }; + let uv_idx = match &uvs_param { + Some(l) => { + let uv = match l.get::<2>(corner_index, pt, f) { + Some([u, v]) => [u as f32, 1.0 - v as f32], + None => { + bad_uvs += 1; + [0.0, 0.0] + } + }; + intern_uv(&mut uv_pool, &mut uv_ids, uv, self.limits.max_vertices)? + } + None => crate::NONE, + }; + face_corners.push(Corner { position: pt as u32, normal: norm_idx, uv: uv_idx }); + } + // Alembic winds polygons clockwise; reverse to counter-clockwise. + face_corners.reverse(); + + let mat_idx = match face_material.get(f).copied().flatten().and_then(|s| sets.get(s)) { + Some((mat_name, _)) => Some(self.intern_material(mat_name)?), + None => None, + }; + let part = match parts_by_mat.entry(mat_idx) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => { + self.parts += 1; + if self.parts > self.limits.max_parts { + return Err(too_large(KIND, format!("more than {} parts", self.limits.max_parts))); + } + part_order.push(mat_idx); + e.insert(Part { material: mat_idx, ..Part::default() }) + } + }; + part.corners.extend_from_slice(&face_corners); + part.face_sizes.push(face_corners.len() as u32); + } + k = end; + } + + for mat_idx in part_order { + if let Some(mut part) = parts_by_mat.remove(&mat_idx) { + if part.face_sizes.iter().all(|&s| s == 3) { + part.face_sizes.clear(); + } + mesh.parts.push(part); + } + } + if !uv_pool.is_empty() { + mesh.uv_sets.push(uv_pool); + } + if bad_uvs > 0 { + self.warn(format!("{bad_uvs} polygon corners have no UV in the Alembic uv parameter (set to 0, 0)")); + } + Ok(mesh) + } +} + +fn intern_norm(pool: &mut Vec<[f64; 3]>, map: &mut HashMap<[u64; 3], u32>, val: [f64; 3], limit: usize) -> Result { + let key = val.map(f64::to_bits); + if let Some(&id) = map.get(&key) { + return Ok(id); + } + if pool.len() >= limit { + return Err(too_large(KIND, format!("more than {limit} normals"))); + } + let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many normals"))?; + pool.push(val); + map.insert(key, id); + Ok(id) +} + +fn intern_uv(pool: &mut Vec<[f32; 2]>, map: &mut HashMap<[u32; 2], u32>, val: [f32; 2], limit: usize) -> Result { + let key = val.map(f32::to_bits); + if let Some(&id) = map.get(&key) { + return Ok(id); + } + if pool.len() >= limit { + return Err(too_large(KIND, format!("more than {limit} UVs"))); + } + let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many UVs"))?; + pool.push(val); + map.insert(key, id); + Ok(id) +} + +fn axis_angle_matrix(axis: [f64; 3], angle: f64) -> Mat4 { + let len = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt(); + if !len.is_finite() || len == 0.0 { + return IDENTITY; + } + let [x, y, z] = axis.map(|v| v / len); + let (s, c) = angle.sin_cos(); + let t = 1.0 - c; + [ + t * x * x + c, + t * x * y + s * z, + t * x * z - s * y, + 0.0, + t * x * y - s * z, + t * y * y + c, + t * y * z + s * x, + 0.0, + t * x * z + s * y, + t * y * z - s * x, + t * z * z + c, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ] +} + +fn rot_x(a: f64) -> Mat4 { + let (s, c) = a.sin_cos(); + [1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0] +} + +fn rot_y(a: f64) -> Mat4 { + let (s, c) = a.sin_cos(); + [c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0] +} + +fn rot_z(a: f64) -> Mat4 { + let (s, c) = a.sin_cos(); + [c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0] +} diff --git a/crates/mesh/src/dae.rs b/crates/mesh/src/dae.rs new file mode 100644 index 0000000000..b5a06c6123 --- /dev/null +++ b/crates/mesh/src/dae.rs @@ -0,0 +1,583 @@ +//! COLLADA (`.dae`), read: `triangles`, `polylist` and `polygons` with `VERTEX` / `NORMAL` / +//! `TEXCOORD` inputs, materials bound through `instance_geometry` and `instance_controller`, the +//! visual scene's node hierarchy and transforms (`matrix`, `translate`, `rotate`, `scale`, +//! `lookat`), `instance_node`, `instance_camera`, and the asset's unit (`meter`) and `up_axis`. +//! +//! [`read_document`] returns the [`Scene`] in the file's own axes and units alongside +//! [`Document::meter`] and [`Document::up_axis`] (and [`Document::global_transform`] to convert to +//! Y-up metres). [`read`] returns the [`Scene`] directly. +//! +//! UVs are flipped to top-left origin (`1.0 - v`), matching the rest of this crate. + +use std::collections::HashMap; +use std::rc::Rc; + +use craft_xml::{El, Options, UnknownEntity}; + +use crate::{Camera, Corner, IDENTITY, Limits, Mat4, Material, Mesh, Node, Part, Projection, Result, Scene, malformed, mat_mul, too_large}; + +const KIND: &str = "COLLADA"; +const MAX_XML_DEPTH: usize = 256; +const MAX_XML_NODES: usize = 2_000_000; + +/// Up axis of a COLLADA ``. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum UpAxis { + #[default] + YUp, + ZUp, + XUp, +} + +impl UpAxis { + /// Rotation matrix that turns this axis into +Y up. + pub fn to_y_up(self) -> Mat4 { + match self { + UpAxis::YUp => IDENTITY, + UpAxis::ZUp => [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], + UpAxis::XUp => [0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0], + } + } +} + +/// A COLLADA document: the scene in the file's own axes and units, plus its `` scale and +/// up axis. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Document { + pub scene: Scene, + /// Metres per file unit (default `1.0`). + pub meter: f64, + pub up_axis: UpAxis, +} + +impl Document { + /// Transform from the file's axes and units to Y-up metres. + pub fn global_transform(&self) -> Mat4 { + let scale = [self.meter, 0.0, 0.0, 0.0, 0.0, self.meter, 0.0, 0.0, 0.0, 0.0, self.meter, 0.0, 0.0, 0.0, 0.0, 1.0]; + mat_mul(&self.up_axis.to_y_up(), &scale) + } +} + +/// Read a COLLADA file into a [`Scene`] (in the file's own axes and units). +pub fn read(bytes: &[u8], limits: &Limits) -> Result { + Ok(read_document(bytes, limits)?.scene) +} + +/// Read a COLLADA file into a [`Document`]. +pub fn read_document(bytes: &[u8], limits: &Limits) -> Result { + let mut opts = Options::local(); + opts.unknown_entity = UnknownEntity::Literal; + opts.strict_end_tags = true; + opts.limits.max_input = limits.max_data_bytes; + opts.limits.max_depth = MAX_XML_DEPTH; + opts.limits.max_nodes = MAX_XML_NODES; + let root = opts.parse(bytes).map_err(|e| if e.is_limit() { too_large(KIND, e) } else { malformed(KIND, e) })?; + if root.name != "COLLADA" { + return Err(malformed(KIND, "not a COLLADA document")); + } + + let mut ids: HashMap<&str, &El> = HashMap::new(); + let mut stack = vec![&root]; + while let Some(el) = stack.pop() { + if let Some(id) = el.attr("id") { + ids.entry(id).or_insert(el); + } + stack.extend(el.elements()); + } + + let asset = root.child("asset"); + let meter = asset + .and_then(|a| a.child("unit")) + .and_then(|u| u.attr("meter")) + .and_then(|m| m.trim().parse::().ok()) + .filter(|m| m.is_finite() && *m > 0.0) + .unwrap_or(1.0); + let up_axis = match asset.and_then(|a| a.child("up_axis")).map(|u| u.text().trim().to_owned()).as_deref() { + Some("Z_UP") => UpAxis::ZUp, + Some("X_UP") => UpAxis::XUp, + _ => UpAxis::YUp, + }; + + let mut reader = + Reader { ids, sources: HashMap::new(), limits, scene: Scene::default(), materials: HashMap::new(), mesh_cache: HashMap::new(), triangles: 0 }; + + let visual_scene = root + .child("scene") + .and_then(|s| s.child("instance_visual_scene")) + .and_then(|i| reader.get(i.attr("url"))) + .or_else(|| root.child("library_visual_scenes").and_then(|l| l.child("visual_scene"))); + + if let Some(vs) = visual_scene { + for n in vs.children("node") { + let idx = reader.read_node(n, 0)?; + reader.scene.roots.push(idx); + } + } else { + for geom in root.children("library_geometries").flat_map(|l| l.children("geometry")) { + let mesh_idx = reader.get_or_build_mesh(geom, &[])?; + let name = reader.scene.meshes[mesh_idx].name.clone(); + let node_idx = reader.push_node(Node { name, mesh: Some(mesh_idx), ..Node::default() })?; + reader.scene.roots.push(node_idx); + } + } + + Ok(Document { scene: reader.scene, meter, up_axis }) +} + +struct Source { + data: Vec, + stride: usize, + offset: usize, +} + +impl Source { + fn get(&self, i: u32) -> Option<[f64; W]> { + let start = (i as usize).checked_mul(self.stride)?.checked_add(self.offset)?; + self.data.get(start..start.checked_add(W)?)?.try_into().ok() + } +} + +struct Input { + offset: usize, + source: Rc, +} + +struct Reader<'a> { + ids: HashMap<&'a str, &'a El>, + sources: HashMap<&'a str, Rc>, + limits: &'a Limits, + scene: Scene, + materials: HashMap, + /// Keyed by `(geometry element pointer, sorted (symbol, material_name) bindings)`. + mesh_cache: HashMap<(usize, Vec<(String, String)>), usize>, + triangles: usize, +} + +impl<'a> Reader<'a> { + fn get(&self, url: Option<&str>) -> Option<&'a El> { + url.and_then(|u| u.strip_prefix('#')).and_then(|id| self.ids.get(id)).copied() + } + + fn warn(&mut self, msg: String) { + if !self.scene.warnings.contains(&msg) { + self.scene.warnings.push(msg); + } + } + + fn push_node(&mut self, node: Node) -> Result { + if self.scene.nodes.len() >= self.limits.max_nodes { + return Err(too_large(KIND, format!("more than {} nodes", self.limits.max_nodes))); + } + let idx = self.scene.nodes.len(); + self.scene.nodes.push(node); + Ok(idx) + } + + fn intern_material(&mut self, name: &str) -> Result { + if let Some(&idx) = self.materials.get(name) { + return Ok(idx); + } + if self.scene.materials.len() >= self.limits.max_materials { + return Err(too_large(KIND, format!("more than {} materials", self.limits.max_materials))); + } + let idx = self.scene.materials.len(); + self.scene.materials.push(Material { name: name.to_owned(), ..Material::default() }); + self.materials.insert(name.to_owned(), idx); + Ok(idx) + } + + fn source(&mut self, url: Option<&str>) -> Result> { + let el = self.get(url).ok_or_else(|| malformed(KIND, format!("missing source {}", url.unwrap_or("(none)"))))?; + let id = el.attr("id").unwrap_or_default(); + if !id.is_empty() + && let Some(s) = self.sources.get(id) + { + return Ok(s.clone()); + } + let acc = el.child("technique_common").and_then(|t| t.child("accessor")); + let array = acc.and_then(|a| self.get(a.attr("source"))).or_else(|| el.child("float_array")); + let array = array.ok_or_else(|| malformed(KIND, format!("source \"{id}\" has no float_array")))?; + let num = |k: &str, default: usize| acc.and_then(|a| a.attr(k)).and_then(|v| v.parse().ok()).unwrap_or(default); + let data = parse_floats(array)?; + if data.len() / 3 > self.limits.max_vertices { + return Err(too_large(KIND, format!("source has more than {} vertices", self.limits.max_vertices))); + } + let s = Rc::new(Source { data, stride: num("stride", 1).max(1), offset: num("offset", 0) }); + if !id.is_empty() { + self.sources.insert(id, s.clone()); + } + Ok(s) + } + + fn read_node(&mut self, el: &'a El, depth: usize) -> Result { + if depth > self.limits.max_depth { + return Err(too_large(KIND, format!("node hierarchy is deeper than {}", self.limits.max_depth))); + } + let name = el.attr("name").or_else(|| el.attr("id")).unwrap_or_default().to_string(); + let transform = node_transform(el)?; + let mut node = Node { name: name.clone(), transform, ..Node::default() }; + + for inst in el.elements() { + if inst.name == "instance_camera" { + if node.camera.is_none() + && let Some(cam_el) = self.get(inst.attr("url")) + && let Some(cam) = parse_camera(cam_el, &name) + && self.scene.cameras.len() < self.limits.max_extras + { + let cam_idx = self.scene.cameras.len(); + self.scene.cameras.push(cam); + node.camera = Some(cam_idx); + } + continue; + } + let (geom, bind_shape) = match inst.name.as_str() { + "instance_geometry" => (self.get(inst.attr("url")), IDENTITY), + "instance_controller" => { + let skin = self.get(inst.attr("url")).and_then(|c| c.child("skin")); + let bind = skin.and_then(|s| s.child("bind_shape_matrix")).map(parse_floats).transpose()?.and_then(|v| row_major_matrix(&v)); + (skin.and_then(|s| self.get(s.attr("source"))), bind.unwrap_or(IDENTITY)) + } + _ => continue, + }; + let Some(geom) = geom else { + self.warn("an instanced geometry is missing from the file".into()); + continue; + }; + let bind = self.bindings(inst); + let mesh_idx = self.get_or_build_mesh(geom, &bind)?; + if node.mesh.is_none() && bind_shape == IDENTITY { + node.mesh = Some(mesh_idx); + } else { + let child = self.push_node(Node { name: name.clone(), transform: bind_shape, mesh: Some(mesh_idx), ..Node::default() })?; + node.children.push(child); + } + } + + for child_el in el.children("node") { + let child = self.read_node(child_el, depth + 1)?; + node.children.push(child); + } + for inst_node in el.children("instance_node") { + if let Some(target) = self.get(inst_node.attr("url")) { + let child = self.read_node(target, depth + 1)?; + node.children.push(child); + } + } + + self.push_node(node) + } + + fn bindings(&self, inst: &El) -> Vec<(String, String)> { + let mut out: Vec<(String, String)> = inst + .child("bind_material") + .and_then(|b| b.child("technique_common")) + .into_iter() + .flat_map(|t| t.children("instance_material")) + .filter_map(|im| { + let symbol = im.attr("symbol")?; + let mat = self.get(im.attr("target")); + let name = mat.and_then(|m| m.attr("name").or_else(|| m.attr("id"))).unwrap_or(symbol); + Some((symbol.to_string(), name.to_string())) + }) + .collect(); + out.sort(); + out + } + + fn get_or_build_mesh(&mut self, geom: &'a El, bind: &[(String, String)]) -> Result { + let key = ((geom as *const El) as usize, bind.to_vec()); + if let Some(&idx) = self.mesh_cache.get(&key) { + return Ok(idx); + } + if self.scene.meshes.len() >= self.limits.max_meshes { + return Err(too_large(KIND, format!("more than {} meshes", self.limits.max_meshes))); + } + let mesh = self.build_mesh(geom, bind)?; + let idx = self.scene.meshes.len(); + self.scene.meshes.push(mesh); + self.mesh_cache.insert(key, idx); + Ok(idx) + } + + fn build_mesh(&mut self, geom: &'a El, bind: &[(String, String)]) -> Result { + let name = geom.attr("name").or_else(|| geom.attr("id")).unwrap_or_default().to_string(); + let mut mesh = Mesh { name, ..Mesh::default() }; + let Some(mesh_el) = geom.child("mesh") else { return Ok(mesh) }; + + let mut pools = MeshPools::default(); + let mut part_count: usize = self.scene.meshes.iter().map(|m| m.parts.len()).sum(); + + for prim in mesh_el.elements() { + if !matches!(prim.name.as_str(), "triangles" | "polylist" | "polygons") { + if matches!(prim.name.as_str(), "lines" | "linestrips" | "trifans" | "tristrips") { + self.warn(format!("skipped COLLADA <{}> (only triangles and polygons are supported)", prim.name)); + } + continue; + } + let Some(inputs) = self.read_primitive_inputs(prim)? else { + self.warn("skipped COLLADA primitives without positions".into()); + continue; + }; + part_count += 1; + if part_count > self.limits.max_parts { + return Err(too_large(KIND, format!("more than {} parts", self.limits.max_parts))); + } + let material = match prim.attr("material") { + Some(sym) => { + let mat_name = bind.binary_search_by(|(k, _)| k.as_str().cmp(sym)).ok().map_or(sym, |i| bind[i].1.as_str()); + Some(self.intern_material(mat_name)?) + } + None => None, + }; + let lists = read_primitive_lists(prim, inputs.stride)?; + let part = self.build_part(material, &inputs, &lists, &mut mesh, &mut pools)?; + if !part.corners.is_empty() { + mesh.parts.push(part); + } + } + if !pools.uvs.is_empty() { + mesh.uv_sets.push(pools.uvs); + } + Ok(mesh) + } + + fn read_primitive_inputs(&mut self, prim: &'a El) -> Result> { + let (mut position, mut normal, mut uv): (Option, Option, Option<(u32, Input)>) = (None, None, None); + let mut stride = 1usize; + for input in prim.children("input") { + let offset: usize = input.attr("offset").and_then(|o| o.parse().ok()).unwrap_or(0); + stride = stride.max(offset.saturating_add(1)); + let nested: Vec<&El> = match input.attr("semantic") { + Some("VERTEX") => self.get(input.attr("source")).map(|v| v.children("input").collect()).unwrap_or_default(), + _ => vec![input], + }; + for i in nested { + let set: u32 = input.attr("set").or_else(|| i.attr("set")).and_then(|s| s.parse().ok()).unwrap_or(0); + match i.attr("semantic") { + Some("POSITION") => position = Some(Input { offset, source: self.source(i.attr("source"))? }), + Some("NORMAL") if normal.is_none() => normal = Some(Input { offset, source: self.source(i.attr("source"))? }), + Some("TEXCOORD") if uv.as_ref().is_none_or(|(s, _)| set < *s) => { + uv = Some((set, Input { offset, source: self.source(i.attr("source"))? })) + } + _ => {} + } + } + } + Ok(position.map(|position| PrimInputs { stride, position, normal, uv: uv.map(|(_, i)| i) })) + } + + fn build_part( + &mut self, + material: Option, + inputs: &PrimInputs, + lists: &[(Vec, Vec)], + mesh: &mut Mesh, + pools: &mut MeshPools, + ) -> Result { + let mut part = Part { material, ..Part::default() }; + let mut all_triangles = true; + for (p, sizes) in lists { + let mut next = 0usize; + for &size in sizes { + if size > self.limits.max_face_corners { + return Err(too_large(KIND, format!("face has more than {} corners", self.limits.max_face_corners))); + } + if size >= 3 { + self.triangles = self.triangles.saturating_add(size - 2); + if self.triangles > self.limits.max_triangles { + return Err(too_large(KIND, format!("more than {} triangles", self.limits.max_triangles))); + } + if size != 3 { + all_triangles = false; + } + for c in next..next.saturating_add(size) { + let idx = + |input: &Input| c.checked_mul(inputs.stride).and_then(|b| b.checked_add(input.offset)).and_then(|k| p.get(k)).copied(); + let pos = idx(&inputs.position) + .and_then(|i| inputs.position.source.get::<3>(i)) + .ok_or_else(|| malformed(KIND, "polygon index out of range"))?; + let pos_idx = intern_f64_3(&mut mesh.positions, &mut pools.pos_ids, pos, self.limits.max_vertices, "positions")?; + let norm_idx = match inputs.normal.as_ref().and_then(|n| idx(n).and_then(|i| n.source.get::<3>(i))) { + Some(n) => intern_f64_3(&mut mesh.normals, &mut pools.norm_ids, n, self.limits.max_vertices, "normals")?, + None => crate::NONE, + }; + let uv_idx = match inputs.uv.as_ref().and_then(|t| idx(t).and_then(|i| t.source.get::<2>(i))) { + Some([u, v]) => intern_uv(&mut pools.uvs, &mut pools.uv_ids, [u as f32, 1.0 - v as f32], self.limits.max_vertices)?, + None => crate::NONE, + }; + part.corners.push(Corner { position: pos_idx, normal: norm_idx, uv: uv_idx }); + } + part.face_sizes.push(size as u32); + } + next = next.saturating_add(size); + } + } + if all_triangles { + part.face_sizes.clear(); + } + Ok(part) + } +} + +#[derive(Default)] +struct MeshPools { + pos_ids: HashMap<[u64; 3], u32>, + norm_ids: HashMap<[u64; 3], u32>, + uv_ids: HashMap<[u32; 2], u32>, + uvs: Vec<[f32; 2]>, +} + +struct PrimInputs { + stride: usize, + position: Input, + normal: Option, + uv: Option, +} + +fn read_primitive_lists(prim: &El, stride: usize) -> Result, Vec)>> { + match prim.name.as_str() { + "polygons" => prim + .children("p") + .map(|p| { + let p = parse_indices(p)?; + let n = p.len() / stride; + Ok((p, vec![n])) + }) + .collect(), + _ => { + let p = prim.child("p").map(parse_indices).transpose()?.unwrap_or_default(); + let sizes = match prim.child("vcount") { + Some(v) if prim.name == "polylist" => parse_indices(v)?.into_iter().map(|c| c as usize).collect(), + _ => vec![3; p.len() / stride / 3], + }; + Ok(vec![(p, sizes)]) + } + } +} + +fn intern_f64_3(pool: &mut Vec<[f64; 3]>, map: &mut HashMap<[u64; 3], u32>, val: [f64; 3], limit: usize, what: &str) -> Result { + let key = val.map(f64::to_bits); + if let Some(&id) = map.get(&key) { + return Ok(id); + } + if pool.len() >= limit { + return Err(too_large(KIND, format!("more than {limit} {what}"))); + } + let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, format!("too many {what}")))?; + pool.push(val); + map.insert(key, id); + Ok(id) +} + +fn intern_uv(pool: &mut Vec<[f32; 2]>, map: &mut HashMap<[u32; 2], u32>, val: [f32; 2], limit: usize) -> Result { + let key = val.map(f32::to_bits); + if let Some(&id) = map.get(&key) { + return Ok(id); + } + if pool.len() >= limit { + return Err(too_large(KIND, format!("more than {limit} UVs"))); + } + let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many UVs"))?; + pool.push(val); + map.insert(key, id); + Ok(id) +} + +fn parse_floats(el: &El) -> Result> { + el.text().split_whitespace().map(|w| w.parse::().map_err(|_| malformed(KIND, format!("bad number \"{w}\" in <{}>", el.name)))).collect() +} + +fn parse_indices(el: &El) -> Result> { + el.text().split_whitespace().map(|w| w.parse::().map_err(|_| malformed(KIND, format!("bad index \"{w}\" in <{}>", el.name)))).collect() +} + +fn parse_camera(cam: &El, node_name: &str) -> Option { + let tc = cam.child("optics")?.child("technique_common")?; + let num = |e: &El, k: &str| e.child(k).and_then(|v| v.text().trim().parse::().ok()).filter(|v| v.is_finite() && *v > 0.0); + let name = if node_name.is_empty() { cam.attr("name").or_else(|| cam.attr("id")).unwrap_or_default().to_string() } else { node_name.to_string() }; + if let Some(p) = tc.child("perspective") { + let x_to_y = |x: f64| Some(2.0 * ((x * 0.5).to_radians().tan() / num(p, "aspect_ratio")?).atan().to_degrees()); + let fov_deg = num(p, "yfov").or_else(|| num(p, "xfov").and_then(x_to_y)).or_else(|| num(p, "xfov")).unwrap_or(40.0); + let aspect = num(p, "aspect_ratio"); + let znear = num(p, "znear").unwrap_or(0.1); + let zfar = num(p, "zfar"); + return Some(Camera { name, projection: Projection::Perspective { yfov: fov_deg.to_radians(), aspect, znear, zfar } }); + } + let o = tc.child("orthographic")?; + let aspect = num(o, "aspect_ratio"); + let ymag = num(o, "ymag").or_else(|| Some(num(o, "xmag")? / aspect?)).or_else(|| num(o, "xmag")).unwrap_or(1.0); + let xmag = num(o, "xmag").unwrap_or_else(|| ymag * aspect.unwrap_or(1.0)); + let znear = num(o, "znear").unwrap_or(0.1); + let zfar = num(o, "zfar").unwrap_or(1000.0); + Some(Camera { name, projection: Projection::Orthographic { xmag, ymag, znear, zfar } }) +} + +/// Row-major 4×4 floats to a column-major matrix. +fn row_major_matrix(v: &[f64]) -> Option { + let a: [f64; 16] = v.get(..16)?.try_into().ok()?; + Some([a[0], a[4], a[8], a[12], a[1], a[5], a[9], a[13], a[2], a[6], a[10], a[14], a[3], a[7], a[11], a[15]]) +} + +fn node_transform(node: &El) -> Result { + let mut m = IDENTITY; + for t in node.elements() { + let v = match t.name.as_str() { + "matrix" | "translate" | "rotate" | "scale" | "lookat" => parse_floats(t)?, + _ => continue, + }; + let step = match (t.name.as_str(), v.as_slice()) { + ("matrix", _) => row_major_matrix(&v), + ("translate", [x, y, z, ..]) => Some([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, *x, *y, *z, 1.0]), + ("scale", [x, y, z, ..]) => Some([*x, 0.0, 0.0, 0.0, 0.0, *y, 0.0, 0.0, 0.0, 0.0, *z, 0.0, 0.0, 0.0, 0.0, 1.0]), + ("rotate", [x, y, z, deg, ..]) => axis_angle_matrix([*x, *y, *z], deg.to_radians()), + ("lookat", [ex, ey, ez, ix, iy, iz, ux, uy, uz, ..]) => lookat_matrix([*ex, *ey, *ez], [*ix, *iy, *iz], [*ux, *uy, *uz]), + _ => None, + }; + if let Some(s) = step { + m = mat_mul(&m, &s); + } + } + Ok(m) +} + +fn normalize(v: [f64; 3]) -> Option<[f64; 3]> { + let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt(); + (len.is_finite() && len > 0.0).then(|| v.map(|x| x / len)) +} + +fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn axis_angle_matrix(axis: [f64; 3], angle: f64) -> Option { + let [x, y, z] = normalize(axis)?; + let (s, c) = angle.sin_cos(); + let t = 1.0 - c; + let m = [ + t * x * x + c, + t * x * y + s * z, + t * x * z - s * y, + 0.0, + t * x * y - s * z, + t * y * y + c, + t * y * z + s * x, + 0.0, + t * x * z + s * y, + t * y * z - s * x, + t * z * z + c, + 0.0, + 0.0, + 0.0, + 0.0, + 1.0, + ]; + m.iter().all(|v| v.is_finite()).then_some(m) +} + +fn lookat_matrix(eye: [f64; 3], center: [f64; 3], up: [f64; 3]) -> Option { + let f = normalize([center[0] - eye[0], center[1] - eye[1], center[2] - eye[2]])?; + let s = normalize(cross(f, up))?; + let u = cross(s, f); + let m = [s[0], s[1], s[2], 0.0, u[0], u[1], u[2], 0.0, -f[0], -f[1], -f[2], 0.0, eye[0], eye[1], eye[2], 1.0]; + m.iter().all(|v| v.is_finite()).then_some(m) +} diff --git a/crates/mesh/src/lib.rs b/crates/mesh/src/lib.rs index f5368424d9..c1d2e1d4bd 100644 --- a/crates/mesh/src/lib.rs +++ b/crates/mesh/src/lib.rs @@ -31,10 +31,23 @@ #![forbid(unsafe_code)] // The helpers the formats share are not all used by every subset of them. #![cfg_attr( - not(all(feature = "stl", feature = "obj", feature = "ply", feature = "gltf", feature = "fbx", feature = "threemf")), + not(all( + feature = "stl", + feature = "obj", + feature = "ply", + feature = "gltf", + feature = "fbx", + feature = "threemf", + feature = "dae", + feature = "abc" + )), allow(dead_code, unused_imports) )] +#[cfg(feature = "abc")] +pub mod abc; +#[cfg(feature = "dae")] +pub mod dae; #[cfg(feature = "fbx")] pub mod fbx; #[cfg(feature = "gltf")] diff --git a/crates/mesh/src/tests.rs b/crates/mesh/src/tests.rs index 423732de80..0be68b157b 100644 --- a/crates/mesh/src/tests.rs +++ b/crates/mesh/src/tests.rs @@ -2,6 +2,10 @@ use super::*; +#[cfg(feature = "abc")] +mod abc; +#[cfg(feature = "dae")] +mod dae; #[cfg(feature = "fbx")] mod fbx; #[cfg(feature = "gltf")] diff --git a/crates/mesh/src/tests/abc.rs b/crates/mesh/src/tests/abc.rs new file mode 100644 index 0000000000..864ff82612 --- /dev/null +++ b/crates/mesh/src/tests/abc.rs @@ -0,0 +1,198 @@ +use super::*; +use crate::abc::read; + +const DATA_BIT: u64 = 1 << 63; +const OGAWA_MAGIC: &[u8] = b"Ogawa"; +const KEY_BYTES: usize = 16; +const OBJECT_HASH_BYTES: usize = 32; +const F32: u32 = 10; +const I32: u32 = 6; +const U32: u32 = 5; +const U8: u32 = 1; +const F64: u32 = 11; + +struct Writer { + b: Vec, +} + +impl Writer { + fn new() -> Writer { + Writer { b: vec![0; 16] } + } + + fn data(&mut self, bytes: &[u8]) -> u64 { + let at = self.b.len() as u64; + self.b.extend_from_slice(&(bytes.len() as u64).to_le_bytes()); + self.b.extend_from_slice(bytes); + at | DATA_BIT + } + + fn group(&mut self, children: &[u64]) -> u64 { + let at = self.b.len() as u64; + self.b.extend_from_slice(&(children.len() as u64).to_le_bytes()); + for c in children { + self.b.extend_from_slice(&c.to_le_bytes()); + } + at + } + + fn finish(mut self, root: u64) -> Vec { + self.b[..5].copy_from_slice(OGAWA_MAGIC); + self.b[5] = 0xff; + self.b[6..8].copy_from_slice(&[0, 1]); + self.b[8..16].copy_from_slice(&root.to_le_bytes()); + self.b + } +} + +struct P { + name: &'static str, + meta: String, + info: u32, + group: u64, +} + +struct Abc { + w: Writer, +} + +impl Abc { + fn sample(&mut self, raw: &[u8]) -> u64 { + let mut v = vec![7u8; KEY_BYTES]; + v.extend_from_slice(raw); + self.w.data(&v) + } + + fn array(&mut self, name: &'static str, meta: &str, pod: u32, extent: u32, raw: &[u8]) -> P { + let (d, dims) = (self.sample(raw), self.w.data(&[])); + let group = self.w.group(&[d, dims]); + P { name, meta: meta.into(), info: 2 | (2 << 2) | (pod << 4) | (extent << 12), group } + } + + fn scalar(&mut self, name: &'static str, pod: u32, extent: u32, raw: &[u8]) -> P { + let d = self.sample(raw); + let group = self.w.group(&[d]); + P { name, meta: String::new(), info: 1 | (2 << 2) | (pod << 4) | (extent << 12), group } + } + + fn compound(&mut self, name: &'static str, meta: &str, props: Vec

) -> P { + let mut header = Vec::new(); + for p in &props { + let info = p.info | (0xff << 20); + header.extend_from_slice(&info.to_le_bytes()); + if info & 3 != 0 { + header.extend_from_slice(&1u32.to_le_bytes()); + } + header.extend_from_slice(&(p.name.len() as u32).to_le_bytes()); + header.extend_from_slice(p.name.as_bytes()); + header.extend_from_slice(&(p.meta.len() as u32).to_le_bytes()); + header.extend_from_slice(p.meta.as_bytes()); + } + let mut children: Vec = props.iter().map(|p| p.group).collect(); + children.push(self.w.data(&header)); + let group = self.w.group(&children); + P { name, meta: meta.into(), info: 2 << 2, group } + } + + fn object(&mut self, props: Vec

, children: &[(&str, &str, u64)]) -> u64 { + let props = self.compound("", "", props).group; + let mut header = Vec::new(); + for (name, meta, _) in children { + header.extend_from_slice(&(name.len() as u32).to_le_bytes()); + header.extend_from_slice(name.as_bytes()); + if meta.is_empty() { + header.push(1); + } else { + header.push(0xff); + header.extend_from_slice(&(meta.len() as u32).to_le_bytes()); + header.extend_from_slice(meta.as_bytes()); + } + } + header.extend_from_slice(&[0; OBJECT_HASH_BYTES]); + let mut kids = vec![props]; + kids.extend(children.iter().map(|c| c.2)); + kids.push(self.w.data(&header)); + self.w.group(&kids) + } + + fn archive(mut self, top: u64, indexed_meta: &[&str]) -> Vec { + let mut im = Vec::new(); + for m in indexed_meta { + im.push(m.len() as u8); + im.extend_from_slice(m.as_bytes()); + } + let kids = [ + self.w.data(&0i32.to_le_bytes()), + self.w.data(&10709i32.to_le_bytes()), + top, + self.w.data(b"_ai_Application=test"), + self.w.data(&[]), + self.w.data(&im), + ]; + let root = self.w.group(&kids); + self.w.finish(root) + } +} + +fn f32s(v: &[f32]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +fn i32s(v: &[i32]) -> Vec { + v.iter().flat_map(|x| x.to_le_bytes()).collect() +} + +fn sample_file() -> Vec { + let mut a = Abc { w: Writer::new() }; + let p = f32s(&[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 2.0, 1.0, 0.0]); + let indices = i32s(&[0, 3, 4, 1, 1, 4, 5, 2]); + let counts = i32s(&[4, 4]); + let pp = a.array("P", "interpretation=point", F32, 3, &p); + let fi = a.array(".faceIndices", "", I32, 1, &indices); + let fc = a.array(".faceCounts", "", I32, 1, &counts); + let vals = a.array(".vals", "", F32, 2, &f32s(&[0.0, 0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 0.5, 1.0, 1.0, 1.0])); + let uvi = a.array(".indices", "", U32, 1, &i32s(&[0, 3, 4, 1, 1, 4, 5, 2])); + let uv = a.compound("uv", "geoScope=fvr;podName=float32_t;podExtent=2", vec![vals, uvi]); + let n = a.array("N", "geoScope=vtx", F32, 3, &f32s(&[0.0, 0.0, 1.0].repeat(6))); + let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc, uv, n]); + let left_faces = a.array(".faces", "", I32, 1, &i32s(&[0])); + let left_fs = a.compound(".faceset", "schema=AbcGeom_FaceSet_v1", vec![left_faces]); + let left = a.object(vec![left_fs], &[]); + let right_faces = a.array(".faces", "", I32, 1, &i32s(&[1])); + let right_fs = a.compound(".faceset", "schema=AbcGeom_FaceSet_v1", vec![right_faces]); + let right = a.object(vec![right_fs], &[]); + let fs_meta = "schema=AbcGeom_FaceSet_v1;schemaObjTitle=AbcGeom_FaceSet_v1:.faceset"; + let mesh = a.object(vec![geom], &[("left", fs_meta, left), ("right", fs_meta, right)]); + let ops = a.scalar(".ops", U8, 2, &[0x10, 0x00]); + let xv: Vec = [1.0f64, 2.0, 3.0, 2.0, 2.0, 2.0].iter().flat_map(|x| x.to_le_bytes()).collect(); + let vals = a.scalar(".vals", F64, 6, &xv); + let xform = a.compound(".xform", "schema=AbcGeom_Xform_v3", vec![ops, vals]); + let xf = a.object(vec![xform], &[("stripShape", "schema=AbcGeom_PolyMesh_v1;schemaObjTitle=AbcGeom_PolyMesh_v1:.geom", mesh)]); + let top = a.object(vec![], &[("strip", "schema=AbcGeom_Xform_v3", xf)]); + a.archive(top, &["schema=AbcGeom_PolyMesh_v1"]) +} + +#[test] +fn reads_polymesh_xform_face_sets_and_uvs() { + let scene = read(&sample_file(), &Limits::default()).unwrap(); + scene.validate().unwrap(); + assert_eq!(scene.materials.iter().map(|m| m.name.as_str()).collect::>(), ["left", "right"]); + assert_eq!(scene.meshes.len(), 1); + assert_eq!(scene.meshes[0].name, "strip"); + assert_eq!(scene.meshes[0].triangle_count(), 4); + let inst = scene.instances(&Limits::default()).unwrap(); + assert_eq!(inst.len(), 1); + let p0 = transform_point(&inst[0].1, scene.meshes[0].positions[0]); + assert_eq!(p0, [1.0, 2.0, 3.0]); +} + +#[test] +fn hdf5_returns_unsupported() { + let err = read(b"\x89HDF\r\n\x1a\n rest", &Limits::default()).unwrap_err(); + assert!(matches!(err, Error::Unsupported(_))); +} + +#[test] +fn hammer_never_panics() { + hammer(&sample_file(), &|b| read(b, &Limits::default())); +} diff --git a/crates/mesh/src/tests/dae.rs b/crates/mesh/src/tests/dae.rs new file mode 100644 index 0000000000..e8883e217a --- /dev/null +++ b/crates/mesh/src/tests/dae.rs @@ -0,0 +1,130 @@ +use super::*; +use crate::dae::{UpAxis, read, read_document}; + +const DAE: &str = r##" + + Z_UP + + + + + + + + + 0 0 0 2 0 0 2 2 0 0 2 0 + + + + 0 0 1 + + + + 0 0 1 0 1 1 0 1 + + + + + + + + 4 +

0 0 0 1 0 1 2 0 2 3 0 3

+ +
+ + + + + 4 0 0 6 0 0 4 2 0 8 0 0 10 0 0 10 2 0 8 2 0 + + + + 0 0 1 0 0 1 0 0 1 0 1 1 0 1 + + + + + + +

0 1 2

+

3 4 5 6

+

0 1

+
+
+ + + 30 + + + + + 0 0 2 + 0 0 1 90 + + 2 2 2 + + + + + + + 0 -10 0 0 0 0 0 0 1 + + + + + + + + + + + +"##; + +#[test] +fn reads_polylist_transforms_units_and_cameras() { + let doc = read_document(DAE.as_bytes(), &Limits::default()).unwrap(); + doc.scene.validate().unwrap(); + assert_eq!(doc.meter, 0.5); + assert_eq!(doc.up_axis, UpAxis::ZUp); + assert_eq!(doc.scene.materials.iter().map(|m| m.name.as_str()).collect::>(), ["Red", "Blue"]); + assert!(doc.scene.warnings.iter().any(|w| w.contains("lines"))); + assert_eq!(doc.scene.cameras.len(), 1); + assert_eq!(doc.scene.cameras[0].name, "Overview"); + + let global = doc.global_transform(); + let inst = doc.scene.instances(&Limits::default()).unwrap(); + assert_eq!(inst.len(), 2); + let mut tris = 0usize; + for (m_idx, xform) in inst { + let m = &doc.scene.meshes[m_idx]; + tris += m.triangle_count(); + let w = mat_mul(&global, &xform); + for p in &m.positions { + let wp = transform_point(&w, *p); + assert!(wp.iter().all(|v| v.is_finite())); + } + } + assert_eq!(tris, 5); +} + +#[test] +fn entities_and_limits_are_enforced() { + let dae = DAE + .replace(r#""#, r#""#) + .replace(r#"name="Red""#, r#"name="R&D""#); + let scene = read(dae.as_bytes(), &Limits::default()).unwrap(); + scene.validate().unwrap(); + assert!(scene.nodes.iter().any(|n| n.name == "Tom & Jerry <\"'AB")); + assert_eq!(scene.materials[0].name, "R&D"); + + let tight = Limits { max_triangles: 2, ..Limits::default() }; + assert!(matches!(read(DAE.as_bytes(), &tight), Err(Error::TooLarge(_)))); +} + +#[test] +fn hammer_never_panics() { + hammer(DAE.as_bytes(), &|b| read(b, &Limits::default())); +} From 1546550b0d4b79b8156a1fefaac8b3b317a4aee0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:01:09 -0500 Subject: [PATCH 68/79] pptx/drawingml: upstream DeckCraft table caps, has_notes_slide, ModelError, and import_report (#2463) * pptx/drawingml: upstream DeckCraft table caps, has_notes_slide, ModelError, and import_report (#792) * drawingml(table): mark insert_row and insert_col #[must_use] --- crates/drawingml/src/table.rs | 199 +++++++++++++++++++++++++++++---- crates/pptx/src/lib.rs | 25 +++++ crates/pptx/src/read.rs | 33 +++++- crates/pptx/src/read/shapes.rs | 3 + crates/pptx/src/write.rs | 6 +- 5 files changed, 241 insertions(+), 25 deletions(-) diff --git a/crates/drawingml/src/table.rs b/crates/drawingml/src/table.rs index e5fbe1f97b..b5d83d5304 100644 --- a/crates/drawingml/src/table.rs +++ b/crates/drawingml/src/table.rs @@ -83,6 +83,12 @@ impl Default for Table { } } +/// Cells a table may hold after [`Table::normalize`] (PowerPoint's own limit is 75 x 75). +pub const MAX_CELLS: usize = 100_000; +/// Cell visits [`Table::merge`] may spend growing its rectangle over existing merges: a few +/// passes over the largest grid, where a real table needs one or two. +const MAX_MERGE_WORK: usize = 16 * MAX_CELLS; + impl Table { pub fn new(rows: usize, cols: usize, width: f64, row_height: f64) -> Self { let rows = rows.clamp(1, 1000); @@ -113,15 +119,26 @@ impl Table { self.rows.iter().map(|r| r.height).sum() } /// Insert an empty row before `at`. A merge the new row falls inside grows to cover it. - pub fn insert_row(&mut self, at: usize) { + /// Returns false, leaving the table as it was, when the row would take it past [`MAX_CELLS`]. + #[must_use] + pub fn insert_row(&mut self, at: usize) -> bool { + if self.cols.len().saturating_mul(self.rows.len().saturating_add(1)) > MAX_CELLS { + return false; + } let at = at.min(self.rows.len()); let merges = self.merges(); let h = self.rows.get(at.saturating_sub(1)).map(|r| r.height).unwrap_or(30.0); self.rows.insert(at, Row { height: h, cells: (0..self.cols.len()).map(|_| Cell::new("")).collect() }); self.set_merges(merges.into_iter().map(|m| m.insert_row(at))); + true } /// Insert an empty column before `at`. A merge the new column falls inside grows to cover it. - pub fn insert_col(&mut self, at: usize) { + /// Returns false, leaving the table as it was, when the column would take it past [`MAX_CELLS`]. + #[must_use] + pub fn insert_col(&mut self, at: usize) -> bool { + if self.cols.len().saturating_add(1).saturating_mul(self.rows.len()) > MAX_CELLS { + return false; + } let at = at.min(self.cols.len()); let merges = self.merges(); let w = self.cols.get(at.saturating_sub(1)).copied().unwrap_or(80.0); @@ -131,6 +148,7 @@ impl Table { r.cells.insert(i, Cell::new("")); } self.set_merges(merges.into_iter().map(|m| m.insert_col(at))); + true } /// Delete row `at`. Merges through it shrink; a merge anchored on it moves its anchor (and /// text) to the next row it covers. @@ -170,8 +188,12 @@ impl Table { true } /// The merged areas: every uncovered cell spanning more than one cell, clipped to the grid. + /// Merges of a well-formed table do not overlap, so together they cover at most the grid; a + /// file's overlapping spans past that are dropped, so rebuilding them cannot revisit cells + /// without bound. fn merges(&self) -> Vec { let (nr, nc) = (self.rows.len(), self.cols.len()); + let mut area = nr.saturating_mul(nc); let mut out = vec![]; for (r, row) in self.rows.iter().enumerate() { for (c, cell) in row.cells.iter().enumerate().take(nc) { @@ -180,7 +202,10 @@ impl Table { } let rs = (cell.row_span.max(1) as usize).min(nr - r); let gs = (cell.grid_span.max(1) as usize).min(nc - c); - if rs > 1 || gs > 1 { + if (rs > 1 || gs > 1) + && let Some(left) = area.checked_sub(rs.saturating_mul(gs)) + { + area = left; out.push(Merge { r, c, rs, gs }); } } @@ -233,9 +258,17 @@ impl Table { if r1 >= self.rows.len() || c1 >= self.cols.len() || (r0 == r1 && c0 == c1) { return false; } - // Grow the rectangle until no existing merge sticks out of it. + // Grow the rectangle until no existing merge sticks out of it. Each pass reads the whole + // grid and may grow it by one row, so the passes are charged against + // [`MAX_MERGE_WORK`]: past it the merge is refused, before anything changed. let (mut r0, mut c0, mut r1, mut c1) = (r0, c0, r1, c1); + let pass = self.rows.len().saturating_mul(self.cols.len()).max(1); + let mut work = 0usize; loop { + work = work.saturating_add(pass); + if work > MAX_MERGE_WORK { + return false; + } let before = (r0, c0, r1, c1); for (r, row) in self.rows.iter().enumerate() { for (c, cell) in row.cells.iter().enumerate().take(self.cols.len()) { @@ -289,21 +322,50 @@ impl Table { return false; } // Spans come from the file and may reach past the table; only walk the cells that exist. - for rr in r..r.saturating_add(rs).min(self.rows.len()) { - for cc in c..c.saturating_add(gs).min(self.cols.len()) { - if let Some(x) = self.cell_mut(rr, cc) { - x.h_merge = false; - x.v_merge = false; - x.grid_span = 1; - x.row_span = 1; - } + let end = r.saturating_add(rs).min(self.rows.len()); + let gs = gs.min(self.cols.len().saturating_sub(c)); + for row in self.rows.get_mut(r..end).unwrap_or_default() { + for x in row.cells.iter_mut().skip(c).take(gs) { + x.h_merge = false; + x.v_merge = false; + x.grid_span = 1; + x.row_span = 1; } } true } - /// Make every row have exactly `cols.len()` cells (repair after loading). - pub fn normalize(&mut self) { + /// Whether the grid is as [`Table::normalize`] leaves it: within [`MAX_CELLS`], every row + /// exactly `cols.len()` cells wide. + pub fn is_normalized(&self) -> bool { let n = self.cols.len(); + n <= MAX_CELLS && self.rows.len() <= (MAX_CELLS / n.max(1)).max(1) && self.rows.iter().all(|r| r.cells.len() == n) + } + /// Whether [`Table::normalize`] would drop rows or columns to fit [`MAX_CELLS`]. + pub fn over_cap(&self) -> bool { + let n = self.cols.len(); + n > MAX_CELLS || self.rows.len() > (MAX_CELLS / n.max(1)).max(1) + } + /// What [`Table::normalize`] would leave of this table, cloning only the rows and cells that + /// survive (an oversized table is not copied whole first). + pub fn normalized(&self) -> Table { + let n = self.cols.len().min(MAX_CELLS); + let keep = (MAX_CELLS / n.max(1)).max(1); + let rows = self.rows.iter().take(keep).map(|r| Row { height: r.height, cells: r.cells.iter().take(n).cloned().collect() }).collect(); + let mut t = Table { cols: self.cols[..n].to_vec(), rows, background: self.background.clone(), style: self.style.clone(), ..*self }; + t.normalize(); + if self.over_cap() { + t.clip_spans(); + } + t + } + /// Make every row have exactly `cols.len()` cells (repair after loading). A grid over + /// [`MAX_CELLS`] loses its last rows (and columns) first, so a file naming many rows and many + /// columns but few cells cannot make this allocate their product. + pub fn normalize(&mut self) { + let truncated = self.over_cap(); + self.cols.truncate(MAX_CELLS); + let n = self.cols.len(); + self.rows.truncate((MAX_CELLS / n.max(1)).max(1)); for r in &mut self.rows { r.cells.resize_with(n, || Cell::new("")); for c in &mut r.cells { @@ -311,6 +373,20 @@ impl Table { c.row_span = c.row_span.max(1); } } + if truncated { + self.clip_spans(); + } + } + /// Cut every merge span to the rows and columns that remain, so no merge reaches past a + /// table that lost rows or columns to the cell cap. + fn clip_spans(&mut self) { + let (nr, nc) = (self.rows.len(), self.cols.len()); + for (ri, r) in self.rows.iter_mut().enumerate() { + for (ci, c) in r.cells.iter_mut().enumerate() { + c.row_span = c.row_span.min((nr - ri) as u32).max(1); + c.grid_span = c.grid_span.min((nc - ci) as u32).max(1); + } + } } } @@ -554,10 +630,10 @@ mod tests { fn row_and_column_edits_keep_merges_consistent() { for at in 0..=4 { let mut t = merged(); - t.insert_row(at); + assert!(t.insert_row(at)); assert_topology(&t); let mut t = merged(); - t.insert_col(at); + assert!(t.insert_col(at)); assert_topology(&t); } for at in 0..4 { @@ -573,11 +649,11 @@ mod tests { #[test] fn inserting_inside_a_merge_grows_it() { let mut t = merged(); - t.insert_row(2); + assert!(t.insert_row(2)); let a = t.cell(1, 1).unwrap(); assert_eq!((a.row_span, a.grid_span), (3, 2)); assert!(t.cell(2, 2).unwrap().h_merge && t.cell(2, 2).unwrap().v_merge); - t.insert_col(0); + assert!(t.insert_col(0)); assert_eq!(t.cell(1, 2).unwrap().grid_span, 2); assert_eq!(anchor_text(&t, 1, 2), "M"); assert_topology(&t); @@ -619,8 +695,8 @@ mod tests { fn insert_delete_merge_split() { let mut t = Table::new(3, 3, 300.0, 30.0); assert_eq!((t.n_rows(), t.n_cols()), (3, 3)); - t.insert_row(1); - t.insert_col(3); + assert!(t.insert_row(1)); + assert!(t.insert_col(3)); assert_eq!((t.n_rows(), t.n_cols()), (4, 4)); assert!(t.delete_row(0) && t.delete_col(0)); assert_eq!((t.n_rows(), t.n_cols()), (3, 3)); @@ -646,6 +722,89 @@ mod tests { assert!(t.split(0, 0)); assert_eq!(t.cell(0, 0).map(|c| (c.grid_span, c.row_span)), Some((1, 1))); } + + #[test] + fn merge_refuses_work_past_cap() { + let mut t = Table::new(1000, 10, 100.0, 10.0); + for row in &mut t.rows { + for c in &mut row.cells { + c.row_span = 2; + } + } + let before = t.clone(); + assert!(!t.merge(998, 0, 999, 9)); + assert_eq!(t, before); + let mut small = Table::new(4, 4, 400.0, 30.0); + assert!(small.merge(0, 0, 1, 1)); + assert!(small.is_normalized() && !Table { cols: vec![1.0; 3], rows: vec![Row::default(); 2], ..Default::default() }.is_normalized()); + } + + #[test] + fn normalize_caps_a_sparse_grid_at_max_cells() { + let mut t = Table { cols: vec![10.0; 1000], rows: vec![Row::default(); 1000], ..Default::default() }; + t.normalize(); + assert_eq!(t.cols.len(), 1000); + assert_eq!(t.rows.len(), MAX_CELLS / 1000); + assert!(t.rows.iter().all(|r| r.cells.len() == 1000)); + let mut t = Table { cols: vec![1.0; MAX_CELLS + 5], rows: vec![Row::default(); 3], ..Default::default() }; + t.normalize(); + assert_eq!((t.cols.len(), t.rows.len()), (MAX_CELLS, 1)); + let wide = Table { cols: vec![10.0; 1000], rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); 1500] }; 150], ..Default::default() }; + let mut n = wide.clone(); + n.normalize(); + assert_eq!(wide.normalized(), n); + let mut t = Table::new(4, 4, 400.0, 30.0); + t.normalize(); + assert_eq!((t.n_rows(), t.n_cols()), (4, 4)); + } + + #[test] + fn overlapping_file_spans_rebuild_in_bounded_work() { + let n = 200; + let mut t = Table::new(n, n, 400.0, 30.0); + for row in &mut t.rows { + for c in &mut row.cells { + c.grid_span = u32::MAX; + c.row_span = u32::MAX; + } + } + assert_eq!(t.merges().len(), 1, "the first anchor already covers the whole grid"); + assert!(t.insert_row(n)); + assert_eq!(t.n_rows(), n + 1); + assert!(t.split(0, 0)); + } + + #[test] + fn insert_past_the_cap_is_refused() { + const { assert!(MAX_CELLS >= 75 * 75) }; + let mut t = + Table { cols: vec![1.0; 200], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); 200] }; MAX_CELLS / 200], ..Default::default() }; + assert!(!t.over_cap()); + let before = t.clone(); + assert!(!t.insert_row(0)); + assert!(!t.insert_col(0)); + assert_eq!(t, before); + assert!(Table::new(75, 75, 100.0, 10.0).insert_row(0)); + } + + #[test] + fn merges_are_clipped_when_the_cap_drops_rows() { + let cols = 1000; + let rows = MAX_CELLS / cols + 1; + let mut t = Table { cols: vec![1.0; cols], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); cols] }; rows], ..Default::default() }; + t.rows[0].cells[0].row_span = rows as u32; + t.rows[0].cells[cols - 1].grid_span = 5; + let n = t.normalized(); + assert_eq!(n.rows.len(), rows - 1); + assert_eq!(n.rows[0].cells[0].row_span as usize, rows - 1); + assert_eq!(n.rows[0].cells[cols - 1].grid_span, 1); + t.normalize(); + assert_eq!(t.rows[0].cells[0].row_span as usize, rows - 1); + let mut small = Table::new(3, 3, 30.0, 10.0); + small.rows[2].cells[2].grid_span = 4; + small.normalize(); + assert_eq!(small.rows[2].cells[2].grid_span, 4); + } } pub mod styles; diff --git a/crates/pptx/src/lib.rs b/crates/pptx/src/lib.rs index 4c8b708b15..d206caaa94 100644 --- a/crates/pptx/src/lib.rs +++ b/crates/pptx/src/lib.rs @@ -52,6 +52,21 @@ pub enum Error { Xml(String), } +/// Errors returned by presentation model editing helpers. +#[derive(Debug, thiserror::Error)] +pub enum ModelError { + #[error("no slide {0}")] + NoSlide(String), + #[error("no shape {0}")] + NoShape(ShapeId), + #[error("no layout {0}")] + NoLayout(LayoutId), + #[error("{0}")] + Invalid(String), +} + +pub type ModelResult = std::result::Result; + /// What the caller supplies where a file or a presentation leaves something out. The reader asks /// for a master when a file has none it can read, and for the theme of a master that names none; /// the writer for a master when the presentation has none, and for the text styles a master or @@ -112,6 +127,12 @@ pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presenta read::import_checked(bytes, defaults) } +/// [`import_checked`], plus warnings for content the file had that was cut to fit a limit (a +/// table past the cell cap keeps its leading rows). +pub fn import_report(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec, Vec), Error> { + read::import_report(bytes, defaults) +} + /// [`import`] with a lower presentation-wide chart point budget, so tests reach the over-budget /// path without a multi-million-point chart. #[doc(hidden)] @@ -688,6 +709,9 @@ pub struct Slide { pub animations: Vec, /// Speaker notes. pub notes: TextBody, + /// Whether the slide has an associated notes slide even if its text is empty. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub has_notes_slide: bool, pub comments: Vec, /// `clrMapOvr`: a colour map replacing the layout's or master's (`bg1`→`dk1`…); None follows /// the layout. @@ -714,6 +738,7 @@ impl Default for Slide { transition: None, animations: vec![], notes: TextBody::default(), + has_notes_slide: false, comments: vec![], color_map: None, tags: vec![], diff --git a/crates/pptx/src/read.rs b/crates/pptx/src/read.rs index ffafb23198..588ba1357b 100644 --- a/crates/pptx/src/read.rs +++ b/crates/pptx/src/read.rs @@ -58,8 +58,13 @@ pub struct Imp<'a> { /// Whether a part has relationships of its own, by normalized part name: looked up once /// however many embedded objects point at the part. pub has_rels: HashMap, + /// Warnings for content cut to fit a limit during import. + pub warnings: Vec, } +/// Import warnings kept; a hostile file with many oversized tables adds no more than this. +const MAX_IMPORT_WARNINGS: usize = 32; + impl<'a> Imp<'a> { fn new(pkg: &'a Package, defaults: &'a dyn Defaults, next: u32, chart_points_cap: usize) -> Self { Imp { @@ -82,6 +87,14 @@ impl<'a> Imp<'a> { tag_bytes: 0, tags_capped: false, has_rels: HashMap::new(), + warnings: vec![], + } + } + /// Record something the file lost, and log it. + pub fn warn(&mut self, msg: String) { + log::warn!("pptx: {msg}"); + if self.warnings.len() < MAX_IMPORT_WARNINGS { + self.warnings.push(msg); } } pub fn alloc(&mut self) -> u32 { @@ -392,11 +405,26 @@ pub fn import(bytes: &[u8], defaults: &dyn Defaults) -> Result Result<(Presentation, Vec), Error> { - import_with_chart_points(bytes, defaults, chart::MAX_PRESENTATION_CHART_POINTS) + import_report(bytes, defaults).map(|(p, lost, _)| (p, lost)) +} + +/// [`import_checked`], plus warnings for content the file had that was cut to fit a limit (a +/// table past the cell cap keeps its leading rows). +pub fn import_report(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec, Vec), Error> { + import_report_with_chart_points(bytes, defaults, chart::MAX_PRESENTATION_CHART_POINTS) } /// [`import_checked`] with the presentation's chart point budget set (tests lower it). pub(crate) fn import_with_chart_points(bytes: &[u8], defaults: &dyn Defaults, chart_points_cap: usize) -> Result<(Presentation, Vec), Error> { + import_report_with_chart_points(bytes, defaults, chart_points_cap).map(|(p, lost, _)| (p, lost)) +} + +/// [`import_report`] with the presentation's chart point budget set. +fn import_report_with_chart_points( + bytes: &[u8], + defaults: &dyn Defaults, + chart_points_cap: usize, +) -> Result<(Presentation, Vec, Vec), Error> { let mut lost_slides: Vec = vec![]; let pkg = Package::open(bytes)?; let root_rels = pkg.rels(""); @@ -438,7 +466,7 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], defaults: &dyn Defaults, ch p.media = std::mem::take(&mut imp.media); p.next_id = imp.next; p.fix_next_id(); - Ok((p, lost_slides)) + Ok((p, lost_slides, imp.warnings)) } /// Masters, layouts and slides to read, in file order and without duplicates: (master paths, @@ -602,6 +630,7 @@ fn read_slides( let mut slide = read_slide(imp, &part, doc, *id, layout); if let Some(notes) = slide_notes(imp, &part, &mut owned_parts) { slide.notes = notes; + slide.has_notes_slide = true; } read_slide_comments(pkg, pres_part, &part, &mut slide, &mut owned_parts); file_slide_ids.insert(*file_id, *id); diff --git a/crates/pptx/src/read/shapes.rs b/crates/pptx/src/read/shapes.rs index 8e20a5545f..3ebaddb994 100644 --- a/crates/pptx/src/read/shapes.rs +++ b/crates/pptx/src/read/shapes.rs @@ -805,6 +805,9 @@ fn table(imp: &mut Imp, part: &Part, tbl: &El) -> Table { let n = t.rows.iter().map(|r| r.cells.len()).max().unwrap_or(0); t.cols = vec![72.0; n]; } + if t.over_cap() { + imp.warn(format!("a table in {} is over {} cells; its last rows were left out", part.name, craft_drawingml::table::MAX_CELLS)); + } t.normalize(); t } diff --git a/crates/pptx/src/write.rs b/crates/pptx/src/write.rs index 0e8d01b138..30c0b83df2 100644 --- a/crates/pptx/src/write.rs +++ b/crates/pptx/src/write.rs @@ -458,7 +458,7 @@ struct NotesMasterWrite { fn notes_master_write(p: &Presentation) -> Option { let nm = p.notes_master.as_deref(); let kept = nm.filter(|m| !m.shapes.is_empty()); - let has_notes = p.slides.iter().any(|s| !s.notes.is_empty()); + let has_notes = p.slides.iter().any(|s| !s.notes.is_empty() || s.has_notes_slide); if !has_notes && nm.is_none() { return None; } @@ -694,7 +694,7 @@ pub fn export(p: &Presentation, defaults: &dyn Defaults, main_ct: &str) -> Resul if let Some(lp) = layout_parts.get(&s.layout) { so.rels.add("slideLayout", &craft_opc::relative(&sname, lp), false); } - if !s.notes.is_empty() { + if !s.notes.is_empty() || s.has_notes_slide { let nname = format!("ppt/notesSlides/notesSlide{}.xml", i + 1); so.rels.add("notesSlide", &craft_opc::relative(&sname, &nname), false); let mut no = Out::new(&nname); @@ -1360,7 +1360,7 @@ fn app_xml(p: &Presentation, application: &str) -> Vec { .open(); w.leaf("Application", &[], application); w.leaf("Slides", &[], &p.slides.len().to_string()); - w.leaf("Notes", &[], &p.slides.iter().filter(|s| !s.notes.is_empty()).count().to_string()); + w.leaf("Notes", &[], &p.slides.iter().filter(|s| !s.notes.is_empty() || s.has_notes_slide).count().to_string()); w.leaf("HiddenSlides", &[], &p.slides.iter().filter(|s| s.hidden).count().to_string()); if !p.props.company.is_empty() { w.leaf("Company", &[], &p.props.company); From 429937ad72e16fa2bb5a9f085dee80809e4a566d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:03:14 -0500 Subject: [PATCH 69/79] craft-dds: expose shared BC1-7, ETC1/EAC, and packed pixel decoders (#778) (#2460) * craft-dds: expose shared BC1-7, ETC1/EAC, and packed pixel decoders (#778) * fix(dds): qualify super::anchor in bptc test * craft-dds: add independent known-answer test vectors for BC6H, BC7, ETC1, and EAC * fix(dds): remove unused partition/anchor imports in bptc test --- crates/dds/src/bptc.rs | 1152 +++++++++++++++++++++++++++++ crates/dds/src/eac.rs | 107 +++ crates/dds/src/lib.rs | 7 + crates/dds/src/packed.rs | 51 ++ crates/dds/src/pixels.rs | 390 ++++++++++ crates/dds/tests/known_answers.rs | 114 +++ 6 files changed, 1821 insertions(+) create mode 100644 crates/dds/src/bptc.rs create mode 100644 crates/dds/src/eac.rs create mode 100644 crates/dds/src/packed.rs create mode 100644 crates/dds/src/pixels.rs create mode 100644 crates/dds/tests/known_answers.rs diff --git a/crates/dds/src/bptc.rs b/crates/dds/src/bptc.rs new file mode 100644 index 0000000000..e6a5f317de --- /dev/null +++ b/crates/dds/src/bptc.rs @@ -0,0 +1,1152 @@ +//! BPTC blocks: BC7 (8-bit RGBA) and BC6H (half-float RGB), written from the Khronos Data Format +//! Specification's "BPTC Compressed Texture Image Formats" section. Each 16-byte block holds 4×4 +//! texels, row by row. Tables are the specification's, numbered as it numbers them. + +/// A block's bits, read from the lowest up. +struct Bits { + value: u128, + pos: u32, +} + +impl Bits { + fn new(block: &[u8; 16]) -> Self { + Self { value: u128::from_le_bytes(*block), pos: 0 } + } + + /// The next `n` bits (at most 16), as a number. + fn take(&mut self, n: u8) -> u32 { + let n = u32::from(n); + let mask = !u128::MAX.checked_shl(n).unwrap_or(0); + let out = self.value.checked_shr(self.pos).unwrap_or(0) & mask; + self.pos = self.pos.saturating_add(n); + out as u32 + } +} + +/// Interpolation weights by index bits (Table 119). +const WEIGHTS_2: [i32; 4] = [0, 21, 43, 64]; +const WEIGHTS_3: [i32; 8] = [0, 9, 18, 27, 37, 46, 55, 64]; +const WEIGHTS_4: [i32; 16] = [0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64]; + +fn weight(index_bits: u8, index: u32) -> i32 { + let table: &[i32] = match index_bits { + 2 => &WEIGHTS_2, + 3 => &WEIGHTS_3, + _ => &WEIGHTS_4, + }; + table.get(index as usize).copied().unwrap_or(0) +} + +/// Equation 2: a value between two endpoints. +fn interpolate(e0: i32, e1: i32, weight: i32) -> i32 { + ((64 - weight) * e0 + weight * e1 + 32) >> 6 +} + +/// Which subset texel `i` is in, for a block with `subsets` subsets and partition `partition`. +fn subset(subsets: u8, partition: usize, i: usize) -> usize { + let part = match subsets { + 2 => u32::from(PARTITIONS_2.get(partition).copied().unwrap_or(0)) >> i & 1, + 3 => PARTITIONS_3.get(partition).copied().unwrap_or(0) >> (2 * i) & 3, + _ => 0, + }; + part as usize +} + +/// Whether texel `i` is an anchor (its index is stored with one bit fewer). +fn anchor(subsets: u8, partition: usize, i: usize) -> bool { + let at = |table: &[u8; 64]| table.get(partition).is_some_and(|a| usize::from(*a) == i); + i == 0 + || match subsets { + 2 => at(&ANCHOR_2), + 3 => at(&ANCHOR_3_SECOND) || at(&ANCHOR_3_THIRD), + _ => false, + } +} + +/// The 16 indices of a block, each `bits` wide (anchors one fewer). +fn indices(r: &mut Bits, bits: u8, subsets: u8, partition: usize) -> [u32; 16] { + let mut out = [0; 16]; + for (i, x) in out.iter_mut().enumerate() { + *x = r.take(bits - u8::from(anchor(subsets, partition, i))); + } + out +} + +/// BC7's modes (Table 109): subsets, partition bits, rotation bits, index selection bits, colour +/// bits, alpha bits, per-endpoint P-bits, shared P-bits, index bits, secondary index bits. +const BC7_MODES: [[u8; 10]; 8] = [ + [3, 4, 0, 0, 4, 0, 1, 0, 3, 0], + [2, 6, 0, 0, 6, 0, 0, 1, 3, 0], + [3, 6, 0, 0, 5, 0, 0, 0, 2, 0], + [2, 6, 0, 0, 7, 0, 1, 0, 2, 0], + [1, 0, 2, 1, 5, 6, 0, 0, 2, 3], + [1, 0, 2, 0, 7, 8, 0, 0, 2, 2], + [1, 0, 0, 0, 7, 7, 1, 0, 4, 0], + [2, 6, 0, 0, 5, 5, 1, 0, 2, 0], +]; + +/// The 16 RGBA texels of a BC7 block. +pub fn bc7(block: &[u8; 16]) -> [[u8; 4]; 16] { + let mode = block[0].trailing_zeros(); + // A low byte of 0 is reserved: every channel of every texel is 0. + let Some(&[subsets, partition_bits, rotation_bits, selection_bits, colour_bits, alpha_bits, endpoint_p, shared_p, index_bits, index2_bits]) = + BC7_MODES.get(mode as usize) + else { + return [[0; 4]; 16]; + }; + let mut r = Bits::new(block); + r.pos = mode + 1; + let partition = r.take(partition_bits) as usize; + let rotation = r.take(rotation_bits); + let swapped = r.take(selection_bits) == 1; + let ends = usize::from(subsets) * 2; + // Endpoints: every endpoint's red, then green, blue and alpha; then the P-bits. + let mut raw = [[0u32; 4]; 6]; + for channel in 0..4 { + let bits = if channel < 3 { colour_bits } else { alpha_bits }; + for e in raw.iter_mut().take(ends) { + e[channel] = r.take(bits); + } + } + let mut p = [0u32; 6]; + if endpoint_p == 1 { + for x in p.iter_mut().take(ends) { + *x = r.take(1); + } + } + if shared_p == 1 { + for pair in p.chunks_mut(2).take(usize::from(subsets)) { + pair.fill(r.take(1)); + } + } + let has_p = endpoint_p + shared_p > 0; + let endpoints: [[i32; 4]; 6] = std::array::from_fn(|e| { + std::array::from_fn(|channel| { + let bits = u32::from(if channel < 3 { colour_bits } else { alpha_bits }); + let (v, bits) = match (raw[e][channel], bits) { + (_, 0) => return 255, + (v, bits) if has_p => (v << 1 | p[e], bits + 1), + other => other, + }; + // The stored bits are a byte's top bits; its top bits repeat into the rest. + (v << (8 - bits) | v >> (2 * bits - 8)) as i32 + }) + }); + let primary = indices(&mut r, index_bits, subsets, partition); + let secondary = if index2_bits > 0 { indices(&mut r, index2_bits, 1, 0) } else { [0; 16] }; + let (colour, colour_index_bits) = if swapped { (secondary, index2_bits) } else { (primary, index_bits) }; + let (alpha, alpha_index_bits) = if index2_bits > 0 && !swapped { (secondary, index2_bits) } else { (primary, index_bits) }; + std::array::from_fn(|i| { + let s = subset(subsets, partition, i); + let (e0, e1) = (endpoints.get(2 * s).copied().unwrap_or_default(), endpoints.get(2 * s + 1).copied().unwrap_or_default()); + let (wc, wa) = (weight(colour_index_bits, colour[i]), weight(alpha_index_bits, alpha[i])); + let mut px: [u8; 4] = std::array::from_fn(|c| interpolate(e0[c], e1[c], if c < 3 { wc } else { wa }) as u8); + if (1..=3).contains(&rotation) { + px.swap(rotation as usize - 1, 3); + } + px + }) +} + +// BC6H's fields: endpoint `e`'s red, green and blue are fields `3e`, `3e + 1` and `3e + 2`. +const R0: u8 = 0; +const G0: u8 = 1; +const B0: u8 = 2; +const R1: u8 = 3; +const G1: u8 = 4; +const B1: u8 = 5; +const R2: u8 = 6; +const G2: u8 = 7; +const B2: u8 = 8; +const R3: u8 = 9; +const G3: u8 = 10; +const B3: u8 = 11; +/// The partition number. +const PB: u8 = 12; + +/// A BC6H mode (Tables 121 and 122). +struct Bc6hMode { + id: u8, + /// Endpoints after the first are stored as differences from it. + transformed: bool, + subsets: u8, + endpoint_bits: u8, + /// Red, green and blue bits of the endpoints after the first. + delta_bits: [u8; 3], + /// After the mode bits, in block order: `(field, a, b)` is the spec's `field a..b`, so the + /// next `|a - b| + 1` bits of the block go to the field's bits `b`, `b ± 1`, …, `a`. + fields: &'static [(u8, u8, u8)], +} + +fn sign_extend(v: i32, bits: u8) -> i32 { + let shift = 32 - u32::from(bits); + (v << shift) >> shift +} + +/// An endpoint value stretched to 16 bits (the unquantization pseudocode). +fn unquantize(x: i32, bits: u8, signed: bool) -> i32 { + let n = i32::from(bits); + if !signed { + return match x { + _ if n >= 15 => x, + 0 => 0, + _ if x == (1 << n) - 1 => 0xffff, + _ => ((x << 15) + 0x4000) >> (n - 1), + }; + } + if n >= 16 { + return x; + } + let magnitude = match x.abs() { + 0 => 0, + a if a >= (1 << (n - 1)) - 1 => 0x7fff, + a => ((a << 15) + 0x4000) >> (n - 1), + }; + if x < 0 { -magnitude } else { magnitude } +} + +/// An interpolated value as a half float's bits. +fn finish(i: i32, signed: bool) -> u16 { + match (signed, i < 0) { + (false, _) => ((i * 31) >> 6) as u16, + (true, true) => (((-i * 31) >> 5) | 0x8000) as u16, + (true, false) => ((i * 31) >> 5) as u16, + } +} + +/// The 16 RGB texels of a BC6H block as half floats' bits; a reserved mode gives black. +fn bc6h_halves(block: &[u8; 16], signed: bool) -> [[u16; 3]; 16] { + let mut r = Bits::new(block); + let id = match r.take(2) { + low @ 0..=1 => low, + low => low | r.take(3) << 2, + }; + let Some(mode) = BC6H_MODES.iter().find(|m| u32::from(m.id) == id) else { + return [[0; 3]; 16]; + }; + let mut fields = [0i32; 13]; + for &(field, a, b) in mode.fields { + for k in 0..=a.abs_diff(b) { + let bit = if a >= b { b + k } else { b - k }; + if let Some(f) = fields.get_mut(usize::from(field)) { + *f |= (r.take(1) as i32) << bit; + } + } + } + let bits = mode.endpoint_bits; + let ends = usize::from(mode.subsets) * 2; + let mut endpoints = [[0i32; 3]; 4]; + for (e, endpoint) in endpoints.iter_mut().enumerate().take(ends) { + for (c, v) in endpoint.iter_mut().enumerate() { + let (base, stored) = (fields[c], fields[3 * e + c]); + let x = match e { + 0 => stored, + _ if mode.transformed => (base + sign_extend(stored, mode.delta_bits[c])) & ((1 << bits) - 1), + _ => stored, + }; + *v = unquantize(if signed { sign_extend(x, bits) } else { x }, bits, signed); + } + } + let partition = fields[usize::from(PB)] as usize; + let index_bits = if mode.subsets == 2 { 3 } else { 4 }; + let index = indices(&mut r, index_bits, mode.subsets, partition); + std::array::from_fn(|i| { + let s = subset(mode.subsets, partition, i); + let (e0, e1) = (endpoints.get(2 * s).copied().unwrap_or_default(), endpoints.get(2 * s + 1).copied().unwrap_or_default()); + let w = weight(index_bits, index[i]); + std::array::from_fn(|c| finish(interpolate(e0[c], e1[c], w), signed)) + }) +} + +/// A half float's value. +pub fn half(h: u16) -> f32 { + let sign = if h & 0x8000 == 0 { 1.0 } else { -1.0 }; + let (exponent, mantissa) = (i32::from(h >> 10 & 31), f32::from(h & 1023)); + sign * match exponent { + 0 => mantissa * 2f32.powi(-24), + 31 if mantissa != 0.0 => f32::NAN, + 31 => f32::INFINITY, + e => (1024.0 + mantissa) * 2f32.powi(e - 25), + } +} + +/// A linear light value as an 8-bit sRGB value; 0..1 is kept, brighter and negative values clip. +pub fn srgb8(v: f32) -> u8 { + let v = v.clamp(0.0, 1.0); + let s = if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + (s * 255.0 + 0.5) as u8 +} + +/// The 16 texels of a BC6H block, tone-mapped to 8-bit sRGB (opaque). +pub fn bc6h(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + bc6h_halves(block, signed).map(|[r, g, b]| [srgb8(half(r)), srgb8(half(g)), srgb8(half(b)), 255]) +} + +/// Two-subset partitions (Table 114): bit `i` is texel `i`'s subset. +const PARTITIONS_2: [u16; 64] = [ + 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, 0xf710, 0x008e, + 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, + 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, + 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22, +]; + +/// Three-subset partitions (Table 115): bits `2i` and `2i + 1` are texel `i`'s subset. +const PARTITIONS_3: [u32; 64] = [ + 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500, 0xaaaa5500, 0x90909090, + 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, + 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414, 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, + 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, + 0xaa444444, 0x54a854a8, 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, + 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, +]; + +/// The anchor texel of the second subset of two-subset partitions (Table 118). +const ANCHOR_2: [u8; 64] = [ + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, + 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, +]; + +/// The anchor texels of the second and third subsets of three-subset partitions (Tables 116, 117). +const ANCHOR_3_SECOND: [u8; 64] = [ + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, + 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, +]; + +const ANCHOR_3_THIRD: [u8; 64] = [ + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, + 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +]; + +/// BC6H's modes, in the order of Table 121. +const BC6H_MODES: [Bc6hMode; 14] = [ + Bc6hMode { + id: 0, + transformed: true, + subsets: 2, + endpoint_bits: 10, + delta_bits: [5, 5, 5], + fields: &[ + (G2, 4, 4), + (B2, 4, 4), + (B3, 4, 4), + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 1, + transformed: true, + subsets: 2, + endpoint_bits: 7, + delta_bits: [6, 6, 6], + fields: &[ + (G2, 5, 5), + (G3, 4, 4), + (G3, 5, 5), + (R0, 6, 0), + (B3, 0, 0), + (B3, 1, 1), + (B2, 4, 4), + (G0, 6, 0), + (B2, 5, 5), + (B3, 2, 2), + (G2, 4, 4), + (B0, 6, 0), + (B3, 3, 3), + (B3, 5, 5), + (B3, 4, 4), + (R1, 5, 0), + (G2, 3, 0), + (G1, 5, 0), + (G3, 3, 0), + (B1, 5, 0), + (B2, 3, 0), + (R2, 5, 0), + (R3, 5, 0), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 2, + transformed: true, + subsets: 2, + endpoint_bits: 11, + delta_bits: [5, 4, 4], + fields: &[ + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 4, 0), + (R0, 10, 10), + (G2, 3, 0), + (G1, 3, 0), + (G0, 10, 10), + (B3, 0, 0), + (G3, 3, 0), + (B1, 3, 0), + (B0, 10, 10), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 6, + transformed: true, + subsets: 2, + endpoint_bits: 11, + delta_bits: [4, 5, 4], + fields: &[ + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 3, 0), + (R0, 10, 10), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (G0, 10, 10), + (G3, 3, 0), + (B1, 3, 0), + (B0, 10, 10), + (B3, 1, 1), + (B2, 3, 0), + (R2, 3, 0), + (B3, 0, 0), + (B3, 2, 2), + (R3, 3, 0), + (G2, 4, 4), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 10, + transformed: true, + subsets: 2, + endpoint_bits: 11, + delta_bits: [4, 4, 5], + fields: &[ + (R0, 9, 0), + (G0, 9, 0), + (B0, 9, 0), + (R1, 3, 0), + (R0, 10, 10), + (B2, 4, 4), + (G2, 3, 0), + (G1, 3, 0), + (G0, 10, 10), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B0, 10, 10), + (B2, 3, 0), + (R2, 3, 0), + (B3, 1, 1), + (B3, 2, 2), + (R3, 3, 0), + (B3, 4, 4), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 14, + transformed: true, + subsets: 2, + endpoint_bits: 9, + delta_bits: [5, 5, 5], + fields: &[ + (R0, 8, 0), + (B2, 4, 4), + (G0, 8, 0), + (G2, 4, 4), + (B0, 8, 0), + (B3, 4, 4), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 18, + transformed: true, + subsets: 2, + endpoint_bits: 8, + delta_bits: [6, 5, 5], + fields: &[ + (R0, 7, 0), + (G3, 4, 4), + (B2, 4, 4), + (G0, 7, 0), + (B3, 2, 2), + (G2, 4, 4), + (B0, 7, 0), + (B3, 3, 3), + (B3, 4, 4), + (R1, 5, 0), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 5, 0), + (R3, 5, 0), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 22, + transformed: true, + subsets: 2, + endpoint_bits: 8, + delta_bits: [5, 6, 5], + fields: &[ + (R0, 7, 0), + (B3, 0, 0), + (B2, 4, 4), + (G0, 7, 0), + (G2, 5, 5), + (G2, 4, 4), + (B0, 7, 0), + (G3, 5, 5), + (B3, 4, 4), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 5, 0), + (G3, 3, 0), + (B1, 4, 0), + (B3, 1, 1), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 26, + transformed: true, + subsets: 2, + endpoint_bits: 8, + delta_bits: [5, 5, 6], + fields: &[ + (R0, 7, 0), + (B3, 1, 1), + (B2, 4, 4), + (G0, 7, 0), + (B2, 5, 5), + (G2, 4, 4), + (B0, 7, 0), + (B3, 5, 5), + (B3, 4, 4), + (R1, 4, 0), + (G3, 4, 4), + (G2, 3, 0), + (G1, 4, 0), + (B3, 0, 0), + (G3, 3, 0), + (B1, 5, 0), + (B2, 3, 0), + (R2, 4, 0), + (B3, 2, 2), + (R3, 4, 0), + (B3, 3, 3), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 30, + transformed: false, + subsets: 2, + endpoint_bits: 6, + delta_bits: [6, 6, 6], + fields: &[ + (R0, 5, 0), + (G3, 4, 4), + (B3, 0, 0), + (B3, 1, 1), + (B2, 4, 4), + (G0, 5, 0), + (G2, 5, 5), + (B2, 5, 5), + (B3, 2, 2), + (G2, 4, 4), + (B0, 5, 0), + (G3, 5, 5), + (B3, 3, 3), + (B3, 5, 5), + (B3, 4, 4), + (R1, 5, 0), + (G2, 3, 0), + (G1, 5, 0), + (G3, 3, 0), + (B1, 5, 0), + (B2, 3, 0), + (R2, 5, 0), + (R3, 5, 0), + (PB, 4, 0), + ], + }, + Bc6hMode { + id: 3, + transformed: false, + subsets: 1, + endpoint_bits: 10, + delta_bits: [10, 10, 10], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 9, 0), (G1, 9, 0), (B1, 9, 0)], + }, + Bc6hMode { + id: 7, + transformed: true, + subsets: 1, + endpoint_bits: 11, + delta_bits: [9, 9, 9], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 8, 0), (R0, 10, 10), (G1, 8, 0), (G0, 10, 10), (B1, 8, 0), (B0, 10, 10)], + }, + Bc6hMode { + id: 11, + transformed: true, + subsets: 1, + endpoint_bits: 12, + delta_bits: [8, 8, 8], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 7, 0), (R0, 10, 11), (G1, 7, 0), (G0, 10, 11), (B1, 7, 0), (B0, 10, 11)], + }, + Bc6hMode { + id: 15, + transformed: true, + subsets: 1, + endpoint_bits: 16, + delta_bits: [4, 4, 4], + fields: &[(R0, 9, 0), (G0, 9, 0), (B0, 9, 0), (R1, 3, 0), (R0, 10, 15), (G1, 3, 0), (G0, 10, 15), (B1, 3, 0), (B0, 10, 15)], + }, +]; + +#[cfg(test)] +mod tests { + use super::{B0, B1, B2, B3, BC6H_MODES, G0, G1, G2, G3, PB, R0, R1, R2, R3, bc6h, bc6h_halves, bc7, half, srgb8}; + + /// Pack `(value, bits)` fields into a block from the lowest bit up. + fn pack(fields: &[(u32, u32)]) -> [u8; 16] { + let (mut v, mut pos) = (0u128, 0); + for &(x, n) in fields { + assert!(u128::from(x) < 1 << n, "{x} doesn't fit in {n} bits"); + v |= u128::from(x) << pos; + pos += n; + } + assert_eq!(pos, 128, "a block is 128 bits"); + v.to_le_bytes() + } + + /// The mode bits of BC7 mode `m`, then `fields`. + fn bc7_block(m: u32, fields: &[(u32, u32)]) -> [u8; 16] { + pack(&[&[(1 << m, m + 1)], fields].concat()) + } + + /// One `bits`-wide field per value. + fn each(values: &[u32], bits: u32) -> Vec<(u32, u32)> { + values.iter().map(|v| (*v, bits)).collect() + } + + /// 16 indices, `bits` wide, one bit fewer at the `anchors`. + fn texel_indices(values: [u32; 16], bits: u32, anchors: &[usize]) -> Vec<(u32, u32)> { + values.iter().enumerate().map(|(i, v)| (*v, bits - u32::from(anchors.contains(&i)))).collect() + } + + fn index_set(set: &[(usize, u32)]) -> [u32; 16] { + let mut out = [0; 16]; + for (i, v) in set { + out[*i] = *v; + } + out + } + + /// Grey endpoints: the same value in red, green and blue. + fn grey(values: &[u32], bits: u32) -> Vec<(u32, u32)> { + [each(values, bits), each(values, bits), each(values, bits)].concat() + } + + // Each case's colours are worked out from the specification by hand: endpoint bits (and the + // P-bit) are a byte's top bits with its top bits repeated below, and a texel is + // ((64 - w) × e0 + w × e1 + 32) >> 6 with the weight w of its index. + + #[test] + fn bc7_mode_0_three_subsets_with_endpoint_p_bits() { + // Partition 0 of three subsets: rows 0011 / 0011 / 0221 / 2222; anchors 0, 3 and 15. + // Endpoints (4 bits + P-bit): 15+1 → 255, 0 → 0, 8+0 → 132, 8+1 → 140, 2+1 → 41, 4+0 → 66. + let idx = index_set(&[(1, 7), (2, 4), (3, 3), (9, 5), (15, 3)]); + let b = bc7_block( + 0, + &[&[(0, 4)], &grey(&[15, 0, 8, 8, 2, 4], 4)[..], &each(&[1, 0, 0, 1, 1, 0], 1), &texel_indices(idx, 3, &[0, 3, 15])].concat(), + ); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!(px[0], g(255)); + assert_eq!(px[1], g(0), "index 7: the second endpoint"); + assert_eq!(px[2], g(137), "subset 1, weight 37: (27×132 + 37×140 + 32) >> 6"); + assert_eq!(px[3], g(135), "subset 1's anchor, weight 27"); + assert_eq!(px[9], g(59), "subset 2, weight 46: (18×41 + 46×66 + 32) >> 6"); + assert_eq!(px[15], g(52), "subset 2's anchor, weight 27"); + assert_eq!((px[8], px[10], px[11]), (g(255), g(41), g(132))); + } + + #[test] + fn bc7_mode_1_shared_p_bits() { + // Partition 13: texels 0-7 subset 0, 8-15 subset 1 (anchor 15). Endpoints (6 bits + + // shared P-bit): 63+1 → 255, 0+1 → 2; 32+0 → 129, 16+0 → 64. + let idx = index_set(&[(1, 7), (8, 2), (15, 3)]); + let b = bc7_block(1, &[&[(13, 6)], &grey(&[63, 0, 32, 16], 6)[..], &each(&[1, 0], 1), &texel_indices(idx, 3, &[0, 15])].concat()); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!((px[0], px[1], px[2]), (g(255), g(2), g(255))); + assert_eq!(px[8], g(111), "weight 18: (46×129 + 18×64 + 32) >> 6"); + assert_eq!(px[15], g(102), "anchor, weight 27"); + assert_eq!(px[9], g(129)); + } + + #[test] + fn bc7_mode_2_matches_the_specifications_example() { + // Partition 6 of three subsets: rows 0022 / 0022 / 1111 / 1111; anchors 0, 15 and 3 (the + // specification's worked example: texel 9 is subset 1, its index at bits 115-116). + // Endpoints (5 bits): 31 → 255, 0, 10 → 82, 20 → 165, 1 → 8, 30 → 247. + let idx = index_set(&[(0, 1), (2, 2), (3, 1), (9, 3), (15, 1)]); + let b = bc7_block(2, &[&[(6, 6)], &grey(&[31, 0, 10, 20, 1, 30], 5)[..], &texel_indices(idx, 2, &[0, 15, 3])].concat()); + assert_eq!(u128::from_le_bytes(b) >> 115 & 3, 3, "texel 9's index where the specification says"); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!(px[0], g(171), "weight 21: (43×255 + 32) >> 6"); + assert_eq!(px[2], g(169), "subset 2, weight 43: (21×8 + 43×247 + 32) >> 6"); + assert_eq!(px[3], g(86), "subset 2's anchor, weight 21"); + assert_eq!(px[9], g(165)); + assert_eq!(px[15], g(109), "subset 1's anchor, weight 21: (43×82 + 21×165 + 32) >> 6"); + assert_eq!((px[1], px[8], px[6]), (g(255), g(82), g(8))); + } + + #[test] + fn bc7_mode_3_seven_bit_endpoints() { + // Partition 0: columns 2-3 are subset 1 (anchor 15). Endpoints (7 bits + P-bit): + // 100+1 → 201, 10+0 → 20, 127+1 → 255, 0+0 → 0. + let idx = index_set(&[(0, 1), (1, 2), (2, 3), (15, 1)]); + let b = bc7_block(3, &[&[(0, 6)], &grey(&[100, 10, 127, 0], 7)[..], &each(&[1, 0, 1, 0], 1), &texel_indices(idx, 2, &[0, 15])].concat()); + let px = bc7(&b); + let g = |v: u8| [v, v, v, 255]; + assert_eq!(px[0], g(142), "weight 21: (43×201 + 21×20 + 32) >> 6"); + assert_eq!(px[1], g(79), "weight 43"); + assert_eq!(px[2], g(0)); + assert_eq!(px[15], g(171)); + assert_eq!((px[3], px[4]), (g(255), g(201))); + } + + #[test] + fn bc7_mode_4_rotation_and_index_selection() { + // Rotation 1 swaps alpha and red; the selection bit takes colour from the 3-bit indices + // and alpha from the 2-bit ones. Red 31 → 255 to 0, green 0 to 255, blue 16 → 132, + // alpha (6 bits) 63 → 255 to 0. + let colour = index_set(&[(0, 3), (1, 7)]); + let alpha = index_set(&[(0, 1)]); + let ends = [each(&[31, 0, 0, 31, 16, 16], 5), each(&[63, 0], 6)].concat(); + let b = bc7_block(4, &[&[(1, 2), (1, 1)], &ends[..], &texel_indices(alpha, 2, &[0]), &texel_indices(colour, 3, &[0])].concat()); + let px = bc7(&b); + // Before the swap: red (37×255 + 32) >> 6 = 147, green 108, blue 132, alpha 171. + assert_eq!(px[0], [171, 108, 132, 147]); + assert_eq!(px[1], [255, 255, 132, 0]); + assert_eq!(px[2], [255, 0, 132, 255]); + } + + #[test] + fn bc7_mode_5_separate_alpha_indices() { + // Red 127 → 255 to 0, green 64 → 129, blue 0 to 255; alpha (8 bits) 200 to 100. + let colour = index_set(&[(0, 1), (5, 2)]); + let alpha = index_set(&[(0, 1), (5, 3)]); + let ends = [each(&[127, 0, 64, 64, 0, 127], 7), each(&[200, 100], 8)].concat(); + let b = bc7_block(5, &[&[(0, 2)], &ends[..], &texel_indices(colour, 2, &[0]), &texel_indices(alpha, 2, &[0])].concat()); + let px = bc7(&b); + assert_eq!(px[0], [171, 129, 84, 167], "weight 21 for colour and alpha: (43×200 + 21×100 + 32) >> 6"); + assert_eq!(px[5], [84, 129, 171, 100]); + assert_eq!(px[1], [255, 129, 0, 200]); + } + + #[test] + fn bc7_mode_6_four_bit_indices() { + // Endpoints (7 bits + P-bit) in every channel: [255, 1, 129, 255] and [0, 254, 64, 100]. + let idx = index_set(&[(0, 7), (1, 15), (2, 8)]); + let ends = each(&[127, 0, 0, 127, 64, 32, 127, 50], 7); + let b = bc7_block(6, &[&ends[..], &each(&[1, 0], 1), &texel_indices(idx, 4, &[0])].concat()); + let px = bc7(&b); + assert_eq!(px[0], [135, 120, 99, 182], "the anchor's largest index, 7: weight 30"); + assert_eq!(px[1], [0, 254, 64, 100]); + assert_eq!(px[2], [120, 135, 94, 173], "weight 34: red (30×255 + 32) >> 6"); + assert_eq!(px[3], [255, 1, 129, 255]); + } + + #[test] + fn bc7_mode_7_two_subsets_with_alpha() { + // Partition 1: column 3 is subset 1 (anchor 15). Endpoints (5 bits + P-bit): + // [255; 4], [0; 4], [130, 0, 0, 251], [4, 134, 69, 4]. + let idx = index_set(&[(0, 1), (3, 3), (15, 1)]); + let ends = [each(&[31, 0, 16, 0], 5), each(&[31, 0, 0, 16], 5), each(&[31, 0, 0, 8], 5), each(&[31, 0, 31, 0], 5)].concat(); + let b = bc7_block(7, &[&[(1, 6)], &ends[..], &each(&[1, 0, 0, 1], 1), &texel_indices(idx, 2, &[0, 15])].concat()); + let px = bc7(&b); + assert_eq!(px[0], [171; 4]); + assert_eq!(px[3], [4, 134, 69, 4]); + assert_eq!(px[15], [89, 44, 23, 170], "weight 21: red (43×130 + 21×4 + 32) >> 6"); + assert_eq!((px[7], px[1]), ([130, 0, 0, 251], [255; 4])); + } + + #[test] + fn bc7_reserved_block_is_all_zero() { + assert_eq!(bc7(&[0; 16]), [[0; 4]; 16]); + } + + /// A BC6H block of mode `id`: `values` by field (missing ones are 0), then the indices. + fn bc6h_block(id: u8, values: &[(u8, i32)], index: [u32; 16]) -> [u8; 16] { + let mode = BC6H_MODES.iter().find(|m| m.id == id).unwrap(); + let value = |f: u8| values.iter().find(|(g, _)| *g == f).map_or(0, |(_, v)| *v); + let mut fields = vec![(u32::from(id), if id < 2 { 2 } else { 5 })]; + for &(f, a, b) in mode.fields { + for k in 0..=a.abs_diff(b) { + let bit = if a >= b { b + k } else { b - k }; + fields.push(((value(f) >> bit) as u32 & 1, 1)); + } + } + let bits = if mode.subsets == 2 { 3 } else { 4 }; + let partition = value(PB) as usize; + for (i, x) in index.iter().enumerate() { + fields.push((*x, bits - u32::from(super::anchor(mode.subsets, partition, i)))); + } + pack(&fields) + } + + /// The same endpoints for every mode: the first is (largest, 0, middle); the others are small + /// differences from it (or, without transformed endpoints, values near it). Two-subset modes + /// use partition 13 (texels 8-15 are subset 1); indices pick each endpoint and two blends. + fn bc6h_case(id: u8) -> ([u8; 16], Vec) { + let mode = BC6H_MODES.iter().find(|m| m.id == id).unwrap(); + let (max, mid, d) = ((1 << mode.endpoint_bits) - 1, 1 << (mode.endpoint_bits - 1), mode.delta_bits); + let mut v = vec![(R0, max), (G0, 0), (B0, mid)]; + if mode.transformed { + v.extend([(R1, -1), (G1, 1), (B1, 0)]); + } else { + v.extend([(R1, max - 1), (G1, 1), (B1, mid)]); + } + match (mode.transformed, mode.subsets) { + (true, 2) => v.extend([(R2, 0), (G2, 2), (B2, -2), (R3, -(1 << (d[0] - 1))), (G3, 0), (B3, 1), (PB, 13)]), + (false, 2) => v.extend([(R2, max), (G2, 2), (B2, mid - 2), (R3, 0), (G3, max), (B3, mid + 1), (PB, 13)]), + _ => {} + } + if mode.subsets == 2 { + (bc6h_block(id, &v, index_set(&[(1, 7), (8, 7), (2, 4), (9, 3)])), vec![0, 1, 2, 8, 9, 15]) + } else { + (bc6h_block(id, &v, index_set(&[(1, 15), (2, 8)])), vec![0, 1, 2]) + } + } + + // Half-float results for `bc6h_case`, from a separate decoder written from the specification's + // pseudocode. By hand, for mode 3's first texel: red is the largest 10-bit value → 0xffff → + // (0xffff × 31) >> 6 = 0x7bff (65504); blue 512 → ((512 << 15) + 0x4000) >> 9 = 32800 → + // (32800 × 31) >> 6 = 0x3e0f. Signed, red is -1 → -96 → 0x805d and blue -512 → -0x7fff → 0xfbff. + + const UNSIGNED: [(u8, &[[u16; 3]]); 14] = [ + ( + 0, + &[ + [0x7bff, 0x0000, 0x3e0f], + [0x7bd1, 0x002e, 0x3e0f], + [0x7be4, 0x001b, 0x3e0f], + [0x7a00, 0x0000, 0x3e2e], + [0x7b27, 0x002d, 0x3df8], + [0x7bff, 0x004d, 0x3dd1], + ], + ), + ( + 1, + &[ + [0x7bff, 0x0000, 0x3e7c], + [0x7a8c, 0x0174, 0x3e7c], + [0x7b28, 0x00d7, 0x3e7c], + [0x5c84, 0x0000, 0x3f74], + [0x6eb7, 0x0166, 0x3dc5], + [0x7bff, 0x026c, 0x3c8c], + ], + ), + ( + 2, + &[ + [0x7bff, 0x0000, 0x3e07], + [0x7be8, 0x0017, 0x3e07], + [0x7bf2, 0x000d, 0x3e07], + [0x7b00, 0x0000, 0x3e17], + [0x7b93, 0x0016, 0x3dfc], + [0x7bff, 0x0026, 0x3de8], + ], + ), + ( + 6, + &[ + [0x7bff, 0x0000, 0x3e07], + [0x7be8, 0x0017, 0x3e07], + [0x7bf2, 0x000d, 0x3e07], + [0x7b7c, 0x0000, 0x3e17], + [0x7bc8, 0x0016, 0x3dfc], + [0x7bff, 0x0026, 0x3de8], + ], + ), + ( + 10, + &[ + [0x7bff, 0x0000, 0x3e07], + [0x7be8, 0x0017, 0x3e07], + [0x7bf2, 0x000d, 0x3e07], + [0x7b7c, 0x0000, 0x3e17], + [0x7bc8, 0x0016, 0x3dfc], + [0x7bff, 0x0026, 0x3de8], + ], + ), + ( + 14, + &[ + [0x7bff, 0x0000, 0x3e1f], + [0x7ba3, 0x005d, 0x3e1f], + [0x7bca, 0x0035, 0x3e1f], + [0x7801, 0x0000, 0x3e5d], + [0x7a4f, 0x0059, 0x3df1], + [0x7bff, 0x009b, 0x3da3], + ], + ), + ( + 18, + &[ + [0x7bff, 0x0000, 0x3e3e], + [0x7b46, 0x00ba, 0x3e3e], + [0x7b94, 0x006b, 0x3e3e], + [0x6c42, 0x0000, 0x3eba], + [0x755b, 0x00b3, 0x3de2], + [0x7bff, 0x0136, 0x3d46], + ], + ), + ( + 22, + &[ + [0x7bff, 0x0000, 0x3e3e], + [0x7b46, 0x00ba, 0x3e3e], + [0x7b94, 0x006b, 0x3e3e], + [0x7402, 0x0000, 0x3eba], + [0x78a0, 0x00b3, 0x3de2], + [0x7bff, 0x0136, 0x3d46], + ], + ), + ( + 26, + &[ + [0x7bff, 0x0000, 0x3e3e], + [0x7b46, 0x00ba, 0x3e3e], + [0x7b94, 0x006b, 0x3e3e], + [0x7402, 0x0000, 0x3eba], + [0x78a0, 0x00b3, 0x3de2], + [0x7bff, 0x0136, 0x3d46], + ], + ), + ( + 30, + &[ + [0x7bff, 0x0000, 0x3ef8], + [0x7918, 0x02e8, 0x3ef8], + [0x7a51, 0x01ae, 0x3ef8], + [0x0000, 0x7bff, 0x40e8], + [0x47af, 0x371c, 0x3d8b], + [0x7bff, 0x04d8, 0x3b18], + ], + ), + (3, &[[0x7bff, 0x0000, 0x3e0f], [0x7bd1, 0x002e, 0x3e0f], [0x7be7, 0x0018, 0x3e0f]]), + (7, &[[0x7bff, 0x0000, 0x3e07], [0x7be8, 0x0017, 0x3e07], [0x7bf3, 0x000c, 0x3e07]]), + (11, &[[0x7bff, 0x0000, 0x3e03], [0x7bf4, 0x000b, 0x3e03], [0x7bf9, 0x0006, 0x3e03]]), + (15, &[[0x7bff, 0x0000, 0x3e00], [0x7bff, 0x0000, 0x3e00], [0x7bff, 0x0000, 0x3e00]]), + ]; + const SIGNED: [(u8, &[[u16; 3]]); 14] = [ + ( + 0, + &[ + [0x805d, 0x0000, 0xfbff], + [0x809b, 0x005d, 0xfbff], + [0x8080, 0x0036, 0xfbff], + [0x843d, 0x0000, 0xfbff], + [0x81ff, 0x005a, 0x132a], + [0x805d, 0x009b, 0x7ba3], + ], + ), + ( + 1, + &[ + [0x82e8, 0x0000, 0xfbff], + [0x84d8, 0x02e8, 0xfbff], + [0x8406, 0x01ae, 0xfbff], + [0xc0e8, 0x0000, 0xfbff], + [0x9d10, 0x02cc, 0x11b1], + [0x82e8, 0x04d8, 0x7918], + ], + ), + ( + 2, + &[ + [0x802e, 0x0000, 0xfbff], + [0x804d, 0x002e, 0xfbff], + [0x803f, 0x001b, 0xfbff], + [0x821e, 0x0000, 0xfbff], + [0x80ff, 0x002c, 0x1345], + [0x802e, 0x004d, 0x7bd1], + ], + ), + ( + 6, + &[ + [0x802e, 0x0000, 0xfbff], + [0x804d, 0x002e, 0xfbff], + [0x803f, 0x001b, 0xfbff], + [0x8126, 0x0000, 0xfbff], + [0x8097, 0x002c, 0x1345], + [0x802e, 0x004d, 0x7bd1], + ], + ), + ( + 10, + &[ + [0x802e, 0x0000, 0xfbff], + [0x804d, 0x002e, 0xfbff], + [0x803f, 0x001b, 0xfbff], + [0x8126, 0x0000, 0xfbff], + [0x8097, 0x002c, 0x1345], + [0x802e, 0x004d, 0x7bd1], + ], + ), + ( + 14, + &[ + [0x80ba, 0x0000, 0xfbff], + [0x8136, 0x00ba, 0xfbff], + [0x8101, 0x006b, 0xfbff], + [0x887a, 0x0000, 0xfbff], + [0x83ff, 0x00b3, 0x12f4], + [0x80ba, 0x0136, 0x7b46], + ], + ), + ( + 18, + &[ + [0x8174, 0x0000, 0xfbff], + [0x826c, 0x0174, 0xfbff], + [0x8203, 0x00d7, 0xfbff], + [0xa074, 0x0000, 0xfbff], + [0x8e88, 0x0166, 0x1288], + [0x8174, 0x026c, 0x7a8c], + ], + ), + ( + 22, + &[ + [0x8174, 0x0000, 0xfbff], + [0x826c, 0x0174, 0xfbff], + [0x8203, 0x00d7, 0xfbff], + [0x90f4, 0x0000, 0xfbff], + [0x87fe, 0x0166, 0x1288], + [0x8174, 0x026c, 0x7a8c], + ], + ), + ( + 26, + &[ + [0x8174, 0x0000, 0xfbff], + [0x826c, 0x0174, 0xfbff], + [0x8203, 0x00d7, 0xfbff], + [0x90f4, 0x0000, 0xfbff], + [0x87fe, 0x0166, 0x1288], + [0x8174, 0x026c, 0x7a8c], + ], + ), + ( + 30, + &[ + [0x85d0, 0x0000, 0xfbff], + [0x89b0, 0x05d0, 0xfbff], + [0x880d, 0x035c, 0xfbff], + [0x0000, 0x85d0, 0xfbff], + [0x835c, 0x0326, 0x1003], + [0x85d0, 0x09b0, 0x7630], + ], + ), + (3, &[[0x805d, 0x0000, 0xfbff], [0x809b, 0x005d, 0xfbff], [0x807d, 0x0031, 0xfbff]]), + (7, &[[0x802e, 0x0000, 0xfbff], [0x804d, 0x002e, 0xfbff], [0x803e, 0x0019, 0xfbff]]), + (11, &[[0x8017, 0x0000, 0xfbff], [0x8026, 0x0017, 0xfbff], [0x801f, 0x000c, 0xfbff]]), + (15, &[[0x8000, 0x0000, 0xfc00], [0x8001, 0x0000, 0xfc00], [0x8001, 0x0000, 0xfc00]]), + ]; + + #[test] + fn bc6h_every_mode_unsigned_and_signed() { + for (signed, expected) in [(false, &UNSIGNED), (true, &SIGNED)] { + for (id, want) in expected { + let (block, texels) = bc6h_case(*id); + let got = bc6h_halves(&block, signed); + let got: Vec<[u16; 3]> = texels.iter().map(|t| got[*t]).collect(); + assert_eq!(&got[..], *want, "mode {id}, signed {signed}"); + } + } + // Reserved modes (19, 23, 27, 31) are black. + for id in [19u32, 23, 27, 31] { + assert_eq!(bc6h_halves(&pack(&[(id, 5), (0, 123)]), false), [[0; 3]; 16]); + } + } + + #[test] + fn bc6h_tone_maps_to_srgb() { + assert_eq!([0x0000, 0x3800, 0x3c00, 0x7bff, 0xfc00, 0xbc00, 0x0001].map(|h| srgb8(half(h))), [0, 188, 255, 255, 0, 0, 0]); + assert_eq!(half(0x3555), 0.333_251_95, "a normal half: (1024 + 0x155) × 2^(13 - 25)"); + assert_eq!(half(0x0200), 2f32.powi(-15), "a subnormal half"); + // Mode 3's first texel: red 65504 and blue 1.5 clip to white, green is 0. + assert_eq!(bc6h(&bc6h_case(3).0, false)[0], [255, 0, 255, 255]); + } + + #[test] + fn any_block_decodes_without_panicking() { + let mut x = 0x9e37_79b9_7f4a_7c15u128 << 64 | 0x2545_f491_4f6c_dd1d; + for _ in 0..20_000 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + let b = x.to_le_bytes(); + let _ = (bc7(&b), bc6h(&b, false), bc6h(&b, true)); + } + } +} diff --git a/crates/dds/src/eac.rs b/crates/dds/src/eac.rs new file mode 100644 index 0000000000..fe523c90e2 --- /dev/null +++ b/crates/dds/src/eac.rs @@ -0,0 +1,107 @@ +//! ETC1 and EAC 4×4 block decoders. +//! +//! EAC's 11-bit channel blocks are reduced to display bytes after reconstruction and clamping. +//! The signed layouts map -1..1 to 0..255 so negative values remain visible; zero is 128. +//! Layout and modifier tables: . + +// Positive halves of the Khronos EAC modifier tables. Negative entries are -positive - 1. +const MODIFIERS: [[i16; 4]; 16] = [ + [2, 5, 8, 14], + [2, 6, 9, 12], + [1, 4, 7, 12], + [1, 3, 5, 12], + [2, 5, 7, 11], + [2, 6, 8, 10], + [3, 6, 7, 10], + [2, 4, 7, 10], + [1, 5, 7, 9], + [1, 4, 7, 9], + [1, 3, 7, 9], + [1, 4, 6, 9], + [2, 3, 6, 9], + [0, 1, 2, 9], + [3, 5, 7, 8], + [2, 4, 6, 8], +]; + +fn split_halves(block: &[u8; 16]) -> ([u8; 8], [u8; 8]) { + let mut first = [0u8; 8]; + let mut second = [0u8; 8]; + for (i, x) in block.iter().enumerate() { + if i < 8 { + first[i] = *x; + } else { + second[i - 8] = *x; + } + } + (first, second) +} + +/// ETC1 uses big-endian blocks and column-major selector bits, independently of the split. +/// Differential bases outside RGB555 are undefined by the format and are refused. +pub(crate) fn etc1(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> { + const ETC1_MODIFIERS: [[i16; 2]; 8] = [[2, 8], [5, 17], [9, 29], [13, 42], [18, 60], [24, 80], [33, 106], [47, 183]]; + let bits = u64::from_be_bytes(*block); + let differential = bits & (1 << 33) != 0; + let horizontal = bits & (1 << 32) != 0; + let mut bases = [[0i16; 3]; 2]; + for (channel, shift) in [56, 48, 40].into_iter().enumerate() { + let value = ((bits >> shift) & 255) as i16; + let (first, second) = if differential { + let first = value >> 3; + let delta = ((value & 7) ^ 4) - 4; + let second = first + delta; + if !(0..=31).contains(&second) { + return None; + } + ((first << 3) | (first >> 2), (second << 3) | (second >> 2)) + } else { + ((value >> 4) * 17, (value & 15) * 17) + }; + bases[0][channel] = first; + bases[1][channel] = second; + } + let first_table = ETC1_MODIFIERS.get(((bits >> 37) & 7) as usize)?; + let second_table = ETC1_MODIFIERS.get(((bits >> 34) & 7) as usize)?; + Some(std::array::from_fn(|pixel| { + let (x, y) = (pixel % 4, pixel / 4); + let second = if horizontal { y >= 2 } else { x >= 2 }; + let (base, table) = if second { (bases[1], second_table) } else { (bases[0], first_table) }; + let selector = x * 4 + y; + let magnitude = if bits & (1 << selector) == 0 { table[0] } else { table[1] }; + let delta = if bits & (1 << (selector + 16)) == 0 { magnitude } else { -magnitude }; + let rgb = base.map(|channel| (channel + delta).clamp(0, 255) as u8); + [rgb[0], rgb[1], rgb[2], 255] + })) +} + +fn channel(block: &[u8; 8], signed: bool) -> [u8; 16] { + let bits = u64::from_be_bytes(*block); + let base = if signed { i16::from((block[0] as i8).max(-127)) * 8 } else { i16::from(block[0]) * 8 + 4 }; + let scale = (i16::from(block[1] >> 4) * 8).max(1); + let table = MODIFIERS.get(usize::from(block[1] & 15)).copied().unwrap_or_default(); + std::array::from_fn(|pixel| { + let (x, y) = (pixel % 4, pixel / 4); + let selector = ((bits >> (45 - 3 * (x * 4 + y))) & 7) as usize; + let magnitude = table.get(selector & 3).copied().unwrap_or_default(); + let modifier = if selector < 4 { -magnitude - 1 } else { magnitude }; + let value = base + modifier * scale; + if signed { + let value = u32::try_from(value.clamp(-1023, 1023) + 1023).unwrap_or_default(); + ((value * 255 + 1023) / 2046) as u8 + } else { + let value = u32::try_from(value.clamp(0, 2047)).unwrap_or_default(); + ((value * 255 + 1023) / 2047) as u8 + } + }) +} + +pub(crate) fn scalar(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] { + channel(block, signed).map(|value| [value, value, value, 255]) +} + +pub(crate) fn dual(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + let (red, green) = split_halves(block); + let (red, green) = (channel(&red, signed), channel(&green, signed)); + std::array::from_fn(|pixel| [red[pixel], green[pixel], 0, 255]) +} diff --git a/crates/dds/src/lib.rs b/crates/dds/src/lib.rs index 4eb8ff9947..354067f265 100644 --- a/crates/dds/src/lib.rs +++ b/crates/dds/src/lib.rs @@ -39,6 +39,10 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod bc; +pub mod bptc; +mod eac; +mod packed; +pub mod pixels; use std::borrow::Cow; use std::fmt; @@ -84,6 +88,8 @@ pub enum DdsError { Alloc(usize), /// The decoded output exceeds the caller-selected per-buffer byte limit. LimitExceeded { required: usize, limit: u64 }, + /// Input pixel data ended before the declared dimensions or block count. + Truncated(String), } impl fmt::Display for DdsError { @@ -94,6 +100,7 @@ impl fmt::Display for DdsError { DdsError::Encode(reason) => write!(f, "DDS encode failed: {reason}"), DdsError::Alloc(len) => write!(f, "cannot allocate {len} bytes for the texture"), DdsError::LimitExceeded { required, limit } => write!(f, "decoded texture requires {required} bytes, exceeding limit {limit}"), + DdsError::Truncated(reason) => write!(f, "truncated pixel data: {reason}"), } } } diff --git a/crates/dds/src/packed.rs b/crates/dds/src/packed.rs new file mode 100644 index 0000000000..6434a6e3ca --- /dev/null +++ b/crates/dds/src/packed.rs @@ -0,0 +1,51 @@ +//! Four-byte packed RGB layouts. Words are little-endian, with red in the low bits. +//! Unsigned floats: , sections 10.2 and 10.3. + +use crate::bptc; + +pub(crate) fn rgba1010102(bytes: &[u8; 4]) -> [u8; 4] { + let word = u32::from_le_bytes(*bytes); + let channel = |shift: u32| (((word >> shift) & 1023) * 255 + 511) / 1023; + [channel(0) as u8, channel(10) as u8, channel(20) as u8, (word >> 30) as u8 * 85] +} + +// These unsigned formats share binary16's five-bit exponent and bias. Padding the +// six- or five-bit fraction with zeroes produces the same value in a positive half. +fn unsigned_float(bits: u16, padding: u32) -> f32 { + bptc::half(bits << padding) +} + +pub(crate) fn rgb111110(bytes: &[u8; 4]) -> [u8; 4] { + let word = u32::from_le_bytes(*bytes); + let channel = |shift: u32, mask: u32, padding: u32| bptc::srgb8(unsigned_float(((word >> shift) & mask) as u16, padding)); + [channel(0, 0x7ff, 4), channel(11, 0x7ff, 4), channel(22, 0x3ff, 5), 255] +} + +pub(crate) fn rgb9e5(bytes: &[u8; 4]) -> [u8; 4] { + let packed = u32::from_le_bytes(*bytes); + let scale = 2.0f32.powi((packed >> 27) as i32 - 24); + let channel = |shift: u32| bptc::srgb8(((packed >> shift) & 0x1ff) as f32 * scale); + [channel(0), channel(9), channel(18), 255] +} + +#[cfg(test)] +mod tests { + use super::unsigned_float; + + #[test] + fn unsigned_float_boundaries_are_preserved_before_display_quantization() { + for (fraction_bits, padding, smallest, largest_subnormal, maximum) in + [(6, 4, 0x3580_0000, 0x387c_0000, 65024.0), (5, 5, 0x3600_0000, 0x3878_0000, 64512.0)] + { + let fractions = 1u16 << fraction_bits; + assert_eq!(unsigned_float(0, padding).to_bits(), 0); + assert_eq!(unsigned_float(1, padding).to_bits(), smallest); + assert_eq!(unsigned_float(fractions - 1, padding).to_bits(), largest_subnormal); + assert_eq!(unsigned_float(fractions, padding).to_bits(), 0x3880_0000); + assert_eq!(unsigned_float(31 * fractions - 1, padding), maximum); + assert_eq!(unsigned_float(31 * fractions, padding), f32::INFINITY); + assert!(unsigned_float(31 * fractions + 1, padding).is_nan()); + assert!(unsigned_float(32 * fractions - 1, padding).is_nan()); + } + } +} diff --git a/crates/dds/src/pixels.rs b/crates/dds/src/pixels.rs new file mode 100644 index 0000000000..8d39339112 --- /dev/null +++ b/crates/dds/src/pixels.rs @@ -0,0 +1,390 @@ +//! Turning GPU textures' stored pixels into RGBA: uncompressed layouts, packed 32-bit layouts, +//! and 4×4 block formats (BC1–BC7, ETC1, and EAC). Rows come out in the order they're stored. + +use crate::{DdsError, alloc_zeroed, bc, bptc, eac, packed, with_alpha}; + +/// Default RGBA output budget: 256 MiB, matching an 8192×8192 RGBA8 texture. +pub const DEFAULT_MAX_RGBA_BYTES: u64 = 256 << 20; + +/// How a texture's pixels are laid out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PixelLayout { + /// Alpha only (shown as white with that alpha). + Alpha8, + /// One grey channel. + R8, + /// One unsigned 16-bit channel, shown as grey. + R16, + /// Two unsigned 8-bit channels; blue is zero and alpha is opaque. + Rg8, + /// Two unsigned 16-bit channels; blue is zero and alpha is opaque. + Rg16, + /// Three unsigned 16-bit channels; alpha is opaque. + Rgb16, + /// Four unsigned 16-bit channels, including alpha. + Rgba16, + RHalf, + RgHalf, + RgbaHalf, + RFloat, + RgFloat, + RgbaFloat, + /// Nine-bit RGB mantissas with a shared five-bit exponent, displayed as opaque sRGB. + Rgb9e5, + /// Packed unsigned 10-bit RGB with two-bit alpha, low bits first. + Rgba1010102, + /// Packed unsigned 11/11/10-bit floating-point RGB, displayed as opaque sRGB. + Rgb111110Float, + Rgb24, + Rgba32, + Argb32, + Bgra32, + Rgb565, + Rgba4444, + Argb4444, + /// BC1 / DXT1. + Dxt1, + /// BC2 / DXT3: four-colour blocks with one explicit four-bit alpha value per texel. + Dxt3, + /// BC3 / DXT5. + Dxt5, + /// One channel in blocks (shown as grey). + Bc4, + /// Two channels in blocks, usually a normal map (blue is rebuilt from red and green). + Bc5, + /// High dynamic range RGB in blocks (unsigned half floats), tone-mapped to 8-bit sRGB. + Bc6h, + /// BC6H with signed half floats. + Bc6hSigned, + Bc7, + /// ETC1 RGB, with individual or differential base colours. + Etc1, + /// One EAC channel, shown as grey. + EacR, + /// One signed EAC channel; -1..1 maps to 0..255. + EacRSigned, + /// Two EAC channels; blue is zero and alpha is opaque. + EacRg, + /// Two signed EAC channels; -1..1 maps to 0..255. + EacRgSigned, +} + +/// Bytes of a `width`×`height` picture in `layout`. +pub fn size(layout: PixelLayout, width: u32, height: u32) -> Option { + let (w, h) = (width as usize, height as usize); + let blocks = w.div_ceil(4).checked_mul(h.div_ceil(4))?; + match layout { + PixelLayout::Alpha8 | PixelLayout::R8 => w.checked_mul(h), + PixelLayout::Rgb565 | PixelLayout::Rgba4444 | PixelLayout::Argb4444 | PixelLayout::RHalf | PixelLayout::R16 | PixelLayout::Rg8 => { + w.checked_mul(h)?.checked_mul(2) + } + PixelLayout::Rgb24 => w.checked_mul(h)?.checked_mul(3), + PixelLayout::Rg16 => w.checked_mul(h)?.checked_mul(4), + PixelLayout::Rgb16 => w.checked_mul(h)?.checked_mul(6), + PixelLayout::Rgba16 => w.checked_mul(h)?.checked_mul(8), + PixelLayout::Rgba32 + | PixelLayout::Argb32 + | PixelLayout::Bgra32 + | PixelLayout::RgHalf + | PixelLayout::RFloat + | PixelLayout::Rgb9e5 + | PixelLayout::Rgba1010102 + | PixelLayout::Rgb111110Float => w.checked_mul(h)?.checked_mul(4), + PixelLayout::RgbaHalf | PixelLayout::RgFloat => w.checked_mul(h)?.checked_mul(8), + PixelLayout::RgbaFloat => w.checked_mul(h)?.checked_mul(16), + PixelLayout::Dxt1 | PixelLayout::Bc4 | PixelLayout::Etc1 | PixelLayout::EacR | PixelLayout::EacRSigned => blocks.checked_mul(8), + PixelLayout::Dxt3 + | PixelLayout::Dxt5 + | PixelLayout::Bc5 + | PixelLayout::Bc6h + | PixelLayout::Bc6hSigned + | PixelLayout::Bc7 + | PixelLayout::EacRg + | PixelLayout::EacRgSigned => blocks.checked_mul(16), + } +} + +/// Convert an IEEE 754 binary16 half-float's bits to `f32`. +pub fn half_to_f32(h: u16) -> f32 { + bptc::half(h) +} + +/// Convert a linear-light value to 8-bit sRGB; 0..1 is kept, brighter and negative values clip. +pub fn linear_to_srgb8(v: f32) -> u8 { + bptc::srgb8(v) +} + +/// Decode one BC1 (DXT1) 8-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc1_block(block: &[u8; 8]) -> [[u8; 4]; 16] { + bc::decode_colour(block, true) +} + +/// Decode one BC2 (DXT3) 16-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc2_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_bc2_alpha(block.get(..8).unwrap_or_default())) +} + +/// Decode one BC3 (DXT5) 16-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc3_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_values(block.get(..8).unwrap_or_default())) +} + +/// Decode one BC4 8-byte block into 16 greyscale RGBA8 texels (`[r, r, r, 255]`, row by row). +pub fn decode_bc4_block(block: &[u8; 8]) -> [[u8; 4]; 16] { + bc::decode_values(block).map(|r| [r, r, r, 255]) +} + +/// Decode one BC5 16-byte normal-map block into 16 RGBA8 texels with reconstructed Z (row by row). +pub fn decode_bc5_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + let (r, g) = (bc::decode_values(block.get(..8).unwrap_or_default()), bc::decode_values(block.get(8..).unwrap_or_default())); + std::array::from_fn(|k| { + let (x, y) = (f32::from(r[k]) / 127.5 - 1.0, f32::from(g[k]) / 127.5 - 1.0); + let z = (1.0 - x * x - y * y).max(0.0).sqrt(); + [r[k], g[k], ((z + 1.0) * 127.5) as u8, 255] + }) +} + +/// Decode one BC6H 16-byte block into 16 sRGB8 RGBA texels (opaque). +pub fn decode_bc6h_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + bptc::bc6h(block, signed) +} + +/// Decode one BC7 16-byte block into 16 RGBA8 texels (row by row). +pub fn decode_bc7_block(block: &[u8; 16]) -> [[u8; 4]; 16] { + bptc::bc7(block) +} + +/// Decode one ETC1 8-byte block into 16 RGBA8 texels; returns `None` if differential colours overflow 5 bits. +pub fn decode_etc1_block(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> { + eac::etc1(block) +} + +/// Decode one single-channel EAC 8-byte block into 16 greyscale RGBA8 texels. +pub fn decode_eac_r_block(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] { + eac::scalar(block, signed) +} + +/// Decode one dual-channel EAC 16-byte block into 16 RGBA8 texels (blue 0, alpha 255). +pub fn decode_eac_rg_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] { + eac::dual(block, signed) +} + +/// Decode one little-endian `RGB9E5` 4-byte pixel into opaque sRGB8 RGBA. +pub fn decode_rgb9e5(bytes: &[u8; 4]) -> [u8; 4] { + packed::rgb9e5(bytes) +} + +/// Decode one little-endian `RGBA1010102` 4-byte pixel into RGBA8. +pub fn decode_rgba1010102(bytes: &[u8; 4]) -> [u8; 4] { + packed::rgba1010102(bytes) +} + +/// Decode one little-endian `R11G11B10_FLOAT` 4-byte pixel into opaque sRGB8 RGBA. +pub fn decode_rgb111110_float(bytes: &[u8; 4]) -> [u8; 4] { + packed::rgb111110(bytes) +} + +fn unorm8(value: u16) -> u8 { + ((u32::from(value) * 255 + 32767) / 65535) as u8 +} + +fn unorm16_pixels(samples: impl Iterator, channels: usize) -> impl Iterator { + let mut samples = samples.map(unorm8); + std::iter::from_fn(move || { + let (r, g) = (samples.next()?, samples.next()?); + let b = if channels > 2 { samples.next()? } else { 0 }; + let a = if channels > 3 { samples.next()? } else { 255 }; + Some([r, g, b, a]) + }) +} + +fn float_pixels(mut samples: impl Iterator, channels: usize) -> impl Iterator { + std::iter::from_fn(move || { + let r = bptc::srgb8(samples.next()?); + if channels == 1 { + return Some([r, r, r, 255]); + } + let g = bptc::srgb8(samples.next()?); + if channels == 2 { + return Some([r, g, 0, 255]); + } + let b = bptc::srgb8(samples.next()?); + let a = (samples.next()?.clamp(0.0, 1.0) * 255.0).round() as u8; + Some([r, g, b, a]) + }) +} + +fn expand5(v: u16) -> u8 { + let v = (v & 31) as u8; + (v << 3) | (v >> 2) +} + +fn expand6(v: u16) -> u8 { + let v = (v & 63) as u8; + (v << 2) | (v >> 4) +} + +fn rgb565(v: u16) -> [u8; 4] { + [expand5(v >> 11), expand6(v >> 5), expand5(v), 255] +} + +fn nibbles(v: u16, order: [u32; 4]) -> [u8; 4] { + order.map(|shift| ((v >> shift) & 15) as u8 * 17) +} + +fn place_blocks(out: &mut [u8], w: usize, h: usize, texels: impl Iterator) { + let across = w.div_ceil(4); + for (i, block) in texels.enumerate() { + let (bx, by) = (i % across, i / across); + for (k, p) in block.iter().enumerate() { + let (x, y) = (bx * 4 + k % 4, by * 4 + k / 4); + if x < w && y < h { + let at = (y * w + x) * 4; + if let Some(dst) = out.get_mut(at..at + 4) { + dst.copy_from_slice(p); + } + } + } + } +} + +/// Decode a `width`×`height` picture (`data` starts with it) into RGBA8, rows in stored order. +/// +/// Caps the output at [`DEFAULT_MAX_RGBA_BYTES`]; use [`decode_with_limit`] for a different budget. +pub fn decode(layout: PixelLayout, width: u32, height: u32, data: &[u8]) -> Result, DdsError> { + decode_with_limit(layout, width, height, data, DEFAULT_MAX_RGBA_BYTES) +} + +/// Decode into RGBA8, allowing at most `max_bytes` of output. +/// +/// The budget applies to RGBA bytes, not the encoded input, and is checked before reading pixels +/// or reserving the output. +pub fn decode_with_limit(layout: PixelLayout, width: u32, height: u32, data: &[u8], max_bytes: u64) -> Result, DdsError> { + let need = size(layout, width, height).ok_or(DdsError::Alloc(usize::MAX))?; + let (w, h) = (width as usize, height as usize); + let out_len = + w.checked_mul(h).and_then(|pixels| pixels.checked_mul(4)).filter(|bytes| *bytes <= isize::MAX as usize).ok_or(DdsError::Alloc(usize::MAX))?; + if out_len as u64 > max_bytes { + return Err(DdsError::LimitExceeded { required: out_len, limit: max_bytes }); + } + let data = data.get(..need).ok_or_else(|| DdsError::Truncated(format!("{} bytes of pixels, {need} needed", data.len())))?; + if w == 0 || h == 0 { + return Err(DdsError::Malformed("an empty picture".into())); + } + let mut out: Vec = alloc_zeroed(out_len)?; + let mut put = |px: &mut dyn Iterator| { + for (dst, p) in out.as_chunks_mut::<4>().0.iter_mut().zip(px) { + *dst = p; + } + }; + let u16s = data.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)); + let floats = data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)); + match layout { + PixelLayout::RHalf => put(&mut float_pixels(u16s.map(bptc::half), 1)), + PixelLayout::RgHalf => put(&mut float_pixels(u16s.map(bptc::half), 2)), + PixelLayout::RgbaHalf => put(&mut float_pixels(u16s.map(bptc::half), 4)), + PixelLayout::RFloat => put(&mut float_pixels(floats, 1)), + PixelLayout::RgFloat => put(&mut float_pixels(floats, 2)), + PixelLayout::RgbaFloat => put(&mut float_pixels(floats, 4)), + PixelLayout::Rgba1010102 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgba1010102)), + PixelLayout::Rgb111110Float => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb111110)), + PixelLayout::Rgb9e5 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb9e5)), + PixelLayout::Alpha8 => put(&mut data.iter().map(|a| [255, 255, 255, *a])), + PixelLayout::R8 => put(&mut data.iter().map(|r| [*r, *r, *r, 255])), + PixelLayout::R16 => put(&mut u16s.map(|value| { + let grey = unorm8(value); + [grey, grey, grey, 255] + })), + PixelLayout::Rg8 => put(&mut data.as_chunks::<2>().0.iter().map(|[r, g]| [*r, *g, 0, 255])), + PixelLayout::Rg16 => put(&mut unorm16_pixels(u16s, 2)), + PixelLayout::Rgb16 => put(&mut unorm16_pixels(u16s, 3)), + PixelLayout::Rgba16 => put(&mut unorm16_pixels(u16s, 4)), + PixelLayout::Rgb24 => put(&mut data.as_chunks::<3>().0.iter().map(|[r, g, b]| [*r, *g, *b, 255])), + PixelLayout::Rgba32 => put(&mut data.as_chunks::<4>().0.iter().copied()), + PixelLayout::Argb32 => put(&mut data.as_chunks::<4>().0.iter().map(|[a, r, g, b]| [*r, *g, *b, *a])), + PixelLayout::Bgra32 => put(&mut data.as_chunks::<4>().0.iter().map(|[b, g, r, a]| [*r, *g, *b, *a])), + PixelLayout::Rgb565 => put(&mut u16s.map(rgb565)), + PixelLayout::Rgba4444 => put(&mut u16s.map(|v| nibbles(v, [12, 8, 4, 0]))), + PixelLayout::Argb4444 => put(&mut u16s.map(|v| nibbles(v, [8, 4, 0, 12]))), + PixelLayout::Dxt1 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc1_block)), + PixelLayout::Dxt3 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc2_block)), + PixelLayout::Dxt5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc3_block)), + PixelLayout::Bc4 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc4_block)), + PixelLayout::Bc5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc5_block)), + PixelLayout::Bc6h => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, false))), + PixelLayout::Bc6hSigned => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, true))), + PixelLayout::Bc7 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(bptc::bc7)), + PixelLayout::EacR | PixelLayout::EacRSigned => { + place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(|block| eac::scalar(block, layout == PixelLayout::EacRSigned))) + } + PixelLayout::EacRg | PixelLayout::EacRgSigned => { + place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|block| eac::dual(block, layout == PixelLayout::EacRgSigned))) + } + PixelLayout::Etc1 => { + let mut valid = true; + let texels = data.as_chunks::<8>().0.iter().map_while(|block| { + let pixels = eac::etc1(block); + valid &= pixels.is_some(); + pixels + }); + place_blocks(&mut out, w, h, texels); + if !valid { + return Err(DdsError::Malformed("ETC1 differential colour is outside its five-bit range".into())); + } + } + } + Ok(out) +} + +/// Flip a `width`-wide RGBA8 picture upside down. +pub fn flip_rows(rgba: &[u8], width: u32) -> Vec { + let row = (width as usize).saturating_mul(4).max(1); + rgba.chunks(row).rev().flatten().copied().collect() +} + +#[cfg(test)] +mod tests { + use super::{PixelLayout, decode, decode_with_limit, flip_rows, size}; + use crate::DdsError; + + #[test] + fn uncompressed_and_swizzled_layouts() { + assert_eq!(decode(PixelLayout::Rgba32, 1, 2, &[1, 2, 3, 4, 5, 6, 7, 8]).unwrap(), [1, 2, 3, 4, 5, 6, 7, 8]); + assert_eq!(decode(PixelLayout::Argb32, 1, 1, &[9, 1, 2, 3]).unwrap(), [1, 2, 3, 9]); + assert_eq!(decode(PixelLayout::Bgra32, 1, 1, &[3, 2, 1, 9]).unwrap(), [1, 2, 3, 9]); + assert_eq!(decode(PixelLayout::Rgb24, 1, 1, &[1, 2, 3]).unwrap(), [1, 2, 3, 255]); + assert_eq!(decode(PixelLayout::Alpha8, 1, 1, &[7]).unwrap(), [255, 255, 255, 7]); + assert_eq!(decode(PixelLayout::R8, 1, 1, &[7]).unwrap(), [7, 7, 7, 255]); + assert_eq!(decode(PixelLayout::Rgb565, 1, 1, &0xf800u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]); + assert_eq!(decode(PixelLayout::Rgba4444, 1, 1, &0xf00fu16.to_le_bytes()).unwrap(), [255, 0, 0, 255]); + assert_eq!(decode(PixelLayout::Argb4444, 1, 1, &0xff00u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]); + assert_eq!(flip_rows(&[1, 1, 1, 1, 2, 2, 2, 2], 1), [2, 2, 2, 2, 1, 1, 1, 1]); + assert!(matches!(decode(PixelLayout::Rgba32, 2, 2, &[0; 15]), Err(DdsError::Truncated(_)))); + assert!(matches!(decode(PixelLayout::Rgba32, 0, 1, &[]), Err(DdsError::Malformed(_)))); + assert!(matches!(decode_with_limit(PixelLayout::R8, 2, 2, &[0; 4], 15), Err(DdsError::LimitExceeded { .. }))); + } + + #[test] + fn block_and_packed_layouts_crop_partial_blocks() { + assert_eq!(size(PixelLayout::Dxt1, 5, 5), Some(32)); + assert_eq!(decode(PixelLayout::Dxt1, 5, 5, &[0; 32]).unwrap().len(), 100); + // DXT1: colour 0 red, colour 1 blue; the first texel uses index 1, the rest index 0. + let px = decode(PixelLayout::Dxt1, 4, 4, &[0x00, 0xf8, 0x1f, 0x00, 0b01, 0, 0, 0]).unwrap(); + assert_eq!((&px[..4], &px[4..8]), (&[0, 0, 255, 255][..], &[255, 0, 0, 255][..])); + // DXT5: alpha 255 -> 0; first texel index 1 (0), rest index 0 (255). + let mut b = vec![255, 0, 1, 0, 0, 0, 0, 0]; + b.extend_from_slice(&[0x00, 0xf8, 0x1f, 0x00, 0, 0, 0, 0]); + let px = decode(PixelLayout::Dxt5, 4, 4, &b).unwrap(); + assert_eq!((px[3], px[7]), (0, 255)); + // BC4 & BC5. + assert_eq!(&decode(PixelLayout::Bc4, 4, 4, &[200, 10, 0, 0, 0, 0, 0, 0]).unwrap()[..4], &[200, 200, 200, 255]); + let mut n = vec![128, 128, 0, 0, 0, 0, 0, 0]; + n.extend_from_slice(&[128, 128, 0, 0, 0, 0, 0, 0]); + assert_eq!(&decode(PixelLayout::Bc5, 4, 4, &n).unwrap()[..4], &[128, 128, 254, 255]); + // Packed RGB9E5 & RGBA1010102. + let rgb9e5 = (256u32 | (128 << 9) | (64 << 18) | (15 << 27)).to_le_bytes(); + assert_eq!(decode(PixelLayout::Rgb9e5, 1, 1, &rgb9e5).unwrap(), [188, 137, 99, 255]); + let rgba10 = (1023u32 | (512 << 10) | (2 << 30)).to_le_bytes(); + assert_eq!(decode(PixelLayout::Rgba1010102, 1, 1, &rgba10).unwrap(), [255, 128, 0, 170]); + } +} diff --git a/crates/dds/tests/known_answers.rs b/crates/dds/tests/known_answers.rs new file mode 100644 index 0000000000..ce6e5e9f04 --- /dev/null +++ b/crates/dds/tests/known_answers.rs @@ -0,0 +1,114 @@ +//! Independent known-answer test vectors (raw bitstreams and hand-verified spec outputs) +//! for BC6H (unsigned/signed), BC7, ETC1, and EAC R/RG (unsigned/signed). + +use craft_dds::DdsError; +use craft_dds::pixels::{self, PixelLayout}; + +#[test] +fn bc7_mode6_known_bitstream() { + // Raw 128-bit BC7 Mode 6 block (7-bit RGBA endpoints + per-endpoint P-bits, 4-bit indices): + // e0 = (241, 121, 21, 255), e1 = (40, 200, 254, 128); texels 0..3 use indices 0, 15, 8, 4. + let block: [u8; 16] = [0x40, 0x3c, 0x85, 0x47, 0x56, 0xfc, 0xff, 0xc0, 0xf0, 0x48, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44]; + let texels = pixels::decode_bc7_block(&block); + assert_eq!(texels[0], [241, 121, 21, 255]); + assert_eq!(texels[1], [40, 200, 254, 128]); + assert_eq!(texels[2], [134, 163, 145, 188]); + assert_eq!(texels[3], [188, 142, 83, 221]); + + // Reserved mode (low byte 0x00) decodes to all zeroes. + assert_eq!(pixels::decode_bc7_block(&[0; 16]), [[0, 0, 0, 0]; 16]); + + // Cropped 3x2 image keeps the top-left 3x2 texels in row-major order. + let rgba = pixels::decode(PixelLayout::Bc7, 3, 2, &block).unwrap(); + assert_eq!(rgba.len(), 3 * 2 * 4); + assert_eq!(&rgba[..4], &[241, 121, 21, 255]); + assert_eq!(&rgba[4..8], &[40, 200, 254, 128]); + assert_eq!(&rgba[8..12], &[134, 163, 145, 188]); +} + +#[test] +fn bc6h_unsigned_and_signed_known_bitstreams() { + // Mode 11 (untransformed 10-bit endpoints, 1 subset, 4-bit indices): + // e0 = (480, 400, 200), e1 = (200, 480, 400); texels 0..2 use indices 0, 15, 8. + let block: [u8; 16] = [0x03, 0x3c, 0xc8, 0x90, 0x41, 0x06, 0x3c, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + + let unsigned = pixels::decode_bc6h_block(&block, false); + assert_eq!(unsigned[0], [228, 105, 7, 255]); + assert_eq!(unsigned[1], [7, 228, 105, 255]); + assert_eq!(unsigned[2], [51, 160, 39, 255]); + + let signed_pos = pixels::decode_bc6h_block(&block, true); + assert_eq!(signed_pos[0], [255, 255, 105, 255]); + assert_eq!(signed_pos[1], [105, 255, 255, 255]); + assert_eq!(signed_pos[2], [255, 255, 255, 255]); + + // Signed Mode 11 with negative 10-bit endpoints: R0 = -200 (0x338), G1 = -200 (0x338). + // Negative linear values clip to 0 in sRGB8 output. + let neg_block: [u8; 16] = [0x03, 0x67, 0x64, 0x20, 0x43, 0x06, 0x67, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + let signed_neg = pixels::decode_bc6h_block(&neg_block, true); + assert_eq!(signed_neg[0], [0, 105, 255, 255]); + assert_eq!(signed_neg[1], [105, 0, 255, 255]); + assert_eq!(signed_neg[2], [0, 0, 255, 255]); + + let rgba = pixels::decode(PixelLayout::Bc6h, 2, 1, &block).unwrap(); + assert_eq!(rgba, [228, 105, 7, 255, 7, 228, 105, 255]); + let rgba_signed = pixels::decode(PixelLayout::Bc6hSigned, 2, 1, &neg_block).unwrap(); + assert_eq!(rgba_signed, [0, 105, 255, 255, 105, 0, 255, 255]); +} + +#[test] +fn etc1_known_bitstreams_and_invalid_differential() { + // Individual mode (diff=0, flip=0): left half (x<2) RGB4=(15,0,8) + 2, right half (x>=2) RGB4=(0,15,4) + 5. + let individual: [u8; 8] = [0xf0, 0x0f, 0x84, 0x04, 0x00, 0x00, 0x00, 0x00]; + let texels = pixels::decode_etc1_block(&individual).unwrap(); + for y in 0..4 { + for x in 0..4 { + let expected = if x < 2 { [255, 2, 138, 255] } else { [5, 255, 73, 255] }; + assert_eq!(texels[y * 4 + x], expected); + } + } + + // Differential mode (diff=1, flip=1 horizontal): base0=(20,10,4), delta=(+2,-2,+1), tables=(2,3). + let differential: [u8; 8] = [0xa2, 0x56, 0x21, 0x4f, 0x00, 0x00, 0x00, 0x00]; + let texels = pixels::decode_etc1_block(&differential).unwrap(); + for y in 0..4 { + for x in 0..4 { + let expected = if y < 2 { [174, 91, 42, 255] } else { [194, 79, 54, 255] }; + assert_eq!(texels[y * 4 + x], expected); + } + } + + // Differential base + delta outside 0..=31 must be rejected. + let invalid: [u8; 8] = [0x04, 0x40, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00]; + assert!(pixels::decode_etc1_block(&invalid).is_none()); + assert!(matches!(pixels::decode(PixelLayout::Etc1, 4, 4, &invalid), Err(DdsError::Malformed(_)))); +} + +#[test] +fn eac_r_and_rg_unsigned_and_signed_known_bitstreams() { + // Unsigned EAC_R: base=100, mult=2, table=0, all selectors=7 (+14) -> 1028/2047 -> 128. + let eac_r_u: [u8; 8] = [0x64, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; + assert_eq!(pixels::decode_eac_r_block(&eac_r_u, false), [[128, 128, 128, 255]; 16]); + + // Signed EAC_R: base=-64 (0xc0), mult=2, table=0, all selectors=0 (-3) -> (-560+1023)/2046 -> 58. + let eac_r_s: [u8; 8] = [0xc0, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; + assert_eq!(pixels::decode_eac_r_block(&eac_r_s, true), [[58, 58, 58, 255]; 16]); + + // Column-major selector order: texel (x=1, y=0) has selector 7 (+14 -> 142), others selector 0 (-3 -> 125). + let eac_col: [u8; 8] = [0x80, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00]; + let col_texels = pixels::decode_eac_r_block(&eac_col, false); + assert_eq!(col_texels[1], [142, 142, 142, 255]); + assert_eq!(col_texels[0], [125, 125, 125, 255]); + assert_eq!(col_texels[4], [125, 125, 125, 255]); + + // Dual-channel EAC_RG (unsigned and signed): R then G. + let mut eac_rg_u = [0u8; 16]; + eac_rg_u[..8].copy_from_slice(&eac_r_u); + eac_rg_u[8..].copy_from_slice(&[0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); + assert_eq!(pixels::decode(PixelLayout::EacRg, 2, 2, &eac_rg_u).unwrap(), [128, 255, 0, 255].repeat(4)); + + let mut eac_rg_s = [0u8; 16]; + eac_rg_s[..8].copy_from_slice(&eac_r_s); + eac_rg_s[8..].copy_from_slice(&[0x7f, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]); + assert_eq!(pixels::decode(PixelLayout::EacRgSigned, 2, 2, &eac_rg_s).unwrap(), [58, 255, 0, 255].repeat(4)); +} From 1a3be2d4392e67723130ea297d67f5e3fe3df2d2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:23:11 -0500 Subject: [PATCH 70/79] craft-develop: extract ToneMap/CameraTone and pure-Rust finish helpers (#2471) * craft-develop: extract ToneMap/CameraTone and pure-Rust finish helpers * fix(develop): add serde_json dev-dependency for tone tests --- Cargo.lock | 1 + crates/develop/Cargo.toml | 1 + crates/develop/README.md | 2 + crates/develop/src/finish.rs | 235 ++++++++++++ crates/develop/src/lib.rs | 2 + crates/develop/src/tone.rs | 696 +++++++++++++++++++++++++++++++++++ 6 files changed, 937 insertions(+) create mode 100644 crates/develop/src/finish.rs create mode 100644 crates/develop/src/tone.rs diff --git a/Cargo.lock b/Cargo.lock index 90f18fada2..09cea4a312 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1799,6 +1799,7 @@ dependencies = [ "proptest", "rayon", "serde", + "serde_json", ] [[package]] diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml index bc859ea5f4..0ded6bc383 100644 --- a/crates/develop/Cargo.toml +++ b/crates/develop/Cargo.toml @@ -20,3 +20,4 @@ rayon = { workspace = true } [dev-dependencies] craft-render-parity = { workspace = true } proptest = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/develop/README.md b/crates/develop/README.md index 92f543eb31..561e408c18 100644 --- a/crates/develop/README.md +++ b/crates/develop/README.md @@ -14,7 +14,9 @@ craft-develop = { git = "https://github.com/storytold/craft-libs", rev = " f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// How much of the sharpening a pixel gets (`0..1`) under Masking `masking` (`0..1`), from its +/// fine detail `det` (log luminance minus its texture blur): `1` everywhere at `0`, only stronger +/// edges as it rises. +#[inline] +pub fn sharpen_mask_weight(masking: f32, det: f32) -> f32 { + if masking > 0.0 { smooth(masking * 0.25, masking * 0.25 + 0.15, det.abs()) } else { 1.0 } +} + +/// Masking weight for the V3 pixel-scale sharpening band, also used by its Alt-drag preview. +#[inline] +pub fn pixel_sharpen_mask_weight(masking: f32, det: f32) -> f32 { + if masking > 0.0 { smooth(masking * 0.1, masking * 0.1 + 0.06, det.abs()) } else { 1.0 } +} + +/// Gain of the sharpening detail term (per unit of `Amount / 150`), in stops of luminance per stop of detail. +pub const SHARPEN_GAIN: f32 = 7.0; + +/// Soft-clip limit (stops) of the sharpening detail term for Detail `0..=100`: `0.03` stops (large +/// edge detail is flattened so halos stay small) up to `1.5` stops (practically linear). +pub fn sharpen_limit(detail: f64) -> f32 { + let d = (detail / 100.0).clamp(0.0, 1.0) as f32; + 0.03 * 50f32.powf(d) +} + +/// The sharpening boost (stops) for pixel-scale detail `det` (log luminance minus its blur at the +/// sharpen radius): linear for small detail, soft-clipped at `limit`, and gated by the Masking edge +/// mask (`mask` = Masking / 100) so flat areas and noise can be left alone. +#[inline] +pub fn sharpen_term(det: f32, limit: f32, mask: f32) -> f32 { + let m = pixel_sharpen_mask_weight(mask, det); + SHARPEN_GAIN * m * det / (1.0 + det.abs() / limit) +} + +/// Vignette (post-crop) parameters. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Vig { + pub amount: f32, + pub start: f32, + pub width: f32, + pub aspect_mix: f32, + pub power: f32, + pub highlights: f32, + pub style: VignetteStyle, +} + +/// Resolve post-crop vignette parameters from `s`, returning `None` when `s.vignette.amount == 0.0`. +pub fn vignette(s: &DevelopSettings) -> Option { + let v = &s.vignette; + (v.amount != 0.0).then(|| { + let r = (v.roundness / 100.0) as f32; + Vig { + amount: (v.amount / 100.0) as f32, + start: 0.15 + (v.midpoint / 100.0) as f32 * 0.95, + width: 0.05 + (v.feather / 100.0) as f32 * 1.1, + aspect_mix: ((r + 1.0) / 2.0).clamp(0.0, 1.0), + power: if r >= 0.0 { 2.0 } else { 2.0 + (-r) * 6.0 }, + highlights: (v.highlights / 100.0) as f32, + style: v.style, + } + }) +} + +/// Hash constants of [`grain_noise`] (shared with the GPU kernel). +pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995]; + +/// The grain of processes V1 to V6: two octaves of value noise. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ValueGrain { + /// Amplitude (display-encoded). + pub amt: f32, + /// Noise cell size (output pixels). + pub cell: f32, + /// Roughness `0..1`: weight of the finer octave. + pub rough: f32, + pub seed: u32, +} + +/// Resolve [`ValueGrain`] parameters from `s` at `px_per_long` output pixels per long edge, +/// returning `None` when `s.grain.amount <= 0.0`. +pub fn value_grain(s: &DevelopSettings, px_per_long: f64) -> Option { + let g = &s.grain; + (g.amount > 0.0).then(|| { + let cell = (0.0006 + (g.size / 100.0) as f32 * 0.0024) * px_per_long as f32; + ValueGrain { amt: (g.amount / 100.0) as f32 * 0.13, cell: cell.max(0.6), rough: (g.roughness / 100.0) as f32, seed: g.seed } + }) +} + +/// Smooth value noise in `-1..1` at `(x, y)` for `seed`. Non-finite coordinates return `0.0`. +#[inline] +pub fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { + if !x.is_finite() || !y.is_finite() { + return 0.0; + } + let (x0, y0) = (x.floor(), y.floor()); + let (fx, fy) = (x - x0, y - y0); + let h = |i: i32, j: i32| { + let mut v = (i as u32).wrapping_mul(GRAIN_HASH[0]) ^ (j as u32).wrapping_mul(GRAIN_HASH[1]) ^ seed.wrapping_mul(GRAIN_HASH[2]); + v ^= v >> 13; + v = v.wrapping_mul(GRAIN_HASH[3]); + v ^= v >> 15; + (v & 0xffff) as f32 / 32768.0 - 1.0 + }; + let (i, j) = (x0 as i32, y0 as i32); + let (u, v) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy)); + let a = h(i, j) + (h(i + 1, j) - h(i, j)) * u; + let b = h(i, j + 1) + (h(i + 1, j + 1) - h(i, j + 1)) * u; + a + (b - a) * v +} + +/// A colour needing more desaturation than this (scale < `GAMUT_WARN`) to fit is out of gamut for +/// the gamut warnings (tolerates rounding at the gamut boundary). +pub const GAMUT_WARN: f32 = 0.995; + +/// Desaturate linear `r` towards its luminance (weights `luma`) until every channel is in `0..=1`; +/// returns the mapped colour and the chroma scale used (`1.0` = already in gamut). +#[inline] +pub fn gamut_map(r: [f32; 3], luma: [f32; 3]) -> ([f32; 3], f32) { + gamut_map_to(r, luma, 1.0) +} + +/// [`gamut_map`] into `0..=peak` (an HDR render's range; `peak = 1.0` is [`gamut_map`]). +#[inline] +pub fn gamut_map_to(r: [f32; 3], luma: [f32; 3], peak: f32) -> ([f32; 3], f32) { + let yy = (luma[0] * r[0] + luma[1] * r[1] + luma[2] * r[2]).clamp(0.0, peak); + let mut t = 1.0f32; + for c in r { + if c < 0.0 { + t = t.min(yy / (yy - c).max(1e-9)); + } else if c > peak { + t = t.min((peak - yy) / (c - yy).max(1e-9)); + } + } + if t < 1.0 { (r.map(|c| yy + (c - yy) * t), t) } else { (r, 1.0) } +} + +/// Refine Saturation: scale the curved colour's chroma (around its luma, encoded values) so its +/// saturation (chroma / luma) moves from the curve's towards the pre-curve one: the ratio is +/// `(s_curve / s_before)^refine`, so `1` keeps the curve and `0` restores the original saturation. +#[inline] +pub fn refine_saturation(before: [f32; 3], after: [f32; 3], refine: f32) -> [f32; 3] { + let luma = |e: [f32; 3]| 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]; + let chroma = |e: [f32; 3]| e[0].max(e[1]).max(e[2]) - e[0].min(e[1]).min(e[2]); + let (y0, y1) = (luma(before), luma(after)); + let s0 = chroma(before) / y0.max(1e-4); + let s1 = chroma(after) / y1.max(1e-4); + if s1 <= 1e-6 || s0 <= 1e-6 { + return after; + } + let k = (s0 / s1).powf(1.0 - refine).clamp(0.0, 4.0); + after.map(|v| y1 + (v - y1) * k) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sharpen_helpers_behave_smoothly_and_bound_detail() { + assert_eq!(sharpen_mask_weight(0.0, 0.0), 1.0); + assert_eq!(pixel_sharpen_mask_weight(0.0, 0.0), 1.0); + assert_eq!(sharpen_mask_weight(0.8, 0.0), 0.0); + assert!(sharpen_mask_weight(0.8, 1.0) == 1.0); + assert!((sharpen_limit(0.0) - 0.03).abs() < 1e-6); + assert!((sharpen_limit(100.0) - 1.5).abs() < 1e-4); + let lim = sharpen_limit(50.0); + assert!(sharpen_term(0.0, lim, 0.0) == 0.0); + assert!(sharpen_term(10.0, lim, 0.0) < SHARPEN_GAIN * lim); + assert!(sharpen_term(0.1, lim, 0.0) > 0.0); + } + + #[test] + fn vignette_resolves_only_when_nonzero() { + let mut s = DevelopSettings::default(); + assert!(vignette(&s).is_none()); + s.vignette.amount = -50.0; + s.vignette.roundness = -100.0; + let v = vignette(&s).unwrap(); + assert!((v.amount - -0.5).abs() < 1e-6); + assert!((v.power - 8.0).abs() < 1e-6); + assert!((v.aspect_mix - 0.0).abs() < 1e-6); + } + + #[test] + fn grain_is_bounded_and_handles_non_finite_coords() { + let mut s = DevelopSettings::default(); + assert!(value_grain(&s, 2000.0).is_none()); + s.grain.amount = 50.0; + s.grain.size = 25.0; + s.grain.roughness = 50.0; + let g = value_grain(&s, 2000.0).unwrap(); + assert!(g.amt > 0.0 && g.cell >= 0.6); + assert_eq!(grain_noise(f32::NAN, 1.0, 7), 0.0); + assert_eq!(grain_noise(1.0, f32::INFINITY, 7), 0.0); + for i in 0..20 { + let n = grain_noise(i as f32 * 0.37, i as f32 * 0.71, g.seed); + assert!((-1.0..=1.0).contains(&n), "{n}"); + } + } + + #[test] + fn gamut_map_clamps_out_of_gamut_towards_luma() { + let luma = [0.2126, 0.7152, 0.0722]; + let (in_gamut, t0) = gamut_map([0.2, 0.5, 0.8], luma); + assert_eq!(in_gamut, [0.2, 0.5, 0.8]); + assert_eq!(t0, 1.0); + + let (mapped, t1) = gamut_map([1.5, -0.2, 0.3], luma); + assert!(t1 < GAMUT_WARN); + assert!(mapped.iter().all(|&c| (-1e-6..=1.0 + 1e-6).contains(&c)), "{mapped:?}"); + + let (hdr, t2) = gamut_map_to([2.5, 0.5, 0.5], luma, 4.0); + assert_eq!(hdr, [2.5, 0.5, 0.5]); + assert_eq!(t2, 1.0); + } + + #[test] + fn refine_saturation_interpolates_between_original_and_curved() { + let before = [0.4, 0.2, 0.1]; + let after = [0.6, 0.3, 0.15]; + assert_eq!(refine_saturation(before, after, 1.0), after); + let neutral = refine_saturation([0.3, 0.3, 0.3], [0.5, 0.5, 0.5], 0.5); + assert_eq!(neutral, [0.5, 0.5, 0.5]); + } +} diff --git a/crates/develop/src/lib.rs b/crates/develop/src/lib.rs index da88b48c60..e3099235c2 100644 --- a/crates/develop/src/lib.rs +++ b/crates/develop/src/lib.rs @@ -5,5 +5,7 @@ pub mod color; pub mod curve; +pub mod finish; pub mod inpaint; pub mod lut; +pub mod tone; diff --git a/crates/develop/src/tone.rs b/crates/develop/src/tone.rs new file mode 100644 index 0000000000..0ff62fce4f --- /dev/null +++ b/crates/develop/src/tone.rs @@ -0,0 +1,696 @@ +//! The global tone map: scene luminance → display-linear luminance. +//! +//! Built in the log domain around middle grey (0.18): contrast scales log-exposure about grey, +//! whites move the shoulder (white point), blacks move the toe. The shoulder is an extended +//! Reinhard curve so highlights roll off smoothly instead of clipping. +//! +//! Rendered (display-referred) sources such as JPEGs use [`ToneMap::display`] instead: identity at +//! neutral settings (an unedited JPEG renders exactly as the file), with contrast/whites/blacks as +//! S-curve adjustments in a gamma-2.2 perceptual domain and a short shoulder above 0.95. + +pub const GREY: f32 = 0.18; +/// The tone LUT spans `LUT_MIN_EV..LUT_MAX_EV` around grey in `LUT_N` steps. +pub const LUT_MIN_EV: f32 = -14.0; +pub const LUT_MAX_EV: f32 = 10.0; +pub const LUT_N: usize = 4096; +/// Nodes of a camera chroma curve, evenly spaced over display luminance 0..=1. +pub const CHROMA_N: usize = 8; +const NO_CHROMA: [f32; CHROMA_N] = [1.0; CHROMA_N]; + +/// A file-local camera look, fitted independently of the scene-linear colour transform. +/// Knots are scene/display-linear luminance pairs. Keeping this in the finish stage preserves +/// RAW exposure and highlight headroom; it is never baked into the decoded sensor pixels. +/// `chroma` scales colourfulness by display luminance after the curve (a camera's per-channel +/// curve saturates shadows and bleaches highlights toward white, which a luminance curve can't). +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)] +pub struct CameraTone { + knots: [[f32; 2]; 32], + chroma: [f32; CHROMA_N], +} + +impl<'de> serde::Deserialize<'de> for CameraTone { + fn deserialize>(d: D) -> Result { + #[derive(serde::Deserialize)] + struct Wire { + knots: [[f32; 2]; 32], + // absent in smart previews written before the chroma curve existed + #[serde(default)] + chroma: Option<[f32; CHROMA_N]>, + } + let w = Wire::deserialize(d)?; + let tone = Self::new(w.knots).ok_or_else(|| serde::de::Error::custom("invalid camera tone curve"))?; + match w.chroma { + Some(c) => tone.with_chroma(c).ok_or_else(|| serde::de::Error::custom("invalid camera chroma curve")), + None => Ok(tone), + } + } +} + +impl CameraTone { + pub fn new(knots: [[f32; 2]; 32]) -> Option { + let mut previous = [0.0, 0.0]; + for p in knots { + if !p.iter().all(|v| v.is_finite()) || p[0] <= previous[0] || p[1] < previous[1] || p[1] >= 1.0 { + return None; + } + previous = p; + } + Some(Self { knots, chroma: NO_CHROMA }) + } + + /// The curve with chroma scales at display luminance 0, 1/7 … 1 (each finite, 0..=4). + pub fn with_chroma(self, chroma: [f32; CHROMA_N]) -> Option { + chroma.iter().all(|k| k.is_finite() && (0.0..=4.0).contains(k)).then_some(Self { chroma, ..self }) + } + + pub fn chroma(&self) -> &[f32; CHROMA_N] { + &self.chroma + } + + /// The (scene, display) luminance knots, in increasing order. + pub fn knots(&self) -> &[[f32; 2]; 32] { + &self.knots + } + + pub fn apply(&self, y: f32) -> f32 { + if !y.is_finite() || y <= 0.0 { + return 0.0; + } + let mut previous = [0.0, 0.0]; + for p in self.knots { + if y <= p[0] { + let t = (y - previous[0]) / (p[0] - previous[0]); + return previous[1] + t * (p[1] - previous[1]); + } + previous = p; + } + let a = self.knots[30]; + let b = self.knots[31]; + // Extend beyond observed (unclipped) highlights with a continuous, bounded shoulder. + let slope = ((b[1] - a[1]) / (b[0] - a[0])).clamp(0.1, 16.0); + 1.0 - (1.0 - b[1]) * (-(y - b[0]) * slope / (1.0 - b[1]).max(0.01)).exp() + } + + /// [`CameraTone::apply`] as process V5 extends it past the last knot (issue #1632). The curve is + /// fitted only to camera JPEG tones below 0.85, so its last knot lies 1 to 3 stops below the + /// sensor's white on most photos and everything above it is extrapolated. [`CameraTone::apply`] + /// closes the gap to white exponentially in linear light: it reaches 8-bit 255 within about a + /// stop past the sensor's white, and Exposure +1 turns the top stop the sensor recorded white. + /// Here the gap shrinks in stops instead, `gap / (1 + c·(2^(k·t) − 1))` at `t` stops past the + /// knot, with `c` matching the curve's slope there (so the join is smooth) and the gap halving + /// every [`ROLLOFF_STOPS`] stops in the end. Same value as [`CameraTone::apply`] up to the last + /// knot, monotone, finite and at most 1. In real numbers it only approaches white; in `f32` the + /// gap can round to 0 far up, and within a stop or two for a last knot a few ulps below white. + pub fn apply_rolloff(&self, y: f32) -> f32 { + let (a, b) = (self.knots[30], self.knots[31]); + if !y.is_finite() || y <= b[0] { + return self.apply(y); + } + // the last segment's own slope, so the join is smooth even when it is flat (`new` keeps the + // knots non-decreasing, so it is at least 0) + let slope = ((b[1] - a[1]) / (b[0] - a[0])).max(0.0); + // `CameraTone::new` keeps the last knot below 1, so the gap is positive (no floor: one + // would step the curve down past a knot within it of white) + rolloff_past(y, b, slope, CAMERA_MIN_SLOPE) + } +} + +/// The pace [`CameraTone::apply_rolloff`] closes on white at least at, as display per unit of scene +/// luminance at the last knot (the floor [`CameraTone::apply`] puts on its slope there). A last +/// segment flatter than this still joins with its own slope; [`rolloff_past`] then adds a term that +/// has no slope at the knot and reaches this pace further up, so a flat curve does not stay below +/// white. +const CAMERA_MIN_SLOPE: f32 = 0.1; + +/// Stops in which the gap between a V5 curve and white halves, far past where its shoulder starts +/// ([`CameraTone::apply_rolloff`], [`ToneMap::rolloff_hdr`]). With 1, the sensor's white renders at +/// 8-bit 239–250 on the CC0 corpus files with a camera curve (Sony, Nikon, Fujifilm) at Exposure 0 +/// and below 254 up to Exposure +2, where the extension of [`CameraTone::apply`] reaches 254–255 by +/// Exposure +1 (issue #1632). +pub const ROLLOFF_STOPS: f32 = 1.0; + +/// Process V5's shoulder past a knee at scene luminance `x` and display `o` (below 1), where the +/// curve rises at `slope` (display per unit of scene luminance): the gap to white is +/// `gap / (1 + c·(2^(k·t) − 1))` at `t = log2(y / x)` stops past the knee, `k = 1 / ROLLOFF_STOPS`, +/// so it halves every [`ROLLOFF_STOPS`] stops in the end. `c` gives it the curve's slope at the +/// knee: d(display)/d(stop) there is `slope · x · ln 2` on the curve and `gap · c · k · ln 2` on the +/// shoulder. When `slope` is below `min_slope`, `d · (u − ln(1 + u))` (with `u = 2^(k·t) − 1`) +/// joins the denominator: it adds no slope at the knee, so the join keeps the curve's own slope, and +/// far up it grows like `d · u`, so the shoulder closes on white at `min_slope`'s pace (the gap still +/// halves every [`ROLLOFF_STOPS`] stops in the end). A term growing faster than `u` would close a +/// flat curve on white faster than a steeper one far up, and a darker curve would end up above it. +/// Monotone for `y ≥ x`, finite and at most 1; in real numbers it only approaches white, while in +/// `f32` the gap rounds to 0 eventually. +fn rolloff_past(y: f32, [x, o]: [f32; 2], slope: f32, min_slope: f32) -> f32 { + let gap = 1.0 - o; + let k = 1.0 / ROLLOFF_STOPS; + // bounded, so `c · 0` right past the knee stays 0 for a gap of a few ulps + let per = |s: f32| (s * x / (gap * k)).min(1e30); + let c = per(slope); + let d = (per(min_slope) - c).max(0.0); + let u = (k * (y / x).log2()).exp2() - 1.0; + // each term only when its coefficient is positive: `0 · ∞` is NaN far up + let linear = if c > 0.0 { c * u } else { 0.0 }; + let floor = if d > 0.0 { d * past_join(u) } else { 0.0 }; + 1.0 - gap / (1.0 + linear + floor) +} + +/// `u − ln(1 + u)` for `u ≥ 0`: 0 with no slope at 0, then rising like `u` (infinite for infinite +/// `u`). In `f64`, where the difference keeps its digits down to tiny `u`. +fn past_join(u: f32) -> f32 { + if u.is_infinite() { + return u; + } + let u = f64::from(u); + (u - u.ln_1p()).max(0.0) as f32 +} + +/// Stops below its white point where process V5's generic raw curve ([`ToneMap::rolloff_hdr`]) +/// leaves the extended Reinhard curve for the [`ROLLOFF_STOPS`] shoulder, instead of clipping at +/// the white point. With ½, the sensor's white of a raw without a camera curve (scene 1.0, about +/// ¼ stop below that white point at default settings) renders at about 8-bit 235, 248 and 252 at +/// Exposure 0, +1 and +2 where V1 to V4 render 239, 255 and 255 (issue #1632). +pub const GENERIC_KNEE_STOPS: f32 = 0.5; + +/// Scene EV over grey where [`ToneMap::hdr`] starts lifting highlights above the SDR curve. +const HDR_FROM_EV: f32 = 1.5; + +#[derive(Clone, Debug)] +pub struct ToneMap { + lut: Vec, + chroma: [f32; CHROMA_N], +} + +impl ToneMap { + pub fn camera(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64) -> ToneMap { + ToneMap::camera_hdr(curve, contrast, whites, blacks, 1.0) + } + + /// [`ToneMap::camera`] for an HDR render reaching `peak` (linear, SDR white = 1; 1 = SDR + /// exactly): the camera's look up to 1.5 EV over grey, so midtones match the SDR render (and a + /// gain map only lifts highlights), then the highlights gain up to `peak − 1` more as in + /// [`ToneMap::hdr`]. + pub fn camera_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::camera_with(|y| curve.apply(y), curve.chroma, contrast, whites, blacks, peak) + } + + /// [`ToneMap::camera_hdr`] of process V5: past its last knot the camera curve rolls off in stops + /// ([`CameraTone::apply_rolloff`]) instead of closing on white within a stop of the sensor's. + pub fn camera_rolloff_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::camera_with(|y| curve.apply_rolloff(y), curve.chroma, contrast, whites, blacks, peak) + } + + fn camera_with(curve: impl Fn(f32) -> f32, chroma: [f32; CHROMA_N], contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 }; + let adjustment = Self::display(contrast, whites, blacks); + let neutral = contrast == 0.0 && whites == 0.0 && blacks == 0.0; + let top = (2.9 - 1.6 * (whites as f32 / 100.0) + peak.log2() + 1.0).max(HDR_FROM_EV + 0.5); + let lut = (0..LUT_N) + .map(|i| { + let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32; + let y = curve(GREY * 2f32.powf(ev)); + let o = if neutral { y } else { adjustment.apply(y) }; + if peak > 1.0 { (o + (peak - 1.0) * smooth(HDR_FROM_EV, top, ev)).clamp(0.0, peak) } else { o } + }) + .collect(); + ToneMap { lut, chroma } + } + /// `contrast`, `whites`, `blacks` in −100..100 (Lightroom slider units). + pub fn new(contrast: f64, whites: f64, blacks: f64) -> ToneMap { + ToneMap::hdr(contrast, whites, blacks, 1.0) + } + + /// [`ToneMap::new`] for an HDR render reaching `peak` (linear, SDR white = 1; 1 = SDR exactly). + /// Below about half of SDR white the curve is the SDR one; above, the highlights gain up to + /// `peak − 1` more along a smoothstep in scene EV, from 1.5 EV over grey to one stop past the + /// white point moved up by the headroom, so the result stays monotone, never exceeds `peak`, + /// and reaches it there (within the table's range). + pub fn hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::generic(contrast, whites, blacks, peak, false) + } + + /// [`ToneMap::hdr`] of process V5 (issue #1632): from [`GENERIC_KNEE_STOPS`] below the white + /// point the curve rolls off into white in stops, with the same value and slope at the join, + /// instead of reaching white about ¼ stop past the sensor's white and clipping there. The SDR + /// curve stays below 1 (SDR white) and is the same as [`ToneMap::hdr`]'s below the join; for + /// `peak` above 1 the HDR lift then takes highlights up to `peak`, as in [`ToneMap::hdr`]. + pub fn rolloff_hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + ToneMap::generic(contrast, whites, blacks, peak, true) + } + + fn generic(contrast: f64, whites: f64, blacks: f64, peak: f32, rolloff: bool) -> ToneMap { + let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 }; + let c = (contrast / 100.0) as f32; + let slope = if c >= 0.0 { 1.0 + 0.55 * c } else { 1.0 + 0.4 * c }; + // White point: scene luminance (after contrast) that maps to display 1.0. + let white_ev = 2.9 - 1.6 * (whites as f32 / 100.0); + let wl = GREY * 2f32.powf(white_ev); + let pre = 1.0 + GREY / wl; // keep grey near grey + let b = (blacks / 100.0) as f32; + // extended Reinhard with white point wl: y(1 + y/wl²)/(1 + y), reaching 1 at wl + let reinhard = |y: f32| y * (1.0 + y / (wl * wl)) / (1.0 + y); + // V5's knee, below the white point, and the curve's slope there: (1 + y(2 + y)/wl²)/(1 + y)² + let knee = wl * (-GENERIC_KNEE_STOPS).exp2(); + let knee_slope = (1.0 + knee * (2.0 + knee) / (wl * wl)) / ((1.0 + knee) * (1.0 + knee)); + let knee = [knee, reinhard(knee)]; + let lut = (0..LUT_N) + .map(|i| { + let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32; + let y = GREY * 2f32.powf(ev * slope) * pre; + let mut o = if rolloff && y > knee[0] && knee[1] < 1.0 { rolloff_past(y, knee, knee_slope, 0.0) } else { reinhard(y) }; + o = o.min(1.0); + // Toe: blacks < 0 crushes, > 0 lifts. + if b < 0.0 { + // Smooth max(0, o − k) (a soft knee), renormalized so 1 stays 1. + let k = -b * 0.035; + let e = 0.004; + let soft = |v: f32| ((v - k) + ((v - k) * (v - k) + e * e).sqrt()) * 0.5; + o = (soft(o) - soft(0.0)) / (soft(1.0) - soft(0.0)); + } else if b > 0.0 { + let k = b * 0.03; + o = k + (1.0 - k) * o; + } + if peak > 1.0 { + let top = (white_ev + peak.log2() + 1.0).max(HDR_FROM_EV + 0.5); + o += (peak - 1.0) * smooth(HDR_FROM_EV, top, ev * slope); + } + o.clamp(0.0, peak) + }) + .collect(); + ToneMap { lut, chroma: NO_CHROMA } + } + + /// Tone map for display-referred sources: identity at neutral settings. + pub fn display(contrast: f64, whites: f64, blacks: f64) -> ToneMap { + ToneMap::display_hdr(contrast, whites, blacks, 1.0) + } + + /// [`ToneMap::display`] for an HDR render reaching `peak`: values above SDR white (an HDR + /// source, e.g. a decoded gain-map image) pass through and roll off softly towards `peak` + /// instead of clipping at 1; SDR sources (≤ 1) render as with [`ToneMap::display`]. + pub fn display_hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap { + let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 }; + let c = (contrast / 100.0) as f32; + let w = (whites / 100.0) as f32; + let b = (blacks / 100.0) as f32; + let m = GREY.powf(1.0 / 2.2); + // Neutral sliders are the identity up to white (issue #1945): the SDR shoulder below would + // pull 1.0 down to 0.9875 (8-bit 255 to 254), so it only shapes an edited curve. + let neutral = c == 0.0 && w == 0.0 && b == 0.0; + let lut = (0..LUT_N) + .map(|i| { + let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32; + let y = GREY * 2f32.powf(ev); + let mut p = y.powf(1.0 / 2.2); + if p <= 1.0 { + // S-curve anchored at 0, grey and 1 + p += c * 0.35 * (p - m) * (1.0 - (2.0 * p - 1.0).powi(2)); + // whites: lift/lower the upper tones; blacks: the lower tones + let up = smooth(0.45, 1.0, p); + p += w * 0.12 * up * (1.0 - p * 0.5); + let lo = 1.0 - smooth(0.0, 0.45, p); + p += b * 0.07 * lo * (p * 2.0).min(1.0); + } else { + p += w * 0.12 * 0.5; + } + let mut o = p.max(0.0).powf(2.2); + // short shoulder (SDR, edited curves): slope 1 at 0.95, reaching 1.0 at 1.05 + if peak > 1.0 && o > 0.95 { + // exponential shoulder: slope 1 at 0.95, asymptote at `peak` + let r = peak - 0.95; + o = 0.95 + r * (1.0 - (-(o - 0.95) / r).exp()); + } else if o > 0.95 && !neutral { + let d = (o - 0.95).min(0.1); + o = 0.95 + d - d * d / 0.2; + } + o.clamp(0.0, peak) + }) + .collect(); + ToneMap { lut, chroma: NO_CHROMA } + } + + /// The table (`LUT_N` entries, see [`ToneMap::apply`]). + pub fn lut(&self) -> &[f32] { + &self.lut + } + + /// The chroma curve (`CHROMA_N` entries, see [`ToneMap::chroma_scale`]). + pub fn chroma_lut(&self) -> &[f32] { + &self.chroma + } + + /// Chroma scale at display luminance `o` (exactly 1 everywhere unless a camera look sets it). + #[inline] + pub fn chroma_scale(&self, o: f32) -> f32 { + if !o.is_finite() { + return 1.0; + } + let f = o.clamp(0.0, 1.0) * (CHROMA_N - 1) as f32; + let i = (f as usize).min(CHROMA_N - 2); + let t = f - i as f32; + let (a, b) = (self.chroma.get(i).copied().unwrap_or(1.0), self.chroma.get(i + 1).copied().unwrap_or(1.0)); + if a == b { a } else { a + (b - a) * t } + } + + /// Scene luminance → display-linear luminance. + #[inline] + pub fn apply(&self, y: f32) -> f32 { + if y <= 0.0 { + return 0.0; + } + let ev = (y / GREY).log2(); + let f = ((ev - LUT_MIN_EV) / (LUT_MAX_EV - LUT_MIN_EV)).clamp(0.0, 1.0) * (LUT_N - 1) as f32; + let i = (f as usize).min(LUT_N - 2); + let t = f - i as f32; + let v = self.lut[i] + (self.lut[i + 1] - self.lut[i]) * t; + if ev < LUT_MIN_EV { v * (y / (GREY * 2f32.powf(LUT_MIN_EV))) } else { v } + } +} + +fn smooth(e0: f32, e1: f32, x: f32) -> f32 { + let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn knots() -> [[f32; 2]; 32] { + std::array::from_fn(|i| { + let x = 0.004 * 1.18f32.powi(i as i32); + [x, 1.0 - (-2.0 * x).exp()] + }) + } + + #[test] + fn chroma_curve_is_identity_unless_set_and_survives_serde() { + let plain = CameraTone::new(knots()).unwrap(); + let map = ToneMap::camera(&plain, 0.0, 0.0, 0.0); + assert!([0.0, 0.3, 0.77, 1.0, 2.0].iter().all(|o| map.chroma_scale(*o) == 1.0)); + assert!([0.0, 0.5, 1.0].iter().all(|o| ToneMap::new(0.0, 0.0, 0.0).chroma_scale(*o) == 1.0)); + // smart previews written before the chroma curve existed still load (identity) + let old = serde_json::json!({ "knots": knots() }); + assert_eq!(serde_json::from_value::(old).unwrap(), plain); + let tone = plain.with_chroma([1.4, 1.3, 1.1, 1.0, 0.7, 0.4, 0.25, 0.2]).unwrap(); + let back: CameraTone = serde_json::from_value(serde_json::to_value(tone).unwrap()).unwrap(); + assert_eq!(back, tone); + let map = ToneMap::camera(&tone, 0.0, 0.0, 0.0); + assert!((map.chroma_scale(0.0) - 1.4).abs() < 1e-6 && (map.chroma_scale(1.0) - 0.2).abs() < 1e-6); + assert!((map.chroma_scale(0.5 / 7.0) - 1.35).abs() < 1e-5, "interpolates between nodes"); + assert_eq!(map.chroma_scale(f32::NAN), 1.0); + // hostile values are rejected, also when deserialized + assert!(plain.with_chroma([f32::NAN; CHROMA_N]).is_none()); + assert!(plain.with_chroma([-1.0; CHROMA_N]).is_none()); + let bad = serde_json::json!({ "knots": knots(), "chroma": [9.0, 1, 1, 1, 1, 1, 1, 1] }); + assert!(serde_json::from_value::(bad).is_err()); + } + + #[test] + fn camera_curve_preserves_black_and_extends_headroom() { + let knots = std::array::from_fn(|i| { + let x = 0.005 * 1.15f32.powi(i as i32); + [x, 1.0 - (-3.0 * x).exp()] + }); + let curve = CameraTone::new(knots).unwrap(); + let base = ToneMap::camera(&curve, 0.0, 0.0, 0.0); + assert_eq!(base.apply(0.0), 0.0); + assert!(base.apply(0.1) < base.apply(0.2)); + let mut previous = 0.0; + for i in 0..2000 { + let y = 1e-6 * 1.01f32.powi(i); + let v = base.apply(y); + assert!((0.0..=1.0).contains(&v)); + assert!(v >= previous - 1e-6); + previous = v; + } + assert!((base.apply(0.1) - curve.apply(0.1)).abs() < 0.001); + assert!(ToneMap::camera(&curve, 50.0, 0.0, 0.0).apply(0.3) > base.apply(0.3)); + let mut invalid = knots; + invalid[1][0] = invalid[0][0]; + assert!(CameraTone::new(invalid).is_none()); + assert!(serde_json::from_value::(serde_json::json!({"knots": invalid})).is_err()); + } + + #[test] + fn rolloff_joins_the_curve_smoothly_and_never_reaches_white() { + let curve = CameraTone::new(knots()).unwrap(); + let last = curve.knots()[31]; + // the camera's curve up to the last knot + for i in 0..200 { + let y = last[0] * i as f32 / 199.0; + assert_eq!(curve.apply_rolloff(y), curve.apply(y), "{y}"); + } + // continuous, with the slope of the last segment, at the knot + let a = curve.knots()[30]; + let slope = (last[1] - a[1]) / (last[0] - a[0]); + let h = last[0] * 1e-3; + let after = (curve.apply_rolloff(last[0] + h) - curve.apply_rolloff(last[0])) / h; + assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}"); + // monotone, below white, and slower to close on it than the V1/V2 extension + let mut previous = last[1]; + for i in 1..3000 { + let y = last[0] * 1.005f32.powi(i); + let o = curve.apply_rolloff(y); + assert!(o >= previous && o < 1.0, "{y}: {o}"); + assert!(o <= curve.apply(y) + 1e-6, "{y}"); + previous = o; + } + assert!(1.0 - curve.apply_rolloff(last[0] * 8.0) > 4.0 * (1.0 - curve.apply(last[0] * 8.0))); + // a steep last segment joins with its own slope, and a last knot next to white without a step + for top in [0.9, 0.99995, 1.0 - f32::EPSILON] { + let mut k = knots(); + k[31] = [k[30][0] * 1.01, top]; + let c = CameraTone::new(k).unwrap(); + let slope = (k[31][1] - k[30][1]) / (k[31][0] - k[30][0]); + assert!(slope > 16.0 || top < 0.99, "{slope}"); + let mut prev = c.apply_rolloff(k[31][0]); + assert_eq!(prev, top); + for i in 1..2000 { + let o = c.apply_rolloff(k[31][0] * 1.0001f32.powi(i)); + assert!(o.is_finite() && o >= prev && o <= 1.0, "{top} {i}: {o} < {prev}"); + prev = o; + } + if top == 0.9 { + let h = k[31][0] * 1e-5; + let after = (c.apply_rolloff(k[31][0] + h) - top) / h; + assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}"); + } + } + // a flat or shallow last segment joins with its own slope (not the 0.1 floor of the V1/V2 + // extension) and still closes on white further up + for s in [0.0f32, 0.05] { + let mut k = knots(); + k[31][1] = k[30][1] + s * (k[31][0] - k[30][0]); + let c = CameraTone::new(k).unwrap(); + let (x, top) = (k[31][0], k[31][1]); + let h = x * 1e-4; + let after = (c.apply_rolloff(x + h) - top) / h; + assert!((after - s).abs() < 0.01, "{s}: right slope {after}"); + let mut prev = top; + for i in 1..3000 { + let o = c.apply_rolloff(x * 1.005f32.powi(i)); + assert!(o.is_finite() && o >= prev && o <= 1.0, "{s} {i}: {o} < {prev}"); + prev = o; + } + assert!(1.0 - c.apply_rolloff(x * 64.0) < (1.0 - top) / 4.0, "{s}"); + for y in [f32::MAX, f32::INFINITY] { + assert!((0.0..=1.0).contains(&c.apply_rolloff(y)), "{s} {y}"); + } + } + // hostile input + for y in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX] { + let o = curve.apply_rolloff(y); + assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}"); + } + // the tone map built from it is monotone and bounded, SDR and HDR + for peak in [1.0f32, 4.0] { + let t = ToneMap::camera_rolloff_hdr(&curve, 0.0, 0.0, 0.0, peak); + let mut prev = -1.0; + for i in 0..2400 { + let o = t.apply(1e-5 * 1.01f32.powi(i)); + assert!((0.0..=peak).contains(&o) && o >= prev - 1e-6, "{peak} {i}: {o}"); + prev = o; + } + } + } + + #[test] + fn generic_rolloff_joins_the_curve_smoothly_and_never_reaches_white() { + for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0), (0.0, -100.0, 0.0)] { + for peak in [1.0f32, 4.0] { + let (clip, roll) = (ToneMap::hdr(c, w, b, peak), ToneMap::rolloff_hdr(c, w, b, peak)); + let (clip, roll) = (clip.lut(), roll.lut()); + // the generic curve up to the knee, never brighter past it + let join = roll.iter().zip(clip).position(|(r, c)| r != c).expect("the shoulder starts inside the table"); + assert!(join > 2 && roll[join] < clip[join], "{c} {w} {b} {peak}: {join}"); + for (i, (r, c)) in roll.iter().zip(clip).enumerate() { + assert!(*r <= c + 1e-6, "{c} {w} {b} {peak} {i}: {r} > {c}"); + } + // same value and slope at the join: the step across it is the step before it + let (before, across) = (roll[join - 1] - roll[join - 2], roll[join] - roll[join - 1]); + assert!((across / before - 1.0).abs() < 0.02, "{c} {w} {b} {peak}: {before} then {across}"); + // monotone, and below white where the V1/V2 curve clips (SDR) or lifts to `peak` (HDR) + assert!(roll.windows(2).all(|p| p[1] >= p[0] - 1e-6), "{c} {w} {b} {peak}"); + if peak == 1.0 { + assert_eq!(clip[LUT_N - 1], 1.0); + // close to it at the top of the table at default settings (10 EV over grey); + // Whites −100 moves the white point, and so the shoulder, up 1.6 stops + let top = roll[LUT_N - 1]; + assert!(top < 1.0 && (top > 0.999 || w < 0.0), "{c} {w} {b}: {top}"); + } + } + } + // no kink where V1/V2 clip: there the clipped curve stops rising at once + let (clip, roll) = (ToneMap::new(0.0, 0.0, 0.0), ToneMap::rolloff_hdr(0.0, 0.0, 0.0, 1.0)); + let kink = |lut: &[f32]| lut.windows(3).filter(|p| p[1] - p[0] > 1e-5).map(|p| 1.0 - (p[2] - p[1]) / (p[1] - p[0])).fold(0.0f32, f32::max); + assert!(kink(clip.lut()) > 0.9); + assert!(kink(roll.lut()) < 0.05, "{}", kink(roll.lut())); + // hostile input (NaN passes through `ToneMap::apply` as on every curve) + for y in [f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX, f32::MIN_POSITIVE] { + let o = roll.apply(y); + assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}"); + } + } + + #[test] + fn monotone_and_bounded() { + for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0)] { + let t = ToneMap::new(c, w, b); + let mut prev = -1.0; + for i in 0..2000 { + let y = 1e-5 * 1.012f32.powi(i); + let o = t.apply(y); + assert!((0.0..=1.0).contains(&o)); + assert!(o >= prev - 1e-6, "{c} {w} {b} at {y}: {o} < {prev}"); + prev = o; + } + } + } + + #[test] + fn hdr_is_sdr_at_peak_one_and_reaches_peak() { + for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0)] { + assert_eq!(ToneMap::hdr(c, w, b, 1.0).lut(), ToneMap::new(c, w, b).lut()); + for peak in [2.0f32, 8.0, 32.0] { + let sdr = ToneMap::new(c, w, b); + let t = ToneMap::hdr(c, w, b, peak); + let mut prev = -1.0; + for i in 0..2400 { + let y = 1e-5 * 1.01f32.powi(i); + let o = t.apply(y); + assert!((0.0..=peak).contains(&o), "{c} {w} {b} {peak} at {y}: {o}"); + assert!(o >= prev - 1e-6, "{c} {w} {b} {peak} at {y}: {o} < {prev}"); + prev = o; + if y <= GREY * 2f32.powf(0.9) { + assert!((o - sdr.apply(y)).abs() < 1e-6, "midtones differ at {y}"); + } + } + assert!(t.apply(4.0) > sdr.apply(4.0)); + if (c, w, b) == (0.0, 0.0, 0.0) { + assert!(t.apply(GREY * 2f32.powf(LUT_MAX_EV)) > peak * 0.99, "{peak}"); + } + } + } + // a broken peak falls back to SDR + assert_eq!(ToneMap::hdr(0.0, 0.0, 0.0, f32::NAN).lut(), ToneMap::new(0.0, 0.0, 0.0).lut()); + } + + #[test] + fn camera_hdr_keeps_the_camera_look_and_lifts_highlights() { + let curve = CameraTone::new(knots()).unwrap().with_chroma([1.2, 1.1, 1.0, 1.0, 0.9, 0.8, 0.7, 0.6]).unwrap(); + for (c, w, b) in [(0.0, 0.0, 0.0), (40.0, -30.0, -20.0)] { + let sdr = ToneMap::camera(&curve, c, w, b); + assert_eq!(ToneMap::camera_hdr(&curve, c, w, b, 1.0).lut(), sdr.lut()); + assert_eq!(ToneMap::camera_hdr(&curve, c, w, b, f32::NAN).lut(), sdr.lut()); + for peak in [2.0f32, 8.0] { + let t = ToneMap::camera_hdr(&curve, c, w, b, peak); + assert_eq!(t.chroma_lut(), sdr.chroma_lut()); + let mut prev = -1.0; + for i in 0..2400 { + let y = 1e-5 * 1.01f32.powi(i); + let o = t.apply(y); + assert!((0.0..=peak).contains(&o), "{peak} at {y}: {o}"); + assert!(o >= prev - 1e-6, "{peak} at {y}: {o} < {prev}"); + prev = o; + // the camera's midtones, not the generic HDR curve's (issue: dark HDR exports) + if y <= GREY * 2f32.powf(HDR_FROM_EV - 0.01) { + assert!((o - sdr.apply(y)).abs() < 1e-6, "midtones differ at {y}: {o} vs {}", sdr.apply(y)); + } + } + assert!(t.apply(4.0) > 1.0 && t.apply(4.0) > sdr.apply(4.0) + 0.5, "{peak}: highlights lifted"); + } + } + } + + #[test] + fn display_hdr_passes_hdr_sources_and_keeps_sdr() { + assert_eq!(ToneMap::display_hdr(20.0, 10.0, -5.0, 1.0).lut(), ToneMap::display(20.0, 10.0, -5.0).lut()); + let t = ToneMap::display_hdr(0.0, 0.0, 0.0, 8.0); + for i in 1..=90 { + let y = i as f32 / 100.0; + assert!((t.apply(y) - y).abs() < 2e-3, "{y} -> {}", t.apply(y)); + } + let mut prev = 0.0; + for i in 1..2000 { + let o = t.apply(i as f32 / 100.0); + assert!(o >= prev - 1e-6 && o <= 8.0); + prev = o; + } + assert!(t.apply(3.0) > 2.0 && t.apply(3.0) < 3.0); + } + + #[test] + fn display_identity_and_monotone() { + let t = ToneMap::display(0.0, 0.0, 0.0); + // up to and including white (issue #1945: 1.0 came out as 0.9875, 8-bit 255 as 254); the + // tolerance is the LUT's interpolation next to the clip at 1.0, far below an 8-bit level + for i in 1..=100 { + let y = i as f32 / 100.0; + assert!((t.apply(y) - y).abs() < 1e-3, "{y} -> {}", t.apply(y)); + } + assert_eq!(t.apply(4.0), 1.0, "neutral values pushed above white clip"); + for (c, w, b) in [(100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (60.0, -40.0, 30.0)] { + let t = ToneMap::display(c, w, b); + let mut prev = -1.0; + for i in 0..1000 { + let o = t.apply(i as f32 / 500.0); + assert!(o >= prev - 1e-5, "{c} {w} {b}"); + prev = o; + } + } + let c = ToneMap::display(60.0, 0.0, 0.0); + assert!(c.apply(0.05) < 0.05 && c.apply(0.7) > 0.7); + } + + #[test] + fn display_shoulder_stays_on_edited_curves() { + // The short shoulder is part of the V1 look of edited curves (docs/process-versions.md); + // only neutral settings are the identity. + for (c, w, b) in [(20.0, 0.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, -5.0)] { + let t = ToneMap::display(c, w, b); + let o = t.apply(1.0); + assert!(o < 0.999 && o > 0.95, "{c} {w} {b}: {o}"); + } + } + + #[test] + fn grey_stays_near_grey_and_highlights_roll_off() { + let t = ToneMap::new(0.0, 0.0, 0.0); + let g = t.apply(0.18); + assert!((0.15..0.24).contains(&g), "{g}"); + assert!(t.apply(1.0) < 0.95 && t.apply(1.0) > 0.6); + assert!(t.apply(8.0) > 0.97); + } + + #[test] + fn sliders_move_the_right_way() { + let base = ToneMap::new(0.0, 0.0, 0.0); + let contrast = ToneMap::new(60.0, 0.0, 0.0); + assert!(contrast.apply(0.05) < base.apply(0.05)); + assert!(contrast.apply(0.8) > base.apply(0.8)); + assert!(ToneMap::new(0.0, 60.0, 0.0).apply(0.8) > base.apply(0.8)); + assert!(ToneMap::new(0.0, 0.0, -60.0).apply(0.01) < base.apply(0.01)); + assert!(ToneMap::new(0.0, 0.0, 60.0).apply(0.01) > base.apply(0.01)); + } +} From 03d1afced9201e2b5b815dccf64989ec6b74c77d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:36:26 -0500 Subject: [PATCH 71/79] svg: extract shared SVG document/CSS interpretation helpers (#778) (#2456) * svg: extract shared SVG document/CSS interpretation helpers (storytold/craft-libs#778) * svg: document doc_style::length unknown-unit px fallback * style(svg): fix clippy field_reassign_with_default in doc_style test --- crates/svg/README.md | 7 + crates/svg/src/doc_style.rs | 457 ++++++++++++++++++++++++++++++++++++ crates/svg/src/lib.rs | 3 + 3 files changed, 467 insertions(+) create mode 100644 crates/svg/src/doc_style.rs diff --git a/crates/svg/README.md b/crates/svg/README.md index a82d88028c..d6c0d95458 100644 --- a/crates/svg/README.md +++ b/crates/svg/README.md @@ -17,6 +17,13 @@ The shared adapter adds an aggregate 64 MiB stylesheet-text limit and idempotent ### Transform compatibility `transform_compat::parse_transform` preserves EffectCraft transform-list recovery and exact composition. It retains six numeric arguments per operation; scanning is not time/byte capped and matrix overflow behavior is unchanged. The strict geometry reader is unchanged. Source: Brandon Thomas, EffectCraft94e1c86d89a866771f80ad1610afda9aa12e85d8; bounded safe argument matching by Altynzhan Karybai,4035d181329e847d7a57bf3d059502ea2c91b560. +### Document and CSS style compatibility + +`doc_style` preserves EffectCraft's presentation-attribute + stylesheet + inline-`style` +cascade, unit/percentage length resolution, `PaintRef`/`resolve_paint`, and +`viewBox`/`preserveAspectRatio` transform helpers while leaving scene-graph mapping +with the importer. Note that `doc_style::length()` treats unknown units as `px` (`_ => v`). + ### Opt-in validated embedded images diff --git a/crates/svg/src/doc_style.rs b/crates/svg/src/doc_style.rs new file mode 100644 index 0000000000..2efecb102b --- /dev/null +++ b/crates/svg/src/doc_style.rs @@ -0,0 +1,457 @@ +//! Compatibility SVG document/CSS interpretation helpers extracted from EffectCraft. +//! +//! Provides presentation-attribute + stylesheet + inline-`style` declaration collection +//! ([`declared`]), property cascading ([`cascade`]), unit/percentage length resolution +//! ([`length`], [`attr_len`]), paint reference parsing/resolution ([`PaintRef`], [`paint_ref`], +//! [`resolve_paint`]), and `viewBox` / `preserveAspectRatio` transforms ([`viewbox`], +//! [`viewbox_transform`]). + +use std::collections::HashMap; + +use kurbo::Affine; + +use crate::{ + color::parse_rgba_compat, + prefix_path::numbers_bounded, + simple_css::{StyleSheet, declarations}, +}; + +/// SVG `fill-rule` property. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum FillRule { + #[default] + NonZero, + EvenOdd, +} + +/// SVG `stroke-linecap` property. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Cap { + #[default] + Butt, + Round, + Square, +} + +/// SVG `stroke-linejoin` property. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Join { + #[default] + Miter, + Round, + Bevel, +} + +/// Parsed SVG paint reference (`none`, `currentColor`, `url(#id) [fallback]`, or RGBA color). +#[derive(Clone, Debug, PartialEq)] +pub enum PaintRef { + /// Solid straight RGBA color `[r, g, b, a]` in `0.0..=1.0`. + Color([f64; 4]), + /// Paint server reference `url(#id)` with an optional fallback RGBA color. + Url(String, Option<[f64; 4]>), + /// `currentColor`. + Current, +} + +/// Caller outcome when resolving a `url(#id)` paint reference. +#[derive(Clone, Debug, PartialEq)] +pub enum UrlPaint { + /// Resolved to a caller paint server (for example, a gradient or pattern). + Server(S), + /// Resolved to a solid RGBA color (for example, a single-stop gradient). + Color([f64; 4]), + /// No paint server found; fall back to the `url(#id) fallback` color if present. + Fallback, + /// Paint server found but empty or invalid; do not fall back. + None, +} + +/// Result of resolving a [`PaintRef`] without committing to a caller's paint-server type. +#[derive(Clone, Debug, PartialEq)] +pub enum ResolvedPaint { + /// Solid RGB color `[r, g, b]` with alpha `a`. + Color([f64; 3], f64), + /// A caller-resolved paint server (`url(#id)`). + Server(S), +} + +/// Inherited SVG style state. +#[derive(Clone, Debug, PartialEq)] +pub struct Style { + pub fill: Option, + pub fill_opacity: f64, + pub fill_rule: FillRule, + pub stroke: Option, + pub stroke_opacity: f64, + pub stroke_width: f64, + pub cap: Cap, + pub join: Join, + pub miter: f64, + pub dash: Option>, + pub dash_offset: f64, + pub color: [f64; 4], + pub visible: bool, + pub font_size: f64, +} + +impl Default for Style { + fn default() -> Self { + Style { + fill: Some(PaintRef::Color([0.0, 0.0, 0.0, 1.0])), + fill_opacity: 1.0, + fill_rule: FillRule::NonZero, + stroke: None, + stroke_opacity: 1.0, + stroke_width: 1.0, + cap: Cap::Butt, + join: Join::Miter, + miter: 4.0, + dash: None, + dash_offset: 0.0, + color: [0.0, 0.0, 0.0, 1.0], + visible: true, + font_size: 16.0, + } + } +} + +/// Presentation attributes recognised by [`declared`]. +pub const STYLE_PROPS: &[&str] = &[ + "fill", + "fill-opacity", + "fill-rule", + "stroke", + "stroke-width", + "stroke-opacity", + "stroke-linecap", + "stroke-linejoin", + "stroke-miterlimit", + "stroke-dasharray", + "stroke-dashoffset", + "opacity", + "display", + "visibility", + "color", + "font-size", + "transform", + "stop-color", + "stop-opacity", +]; + +/// 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. +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() { + if STYLE_PROPS.contains(&a.name()) && a.name() != "transform" { + 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); + if let Some(st) = n.attribute("style") { + for (k, v) in declarations(st) { + out.insert(k, v); + } + } + out +} + +/// Parse an SVG length or percentage into user-space pixels. +/// +/// `axis` selects the percentage reference base: `'x'` uses `vw`, `'y'` uses `vh`, and any +/// other value uses the normalized diagonal `((vw^2 + vh^2) / 2).sqrt()`. +pub fn length(s: &str, axis: char, font: f64, vw: f64, vh: f64) -> Option { + let s = s.trim(); + let num_end = s.find(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'))).unwrap_or(s.len()); + // "e" also starts "em"/"ex": back off if the number does not parse. + let (mut num, mut unit) = (&s[..num_end], &s[num_end..]); + if num.parse::().is_err() && (num.ends_with('e') || num.ends_with('E')) { + let back = num_end.saturating_sub(1); + num = &s[..back]; + unit = &s[back..]; + } + let v: f64 = num.parse().ok()?; + let value = match unit.trim() { + "" | "px" => v, + "pt" => v * 4.0 / 3.0, + "pc" => v * 16.0, + "mm" => v * 96.0 / 25.4, + "cm" => v * 96.0 / 2.54, + "in" => v * 96.0, + "em" => v * font, + "ex" => v * font / 2.0, + "%" => { + let base = match axis { + 'x' => vw, + 'y' => vh, + _ => ((vw * vw + vh * vh) / 2.0).sqrt(), + }; + v / 100.0 * base + } + _ => v, + }; + value.is_finite().then_some(value) +} + +/// Parse a length attribute on `n`, returning `0.0` if missing or invalid. +pub fn attr_len(n: roxmltree::Node, name: &str, axis: char, st: &Style, vw: f64, vh: f64) -> f64 { + n.attribute(name).and_then(|v| length(v, axis, st.font_size, vw, vh)).unwrap_or(0.0) +} + +/// Parse an SVG paint value (`none`, `currentColor`, `url(#id) [fallback]`, `inherit`, or color). +/// +/// Returns `None` for `"inherit"` or unrecognized values, `Some(None)` for `"none"`, and +/// `Some(Some(PaintRef))` for concrete paints or `url(...)` / `currentColor` references. +pub fn paint_ref(v: &str) -> Option> { + let v = v.trim(); + if v == "none" { + return Some(None); + } + if v == "currentColor" || v == "currentcolor" { + return Some(Some(PaintRef::Current)); + } + if let Some(rest) = v.strip_prefix("url(") { + let (url, fallback) = rest.split_once(')').unwrap_or((rest, "")); + let url = url.trim().trim_matches(['"', '\'']); + let id = url.strip_prefix('#').filter(|id| !id.is_empty()).unwrap_or_default().to_string(); + let fb = fallback.trim(); + let fb = if fb.is_empty() || fb == "none" { None } else { parse_rgba_compat(fb) }; + return Some(Some(PaintRef::Url(id, fb))); + } + if v == "inherit" { + return None; + } + parse_rgba_compat(v).map(|c| Some(PaintRef::Color(c))) +} + +/// Apply an element's declared inherited properties to `st`. +/// +/// Returns `(opacity, display)` where `display` is `false` when `display: none` is set. +pub fn cascade(n: roxmltree::Node, css: &StyleSheet, st: &mut Style, vw: f64, vh: f64, charge_css: impl FnMut(usize) -> bool) -> (f64, bool) { + let d = declared(n, css, charge_css); + let num = |k: &str| { + d.get(k) + .and_then(|v| v.trim().trim_end_matches('%').parse::().ok().map(|x| if v.trim().ends_with('%') { x / 100.0 } else { x })) + .filter(|x| x.is_finite()) + }; + if let Some(c) = d.get("color").and_then(|v| parse_rgba_compat(v)) { + st.color = c; + } + let font_size = d.get("font-size").and_then(|v| match v.trim().strip_suffix('%') { + Some(p) => p.trim().parse::().ok().map(|p| p / 100.0 * st.font_size), + None => length(v, 'o', st.font_size, vw, vh), + }); + if let Some(v) = font_size.filter(|v| v.is_finite()) { + st.font_size = v; + } + if let Some(p) = d.get("fill").and_then(|v| paint_ref(v)) { + st.fill = p; + } + if let Some(p) = d.get("stroke").and_then(|v| paint_ref(v)) { + st.stroke = p; + } + if let Some(v) = num("fill-opacity") { + st.fill_opacity = v.clamp(0.0, 1.0); + } + if let Some(v) = num("stroke-opacity") { + st.stroke_opacity = v.clamp(0.0, 1.0); + } + if let Some(v) = d.get("stroke-width").and_then(|v| length(v, 'o', st.font_size, vw, vh)) { + st.stroke_width = v.max(0.0); + } + if let Some(v) = num("stroke-miterlimit") { + st.miter = v.max(1.0); + } + if let Some(v) = d.get("fill-rule") { + st.fill_rule = if v.trim() == "evenodd" { FillRule::EvenOdd } else { FillRule::NonZero }; + } + if let Some(v) = d.get("stroke-linecap") { + st.cap = match v.trim() { + "round" => Cap::Round, + "square" => Cap::Square, + _ => Cap::Butt, + }; + } + if let Some(v) = d.get("stroke-linejoin") { + st.join = match v.trim() { + "round" => Join::Round, + "bevel" => Join::Bevel, + _ => Join::Miter, + }; + } + if let Some(v) = d.get("stroke-dasharray") { + st.dash = if v.trim() == "none" { + None + } else { + let a: Vec = v + .split(|c: char| c == ',' || c.is_whitespace()) + .filter(|t| !t.is_empty()) + .filter_map(|t| length(t, 'o', st.font_size, vw, vh)) + .collect(); + if a.iter().all(|x| *x >= 0.0) && a.iter().any(|x| *x > 0.0) { Some(a) } else { None } + }; + } + if let Some(v) = d.get("stroke-dashoffset").and_then(|v| length(v, 'o', st.font_size, vw, vh)) { + st.dash_offset = v; + } + if let Some(v) = d.get("visibility") { + st.visible = !matches!(v.trim(), "hidden" | "collapse"); + } + let display = d.get("display").is_none_or(|v| v.trim() != "none"); + (num("opacity").unwrap_or(1.0).clamp(0.0, 1.0), display) +} + +/// Resolve a [`PaintRef`] against `st` and a caller-supplied `url(#id)` resolver. +pub fn resolve_paint(paint: &PaintRef, st: &Style, resolve_url: impl FnOnce(&str, Option<[f64; 4]>) -> UrlPaint) -> Option> { + match paint { + PaintRef::Color(c) => Some(ResolvedPaint::Color([c[0], c[1], c[2]], c[3])), + PaintRef::Current => Some(ResolvedPaint::Color([st.color[0], st.color[1], st.color[2]], st.color[3])), + PaintRef::Url(id, fallback) => match resolve_url(id, *fallback) { + UrlPaint::Server(s) => Some(ResolvedPaint::Server(s)), + UrlPaint::Color(c) => Some(ResolvedPaint::Color([c[0], c[1], c[2]], c[3])), + UrlPaint::Fallback => fallback.map(|c| ResolvedPaint::Color([c[0], c[1], c[2]], c[3])), + UrlPaint::None => None, + }, + } +} + +/// Parse an element's `viewBox` attribute into `([min_x, min_y], width, height)`. +pub fn viewbox(n: roxmltree::Node) -> Option<([f64; 2], f64, f64)> { + let (v, exceeded) = numbers_bounded(n.attribute("viewBox")?, 5); + if exceeded || !v.iter().all(|x| x.is_finite()) { + return None; + } + let [x, y, width, height] = v.as_slice() else { return None }; + (*width > 0.0 && *height > 0.0).then_some(([*x, *y], *width, *height)) +} + +/// The `viewBox` -> viewport transform (`preserveAspectRatio`, default `xMidYMid meet`). +pub fn viewbox_transform(n: roxmltree::Node, w: f64, h: f64) -> Affine { + let Some(([x, y], vw, vh)) = viewbox(n) else { return Affine::IDENTITY }; + let par = n.attribute("preserveAspectRatio").unwrap_or("xMidYMid meet"); + let mut parts = par.split_whitespace(); + let mut align = parts.next().unwrap_or("xMidYMid"); + if align == "defer" { + align = parts.next().unwrap_or("xMidYMid"); + } + let slice = parts.next() == Some("slice"); + let (sx, sy) = (w / vw, h / vh); + if align == "none" { + return Affine::scale_non_uniform(sx, sy) * Affine::translate((-x, -y)); + } + let s = if slice { sx.max(sy) } else { sx.min(sy) }; + let fx = if align.contains("xMid") { + 0.5 + } else if align.contains("xMax") { + 1.0 + } else { + 0.0 + }; + let fy = if align.contains("YMid") { + 0.5 + } else if align.contains("YMax") { + 1.0 + } else { + 0.0 + }; + let tx = (w - vw * s) * fx; + let ty = (h - vh * s) * fy; + Affine::translate((tx, ty)) * Affine::scale(s) * Affine::translate((-x, -y)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::simple_css::parse as parse_css; + + #[test] + fn declared_precedence_and_transform_exclusion() { + let doc = roxmltree::Document::parse( + r#""#, + ) + .unwrap(); + let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let mut css = StyleSheet::default(); + parse_css(".a { fill: green; stroke: red; }", &mut css).unwrap(); + css.index(); + let d = declared(rect, &css, |_| true); + 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")); + } + + #[test] + fn length_units_and_exponents() { + assert_eq!(length("10", 'x', 16.0, 200.0, 100.0), Some(10.0)); + assert_eq!(length("12pt", 'x', 16.0, 200.0, 100.0), Some(16.0)); + assert_eq!(length("1in", 'x', 16.0, 200.0, 100.0), Some(96.0)); + assert_eq!(length("2em", 'x', 16.0, 200.0, 100.0), Some(32.0)); + assert_eq!(length("2ex", 'x', 16.0, 200.0, 100.0), Some(16.0)); + assert_eq!(length("1e2em", 'x', 10.0, 200.0, 100.0), Some(1000.0)); + assert_eq!(length("50%", 'x', 16.0, 200.0, 100.0), Some(100.0)); + assert_eq!(length("50%", 'y', 16.0, 200.0, 100.0), Some(50.0)); + assert_eq!(length("nan", 'x', 16.0, 200.0, 100.0), None); + } + + #[test] + fn attr_len_reads_or_defaults_to_zero() { + let doc = roxmltree::Document::parse(r#""#).unwrap(); + let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap(); + let st = Style::default(); + assert_eq!(attr_len(rect, "x", 'x', &st, 200.0, 100.0), 100.0); + assert_eq!(attr_len(rect, "y", 'y', &st, 200.0, 100.0), 0.0); + assert_eq!(attr_len(rect, "width", 'x', &st, 200.0, 100.0), 0.0); + } + + #[test] + fn cascade_applies_inheritance_and_display() { + let doc = roxmltree::Document::parse( + r##""##, + ) + .unwrap(); + let g = doc.descendants().find(|n| n.tag_name().name() == "g").unwrap(); + let css = StyleSheet::default(); + let mut st = Style::default(); + let (opacity, display) = cascade(g, &css, &mut st, 100.0, 100.0, |_| true); + assert_eq!(opacity, 0.5); + assert!(!display); + assert!(!st.visible); + assert_eq!(st.font_size, 20.0); + assert_eq!(st.stroke_width, 40.0); + assert_eq!(st.fill, Some(PaintRef::Current)); + assert_eq!(st.fill_rule, FillRule::EvenOdd); + assert_eq!(st.cap, Cap::Round); + assert_eq!(st.join, Join::Bevel); + assert_eq!(st.dash, Some(vec![4.0, 2.0])); + } + + #[test] + fn paint_ref_and_resolve_paint_handle_fallbacks() { + assert_eq!(paint_ref("none"), Some(None)); + assert_eq!(paint_ref("inherit"), None); + assert_eq!(paint_ref("currentColor"), Some(Some(PaintRef::Current))); + assert_eq!(paint_ref("url(#grad) red"), Some(Some(PaintRef::Url("grad".into(), Some([1.0, 0.0, 0.0, 1.0]))))); + + let st = Style { color: [0.0, 1.0, 0.0, 0.5], ..Style::default() }; + assert_eq!(resolve_paint(&PaintRef::Current, &st, |_, _| UrlPaint::<()>::None), Some(ResolvedPaint::Color([0.0, 1.0, 0.0], 0.5))); + + let url = PaintRef::Url("g".into(), Some([1.0, 0.0, 0.0, 1.0])); + assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::Server("ok")), Some(ResolvedPaint::Server("ok"))); + assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::Fallback), Some(ResolvedPaint::Color([1.0, 0.0, 0.0], 1.0))); + assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::None), None); + } + + #[test] + fn viewbox_and_transform_preserve_aspect_ratio() { + let doc = roxmltree::Document::parse( + r#""#, + ) + .unwrap(); + let root = doc.root_element(); + assert_eq!(viewbox(root), Some(([10.0, 20.0], 100.0, 50.0))); + let m = viewbox_transform(root, 200.0, 200.0); + // Scale is min(2, 4) = 2; tx = (200 - 200) * 1.0 = 0; ty = (200 - 100) * 0.5 = 50. + let p = m * kurbo::Point::new(10.0, 20.0); + assert_eq!(p, kurbo::Point::new(0.0, 50.0)); + } +} diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 79a7060525..6b331a3dea 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -38,3 +38,6 @@ pub mod simple_css; /// Prefix-preserving SVG transform-list compatibility. pub mod transform_compat; + +/// Compatibility SVG document/CSS interpretation helpers (style cascade, lengths, paints, viewBox). +pub mod doc_style; From 483f2ab81f42af1850744484fd02ad05197d1fca Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:36:34 -0500 Subject: [PATCH 72/79] craft-usd: extract neutral USDA/USDC scene, prim, and layer read/write (#778) (#2459) * craft-usd: extract neutral USDA/USDC scene, prim, and layer read/write (#778) * chore: update Cargo.lock for craft-usd * craft-usd: add integration tests for USDA/USDC scene read/write (#778) * fix(usd): use asset-only external reference syntax in scene test * test(usd): include Shader child prim for material surface target in neutral layer test --- Cargo.lock | 1 + crates/usd/Cargo.toml | 1 + crates/usd/README.md | 10 +- crates/usd/src/codec.rs | 113 +++++ crates/usd/src/lib.rs | 10 +- crates/usd/src/scene/mod.rs | 275 +++++++++++ crates/usd/src/scene/usda.rs | 512 +++++++++++++++++++++ crates/usd/src/scene/usdc.rs | 840 ++++++++++++++++++++++++++++++++++ crates/usd/src/scene/write.rs | 662 +++++++++++++++++++++++++++ crates/usd/tests/scene.rs | 234 ++++++++++ 10 files changed, 2653 insertions(+), 5 deletions(-) create mode 100644 crates/usd/src/codec.rs create mode 100644 crates/usd/src/scene/mod.rs create mode 100644 crates/usd/src/scene/usda.rs create mode 100644 crates/usd/src/scene/usdc.rs create mode 100644 crates/usd/src/scene/write.rs create mode 100644 crates/usd/tests/scene.rs diff --git a/Cargo.lock b/Cargo.lock index 09cea4a312..79eb278cda 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3508,6 +3508,7 @@ dependencies = [ name = "craft-usd" version = "0.1.0" dependencies = [ + "half", "lz4_flex", "thiserror 2.0.21", ] diff --git a/crates/usd/Cargo.toml b/crates/usd/Cargo.toml index ac1c64d0c7..a97954d7ff 100644 --- a/crates/usd/Cargo.toml +++ b/crates/usd/Cargo.toml @@ -11,5 +11,6 @@ repository.workspace = true workspace = true [dependencies] +half = "2" lz4_flex = { version = "0.11", default-features = false, features = ["safe-decode", "safe-encode"] } thiserror.workspace = true diff --git a/crates/usd/README.md b/crates/usd/README.md index fcf585760e..47f624c478 100644 --- a/crates/usd/README.md +++ b/crates/usd/README.md @@ -1,7 +1,11 @@ # craft-usd -Bounded wire primitives for USD Crate, independent of application scene and material models. +Bounded wire primitives and neutral `.usda`/`.usdc` scene, prim, and layer read/write for USD, independent of application mesh and material models. -Provides bounded integer-delta array decoding and Crate-framed LZ4 compression/decompression: a single unprefixed block or up to 127 length-prefixed blocks, under a caller-provided output-byte cap with fallible output allocation. Trailing bytes after counted chunks retain the original reader's ignored-tail policy. This is not a complete USD reader/writer; scene interpretation, integer packing and full scene export remain outside this extraction. Compression uses a caller cap on worst-case reserved output and fallible allocation. Integer decoding uses explicit 32/64-bit widths, signed wrapping arithmetic, a caller output-byte cap and fallible allocation. +Provides: +- Bounded integer-delta array decoding/encoding and Crate-framed LZ4 compression/decompression (`compress`, `integers`, `decompress`) under caller-provided output-byte caps with fallible allocation. +- Shared Crate wire constants and type metadata (`codec`). +- Neutral `.usda` (text) and `.usdc` (Crate binary) layer reader (`scene::read_layer`, `scene::read_layer_with_budget`) preserving `def`/`over`/`class` specifiers, internal references, coordinate metadata (`metersPerUnit`, `upAxis`), payload/sublayer/variant warnings, and decoded byte budgets (`scene::Budget`). +- Neutral `.usda` and `.usdc` scene/prim/layer writer (`scene::write_usda`, `scene::write_usdc`). -Adapted from TextureCraft `crates/formats/src/mesh_import/usd/codec.rs`, introduced by bflatastic in `bdbb52c9b66b221a55b370105b42f485a76e6fc7`. The LZ4 backend is MIT-licensed `lz4_flex`. +Adapted from TextureCraft's `mesh_import/usd` and `mesh_export/{usd,usdc}.rs`, originally introduced by bflatastic in `bdbb52c9b66b221a55b370105b42f485a76e6fc7`. The LZ4 backend is MIT-licensed `lz4_flex`. diff --git a/crates/usd/src/codec.rs b/crates/usd/src/codec.rs new file mode 100644 index 0000000000..659cc87f17 --- /dev/null +++ b/crates/usd/src/codec.rs @@ -0,0 +1,113 @@ +//! Shared USD Crate (`.usdc`) wire constants and type metadata. + +/// Magic bytes at the start of every USD Crate file. +pub const MAGIC: &[u8; 8] = b"PXR-USDC"; +/// Size of the bootstrap header: magic, version, TOC offset, reserved. +pub const BOOTSTRAP_LEN: usize = 88; +/// Arrays shorter than this are never stored compressed. +pub const MIN_COMPRESSED_ARRAY: usize = 16; + +/// ValueRep array flag. +pub const IS_ARRAY: u64 = 1 << 63; +/// ValueRep inline flag. +pub const IS_INLINED: u64 = 1 << 62; +/// ValueRep compressed flag. +pub const IS_COMPRESSED: u64 = 1 << 61; +/// ValueRep array-edit flag. +pub const IS_ARRAY_EDIT: u64 = 1 << 60; +/// ValueRep 48-bit payload mask. +pub const PAYLOAD_MASK: u64 = (1 << 48) - 1; + +/// Value type ids (Crate data types). +pub mod ty { + pub const BOOL: u8 = 1; + pub const UCHAR: u8 = 2; + pub const INT: u8 = 3; + pub const UINT: u8 = 4; + pub const INT64: u8 = 5; + pub const UINT64: u8 = 6; + pub const HALF: u8 = 7; + pub const FLOAT: u8 = 8; + pub const DOUBLE: u8 = 9; + pub const STRING: u8 = 10; + pub const TOKEN: u8 = 11; + pub const ASSET_PATH: u8 = 12; + pub const MATRIX2D: u8 = 13; + pub const MATRIX3D: u8 = 14; + pub const MATRIX4D: u8 = 15; + pub const QUATD: u8 = 16; + pub const QUATF: u8 = 17; + pub const QUATH: u8 = 18; + pub const VEC2D: u8 = 19; + pub const VEC2F: u8 = 20; + pub const VEC3F: u8 = 24; + pub const VEC4F: u8 = 28; + pub const VEC4I: u8 = 30; + pub const TOKEN_LIST_OP: u8 = 32; + pub const PATH_LIST_OP: u8 = 34; + pub const REFERENCE_LIST_OP: u8 = 35; + pub const PATH_VECTOR: u8 = 40; + pub const TOKEN_VECTOR: u8 = 41; + pub const SPECIFIER: u8 = 42; + pub const PERMISSION: u8 = 43; + pub const VARIABILITY: u8 = 44; + pub const TIME_SAMPLES: u8 = 46; + pub const DOUBLE_VECTOR: u8 = 48; +} + +/// Scalar kind of numeric Crate types. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Scalar { + U8, + I32, + U32, + I64, + U64, + F16, + F32, + F64, +} + +impl Scalar { + /// Byte size of one scalar element. + pub fn size(self) -> usize { + match self { + Self::U8 => 1, + Self::F16 => 2, + Self::I32 | Self::U32 | Self::F32 => 4, + Self::I64 | Self::U64 | Self::F64 => 8, + } + } +} + +/// `(scalar, components)` of numeric type `t`, or `None` for non-numeric types. +pub fn numeric(t: u8) -> Option<(Scalar, usize)> { + Some(match t { + ty::BOOL | ty::UCHAR => (Scalar::U8, 1), + ty::INT => (Scalar::I32, 1), + ty::UINT => (Scalar::U32, 1), + ty::INT64 => (Scalar::I64, 1), + ty::UINT64 => (Scalar::U64, 1), + ty::HALF => (Scalar::F16, 1), + ty::FLOAT => (Scalar::F32, 1), + ty::DOUBLE => (Scalar::F64, 1), + ty::MATRIX2D => (Scalar::F64, 4), + ty::MATRIX3D => (Scalar::F64, 9), + ty::MATRIX4D => (Scalar::F64, 16), + ty::QUATD => (Scalar::F64, 4), + ty::QUATF => (Scalar::F32, 4), + ty::QUATH => (Scalar::F16, 4), + // Vec{2,3,4}{d,f,h,i}: ids 19..=30 in that order. + ty::VEC2D..=ty::VEC4I => { + let k = t - ty::VEC2D; + let scalar = [Scalar::F64, Scalar::F32, Scalar::F16, Scalar::I32][usize::from(k % 4)]; + (scalar, usize::from(k / 4) + 2) + } + _ => return None, + }) +} + +/// Upper bound of the encoded size of `n` integers of `width` bytes. +pub fn encoded_ints_len(n: usize, width: usize) -> usize { + if n == 0 { 0 } else { width.saturating_add(n.saturating_mul(2).saturating_add(7) / 8).saturating_add(n.saturating_mul(width)) } +} diff --git a/crates/usd/src/lib.rs b/crates/usd/src/lib.rs index 33c7f3484b..9bf2a88a2f 100644 --- a/crates/usd/src/lib.rs +++ b/crates/usd/src/lib.rs @@ -1,16 +1,22 @@ -//! Bounded USD Crate wire primitives. Not a complete USD scene reader or writer. +//! Bounded USD Crate wire primitives and neutral `.usda`/`.usdc` scene/prim/layer read/write. //! -//! The framing decoder is adapted from TextureCraft's `usd/codec.rs`, originally +//! The Crate framing decoder is adapted from TextureCraft's `usd/codec.rs`, originally //! bflatastic, commit bdbb52c9b66b221a55b370105b42f485a76e6fc7. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +/// Shared USD Crate wire constants and type metadata. +pub mod codec; + /// Bounded single-block Crate LZ4 compression. pub mod compress; /// Bounded Crate integer delta arrays. pub mod integers; +/// Neutral USDA/USDC scene, prim, and layer read/write. +pub mod scene; + /// Failure to read a bounded Crate LZ4 frame. #[derive(Debug, thiserror::Error)] pub enum Error { diff --git a/crates/usd/src/scene/mod.rs b/crates/usd/src/scene/mod.rs new file mode 100644 index 0000000000..b69e5463af --- /dev/null +++ b/crates/usd/src/scene/mod.rs @@ -0,0 +1,275 @@ +//! Neutral USDA/USDC scene, prim, and layer read/write. +//! +//! Parses `.usda` (text) and `.usdc` (Crate binary) layers into a neutral [`Layer`] +//! representation (keeping `def`/`over`/`class` specifiers, internal references, coordinate +//! metadata, payload/sublayer/variant warnings, and decoded byte budgets), and writes neutral +//! [`UsdLayer`] scenes to `.usda` text or `.usdc` Crate binary. + +pub mod usda; +pub mod usdc; +pub mod write; + +use std::collections::HashMap; + +use crate::codec; + +/// Default memory budget for decoded layer values (2 GiB). +pub const MAX_DECODED_BYTES: usize = 1 << 31; +/// Deepest prim nesting and reference chain followed. +pub const MAX_DEPTH: usize = 128; + +/// Error returned when reading or writing a USD layer or scene. +#[derive(Debug, thiserror::Error)] +pub enum SceneError { + /// Syntax, framing, or structural error in the input. + #[error("malformed USD: {0}")] + Malformed(String), + /// Decoded data or table size exceeds the configured budget or limit. + #[error("{0}")] + TooLarge(String), + /// Unsupported USD Crate version. + #[error("unsupported USD: {0}")] + Unsupported(String), + /// Invalid scene structure when writing (for example, an unknown target path). + #[error("invalid USD: {0}")] + Invalid(String), +} + +/// Result alias for USD scene operations. +pub type Result = std::result::Result; + +/// Charges decoded data against a byte ceiling. +#[derive(Clone, Debug)] +pub struct Budget(pub usize); + +impl Budget { + /// Create a budget with [`MAX_DECODED_BYTES`]. + pub fn new() -> Self { + Self(MAX_DECODED_BYTES) + } + + /// Create a budget with a custom byte limit. + pub fn with_limit(limit: usize) -> Self { + Self(limit) + } + + /// Deduct `bytes` from the remaining budget, failing with [`SceneError::TooLarge`] if exceeded. + pub fn take(&mut self, bytes: usize) -> Result<()> { + self.0 = self + .0 + .checked_sub(bytes) + .ok_or_else(|| SceneError::TooLarge(format!("the USD file decodes to more than {} MiB", MAX_DECODED_BYTES >> 20)))?; + Ok(()) + } +} + +impl Default for Budget { + fn default() -> Self { + Self::new() + } +} + +/// A decoded value: numbers (scalars, vectors, quaternions as `w x y z`, matrices row-major, +/// and bools all flattened), tokens / strings / asset paths, or prim/property paths. +#[derive(Clone, Debug, PartialEq)] +pub enum Val { + Num(Vec), + Tok(Vec), + Path(Vec), +} + +/// A decoded prim property (attribute or relationship). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Prop { + /// Declared type (`point3f[]`, `texCoord2f[]`, `rel`, ...). + pub type_name: String, + pub value: Option, + pub interpolation: Option, + /// The first connection source (`name.connect`): an attribute path. + pub connect: Option, +} + +/// Prim specifier (`def`, `over`, `class`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Specifier { + #[default] + Def, + Over, + Class, +} + +/// One prim spec of a decoded [`Layer`]. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct PrimSpec { + pub name: String, + pub path: String, + pub type_name: String, + pub specifier: Specifier, + pub active: Option, + pub props: HashMap, + pub children: Vec, + /// Internal references: absolute prim paths in this layer. + pub references: Vec, +} + +/// A parsed USD layer: prim specs (index 0 is the pseudo-root `/`) and stage metadata. +#[derive(Clone, Debug, PartialEq)] +pub struct Layer { + pub prims: Vec, + pub meters_per_unit: Option, + pub up_axis: Option, + pub warnings: Vec, +} + +impl Layer { + /// Create an empty layer with a pseudo-root prim at index 0 (`"/"`). + pub fn new() -> Self { + Self { prims: vec![PrimSpec { path: "/".into(), ..PrimSpec::default() }], meters_per_unit: None, up_axis: None, warnings: Vec::new() } + } + + /// Add a prim spec named `name` under prim `parent` and return its index. + pub fn add_prim(&mut self, parent: usize, name: &str) -> usize { + let path = match self.prims.get(parent) { + Some(p) if p.path == "/" => format!("/{name}"), + Some(p) => format!("{}/{name}", p.path), + None => format!("/{name}"), + }; + let id = self.prims.len(); + self.prims.push(PrimSpec { name: name.into(), path, ..PrimSpec::default() }); + if let Some(p) = self.prims.get_mut(parent) { + p.children.push(id); + } + id + } + + /// Record a deduplicated warning message on the layer. + pub fn warn(&mut self, msg: &str) { + if !self.warnings.iter().any(|w| w == msg) { + self.warnings.push(msg.into()); + } + } +} + +impl Default for Layer { + fn default() -> Self { + Self::new() + } +} + +/// Read a `.usda` or `.usdc` layer from `bytes` using [`Budget::new()`]. +pub fn read_layer(bytes: &[u8]) -> Result { + let mut budget = Budget::new(); + read_layer_with_budget(bytes, &mut budget) +} + +/// Read a `.usda` or `.usdc` layer from `bytes`, charging decoded allocations to `budget`. +pub fn read_layer_with_budget(bytes: &[u8], budget: &mut Budget) -> Result { + if bytes.starts_with(codec::MAGIC) { + usdc::read(bytes, budget) + } else if bytes.trim_ascii_start().starts_with(b"#usda") { + usda::read(bytes, budget) + } else { + Err(SceneError::Malformed("neither a USD text layer (#usda) nor a Crate binary (PXR-USDC)".into())) + } +} + +/// A value written to a [`UsdLayer`]. +#[derive(Clone, Debug, PartialEq)] +pub enum UsdValue { + Token(String), + Str(String), + Int(i32), + Double(f64), + Asset(String), + Float4([f32; 4]), + Ints(Vec), + Vec2fs(Vec<[f32; 2]>), + Vec3fs(Vec<[f32; 3]>), + /// A relationship target or attribute connection (absolute path). + Target(String), +} + +/// An attribute (or, with type `"rel"`, a relationship) to write. +#[derive(Clone, Debug, PartialEq)] +pub struct UsdAttr { + pub name: String, + pub type_name: String, + pub uniform: bool, + pub value: Option, + /// Connection source of an attribute (`name.connect`). + pub connect: Option, + pub interpolation: Option, +} + +impl UsdAttr { + /// Create a new attribute with `name`, `type_name`, and optional `value`. + pub fn new(name: &str, type_name: &str, value: Option) -> Self { + Self { name: name.into(), type_name: type_name.into(), uniform: false, value, connect: None, interpolation: None } + } + + /// Mark this attribute as `uniform`. + pub fn uniform(mut self) -> Self { + self.uniform = true; + self + } + + /// Set the `interpolation` metadata on this attribute. + pub fn with_interpolation(mut self, interpolation: &str) -> Self { + self.interpolation = Some(interpolation.into()); + self + } + + /// Create a relationship (`rel`) targeting `target`. + pub fn rel(name: &str, target: String) -> Self { + Self::new(name, "rel", Some(UsdValue::Target(target))) + } + + /// Create a connected attribute (`name.connect = `). + pub fn connected(name: &str, type_name: &str, source: String) -> Self { + Self { connect: Some(source), ..Self::new(name, type_name, None) } + } +} + +/// A prim to write into a [`UsdLayer`]. +#[derive(Clone, Debug, PartialEq)] +pub struct UsdPrim { + pub name: String, + pub type_name: String, + /// Applies `MaterialBindingAPI` (when the prim has a `material:binding`). + pub binding_api: bool, + pub attrs: Vec, + pub children: Vec, +} + +impl UsdPrim { + /// Create a new `def` prim with `name` and `type_name`. + pub fn new(name: &str, type_name: &str) -> Self { + Self { name: name.into(), type_name: type_name.into(), binding_api: false, attrs: Vec::new(), children: Vec::new() } + } +} + +/// A neutral writable USD layer with its root prim and stage metadata. +#[derive(Clone, Debug, PartialEq)] +pub struct UsdLayer { + pub root: UsdPrim, + pub doc: Option, + pub meters_per_unit: f64, + pub up_axis: String, +} + +impl UsdLayer { + /// Create a writable layer with `root` as the default prim, `metersPerUnit = 1`, `upAxis = "Y"`. + pub fn new(root: UsdPrim) -> Self { + Self { root, doc: None, meters_per_unit: 1.0, up_axis: "Y".into() } + } +} + +/// Format `layer` as `.usda` text. +pub fn write_usda(layer: &UsdLayer) -> String { + write::usda(layer) +} + +/// Encode `layer` as a `.usdc` Crate binary. +pub fn write_usdc(layer: &UsdLayer) -> Result> { + write::usdc(layer) +} diff --git a/crates/usd/src/scene/usda.rs b/crates/usd/src/scene/usda.rs new file mode 100644 index 0000000000..40637ea049 --- /dev/null +++ b/crates/usd/src/scene/usda.rs @@ -0,0 +1,512 @@ +//! The USD text format (`.usda`): layer metadata, `def` / `over` / `class` prims with metadata +//! (`references`, `active`), attributes (default values, the first time sample, +//! `interpolation`) and relationships. Variant sets, dictionaries and connections are skipped. + +use super::{Budget, Layer, Result, SceneError, Specifier, Val}; + +/// Deepest value / prim nesting accepted. +const MAX_NESTING: usize = 128; + +#[derive(Clone, Debug, PartialEq)] +enum Tok { + Punct(u8), + Ident(String), + Str(String), + Num(f64), + Asset(String), + Path(String), + Eof, +} + +struct Lexer<'a> { + s: &'a [u8], + pos: usize, + peeked: Option, +} + +fn is_ident_start(c: u8) -> bool { + c.is_ascii_alphabetic() || c == b'_' +} + +fn is_ident(c: u8) -> bool { + c.is_ascii_alphanumeric() || matches!(c, b'_' | b':' | b'.') +} + +impl Lexer<'_> { + fn at(&self, k: usize) -> u8 { + self.s.get(self.pos + k).copied().unwrap_or(0) + } + + fn line(&self) -> usize { + 1 + self.s.get(..self.pos).unwrap_or_default().iter().filter(|&&c| c == b'\n').count() + } + + fn err(&self, msg: impl std::fmt::Display) -> SceneError { + SceneError::Malformed(format!("line {}: {msg}", self.line())) + } + + fn skip_space(&mut self) { + loop { + match self.at(0) { + b' ' | b'\t' | b'\r' | b'\n' => self.pos += 1, + b'#' => self.skip_until(b"\n"), + b'/' if self.at(1) == b'/' => self.skip_until(b"\n"), + b'/' if self.at(1) == b'*' => { + self.pos += 2; + self.skip_until(b"*/"); + self.pos = (self.pos + 2).min(self.s.len()); + } + _ => return, + } + } + } + + /// Advance to the next `end` (or the end of input). + fn skip_until(&mut self, end: &[u8]) { + let rest = self.s.get(self.pos..).unwrap_or_default(); + self.pos += rest.windows(end.len()).position(|w| w == end).unwrap_or(rest.len()); + } + + /// Bytes up to the next `end`, consuming the delimiter. + fn delimited(&mut self, end: &[u8]) -> Result<&[u8]> { + let start = self.pos; + self.skip_until(end); + if self.pos >= self.s.len() { + return Err(self.err("unterminated string, asset path or path")); + } + let body = self.s.get(start..self.pos).unwrap_or_default(); + self.pos += end.len(); + Ok(body) + } + + fn string(&mut self, quote: u8) -> Result { + if self.at(0) == quote && self.at(1) == quote { + self.pos += 2; + let body = self.delimited(&[quote; 3])?; + return Ok(String::from_utf8_lossy(body).into_owned()); + } + let mut out = Vec::new(); + loop { + match self.at(0) { + 0 if self.pos >= self.s.len() => return Err(self.err("unterminated string")), + b'\n' => return Err(self.err("newline in a string")), + b'\\' => { + out.push(match self.at(1) { + b'n' => b'\n', + b't' => b'\t', + c => c, + }); + self.pos += 2; + } + c if c == quote => { + self.pos += 1; + return Ok(String::from_utf8_lossy(&out).into_owned()); + } + c => { + out.push(c); + self.pos += 1; + } + } + } + } + + fn lex(&mut self) -> Result { + self.skip_space(); + let c = self.at(0); + if self.pos >= self.s.len() { + return Ok(Tok::Eof); + } + let text = |s: &[u8]| String::from_utf8_lossy(s).into_owned(); + Ok(match c { + b'"' | b'\'' => { + self.pos += 1; + Tok::Str(self.string(c)?) + } + b'@' if self.at(1) == b'@' && self.at(2) == b'@' => { + self.pos += 3; + Tok::Asset(text(self.delimited(b"@@@")?)) + } + b'@' => { + self.pos += 1; + Tok::Asset(text(self.delimited(b"@")?)) + } + b'<' => { + self.pos += 1; + Tok::Path(text(self.delimited(b">")?)) + } + b'0'..=b'9' | b'-' | b'+' | b'.' => { + let start = self.pos; + self.pos += 1; + while self.at(0).is_ascii_alphanumeric() || matches!(self.at(0), b'.' | b'-' | b'+') { + self.pos += 1; + } + let word = std::str::from_utf8(self.s.get(start..self.pos).unwrap_or_default()).unwrap_or_default(); + Tok::Num(word.parse().map_err(|_| self.err(format!("bad number \"{word}\"")))?) + } + c if is_ident_start(c) => { + let start = self.pos; + while is_ident(self.at(0)) { + self.pos += 1; + } + Tok::Ident(text(self.s.get(start..self.pos).unwrap_or_default())) + } + c => { + self.pos += 1; + Tok::Punct(c) + } + }) + } + + fn next(&mut self) -> Result { + match self.peeked.take() { + Some(t) => Ok(t), + None => self.lex(), + } + } + + fn peek(&mut self) -> Result<&Tok> { + if self.peeked.is_none() { + self.peeked = Some(self.lex()?); + } + Ok(self.peeked.get_or_insert(Tok::Eof)) + } + + fn eat(&mut self, p: u8) -> Result { + let hit = *self.peek()? == Tok::Punct(p); + if hit { + self.peeked = None; + } + Ok(hit) + } + + fn expect(&mut self, p: u8) -> Result<()> { + match self.next()? { + Tok::Punct(c) if c == p => Ok(()), + t => Err(self.err(format!("expected '{}', found {t:?}", p as char))), + } + } +} + +/// A value, flattened: numbers, strings (tokens, asset paths) and paths in document order. +#[derive(Default)] +struct Acc { + nums: Vec, + strs: Vec, + paths: Vec, + /// The last item was an asset path (a path right after one names a prim in that asset). + after_asset: bool, + none: bool, +} + +impl Acc { + fn into_val(self) -> Option { + if self.none { + None + } else if !self.paths.is_empty() { + Some(Val::Path(self.paths)) + } else if !self.strs.is_empty() { + Some(Val::Tok(self.strs)) + } else { + Some(Val::Num(self.nums)) + } + } +} + +struct Parser<'a, 'b> { + lx: Lexer<'a>, + layer: Layer, + budget: &'b mut Budget, +} + +/// Metadata keys whose values are kept. +const KEPT_METADATA: [&str; 7] = ["metersPerUnit", "upAxis", "subLayers", "references", "active", "interpolation", "payload"]; + +/// Parse a `.usda` text layer, charging decoded allocations against `budget`. +pub fn read(bytes: &[u8], budget: &mut Budget) -> Result { + let mut lx = Lexer { s: bytes, pos: 0, peeked: None }; + // The header is a comment: `#usda 1.0`. + lx.skip_space(); + let mut p = Parser { lx, layer: Layer::new(), budget }; + if *p.lx.peek()? == Tok::Punct(b'(') { + for (key, acc) in p.metadata()? { + match (key.as_str(), acc.into_val()) { + ("metersPerUnit", Some(Val::Num(v))) => p.layer.meters_per_unit = v.first().copied(), + ("upAxis", Some(Val::Tok(v))) => p.layer.up_axis = v.into_iter().next(), + ("subLayers", Some(Val::Tok(v))) if !v.is_empty() => p.layer.warn("sublayers are not loaded"), + _ => {} + } + } + } + loop { + match p.lx.next()? { + Tok::Eof => break, + Tok::Ident(kw) if matches!(kw.as_str(), "def" | "over" | "class") => p.prim(0, &kw, 0)?, + Tok::Punct(b';') => {} + t => return Err(p.lx.err(format!("expected a prim, found {t:?}"))), + } + } + Ok(p.layer) +} + +impl Parser<'_, '_> { + /// One value into `acc`. + fn value(&mut self, acc: &mut Acc, depth: usize) -> Result<()> { + if depth > MAX_NESTING { + return Err(self.lx.err("values are nested too deeply")); + } + let after_asset = std::mem::take(&mut acc.after_asset); + match self.lx.next()? { + Tok::Num(v) => { + self.budget.take(8)?; + acc.nums.push(v); + } + Tok::Ident(w) => match w.as_str() { + "true" | "false" => { + self.budget.take(8)?; + acc.nums.push(if w == "true" { 1.0 } else { 0.0 }); + } + "inf" | "nan" => { + self.budget.take(8)?; + acc.nums.push(w.parse().unwrap_or(f64::NAN)); + } + "None" => acc.none = true, + _ => self.push_str(acc, w)?, + }, + Tok::Str(s) => self.push_str(acc, s)?, + Tok::Asset(s) => { + self.push_str(acc, s)?; + acc.after_asset = true; + } + // A path right after an asset path names a prim in that (external) layer. + Tok::Path(_) if after_asset => {} + Tok::Path(p) => { + self.budget.take(p.len() + 24)?; + acc.paths.push(p); + } + Tok::Punct(open @ (b'[' | b'(')) => { + let close = if open == b'[' { b']' } else { b')' }; + loop { + match self.lx.peek()? { + Tok::Punct(c) if *c == close => break, + Tok::Punct(b',' | b';' | b'=') => { + acc.after_asset = false; + self.lx.next()?; + } + Tok::Eof => return Err(self.lx.err("unterminated list")), + _ => self.value(acc, depth + 1)?, + } + } + self.lx.next()?; + } + Tok::Punct(b'{') => self.skip_block(b'{', b'}')?, + t => return Err(self.lx.err(format!("unexpected {t:?} in a value"))), + } + Ok(()) + } + + fn push_str(&mut self, acc: &mut Acc, s: String) -> Result<()> { + self.budget.take(s.len() + 24)?; + acc.strs.push(s); + Ok(()) + } + + /// Skip a balanced block whose opening token was just read. + fn skip_block(&mut self, open: u8, close: u8) -> Result<()> { + let mut depth = 1usize; + while depth > 0 { + match self.lx.next()? { + Tok::Punct(c) if c == open => depth += 1, + Tok::Punct(c) if c == close => depth -= 1, + Tok::Eof => return Err(self.lx.err("unterminated block")), + _ => {} + } + } + Ok(()) + } + + /// A `( ... )` metadata block (the `(` not yet read): the kept entries, by key. List-op + /// `delete` and `reorder` entries are dropped. + fn metadata(&mut self) -> Result> { + self.lx.expect(b'(')?; + let mut out = Vec::new(); + loop { + let (mut key, mut keep) = match self.lx.next()? { + Tok::Punct(b')') => return Ok(out), + Tok::Punct(b';' | b',') | Tok::Str(_) => continue, + Tok::Ident(k) => (k, true), + t => return Err(self.lx.err(format!("unexpected {t:?} in metadata"))), + }; + if matches!(key.as_str(), "prepend" | "append" | "add" | "delete" | "reorder") { + keep = !matches!(key.as_str(), "delete" | "reorder"); + key = match self.lx.next()? { + Tok::Ident(k) => k, + t => return Err(self.lx.err(format!("expected a metadata key, found {t:?}"))), + }; + } + if !self.lx.eat(b'=')? { + continue; + } + let mut acc = Acc::default(); + self.value(&mut acc, 0)?; + if keep && KEPT_METADATA.contains(&key.as_str()) { + out.push((key, acc)); + } + } + } + + fn prim(&mut self, parent: usize, specifier: &str, depth: usize) -> Result<()> { + if depth > MAX_NESTING { + return Err(self.lx.err("prims are nested too deeply")); + } + let (type_name, name) = match self.lx.next()? { + Tok::Ident(t) => match self.lx.next()? { + Tok::Str(n) => (t, n), + t => return Err(self.lx.err(format!("expected a prim name, found {t:?}"))), + }, + Tok::Str(n) => (String::new(), n), + t => return Err(self.lx.err(format!("expected a prim name, found {t:?}"))), + }; + self.budget.take(name.len() * 2 + 256)?; + let id = self.layer.add_prim(parent, &name); + let mut references = Vec::new(); + let mut active = None; + if *self.lx.peek()? == Tok::Punct(b'(') { + for (key, acc) in self.metadata()? { + match key.as_str() { + "references" | "payload" => { + if !acc.strs.is_empty() { + self.layer.warn("external references and payloads are not loaded"); + } + references.extend(acc.paths); + } + "active" => active = acc.nums.first().map(|v| *v != 0.0), + _ => {} + } + } + } + if let Some(spec) = self.layer.prims.get_mut(id) { + spec.type_name = type_name; + spec.specifier = match specifier { + "over" => Specifier::Over, + "class" => Specifier::Class, + _ => Specifier::Def, + }; + spec.active = active; + spec.references = references; + } + self.lx.expect(b'{')?; + loop { + let word = match self.lx.next()? { + Tok::Punct(b'}') => return Ok(()), + Tok::Punct(b';') => continue, + Tok::Ident(w) => w, + t => return Err(self.lx.err(format!("unexpected {t:?} in prim \"{name}\""))), + }; + match word.as_str() { + "def" | "over" | "class" => self.prim(id, &word, depth + 1)?, + "variantSet" => { + self.layer.warn("variant sets are not applied"); + while !self.lx.eat(b'{')? { + if self.lx.next()? == Tok::Eof { + return Err(self.lx.err("unterminated variant set")); + } + } + self.skip_block(b'{', b'}')?; + } + "reorder" => { + self.lx.next()?; + self.lx.expect(b'=')?; + self.value(&mut Acc::default(), 0)?; + } + _ => self.property(id, word)?, + } + } + } + + /// An attribute or relationship whose first word was read. + fn property(&mut self, prim: usize, mut word: String) -> Result<()> { + let mut keep = true; + while matches!(word.as_str(), "custom" | "uniform" | "varying" | "config" | "prepend" | "append" | "add" | "delete") { + keep &= word != "delete"; + word = match self.lx.next()? { + Tok::Ident(w) => w, + t => return Err(self.lx.err(format!("expected a property type, found {t:?}"))), + }; + } + let mut type_name = word; + if self.lx.eat(b'[')? { + self.lx.expect(b']')?; + type_name.push_str("[]"); + } + let full = match self.lx.next()? { + Tok::Ident(n) => n, + t => return Err(self.lx.err(format!("expected a property name, found {t:?}"))), + }; + let (name, suffix) = match full.rsplit_once('.') { + Some((n, s @ ("connect" | "timeSamples" | "spline" | "default"))) => (n.to_string(), s), + _ => (full, ""), + }; + let mut acc = Acc::default(); + let mut has_value = false; + if self.lx.eat(b'=')? { + has_value = true; + if suffix == "timeSamples" || suffix == "spline" { + self.first_sample(&mut acc)?; + } else { + self.value(&mut acc, 0)?; + } + } + let mut interpolation = None; + if *self.lx.peek()? == Tok::Punct(b'(') { + for (key, meta) in self.metadata()? { + if key == "interpolation" { + interpolation = meta.strs.into_iter().next(); + } + } + } + if !keep || suffix == "spline" { + return Ok(()); + } + let Some(spec) = self.layer.prims.get_mut(prim) else { return Ok(()) }; + let prop = spec.props.entry(name).or_default(); + if suffix == "connect" { + prop.connect = acc.paths.into_iter().next(); + return Ok(()); + } + // A plain default and its time samples may both be authored; the default wins. + if has_value && (suffix != "timeSamples" || prop.value.is_none()) { + prop.value = acc.into_val(); + } + prop.type_name = type_name; + if interpolation.is_some() { + prop.interpolation = interpolation; + } + Ok(()) + } + + /// `{ time: value, ... }`: the first sample's value into `acc`, the rest skipped. + fn first_sample(&mut self, acc: &mut Acc) -> Result<()> { + self.lx.expect(b'{')?; + let mut first = true; + loop { + match self.lx.next()? { + Tok::Punct(b'}') => return Ok(()), + Tok::Punct(b',') => {} + Tok::Num(_) => { + self.lx.expect(b':')?; + if first { + self.value(acc, 0)?; + first = acc.none; + acc.none = false; + } else { + let mut skip = Acc::default(); + self.value(&mut skip, 0)?; + // Skipped samples do not stay in memory. + self.budget.0 = self.budget.0.saturating_add(8 * skip.nums.len()); + } + } + t => return Err(self.lx.err(format!("unexpected {t:?} in time samples"))), + } + } + } +} diff --git a/crates/usd/src/scene/usdc.rs b/crates/usd/src/scene/usdc.rs new file mode 100644 index 0000000000..89a2daddf3 --- /dev/null +++ b/crates/usd/src/scene/usdc.rs @@ -0,0 +1,840 @@ +//! The USD Crate binary format (`.usdc`, versions 0.4.0 and newer): bootstrap header, table of +//! contents, the TOKENS / STRINGS / FIELDS / FIELDSETS / PATHS / SPECS sections, and decoded +//! values (numeric scalars, vectors, quaternions, matrices, arrays, tokens, strings, asset paths, +//! token/path vectors, token/path/reference list ops, and the first time sample). + +use std::collections::HashMap; + +use crate::codec::{self, Scalar, ty}; +use crate::integers::{self, Width}; +use crate::scene::{Budget, Layer, MAX_DECODED_BYTES, MAX_DEPTH, Prop, Result, SceneError, Specifier, Val}; + +/// Oldest Crate version read (compressed structural sections). +const MIN_VERSION: (u8, u8, u8) = (0, 4, 0); +const MAX_SECTIONS: usize = 64; +/// Items in one table or array. +const MAX_ITEMS: usize = 1 << 28; +/// Entries in the PATHS table. The declared count is tiny in the file but each entry is a +/// materialised path, so it needs its own ceiling as well as the decoded-byte budget. +const MAX_PATHS: usize = 4_000_000; + +/// Spec types. +const SPEC_ATTRIBUTE: i64 = 1; +const SPEC_PRIM: i64 = 6; +const SPEC_PSEUDO_ROOT: i64 = 7; +const SPEC_RELATIONSHIP: i64 = 8; +const SPEC_VARIANT: i64 = 10; +const SPEC_VARIANT_SET: i64 = 11; + +fn truncated() -> SceneError { + SceneError::Malformed("the file is truncated or an offset points outside it".into()) +} + +fn check_count(n: u64, cap: usize) -> Result { + usize::try_from(n).ok().filter(|n| *n <= cap).ok_or_else(|| SceneError::TooLarge(format!("USD array of {n} items (limit {cap})"))) +} + +fn decompress_block(input: &[u8], max_out: usize) -> Result> { + crate::decompress(input, max_out).map_err(|e| SceneError::Malformed(e.to_string())) +} + +fn decode_ints(data: &[u8], n: usize, width: usize) -> Result> { + let width = match width { + 4 => Width::I32, + 8 => Width::I64, + _ => return Err(SceneError::Malformed("unsupported integer width".into())), + }; + integers::decode(data, n, width, MAX_DECODED_BYTES).map_err(|e| SceneError::Malformed(e.to_string())) +} + +/// A bounds-checked little-endian cursor. +#[derive(Clone)] +struct Cur<'a> { + b: &'a [u8], + pos: usize, +} + +impl<'a> Cur<'a> { + fn bytes(&mut self, n: usize) -> Result<&'a [u8]> { + let s = self.b.get(self.pos..self.pos.checked_add(n).ok_or_else(truncated)?).ok_or_else(truncated)?; + self.pos += n; + Ok(s) + } + + fn array(&mut self) -> Result<[u8; N]> { + self.bytes(N)?.try_into().map_err(|_| truncated()) + } + + fn u8(&mut self) -> Result { + let [b] = self.array::<1>()?; + Ok(b) + } + + fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.array()?)) + } + + fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.array()?)) + } + + fn f64(&mut self) -> Result { + Ok(f64::from_le_bytes(self.array()?)) + } + + fn remaining(&self) -> usize { + self.b.len().saturating_sub(self.pos) + } + + /// A count of items of `item_bytes` each that must fit in the rest of the data (0: items + /// that follow compressed, bounded by [`MAX_ITEMS`] only). + fn count(&mut self, item_bytes: usize) -> Result { + let n = self.u64()?; + check_count(n, self.cap(item_bytes)) + } + + /// Most items of `item_bytes` each the rest of the data can hold (0: [`MAX_ITEMS`]). + fn cap(&self, item_bytes: usize) -> usize { + self.remaining().checked_div(item_bytes).map_or(MAX_ITEMS, |n| n.min(MAX_ITEMS)) + } + + fn seek(&mut self, pos: u64) -> Result<()> { + self.pos = usize::try_from(pos).ok().filter(|p| *p <= self.b.len()).ok_or_else(truncated)?; + Ok(()) + } + + /// Follow a relative int64 offset stored at the cursor (Crate's nested values). + fn jump(&mut self) -> Result<()> { + let start = self.pos as u64; + let off = i64::from_le_bytes(self.array()?); + self.seek(start.checked_add_signed(off).filter(|_| off >= 8).ok_or_else(truncated)?) + } + + /// `n` integers of `width` bytes in the compressed integer coding. + fn ints(&mut self, n: usize, width: usize, budget: &mut Budget) -> Result> { + let size = self.u64()?; + let comp = self.bytes(usize::try_from(size).map_err(|_| truncated())?)?; + if n == 0 { + return Ok(Vec::new()); + } + // LZ4 expands at most ~255x; a coded integer takes at least 2 bits. + if n > comp.len().saturating_mul(1024).saturating_add(64) { + return Err(SceneError::Malformed("integer array is larger than its compressed data allows".into())); + } + budget.take(n.saturating_mul(8))?; + let raw = decompress_block(comp, codec::encoded_ints_len(n, width))?; + decode_ints(&raw, n, width) + } +} + +/// A little-endian scalar from its `s.size()` bytes. +fn scalar(s: Scalar, b: &[u8]) -> f64 { + let mut a = [0u8; 8]; + for (o, v) in a.iter_mut().zip(b.iter().take(s.size())) { + *o = *v; + } + let le = u64::from_le_bytes(a); + match s { + Scalar::U8 => f64::from(le as u8), + Scalar::I32 => f64::from(le as u32 as i32), + Scalar::U32 => f64::from(le as u32), + Scalar::I64 => le as i64 as f64, + Scalar::U64 => le as f64, + Scalar::F16 => f64::from(half::f16::from_bits(le as u16).to_f32()), + Scalar::F32 => f64::from(f32::from_bits(le as u32)), + Scalar::F64 => f64::from_bits(le), + } +} + +fn is_quat(t: u8) -> bool { + (ty::QUATD..=ty::QUATH).contains(&t) +} + +/// Quaternions are stored imaginary first; values keep USD's text order (real first). +fn quat_order(t: u8, v: &mut [f64]) { + if is_quat(t) { + for q in v.as_chunks_mut::<4>().0 { + q.rotate_right(1); + } + } +} + +#[derive(Clone)] +struct PathEl { + text: String, + parent: Option, + name: String, + prop: bool, +} + +struct Crate<'a> { + b: &'a [u8], + ver: (u8, u8, u8), + tokens: Vec, + strings: Vec, + fields: Vec<(u32, u64)>, + fieldsets: Vec, + paths: Vec>, +} + +/// Parse a `.usdc` Crate binary layer, charging decoded allocations against `budget`. +pub fn read(bytes: &[u8], budget: &mut Budget) -> Result { + let mut boot = Cur { b: bytes, pos: 8 }; + let [major, minor, patch] = boot.array::<3>()?; + let ver = (major, minor, patch); + if ver < MIN_VERSION { + return Err(SceneError::Unsupported(format!("USD Crate version {major}.{minor}.{patch} (reads 0.4.0 and newer)"))); + } + boot.seek(16)?; + let mut toc = Cur { b: bytes, pos: 0 }; + toc.seek(boot.u64()?)?; + let n = toc.count(32)?.min(MAX_SECTIONS); + let mut sections = HashMap::new(); + for _ in 0..n { + let name = toc.array::<16>()?; + let name = String::from_utf8_lossy(name.split(|&c| c == 0).next().unwrap_or_default()).into_owned(); + let (start, size) = (toc.u64()?, toc.u64()?); + let end = start.checked_add(size).filter(|e| *e <= bytes.len() as u64).ok_or_else(truncated)?; + sections.insert(name, bytes.get(start as usize..end as usize).ok_or_else(truncated)?); + } + let section = |name: &str| sections.get(name).map(|b| Cur { b, pos: 0 }).ok_or_else(|| SceneError::Malformed(format!("missing {name} section"))); + let mut c = Crate { b: bytes, ver, tokens: Vec::new(), strings: Vec::new(), fields: Vec::new(), fieldsets: Vec::new(), paths: Vec::new() }; + c.read_tokens(section("TOKENS")?, budget)?; + if let Ok(mut s) = section("STRINGS") { + let n = s.count(4)?; + c.strings = (0..n).map(|_| s.u32()).collect::>()?; + } + c.read_fields(section("FIELDS")?, budget)?; + let mut s = section("FIELDSETS")?; + let n = s.count(0)?; + c.fieldsets = s.ints(n, 4, budget)?.into_iter().map(|v| v as u32).collect(); + c.read_paths(section("PATHS")?, budget)?; + let mut s = section("SPECS")?; + let n = s.count(0)?; + let (paths, sets, kinds) = (s.ints(n, 4, budget)?, s.ints(n, 4, budget)?, s.ints(n, 4, budget)?); + c.build(paths.iter().zip(&sets).zip(&kinds).map(|((p, f), k)| (*p as u32 as usize, *f as u32 as usize, *k)), budget) +} + +impl<'a> Crate<'a> { + fn token(&self, i: u64) -> Result<&str> { + usize::try_from(i) + .ok() + .and_then(|i| self.tokens.get(i)) + .map(String::as_str) + .ok_or_else(|| SceneError::Malformed(format!("token index {i} out of range"))) + } + + fn string(&self, i: u32) -> Result<&str> { + let t = self.strings.get(i as usize).ok_or_else(|| SceneError::Malformed(format!("string index {i} out of range")))?; + self.token(u64::from(*t)) + } + + fn path(&self, i: u32) -> Result<&PathEl> { + self.paths.get(i as usize).and_then(Option::as_ref).ok_or_else(|| SceneError::Malformed(format!("path index {i} out of range"))) + } + + fn read_tokens(&mut self, mut s: Cur, budget: &mut Budget) -> Result<()> { + let n = s.u64()?; + let (raw_len, comp_len) = (s.u64()?, s.u64()?); + let raw_len = check_count(raw_len, MAX_ITEMS)?; + let n = check_count(n, raw_len)?; + budget.take(raw_len.saturating_add(n.saturating_mul(24)))?; + let comp = s.bytes(usize::try_from(comp_len).map_err(|_| truncated())?)?; + let raw = decompress_block(comp, raw_len)?; + self.tokens = raw.split(|&c| c == 0).take(n).map(|t| String::from_utf8_lossy(t).into_owned()).collect(); + if self.tokens.len() < n { + return Err(SceneError::Malformed("fewer tokens than declared".into())); + } + Ok(()) + } + + fn read_fields(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> { + let count = section.count(0)?; + let tokens = section.ints(count, 4, budget)?; + let size = section.u64()?; + let compressed = section.bytes(usize::try_from(size).map_err(|_| truncated())?)?; + budget.take(count.saturating_mul(24))?; + let representations = decompress_block(compressed, count.saturating_mul(8))?; + if representations.len() != count * 8 { + return Err(SceneError::Malformed("field values are truncated".into())); + } + + self.fields = tokens.iter().zip(representations.as_chunks::<8>().0.iter()).map(|(t, r)| (*t as u32, u64::from_le_bytes(*r))).collect(); + + Ok(()) + } + + fn decode_path_element(&self, parent: Option, element_token: i64, budget: &mut Budget) -> Result { + let Some(parent_index) = parent else { + return Ok(PathEl { text: "/".into(), parent: None, name: String::new(), prop: false }); + }; + let path_error = || SceneError::Malformed("corrupt path table".into()); + let name = self.token(element_token.unsigned_abs())?; + let parent_path = self.paths.get(parent_index).and_then(Option::as_ref).map(|b| b.text.as_str()).ok_or_else(path_error)?; + let separator_bytes = usize::from(element_token < 0 || (!name.starts_with('{') && parent_path != "/")); + let text_bytes = parent_path.len().saturating_add(name.len()).saturating_add(separator_bytes); + + // Charge both retained strings before allocating either one + budget.take(text_bytes.saturating_add(name.len()))?; + let name = name.to_string(); + let text = match (element_token < 0, parent_path) { + (true, _) => format!("{parent_path}.{name}"), + (false, _) if name.starts_with('{') => format!("{parent_path}{name}"), + (false, "/") => format!("/{name}"), + (false, _) => format!("{parent_path}/{name}"), + }; + Ok(PathEl { text, parent: Some(parent_index), name, prop: element_token < 0 }) + } + + /// Paths are stored as a pre-order tree: element token (negative for properties) and a + /// jump per node (-2 leaf, -1 child only, 0 sibling only, >0 child and sibling at +jump). + fn read_paths(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> { + let path_count = section.count(0)?; + let encoded_count = section.count(0)?; + let path_indices = section.ints(encoded_count, 4, budget)?; + let elements = section.ints(encoded_count, 4, budget)?; + let jumps = section.ints(encoded_count, 4, budget)?; + if path_count > MAX_PATHS { + return Err(SceneError::TooLarge(format!("the USD path table has {path_count} entries (limit {MAX_PATHS})"))); + } + + // Charge slot storage before allocating the table + budget.take(path_count.saturating_mul(std::mem::size_of::>()))?; + self.paths = vec![None; path_count]; + let mut pending_branches: Vec<(usize, Option)> = vec![(0, None)]; + let mut visited_count = 0usize; + let path_error = || SceneError::Malformed("corrupt path table".into()); + while let Some((mut cursor_index, mut parent)) = pending_branches.pop() { + loop { + visited_count += 1; + if visited_count > encoded_count { + return Err(path_error()); + } + + let node_index = cursor_index; + cursor_index += 1; + let path_index = path_indices + .get(node_index) + .map(|v| *v as u32 as usize) + .filter(|parent_index| *parent_index < path_count) + .ok_or_else(path_error)?; + let element_token = if parent.is_some() { *elements.get(node_index).ok_or_else(path_error)? } else { 0 }; + let path_element = self.decode_path_element(parent, element_token, budget)?; + + if let Some(slot) = self.paths.get_mut(path_index) { + *slot = Some(path_element); + } + + let jump = *jumps.get(node_index).ok_or_else(path_error)?; + let (child, sibling) = (jump > 0 || jump == -1, jump >= 0); + if child { + if sibling { + pending_branches + .push((node_index.checked_add(usize::try_from(jump).map_err(|_| path_error())?).ok_or_else(path_error)?, parent)); + } + parent = Some(path_index); + } + if !child && !sibling { + break; + } + } + } + + Ok(()) + } + + /// (name, value rep) of the fields of field set `set`. + fn fields_of(&self, set: usize) -> Vec<(&str, u64)> { + self.fieldsets + .get(set..) + .unwrap_or_default() + .iter() + .take_while(|f| **f != u32::MAX) + .filter_map(|f| self.fields.get(*f as usize)) + .filter_map(|(t, rep)| Some((self.token(u64::from(*t)).ok()?, *rep))) + .collect() + } + + fn build_pseudo_root( + &self, + layer: &mut Layer, + prims: &mut HashMap, + path: usize, + fields: &[(&str, u64)], + budget: &mut Budget, + ) -> Result<()> { + prims.insert(path, 0); + for &(name, rep) in fields { + match name { + "metersPerUnit" => layer.meters_per_unit = self.number(rep, budget)?, + "upAxis" => layer.up_axis = self.tokens_of(rep, budget)?.into_iter().next(), + "subLayers" => layer.warn("sublayers are not loaded"), + _ => {} + } + } + Ok(()) + } + + fn build_prim( + &self, + layer: &mut Layer, + prims: &mut HashMap, + path: usize, + fields: &[(&str, u64)], + budget: &mut Budget, + ) -> Result<()> { + let Some(id) = self.prim(layer, prims, path, 0) else { return Ok(()) }; + let mut spec = std::mem::take(layer.prims.get_mut(id).ok_or_else(truncated)?); + for &(name, rep) in fields { + match name { + "typeName" => spec.type_name = self.tokens_of(rep, budget)?.into_iter().next().unwrap_or_default(), + "specifier" => { + spec.specifier = match self.value(rep, budget)? { + Some(Val::Num(v)) if v.first() == Some(&1.0) => Specifier::Over, + Some(Val::Num(v)) if v.first() == Some(&2.0) => Specifier::Class, + _ => Specifier::Def, + } + } + "active" => spec.active = self.number(rep, budget)?.map(|v| v != 0.0), + "references" => { + let (internal, external) = self.references(rep)?; + spec.references.extend(internal); + if external { + layer.warn("external references and payloads are not loaded"); + } + } + "payload" => layer.warn("external references and payloads are not loaded"), + _ => {} + } + } + if let Some(slot) = layer.prims.get_mut(id) { + *slot = spec; + } + Ok(()) + } + + fn build_prop( + &self, + layer: &mut Layer, + prims: &mut HashMap, + el: &PathEl, + kind: i64, + fields: &[(&str, u64)], + budget: &mut Budget, + ) -> Result<()> { + let Some(owner) = el.parent.filter(|_| el.prop).and_then(|p| self.prim(layer, prims, p, 0)) else { return Ok(()) }; + let mut prop = Prop { type_name: if kind == SPEC_RELATIONSHIP { "rel".into() } else { String::new() }, ..Prop::default() }; + let mut samples = None; + for &(name, rep) in fields { + match name { + "typeName" => prop.type_name = self.tokens_of(rep, budget)?.into_iter().next().unwrap_or_default(), + "default" | "targetPaths" => prop.value = self.value(rep, budget)?, + "connectionPaths" => { + if let Some(Val::Path(p)) = self.value(rep, budget)? { + prop.connect = p.into_iter().next(); + } + } + "timeSamples" => samples = Some(rep), + "interpolation" => prop.interpolation = self.tokens_of(rep, budget)?.into_iter().next(), + _ => {} + } + } + if prop.value.is_none() + && let Some(rep) = samples + { + prop.value = self.value(rep, budget)?; + } + if let Some(spec) = layer.prims.get_mut(owner) { + spec.props.insert(el.name.clone(), prop); + } + Ok(()) + } + + fn build(&self, specs: impl Iterator, budget: &mut Budget) -> Result { + let mut layer = Layer::new(); + let mut prims: HashMap = HashMap::new(); + for (path, set, kind) in specs { + let Some(el) = self.paths.get(path).and_then(Option::as_ref) else { + return Err(SceneError::Malformed(format!("spec path {path} out of range"))); + }; + let fields = self.fields_of(set); + match kind { + SPEC_PSEUDO_ROOT => self.build_pseudo_root(&mut layer, &mut prims, path, &fields, budget)?, + SPEC_PRIM => self.build_prim(&mut layer, &mut prims, path, &fields, budget)?, + SPEC_ATTRIBUTE | SPEC_RELATIONSHIP => self.build_prop(&mut layer, &mut prims, el, kind, &fields, budget)?, + SPEC_VARIANT | SPEC_VARIANT_SET => layer.warn("variant sets are not applied"), + _ => {} + } + } + Ok(layer) + } + + /// The layer prim of prim path `path`, created (with its ancestors) on first use; None for + /// paths inside variants or nested deeper than [`MAX_DEPTH`]. + fn prim(&self, layer: &mut Layer, prims: &mut HashMap, path: usize, depth: usize) -> Option { + if let Some(id) = prims.get(&path) { + return Some(*id); + } + let el = self.paths.get(path)?.as_ref()?; + if el.prop || el.name.starts_with('{') || depth > MAX_DEPTH { + return None; + } + let parent = match el.parent { + Some(p) if self.paths.get(p)?.as_ref()?.parent.is_none() => 0, + Some(p) => self.prim(layer, prims, p, depth + 1)?, + None => return Some(0), + }; + let id = layer.add_prim(parent, &el.name); + prims.insert(path, id); + Some(id) + } + + fn number(&self, rep: u64, budget: &mut Budget) -> Result> { + Ok(match self.value(rep, budget)? { + Some(Val::Num(v)) => v.first().copied(), + _ => None, + }) + } + + fn tokens_of(&self, rep: u64, budget: &mut Budget) -> Result> { + Ok(match self.value(rep, budget)? { + Some(Val::Tok(v)) => v, + _ => Vec::new(), + }) + } + + fn at(&self, offset: u64) -> Result> { + let mut c = Cur { b: self.b, pos: 0 }; + c.seek(offset)?; + Ok(c) + } + + fn strings_from_ids(&self, t: u8, ids: Vec, budget: &mut Budget) -> Result> { + ids.into_iter() + .map(|i| { + let s = match t { + ty::STRING => self.string(i), + _ => self.token(u64::from(i)), + }? + .to_string(); + budget.take(s.len() + 24)?; + Ok(s) + }) + .collect() + } + + /// Decode a value rep; None for types a neutral layer does not need. + fn value(&self, rep: u64, budget: &mut Budget) -> Result> { + self.value_at_depth(rep, budget, 0) + } + + fn value_at_depth(&self, rep: u64, budget: &mut Budget, depth: usize) -> Result> { + let t = ((rep >> 48) & 0xFF) as u8; + let payload = rep & codec::PAYLOAD_MASK; + let (array, inlined, compressed) = (rep & codec::IS_ARRAY != 0, rep & codec::IS_INLINED != 0, rep & codec::IS_COMPRESSED != 0); + if rep & codec::IS_ARRAY_EDIT != 0 { + return Ok(None); + } + if array && inlined { + return Ok(Some(Val::Num(Vec::new()))); + } + Ok(Some(match t { + ty::STRING | ty::TOKEN | ty::ASSET_PATH if !array => Val::Tok(self.strings_from_ids(t, vec![payload as u32], budget)?), + ty::STRING | ty::TOKEN | ty::ASSET_PATH => { + let mut c = self.at(payload)?; + let ids = self.array_header(&mut c, 4)?; + Val::Tok(self.strings_from_ids(t, (0..ids).map(|_| c.u32()).collect::>()?, budget)?) + } + ty::SPECIFIER | ty::VARIABILITY | ty::PERMISSION => Val::Num(vec![f64::from(payload as u32)]), + ty::TOKEN_VECTOR => { + let mut c = self.at(payload)?; + let n = c.count(4)?; + Val::Tok(self.strings_from_ids(t, (0..n).map(|_| c.u32()).collect::>()?, budget)?) + } + ty::PATH_VECTOR => { + let mut c = self.at(payload)?; + let n = c.count(4)?; + Val::Path((0..n).map(|_| Ok(self.path(c.u32()?)?.text.clone())).collect::>()?) + } + ty::PATH_LIST_OP => Val::Path(self.list_op(payload)?.into_iter().map(|i| Ok(self.path(i)?.text.clone())).collect::>()?), + ty::TOKEN_LIST_OP => Val::Tok(self.strings_from_ids(t, self.list_op(payload)?, budget)?), + ty::DOUBLE_VECTOR => { + let mut c = self.at(payload)?; + let n = c.count(8)?; + budget.take(n * 8)?; + Val::Num((0..n).map(|_| c.f64()).collect::>()?) + } + ty::TIME_SAMPLES if depth == 0 => { + let mut c = self.at(payload)?; + c.jump()?; + c.u64()?; + c.jump()?; + if c.u64()? == 0 { + return Ok(None); + } + return self.value_at_depth(c.u64()?, budget, 1); + } + _ => match codec::numeric(t) { + Some((s, comps)) if inlined => Val::Num(inline_numeric(t, s, comps, payload)), + Some((s, comps)) if array => self.numeric_array(t, s, comps, payload, compressed, budget)?, + Some((s, comps)) => { + let mut c = self.at(payload)?; + let raw = c.bytes(s.size() * comps)?; + let mut v: Vec = raw.chunks_exact(s.size()).map(|b| scalar(s, b)).collect(); + quat_order(t, &mut v); + Val::Num(v) + } + None => return Ok(None), + }, + })) + } + + /// Element count of an array at `c` (`elem` bytes each), past the pre-0.5 shape word. + fn array_header(&self, c: &mut Cur, elem: usize) -> Result { + if self.ver < (0, 5, 0) { + c.u32()?; + } + let n = if self.ver < (0, 7, 0) { u64::from(c.u32()?) } else { c.u64()? }; + check_count(n, c.cap(elem)) + } + + fn numeric_array(&self, t: u8, s: Scalar, comps: usize, payload: u64, compressed: bool, budget: &mut Budget) -> Result { + let mut c = self.at(payload)?; + let int = matches!(s, Scalar::I32 | Scalar::U32 | Scalar::I64 | Scalar::U64) && comps == 1 && self.ver >= (0, 5, 0); + let float = matches!(s, Scalar::F16 | Scalar::F32 | Scalar::F64) && comps == 1 && self.ver >= (0, 6, 0); + let packed = compressed && (int || float); + let n = self.array_header(&mut c, if packed { 0 } else { s.size() * comps })?; + budget.take(n.saturating_mul(comps).saturating_mul(8))?; + if packed && n >= codec::MIN_COMPRESSED_ARRAY { + let as_f64 = |v: i64| match s { + Scalar::U32 => f64::from(v as u32), + Scalar::U64 => v as u64 as f64, + _ => v as f64, + }; + if int { + let width = s.size(); + return Ok(Val::Num(c.ints(n, width, budget)?.into_iter().map(as_f64).collect())); + } + return Ok(Val::Num(match c.u8()? { + b'i' => c.ints(n, 4, budget)?.into_iter().map(|v| v as f64).collect(), + b't' => { + let lut_len = c.u32()? as usize; + let lut: Vec = + c.bytes(lut_len.checked_mul(s.size()).ok_or_else(truncated)?)?.chunks_exact(s.size()).map(|b| scalar(s, b)).collect(); + let idx = c.ints(n, 4, budget)?; + idx.into_iter() + .map(|i| lut.get(i as u32 as usize).copied().ok_or_else(|| SceneError::Malformed("lookup table index out of range".into()))) + .collect::>()? + } + code => return Err(SceneError::Malformed(format!("unknown float array coding {code}"))), + })); + } + let raw = c.bytes(n.checked_mul(comps).and_then(|k| k.checked_mul(s.size())).ok_or_else(truncated)?)?; + let mut v: Vec = raw.chunks_exact(s.size()).map(|b| scalar(s, b)).collect(); + quat_order(t, &mut v); + Ok(Val::Num(v)) + } + + /// The kept items (explicit, added, prepended, appended) of a token or path list op. + fn list_op(&self, payload: u64) -> Result> { + let mut c = self.at(payload)?; + let header = c.u8()?; + let mut out = Vec::new(); + // Lists in file order: explicit, added, prepended, appended, deleted, ordered. + for bit in [1, 2, 5, 6, 3, 4] { + if header & (1 << bit) == 0 { + continue; + } + let n = c.count(4)?; + let items: Vec = (0..n).map(|_| c.u32()).collect::>()?; + if bit <= 2 || bit >= 5 { + out.extend(items); + } + } + Ok(out) + } + + fn skip_custom_data(c: &mut Cur<'_>) -> Result<()> { + let entries = c.count(12)?; + for _ in 0..entries { + c.u32()?; + c.jump()?; + c.u64()?; + } + Ok(()) + } + + /// Internal reference targets of a reference list op, and whether any was external. + fn references(&self, rep: u64) -> Result<(Vec, bool)> { + if ((rep >> 48) & 0xFF) as u8 != ty::REFERENCE_LIST_OP || rep & codec::IS_INLINED != 0 { + return Ok((Vec::new(), false)); + } + let mut c = self.at(rep & codec::PAYLOAD_MASK)?; + let header = c.u8()?; + let (mut internal, mut external) = (Vec::new(), false); + for bit in [1, 2, 5, 6, 3, 4] { + if header & (1 << bit) == 0 { + continue; + } + let n = c.count(28)?; + for _ in 0..n { + let asset = self.string(c.u32()?)?.to_string(); + let prim = self.path(c.u32()?)?.text.clone(); + c.f64()?; + c.f64()?; + Self::skip_custom_data(&mut c)?; + if bit == 3 || bit == 4 { + continue; + } + match (asset.is_empty(), prim.as_str()) { + (true, p) if p != "/" && !p.is_empty() => internal.push(prim), + _ => external = true, + } + } + } + Ok((internal, external)) + } +} + +/// A numeric value stored in the rep itself: 32-bit scalars (doubles as floats, 64-bit ints as +/// 32-bit), vectors as int8 components and matrices as int8 diagonals. +fn inline_numeric(t: u8, s: Scalar, comps: usize, payload: u64) -> Vec { + let bytes = payload.to_le_bytes(); + let i8s = |n: usize| bytes.iter().take(n).map(|b| f64::from(*b as i8)).collect::>(); + match (t, comps) { + (ty::MATRIX2D..=ty::MATRIX4D, _) => { + let dim = usize::from(t - ty::MATRIX2D) + 2; + let diag = i8s(dim); + (0..dim * dim).map(|k| if k % (dim + 1) == 0 { diag.get(k / (dim + 1)).copied().unwrap_or(1.0) } else { 0.0 }).collect() + } + (_, 1) => vec![match s { + Scalar::U8 => f64::from(payload as u8), + Scalar::I32 | Scalar::I64 => f64::from(payload as u32 as i32), + Scalar::U32 | Scalar::U64 => f64::from(payload as u32), + Scalar::F16 => f64::from(half::f16::from_bits(payload as u16).to_f32()), + Scalar::F32 | Scalar::F64 => f64::from(f32::from_bits(payload as u32)), + }], + _ => i8s(comps), + } +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::{Crate, Cur, PathEl, Scalar, inline_numeric}; + use crate::codec::{self, ty}; + use crate::compress; + use crate::integers::{self, Width}; + use crate::scene::{Budget, MAX_DECODED_BYTES, SceneError, Val}; + + fn crate_over(b: &[u8], ver: (u8, u8, u8)) -> Crate<'_> { + Crate { b, ver, tokens: Vec::new(), strings: Vec::new(), fields: Vec::new(), fieldsets: Vec::new(), paths: Vec::new() } + } + + fn compressed_ints(out: &mut Vec, v: &[i64]) { + let comp = compress::compress(&integers::encode(v, Width::I32, MAX_DECODED_BYTES).unwrap(), MAX_DECODED_BYTES).unwrap(); + out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); + out.extend_from_slice(&comp); + } + + #[test] + fn repeated_path_names_count_toward_the_decode_budget() { + let name = "long_name_reused"; + let mut section = Vec::new(); + section.extend_from_slice(&3u64.to_le_bytes()); + section.extend_from_slice(&3u64.to_le_bytes()); + compressed_ints(&mut section, &[0, 1, 2]); + compressed_ints(&mut section, &[0, 0, 0]); + compressed_ints(&mut section, &[-1, 0, -2]); + let mut crate_data = crate_over(§ion, (0, 8, 0)); + crate_data.tokens.push(name.into()); + + let decoded_arrays_bytes = 3 * 3 * std::mem::size_of::(); + let path_slots_bytes = 3 * std::mem::size_of::>(); + let path_text_bytes = 2 * (1 + name.len()); + let one_name_budget = decoded_arrays_bytes + path_slots_bytes + path_text_bytes + name.len(); + let mut insufficient_budget = Budget(one_name_budget); + + let rejected = crate_data.read_paths(Cur { b: §ion, pos: 0 }, &mut insufficient_budget); + + assert!(matches!(rejected, Err(SceneError::TooLarge(_))), "two path names cannot fit a one-name budget"); + drop(crate_data); + + let mut complete_budget = Budget(one_name_budget + name.len()); + let mut crate_data = crate_over(§ion, (0, 8, 0)); + crate_data.tokens.push(name.into()); + crate_data.read_paths(Cur { b: §ion, pos: 0 }, &mut complete_budget).unwrap(); + + assert_eq!(complete_budget.0, 0); + assert_eq!(crate_data.path(1).unwrap().text, format!("/{name}")); + assert_eq!(crate_data.path(2).unwrap().text, format!("/{name}")); + } + + #[test] + fn compressed_float_and_int_arrays() { + let n = 20usize; + let mut b = Vec::new(); + // 'i': integral floats as compressed ints. + b.extend_from_slice(&(n as u64).to_le_bytes()); + b.push(b'i'); + let ints: Vec = (0..n as i64).map(|i| i * 3 - 7).collect(); + compressed_ints(&mut b, &ints); + let lut_at = b.len() as u64; + // 't': a lookup table of doubles and compressed indexes into it. + b.extend_from_slice(&(n as u64).to_le_bytes()); + b.push(b't'); + b.extend_from_slice(&2u32.to_le_bytes()); + b.extend_from_slice(&0.25f64.to_le_bytes()); + b.extend_from_slice(&(-8.5f64).to_le_bytes()); + let idx: Vec = (0..n as i64).map(|i| i % 2).collect(); + compressed_ints(&mut b, &idx); + let i64_at = b.len() as u64; + b.extend_from_slice(&(n as u64).to_le_bytes()); + let comp = compress::compress( + &integers::encode(&(0..n as i64).map(|i| i << 33).collect::>(), Width::I64, MAX_DECODED_BYTES).unwrap(), + MAX_DECODED_BYTES, + ) + .unwrap(); + b.extend_from_slice(&(comp.len() as u64).to_le_bytes()); + b.extend_from_slice(&comp); + let c = crate_over(&b, (0, 8, 0)); + let mut budget = Budget::new(); + let f32s = c.numeric_array(ty::FLOAT, Scalar::F32, 1, 0, true, &mut budget).unwrap(); + assert_eq!(f32s, Val::Num(ints.iter().map(|&i| i as f64).collect())); + let lut = c.numeric_array(ty::DOUBLE, Scalar::F64, 1, lut_at, true, &mut budget).unwrap(); + assert_eq!(lut, Val::Num((0..n).map(|i| if i % 2 == 0 { 0.25 } else { -8.5 }).collect())); + let wide = c.numeric_array(ty::INT64, Scalar::I64, 1, i64_at, true, &mut budget).unwrap(); + assert_eq!(wide, Val::Num((0..n as i64).map(|i| (i << 33) as f64).collect())); + // Out-of-range lookups and unknown codings are errors. + let mut bad = b.clone(); + bad[lut_at as usize + 8] = b'x'; + assert!(crate_over(&bad, (0, 8, 0)).numeric_array(ty::DOUBLE, Scalar::F64, 1, lut_at, true, &mut budget).is_err()); + } + + #[test] + fn old_array_headers_halves_quats_and_inlined_values() { + // 0.4: discarded shape word and a u32 count; half floats. + let mut b = Vec::new(); + b.extend_from_slice(&1u32.to_le_bytes()); + b.extend_from_slice(&2u32.to_le_bytes()); + for v in [1.5f32, -2.0] { + b.extend_from_slice(&half::f16::from_f32(v).to_bits().to_le_bytes()); + } + let quat_at = b.len() as u64; + for v in [0.0f32, 0.0, 1.0, 0.5] { + b.extend_from_slice(&v.to_le_bytes()); + } + let c = crate_over(&b, (0, 4, 0)); + let mut budget = Budget::new(); + assert_eq!(c.numeric_array(ty::HALF, Scalar::F16, 1, 0, false, &mut budget).unwrap(), Val::Num(vec![1.5, -2.0])); + let quat = c.value((17u64 << 48) | quat_at, &mut budget).unwrap(); + assert_eq!(quat, Some(Val::Num(vec![0.5, 0.0, 0.0, 1.0])), "quaternions read real first"); + assert_eq!(inline_numeric(ty::MATRIX2D, Scalar::F64, 4, 0x0302), vec![2.0, 0.0, 0.0, 3.0]); + assert_eq!(inline_numeric(24, Scalar::F32, 3, 0x00FF_0201), vec![1.0, 2.0, -1.0]); + assert_eq!(inline_numeric(ty::DOUBLE, Scalar::F64, 1, u64::from(0.5f32.to_bits())), vec![0.5]); + assert_eq!(inline_numeric(ty::INT, Scalar::I32, 1, u64::from((-3i32) as u32)), vec![-3.0]); + // Array edits are not applied; empty arrays are inlined. + assert_eq!(c.value(codec::IS_ARRAY_EDIT | (3u64 << 48), &mut budget).unwrap(), None); + assert_eq!(c.value(codec::IS_ARRAY | codec::IS_INLINED | (3u64 << 48), &mut budget).unwrap(), Some(Val::Num(vec![]))); + } +} diff --git a/crates/usd/src/scene/write.rs b/crates/usd/src/scene/write.rs new file mode 100644 index 0000000000..53470d5188 --- /dev/null +++ b/crates/usd/src/scene/write.rs @@ -0,0 +1,662 @@ +//! Writers for neutral [`UsdLayer`] scenes: `.usda` text and `.usdc` Crate binary (0.8.0). + +use std::collections::HashMap; +use std::fmt::Write as _; + +use crate::codec::{self, ty}; +use crate::compress; +use crate::integers::{self, Width}; +use crate::scene::{MAX_DECODED_BYTES, Result, SceneError, UsdAttr, UsdLayer, UsdPrim, UsdValue}; + +const VERSION: [u8; 3] = [0, 8, 0]; +const SPEC_ATTRIBUTE: i64 = 1; +const SPEC_PRIM: i64 = 6; +const SPEC_PSEUDO_ROOT: i64 = 7; +const SPEC_RELATIONSHIP: i64 = 8; +/// List-op header bits. +const LIST_EXPLICIT: u8 = 0b11; +const LIST_PREPENDED: u8 = 1 << 5; + +fn rep(t: u8, flags: u64, payload: u64) -> u64 { + (u64::from(t) << 48) | flags | (payload & codec::PAYLOAD_MASK) +} + +fn compress_block(input: &[u8]) -> Result> { + compress::compress(input, MAX_DECODED_BYTES).map_err(|e| SceneError::Malformed(e.to_string())) +} + +fn encode_ints(values: &[i64]) -> Result> { + integers::encode(values, Width::I32, MAX_DECODED_BYTES).map_err(|e| SceneError::Malformed(e.to_string())) +} + +/// Text of a value as `.usda` writes it. +fn usda_value(s: &mut String, v: &UsdValue) { + let tuple = |s: &mut String, c: &[f32]| { + s.push('('); + for (i, x) in c.iter().enumerate() { + let _ = write!(s, "{}{x}", if i > 0 { ", " } else { "" }); + } + s.push(')'); + }; + let list = |s: &mut String, n: usize, item: &mut dyn FnMut(&mut String, usize)| { + s.push('['); + for i in 0..n { + if i > 0 { + s.push_str(", "); + } + item(s, i); + } + s.push(']'); + }; + match v { + UsdValue::Token(t) | UsdValue::Str(t) => { + let _ = write!(s, "\"{t}\""); + } + UsdValue::Int(i) => { + let _ = write!(s, "{i}"); + } + UsdValue::Double(d) => { + let _ = write!(s, "{d}"); + } + UsdValue::Asset(a) => { + let _ = write!(s, "@{a}@"); + } + UsdValue::Target(p) => { + let _ = write!(s, "<{p}>"); + } + UsdValue::Float4(c) => tuple(s, c), + UsdValue::Ints(v) => list(s, v.len(), &mut |s, i| { + let _ = write!(s, "{}", v.get(i).copied().unwrap_or_default()); + }), + UsdValue::Vec2fs(v) => list(s, v.len(), &mut |s, i| tuple(s, v.get(i).map_or(&[][..], |x| &x[..]))), + UsdValue::Vec3fs(v) => list(s, v.len(), &mut |s, i| tuple(s, v.get(i).map_or(&[][..], |x| &x[..]))), + } +} + +fn usda_prim(s: &mut String, p: &UsdPrim, depth: usize) { + let pad = " ".repeat(depth); + let _ = write!(s, "\n{pad}def {} \"{}\"", p.type_name, p.name); + if p.binding_api { + let _ = write!(s, " (\n{pad} prepend apiSchemas = [\"MaterialBindingAPI\"]\n{pad})"); + } + let _ = writeln!(s, "\n{pad}{{"); + for a in &p.attrs { + s.push_str(&pad); + s.push_str(" "); + if a.type_name == "rel" { + let _ = write!(s, "rel {}", a.name); + } else { + let _ = write!(s, "{}{} {}", if a.uniform { "uniform " } else { "" }, a.type_name, a.name); + } + if let Some(c) = &a.connect { + let _ = write!(s, ".connect = <{c}>"); + } else if let Some(v) = &a.value { + s.push_str(" = "); + usda_value(s, v); + } + if let Some(i) = &a.interpolation { + let _ = write!(s, " (\n{pad} interpolation = \"{i}\"\n{pad} )"); + } + s.push('\n'); + } + for c in &p.children { + usda_prim(s, c, depth + 1); + } + let _ = writeln!(s, "{pad}}}"); +} + +/// Format `layer` as `.usda` text. +pub fn usda(layer: &UsdLayer) -> String { + let mut s = format!("#usda 1.0\n(\n defaultPrim = \"{}\"\n", layer.root.name); + if let Some(doc) = &layer.doc { + let _ = writeln!(s, " doc = \"{doc}\""); + } + let _ = writeln!(s, " metersPerUnit = {}\n upAxis = \"{}\"\n)", layer.meters_per_unit, layer.up_axis); + usda_prim(&mut s, &layer.root, 0); + s +} + +struct Node { + token: u32, + prop: bool, + children: Vec, +} + +#[derive(Default)] +struct Writer { + out: Vec, + tokens: Vec, + token_ids: HashMap, + /// String table: token index per string. + strings: Vec, + fields: Vec<(u32, u64)>, + field_ids: HashMap<(u32, u64), u32>, + fieldsets: Vec, + fieldset_ids: HashMap, u32>, + /// Path tree (index 0 is the root). + paths: Vec, + path_ids: HashMap, + specs: Vec<[i64; 3]>, +} + +impl Writer { + /// The bootstrap header and the root path; values follow. + fn new() -> Writer { + let mut w = Writer::default(); + // Token 0 must never name a property (properties store their token negated). + w.token("Xform"); + w.paths.push(Node { token: 0, prop: false, children: Vec::new() }); + w.path_ids.insert("/".into(), 0); + w.out.extend_from_slice(codec::MAGIC); + w.out.extend_from_slice(&VERSION); + w.out.resize(codec::BOOTSTRAP_LEN, 0); + w + } + + fn token(&mut self, s: &str) -> u32 { + if let Some(&i) = self.token_ids.get(s) { + return i; + } + let i = self.tokens.len() as u32; + self.tokens.push(s.into()); + self.token_ids.insert(s.into(), i); + i + } + + /// Index of `s` in the string table (which holds token indices). + fn string(&mut self, s: &str) -> u32 { + let t = self.token(s); + match self.strings.iter().position(|x| *x == t) { + Some(i) => i as u32, + None => { + self.strings.push(t); + (self.strings.len() - 1) as u32 + } + } + } + + fn add_path(&mut self, parent: usize, parent_text: &str, name: &str, prop: bool) -> (usize, String) { + let text = match (prop, parent_text) { + (true, _) => format!("{parent_text}.{name}"), + (false, "/") => format!("/{name}"), + _ => format!("{parent_text}/{name}"), + }; + let id = self.paths.len(); + let token = self.token(name); + self.paths.push(Node { token, prop, children: Vec::new() }); + if let Some(p) = self.paths.get_mut(parent) { + p.children.push(id); + } + self.path_ids.insert(text.clone(), id); + (id, text) + } + + /// Pre-order path nodes of `p` (attributes before child prims). + fn add_prim_paths(&mut self, parent: usize, parent_text: &str, p: &UsdPrim) { + let (id, text) = self.add_path(parent, parent_text, &p.name, false); + for a in &p.attrs { + self.add_path(id, &text, &a.name, true); + } + for c in &p.children { + self.add_prim_paths(id, &text, c); + } + } + + fn path_id(&self, path: &str) -> Result { + self.path_ids.get(path).map(|&i| i as u32).ok_or_else(|| SceneError::Invalid(format!("USD export: unknown path {path}"))) + } + + fn offset(&self) -> u64 { + self.out.len() as u64 + } + + fn u32s(&mut self, v: impl Iterator) { + for x in v { + self.out.extend_from_slice(&x.to_le_bytes()); + } + } + + fn list_op(&mut self, t: u8, header: u8, items: &[u32]) -> u64 { + let at = self.offset(); + self.out.push(header); + self.out.extend_from_slice(&(items.len() as u64).to_le_bytes()); + self.u32s(items.iter().copied()); + rep(t, 0, at) + } + + fn token_vector(&mut self, names: &[&str]) -> u64 { + let ids: Vec = names.iter().map(|n| self.token(n)).collect(); + let at = self.offset(); + self.out.extend_from_slice(&(ids.len() as u64).to_le_bytes()); + self.u32s(ids.into_iter()); + rep(ty::TOKEN_VECTOR, 0, at) + } + + /// An array of `n` elements whose little-endian bytes are `bytes`. + fn raw_array(&mut self, t: u8, n: usize, bytes: impl Iterator) -> u64 { + let at = self.offset(); + self.out.extend_from_slice(&(n as u64).to_le_bytes()); + self.out.extend(bytes); + rep(t, codec::IS_ARRAY, at) + } + + fn value(&mut self, v: &UsdValue) -> Result { + let floats = |v: &mut dyn Iterator| v.flat_map(f32::to_le_bytes).collect::>(); + Ok(match v { + UsdValue::Token(t) => rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(t))), + UsdValue::Asset(a) => rep(ty::ASSET_PATH, codec::IS_INLINED, u64::from(self.token(a))), + UsdValue::Str(s) => rep(ty::STRING, codec::IS_INLINED, u64::from(self.string(s))), + UsdValue::Int(i) => rep(ty::INT, codec::IS_INLINED, u64::from(*i as u32)), + UsdValue::Double(d) => { + let at = self.offset(); + self.out.extend_from_slice(&d.to_le_bytes()); + rep(ty::DOUBLE, 0, at) + } + UsdValue::Float4(c) => { + let at = self.offset(); + self.out.extend(floats(&mut c.iter().copied())); + rep(ty::VEC4F, 0, at) + } + UsdValue::Ints(v) if v.len() >= codec::MIN_COMPRESSED_ARRAY => { + let at = self.offset(); + self.out.extend_from_slice(&(v.len() as u64).to_le_bytes()); + self.ints(&v.iter().map(|&i| i64::from(i)).collect::>())?; + rep(ty::INT, codec::IS_ARRAY | codec::IS_COMPRESSED, at) + } + UsdValue::Ints(v) => self.raw_array(ty::INT, v.len(), v.iter().flat_map(|i| i.to_le_bytes())), + UsdValue::Vec2fs(v) => { + let bytes = floats(&mut v.iter().flatten().copied()); + self.raw_array(ty::VEC2F, v.len(), bytes.into_iter()) + } + UsdValue::Vec3fs(v) => { + let bytes = floats(&mut v.iter().flatten().copied()); + self.raw_array(ty::VEC3F, v.len(), bytes.into_iter()) + } + UsdValue::Target(p) => { + let id = self.path_id(p)?; + self.list_op(ty::PATH_LIST_OP, LIST_EXPLICIT, &[id]) + } + }) + } + + /// Compressed integers: their compressed size, then the LZ4-framed coding. + fn ints(&mut self, v: &[i64]) -> Result<()> { + let comp = compress_block(&encode_ints(v)?)?; + self.out.extend_from_slice(&(comp.len() as u64).to_le_bytes()); + self.out.extend_from_slice(&comp); + Ok(()) + } + + fn spec(&mut self, path: usize, kind: i64, fields: Vec<(&str, u64)>) { + let ids: Vec = fields + .into_iter() + .map(|(name, value)| { + let key = (self.token(name), value); + let next = self.fields.len() as u32; + *self.field_ids.entry(key).or_insert_with(|| { + self.fields.push(key); + next + }) + }) + .collect(); + let set = match self.fieldset_ids.get(&ids) { + Some(&s) => s, + None => { + let s = self.fieldsets.len() as u32; + self.fieldsets.extend(ids.iter().map(|&i| i64::from(i))); + self.fieldsets.push(i64::from(u32::MAX)); + self.fieldset_ids.insert(ids, s); + s + } + }; + self.specs.push([path as i64, i64::from(set), kind]); + } + + fn prim_specs(&mut self, text: &str, p: &UsdPrim) -> Result<()> { + let id = *self.path_ids.get(text).ok_or_else(|| SceneError::Invalid(format!("USD export: unknown path {text}")))?; + let mut fields = vec![ + ("specifier", rep(ty::SPECIFIER, codec::IS_INLINED, 0)), + ("typeName", rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(&p.type_name)))), + ]; + if p.binding_api { + let api = self.token("MaterialBindingAPI"); + fields.push(("apiSchemas", self.list_op(ty::TOKEN_LIST_OP, LIST_PREPENDED, &[api]))); + } + if !p.attrs.is_empty() { + let names: Vec<&str> = p.attrs.iter().map(|a| a.name.as_str()).collect(); + fields.push(("properties", self.token_vector(&names))); + } + if !p.children.is_empty() { + let names: Vec<&str> = p.children.iter().map(|c| c.name.as_str()).collect(); + fields.push(("primChildren", self.token_vector(&names))); + } + self.spec(id, SPEC_PRIM, fields); + for a in &p.attrs { + self.attr_spec(&format!("{text}.{}", a.name), a)?; + } + for c in &p.children { + self.prim_specs(&format!("{text}/{}", c.name), c)?; + } + Ok(()) + } + + fn attr_spec(&mut self, text: &str, a: &UsdAttr) -> Result<()> { + let id = *self.path_ids.get(text).ok_or_else(|| SceneError::Invalid(format!("USD export: unknown path {text}")))?; + let rel = a.type_name == "rel"; + let mut fields = vec![ + ("custom", rep(ty::BOOL, codec::IS_INLINED, 0)), + ("variability", rep(ty::VARIABILITY, codec::IS_INLINED, u64::from(rel || a.uniform))), + ]; + if !rel { + fields.push(("typeName", rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(&a.type_name))))); + } + if let Some(c) = &a.connect { + let id = self.path_id(c)?; + fields.push(("connectionPaths", self.list_op(ty::PATH_LIST_OP, LIST_EXPLICIT, &[id]))); + } + if let Some(v) = &a.value { + fields.push((if rel { "targetPaths" } else { "default" }, self.value(v)?)); + } + if let Some(i) = &a.interpolation { + fields.push(("interpolation", rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(i))))); + } + self.spec(id, if rel { SPEC_RELATIONSHIP } else { SPEC_ATTRIBUTE }, fields); + Ok(()) + } + + /// (path index, element token, jump) per node, in pre-order. + fn path_table(&self) -> [Vec; 3] { + let n = self.paths.len(); + let mut order = Vec::with_capacity(n); + let mut stack = vec![0usize]; + while let Some(i) = stack.pop() { + order.push(i); + stack.extend(self.paths.get(i).into_iter().flat_map(|p| p.children.iter().rev())); + } + // Subtree sizes: the next sibling follows a node's whole subtree. + let mut size = vec![1i64; n]; + for &i in order.iter().rev() { + let s: i64 = self.paths.get(i).map_or(0, |p| p.children.iter().filter_map(|c| size.get(*c)).sum()); + if let Some(x) = size.get_mut(i) { + *x += s; + } + } + let mut has_sibling = vec![false; n]; + for p in &self.paths { + for w in p.children.windows(2) { + if let Some(s) = w.first().and_then(|&c| has_sibling.get_mut(c)) { + *s = true; + } + } + } + let mut table = [Vec::with_capacity(n), Vec::with_capacity(n), Vec::with_capacity(n)]; + for i in order { + let Some(p) = self.paths.get(i) else { continue }; + let jump = match (!p.children.is_empty(), has_sibling.get(i).copied().unwrap_or(false)) { + (true, true) => size.get(i).copied().unwrap_or(1), + (true, false) => -1, + (false, true) => 0, + (false, false) => -2, + }; + let token = i64::from(p.token); + table[0].push(i as i64); + table[1].push(if p.prop { -token } else { token }); + table[2].push(jump); + } + table + } + + fn section(&mut self, toc: &mut Vec<(&'static str, u64, u64)>, name: &'static str, start: u64) { + toc.push((name, start, self.offset() - start)); + } + + fn u64(&mut self, v: usize) { + self.out.extend_from_slice(&(v as u64).to_le_bytes()); + } + + fn sections(&mut self) -> Result<()> { + let mut toc = Vec::new(); + let start = self.offset(); + let mut raw = Vec::new(); + for t in &self.tokens { + raw.extend_from_slice(t.as_bytes()); + raw.push(0); + } + let comp = compress_block(&raw)?; + self.u64(self.tokens.len()); + self.u64(raw.len()); + self.u64(comp.len()); + self.out.extend_from_slice(&comp); + self.section(&mut toc, "TOKENS", start); + + let start = self.offset(); + let strings = std::mem::take(&mut self.strings); + self.u64(strings.len()); + self.u32s(strings.into_iter()); + self.section(&mut toc, "STRINGS", start); + + let start = self.offset(); + let fields = std::mem::take(&mut self.fields); + self.u64(fields.len()); + self.ints(&fields.iter().map(|f| i64::from(f.0)).collect::>())?; + let reps: Vec = fields.iter().flat_map(|f| f.1.to_le_bytes()).collect(); + let comp = compress_block(&reps)?; + self.u64(comp.len()); + self.out.extend_from_slice(&comp); + self.section(&mut toc, "FIELDS", start); + + let start = self.offset(); + let sets = std::mem::take(&mut self.fieldsets); + self.u64(sets.len()); + self.ints(&sets)?; + self.section(&mut toc, "FIELDSETS", start); + + let start = self.offset(); + let table = self.path_table(); + self.u64(self.paths.len()); + self.u64(self.paths.len()); + for column in &table { + self.ints(column)?; + } + self.section(&mut toc, "PATHS", start); + + let start = self.offset(); + let specs = std::mem::take(&mut self.specs); + self.u64(specs.len()); + for k in 0..3 { + self.ints(&specs.iter().map(|s| s.get(k).copied().unwrap_or_default()).collect::>())?; + } + self.section(&mut toc, "SPECS", start); + + let toc_at = self.offset(); + self.u64(toc.len()); + for (name, start, size) in toc { + let mut n = [0u8; 16]; + for (d, s) in n.iter_mut().zip(name.bytes()) { + *d = s; + } + self.out.extend_from_slice(&n); + self.out.extend_from_slice(&start.to_le_bytes()); + self.out.extend_from_slice(&size.to_le_bytes()); + } + if let Some(slot) = self.out.get_mut(16..24) { + slot.copy_from_slice(&toc_at.to_le_bytes()); + } + Ok(()) + } + + fn root_spec(&mut self, default_prim: &str, meters_per_unit: f64, up_axis: &str) -> Result<()> { + let fields = vec![ + ("defaultPrim", rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(default_prim)))), + ("metersPerUnit", self.value(&UsdValue::Double(meters_per_unit))?), + ("upAxis", rep(ty::TOKEN, codec::IS_INLINED, u64::from(self.token(up_axis)))), + ("primChildren", self.token_vector(&[default_prim])), + ]; + self.spec(0, SPEC_PSEUDO_ROOT, fields); + Ok(()) + } + + fn finish(mut self) -> Result> { + self.sections()?; + Ok(self.out) + } +} + +/// Encode `layer` as a `.usdc` Crate binary. +pub fn usdc(layer: &UsdLayer) -> Result> { + let mut w = Writer::new(); + let root = &layer.root; + w.add_prim_paths(0, "/", root); + w.root_spec(&root.name, layer.meters_per_unit, &layer.up_axis)?; + w.prim_specs(&format!("/{}", root.name), root)?; + w.finish() +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::{SPEC_ATTRIBUTE, SPEC_PRIM, Writer, rep, usda, usdc}; + use crate::codec::{self, ty}; + use crate::scene::{Specifier, UsdAttr, UsdLayer, UsdPrim, UsdValue, Val, read_layer}; + + impl Writer { + fn raw(&mut self, bytes: &[u8]) -> u64 { + let at = self.offset(); + self.out.extend_from_slice(bytes); + at + } + + fn prop_path(&mut self, parent: (usize, &str), name: &str) -> usize { + self.add_path(parent.0, parent.1, name, true).0 + } + } + + fn le(values: &[f64]) -> Vec { + values.iter().flat_map(|v| v.to_le_bytes()).collect() + } + + #[test] + fn usda_and_usdc_round_trip_neutral_layer() { + let mut root = UsdPrim::new("World", "Xform"); + let mut mesh = UsdPrim::new("Tri", "Mesh"); + mesh.binding_api = true; + mesh.attrs = vec![ + UsdAttr::new("points", "point3f[]", Some(UsdValue::Vec3fs(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]))), + UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3]))), + UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(vec![0, 1, 2]))), + UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]))) + .with_interpolation("vertex"), + UsdAttr::rel("material:binding", "/World/Mat".into()), + ]; + root.children.push(mesh); + let mut mat = UsdPrim::new("Mat", "Material"); + mat.attrs.push(UsdAttr::connected("outputs:surface", "token", "/World/Mat/PBR.outputs:surface".into())); + let mut pbr = UsdPrim::new("PBR", "Shader"); + pbr.attrs.push(UsdAttr::new("outputs:surface", "token", None)); + mat.children.push(pbr); + root.children.push(mat); + + let mut layer = UsdLayer::new(root); + layer.doc = Some("Test doc".into()); + layer.meters_per_unit = 0.01; + layer.up_axis = "Z".into(); + + let text = usda(&layer); + assert!(text.contains("doc = \"Test doc\"")); + assert!(text.contains("metersPerUnit = 0.01")); + assert!(text.contains("upAxis = \"Z\"")); + + for bytes in [text.as_bytes(), &usdc(&layer).unwrap()] { + let parsed = read_layer(bytes).unwrap(); + assert_eq!(parsed.meters_per_unit, Some(0.01)); + assert_eq!(parsed.up_axis.as_deref(), Some("Z")); + let tri = parsed.prims.iter().find(|p| p.path == "/World/Tri").unwrap(); + assert_eq!(tri.type_name, "Mesh"); + assert_eq!(tri.specifier, Specifier::Def); + assert_eq!(tri.props.get("primvars:st").and_then(|p| p.interpolation.as_deref()), Some("vertex")); + assert_eq!(tri.props.get("material:binding").and_then(|p| p.value.as_ref()), Some(&Val::Path(vec!["/World/Mat".into()]))); + } + } + + /// A Crate file assembled spec by spec with a class prim referenced by a def prim + /// (with customData on the reference), a time-sampled out-of-line double3 translate, + /// a token[] xformOpOrder, and an inlined diagonal matrix. + #[test] + fn crafted_crate_with_references_time_samples_and_inlined_values() { + let mut w = Writer::new(); + let (wp, wt) = w.add_path(0, "/", "W", false); + let (pp, pt) = w.add_path(0, "/", "P", false); + let (mp, mt) = w.add_path(pp, &pt, "M", false); + let ops = ["xformOp:translate", "xformOp:transform", "xformOpOrder"].map(|n| w.prop_path((wp, &wt), n)); + let attrs = ["points", "faceVertexCounts", "faceVertexIndices"].map(|n| w.prop_path((mp, &mt), n)); + w.root_spec("W", 1.0, "Y").unwrap(); + let empty = w.token(""); + let key = w.token("note"); + w.strings = vec![empty, key]; + let def = |t: &str, w: &mut Writer| { + vec![("specifier", rep(ty::SPECIFIER, codec::IS_INLINED, 0)), ("typeName", rep(ty::TOKEN, codec::IS_INLINED, u64::from(w.token(t))))] + }; + + // /W: def Xform (prepend references =

with customData = {note: 7}). + let mut fields = def("Xform", &mut w); + let mut r = vec![1u8 << 5]; + r.extend_from_slice(&1u64.to_le_bytes()); + r.extend_from_slice(&0u32.to_le_bytes()); + r.extend_from_slice(&(pp as u32).to_le_bytes()); + r.extend(le(&[0.0, 1.0])); + r.extend_from_slice(&1u64.to_le_bytes()); + r.extend_from_slice(&1u32.to_le_bytes()); + r.extend_from_slice(&8i64.to_le_bytes()); + r.extend_from_slice(&rep(ty::INT, codec::IS_INLINED, 7).to_le_bytes()); + fields.push(("references", rep(ty::REFERENCE_LIST_OP, 0, w.raw(&r)))); + w.spec(wp, SPEC_PRIM, fields); + + // translate.timeSamples = {0: (1, 0, 0), 10: (5, 0, 0)}, out-of-line double3 values. + let at = w.offset(); + let mut t = 32i64.to_le_bytes().to_vec(); + t.extend_from_slice(&2u64.to_le_bytes()); + t.extend(le(&[0.0, 10.0])); + t.extend_from_slice(&rep(ty::DOUBLE_VECTOR, 0, at + 8).to_le_bytes()); + let values_at = at + 40 + 8; + t.extend_from_slice(&56i64.to_le_bytes()); + t.extend(le(&[1.0, 0.0, 0.0, 5.0, 0.0, 0.0])); + t.extend_from_slice(&2u64.to_le_bytes()); + t.extend_from_slice(&rep(23, 0, values_at).to_le_bytes()); + t.extend_from_slice(&rep(23, 0, values_at + 24).to_le_bytes()); + let samples = rep(ty::TIME_SAMPLES, 0, w.raw(&t)); + let double3 = rep(ty::TOKEN, codec::IS_INLINED, u64::from(w.token("double3"))); + w.spec(ops[0], SPEC_ATTRIBUTE, vec![("typeName", double3), ("timeSamples", samples)]); + // transform: diag(2, 2, 2, 1), inlined. + w.spec(ops[1], SPEC_ATTRIBUTE, vec![("default", rep(ty::MATRIX4D, codec::IS_INLINED, 0x0102_0202))]); + let order: Vec = ["xformOp:translate", "xformOp:transform"].iter().map(|n| w.token(n)).collect(); + let mut o = 2u64.to_le_bytes().to_vec(); + o.extend(order.iter().flat_map(|t| t.to_le_bytes())); + let order = rep(ty::TOKEN, codec::IS_ARRAY, w.raw(&o)); + w.spec(ops[2], SPEC_ATTRIBUTE, vec![("default", order)]); + + // /P: class Xform holding def Mesh M. + let mut fields = def("Xform", &mut w); + fields[0].1 = rep(ty::SPECIFIER, codec::IS_INLINED, 2); + w.spec(pp, SPEC_PRIM, fields); + let fields = def("Mesh", &mut w); + w.spec(mp, SPEC_PRIM, fields); + let points = w.value(&UsdValue::Vec3fs(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])).unwrap(); + let counts = w.value(&UsdValue::Ints(vec![3])).unwrap(); + let indices = w.value(&UsdValue::Ints(vec![0, 1, 2])).unwrap(); + for (path, value) in attrs.into_iter().zip([points, counts, indices]) { + w.spec(path, SPEC_ATTRIBUTE, vec![("default", value)]); + } + let bytes = w.finish().unwrap(); + + let layer = read_layer(&bytes).unwrap(); + let w_prim = layer.prims.iter().find(|p| p.path == "/W").unwrap(); + assert_eq!(w_prim.references, vec!["/P"]); + assert_eq!(w_prim.props.get("xformOp:translate").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![1.0, 0.0, 0.0]))); + assert_eq!( + w_prim.props.get("xformOp:transform").and_then(|p| p.value.as_ref()), + Some(&Val::Num(vec![2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0])) + ); + let p_prim = layer.prims.iter().find(|p| p.path == "/P").unwrap(); + assert_eq!(p_prim.specifier, Specifier::Class); + } +} diff --git a/crates/usd/tests/scene.rs b/crates/usd/tests/scene.rs new file mode 100644 index 0000000000..d8fa22c7fe --- /dev/null +++ b/crates/usd/tests/scene.rs @@ -0,0 +1,234 @@ +//! Known-answer USDA and USDC (Crate binary) corpus and round-trip integration tests. + +#![allow(clippy::unwrap_used)] + +use craft_usd::codec; +use craft_usd::scene::{ + Budget, MAX_DEPTH, SceneError, Specifier, UsdAttr, UsdLayer, UsdPrim, UsdValue, Val, read_layer, read_layer_with_budget, write_usda, write_usdc, +}; + +const CORPUS_USDA: &str = r#"#usda 1.0 +( + defaultPrim = "World" + doc = "Corpus test" + metersPerUnit = 0.01 + upAxis = "Z" + subLayers = [@./base.usda@] +) + +class Xform "Proto" +{ + def Mesh "Leaf" ( + prepend apiSchemas = ["MaterialBindingAPI"] + ) + { + int[] faceVertexCounts = [3] + int[] faceVertexIndices = [0, 1, 2] + point3f[] points = [(0, 0, 0), (100, 0, 0), (0, 100, 0)] + normal3f[] normals = [(0, 0, 1), (0, 0, 1), (0, 0, 1)] ( + interpolation = "vertex" + ) + texCoord2f[] primvars:st = [(0, 0), (1, 0), (0, 1)] ( + interpolation = "vertex" + ) + rel material:binding = + } +} + +def Xform "World" +{ + double3 xformOp:translate = (0, 0, 100) + float3 xformOp:rotateXYZ = (0, 0, 90) + float3 xformOp:scale = (2, 2, 2) + uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] + + def Xform "Instance" ( + prepend references = + ) + { + matrix4d xformOp:transform = ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (10, 0, 0, 1) ) + uniform token[] xformOpOrder = ["xformOp:transform"] + } + + over "Overlay" ( + active = false + ) + { + float3 xformOp:translate.timeSamples = { + 0: (1, 2, 3), + 10: (4, 5, 6), + } + } + + def Xform "External" ( + prepend references = @./other.usda@ + ) + { + variantSet "look" = { + "a" { + def Mesh "V" {} + } + } + } +} +"#; + +#[test] +fn usda_corpus_overlays_references_coordinates_transforms_and_meshes() { + let layer = read_layer(CORPUS_USDA.as_bytes()).unwrap(); + assert_eq!(layer.meters_per_unit, Some(0.01)); + assert_eq!(layer.up_axis.as_deref(), Some("Z")); + assert!(layer.warnings.iter().any(|w| w.contains("sublayers"))); + assert!(layer.warnings.iter().any(|w| w.contains("external references"))); + assert!(layer.warnings.iter().any(|w| w.contains("variant sets"))); + + let proto = layer.prims.iter().find(|p| p.path == "/Proto").unwrap(); + assert_eq!(proto.specifier, Specifier::Class); + assert_eq!(proto.type_name, "Xform"); + + let leaf = layer.prims.iter().find(|p| p.path == "/Proto/Leaf").unwrap(); + assert_eq!(leaf.specifier, Specifier::Def); + assert_eq!(leaf.type_name, "Mesh"); + assert_eq!(leaf.props.get("faceVertexCounts").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![3.0]))); + assert_eq!(leaf.props.get("faceVertexIndices").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![0.0, 1.0, 2.0]))); + assert_eq!(leaf.props.get("points").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![0.0, 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, 100.0, 0.0]))); + assert_eq!(leaf.props.get("normals").and_then(|p| p.interpolation.as_deref()), Some("vertex")); + assert_eq!(leaf.props.get("primvars:st").and_then(|p| p.interpolation.as_deref()), Some("vertex")); + assert_eq!(leaf.props.get("material:binding").and_then(|p| p.value.as_ref()), Some(&Val::Path(vec!["/World/Materials/LeafMat".into()]))); + + let world = layer.prims.iter().find(|p| p.path == "/World").unwrap(); + assert_eq!(world.specifier, Specifier::Def); + assert_eq!(world.props.get("xformOp:translate").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![0.0, 0.0, 100.0]))); + assert_eq!( + world.props.get("xformOpOrder").and_then(|p| p.value.as_ref()), + Some(&Val::Tok(vec!["xformOp:translate".into(), "xformOp:rotateXYZ".into(), "xformOp:scale".into()])) + ); + + let instance = layer.prims.iter().find(|p| p.path == "/World/Instance").unwrap(); + assert_eq!(instance.references, vec!["/Proto"]); + assert_eq!( + instance.props.get("xformOp:transform").and_then(|p| p.value.as_ref()), + Some(&Val::Num(vec![1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 10.0, 0.0, 0.0, 1.0])) + ); + + let overlay = layer.prims.iter().find(|p| p.path == "/World/Overlay").unwrap(); + assert_eq!(overlay.specifier, Specifier::Over); + assert_eq!(overlay.active, Some(false)); + assert_eq!(overlay.props.get("xformOp:translate").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![1.0, 2.0, 3.0]))); +} + +fn sample_scene_layer() -> UsdLayer { + let mut root = UsdPrim::new("Scene", "Xform"); + let mut mesh = UsdPrim::new("QuadMesh", "Mesh"); + mesh.binding_api = true; + mesh.attrs = vec![ + UsdAttr::new("extent", "float3[]", Some(UsdValue::Vec3fs(vec![[0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]))), + UsdAttr::new("points", "point3f[]", Some(UsdValue::Vec3fs(vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]]))), + UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3, 3]))), + UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(vec![0, 1, 2, 0, 2, 3]))), + UsdAttr::new("normals", "normal3f[]", Some(UsdValue::Vec3fs(vec![[0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]))) + .with_interpolation("vertex"), + UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(vec![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]))) + .with_interpolation("vertex"), + UsdAttr::new("subdivisionScheme", "token", Some(UsdValue::Token("none".into()))).uniform(), + UsdAttr::rel("material:binding", "/Scene/Materials/Default".into()), + ]; + + let mut subset = UsdPrim::new("Sub0", "GeomSubset"); + subset.binding_api = true; + subset.attrs = vec![ + UsdAttr::new("elementType", "token", Some(UsdValue::Token("face".into()))).uniform(), + UsdAttr::new("familyName", "token", Some(UsdValue::Token("materialBind".into()))).uniform(), + UsdAttr::new("indices", "int[]", Some(UsdValue::Ints(vec![1]))), + UsdAttr::rel("material:binding", "/Scene/Materials/Accent".into()), + ]; + mesh.children.push(subset); + root.children.push(mesh); + + let mut materials = UsdPrim::new("Materials", "Scope"); + for mat_name in ["Default", "Accent"] { + let mut mat = UsdPrim::new(mat_name, "Material"); + mat.attrs.push(UsdAttr::connected("outputs:surface", "token", format!("/Scene/Materials/{mat_name}/PBR.outputs:surface"))); + let mut pbr = UsdPrim::new("PBR", "Shader"); + pbr.attrs = vec![ + UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPreviewSurface".into()))).uniform(), + UsdAttr::new("inputs:useSpecularWorkflow", "int", Some(UsdValue::Int(0))), + UsdAttr::new("inputs:scale", "float4", Some(UsdValue::Float4([2.0, 2.0, 2.0, 1.0]))), + UsdAttr::new("inputs:file", "asset", Some(UsdValue::Asset("./tex.png".into()))), + UsdAttr::new("inputs:varname", "string", Some(UsdValue::Str("st".into()))), + UsdAttr::new("outputs:surface", "token", None), + ]; + mat.children.push(pbr); + materials.children.push(mat); + } + root.children.push(materials); + + let mut layer = UsdLayer::new(root); + layer.doc = Some("Integration round-trip".into()); + layer.meters_per_unit = 0.01; + layer.up_axis = "Z".into(); + layer +} + +#[test] +fn usda_and_usdc_round_trip_known_answers() { + let scene = sample_scene_layer(); + let text = write_usda(&scene); + assert!(text.starts_with("#usda 1.0")); + assert!(text.contains("defaultPrim = \"Scene\"")); + assert!(text.contains("doc = \"Integration round-trip\"")); + assert!(text.contains("metersPerUnit = 0.01")); + assert!(text.contains("upAxis = \"Z\"")); + + let crate_bytes = write_usdc(&scene).unwrap(); + assert!(crate_bytes.starts_with(codec::MAGIC)); + assert_eq!(&crate_bytes[8..11], &[0, 8, 0]); + + for (label, bytes) in [("usda", text.as_bytes()), ("usdc", crate_bytes.as_slice())] { + let parsed = read_layer(bytes).unwrap(); + assert_eq!(parsed.meters_per_unit, Some(0.01), "{label}"); + assert_eq!(parsed.up_axis.as_deref(), Some("Z"), "{label}"); + + let mesh = parsed.prims.iter().find(|p| p.path == "/Scene/QuadMesh").unwrap(); + assert_eq!(mesh.type_name, "Mesh", "{label}"); + assert_eq!(mesh.specifier, Specifier::Def, "{label}"); + assert_eq!(mesh.props.get("faceVertexCounts").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![3.0, 3.0])), "{label}"); + assert_eq!( + mesh.props.get("faceVertexIndices").and_then(|p| p.value.as_ref()), + Some(&Val::Num(vec![0.0, 1.0, 2.0, 0.0, 2.0, 3.0])), + "{label}" + ); + assert_eq!(mesh.props.get("primvars:st").and_then(|p| p.interpolation.as_deref()), Some("vertex"), "{label}"); + assert_eq!( + mesh.props.get("material:binding").and_then(|p| p.value.as_ref()), + Some(&Val::Path(vec!["/Scene/Materials/Default".into()])), + "{label}" + ); + + let subset = parsed.prims.iter().find(|p| p.path == "/Scene/QuadMesh/Sub0").unwrap(); + assert_eq!(subset.type_name, "GeomSubset", "{label}"); + assert_eq!(subset.props.get("indices").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![1.0])), "{label}"); + + let pbr = parsed.prims.iter().find(|p| p.path == "/Scene/Materials/Default/PBR").unwrap(); + assert_eq!(pbr.props.get("info:id").and_then(|p| p.value.as_ref()), Some(&Val::Tok(vec!["UsdPreviewSurface".into()])), "{label}"); + assert_eq!(pbr.props.get("inputs:file").and_then(|p| p.value.as_ref()), Some(&Val::Tok(vec!["./tex.png".into()])), "{label}"); + assert_eq!(pbr.props.get("inputs:varname").and_then(|p| p.value.as_ref()), Some(&Val::Tok(vec!["st".into()])), "{label}"); + assert_eq!(pbr.props.get("inputs:scale").and_then(|p| p.value.as_ref()), Some(&Val::Num(vec![2.0, 2.0, 2.0, 1.0])), "{label}"); + } +} + +#[test] +fn decoded_budget_and_invalid_inputs_are_enforced() { + let scene = sample_scene_layer(); + let crate_bytes = write_usdc(&scene).unwrap(); + let mut tiny_budget = Budget::with_limit(64); + assert!(matches!(read_layer_with_budget(&crate_bytes, &mut tiny_budget), Err(SceneError::TooLarge(_)))); + + assert!(matches!(read_layer(b"not a usd file"), Err(SceneError::Malformed(_)))); + assert!(matches!(read_layer(b"PXR-USDC\x00\x03\x00\x00"), Err(SceneError::Unsupported(_)))); + + let mut bad_target = UsdLayer::new(UsdPrim::new("Root", "Xform")); + bad_target.root.attrs.push(UsdAttr::rel("material:binding", "/Does/Not/Exist".into())); + assert!(matches!(write_usdc(&bad_target), Err(SceneError::Invalid(_)))); + assert_eq!(MAX_DEPTH, 128); +} From 106134631c5f2ed46568b8fc1b619d1524a868a1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:36:39 -0500 Subject: [PATCH 73/79] video: add TrackDecoderOptions, with_threads, and set_draft on TrackDecoder (#2461) * video: add TrackDecoderOptions, with_threads, and set_draft on TrackDecoder (#778) * fix(video): allow unused opts when decoder features disabled * video: fix unreachable pattern in TrackDecoder::set_draft and verify inner state on reset * fix(video): allow irrefutable_let_patterns when single decoder feature enabled * fix(video): remove nonexistent hevc/av1 Decoder::threads test getters * style(video): allow clippy::cognitive_complexity in track options test --- crates/video/src/av1/decode/decoder.rs | 5 ++ crates/video/src/hevc/decode/decoder.rs | 5 ++ crates/video/src/lib.rs | 2 +- crates/video/src/track.rs | 100 +++++++++++++++++++++--- crates/video/src/track/tests.rs | 82 +++++++++++++++++++ crates/video/src/vp9/decode/decoder.rs | 5 ++ 6 files changed, 188 insertions(+), 11 deletions(-) diff --git a/crates/video/src/av1/decode/decoder.rs b/crates/video/src/av1/decode/decoder.rs index 4a922cce15..1aa8d92612 100644 --- a/crates/video/src/av1/decode/decoder.rs +++ b/crates/video/src/av1/decode/decoder.rs @@ -604,6 +604,11 @@ impl Decoder { self.draft = on; } + #[cfg(test)] + pub(crate) fn draft(&self) -> bool { + self.draft + } + pub fn stats(&self) -> DecodeStats { self.stats.lock().map(|s| *s).unwrap_or_default() } diff --git a/crates/video/src/hevc/decode/decoder.rs b/crates/video/src/hevc/decode/decoder.rs index 2f226d5713..66c3ac77f9 100644 --- a/crates/video/src/hevc/decode/decoder.rs +++ b/crates/video/src/hevc/decode/decoder.rs @@ -296,6 +296,11 @@ impl Decoder { self.draft = on; } + #[cfg(test)] + pub(crate) fn draft(&self) -> bool { + self.draft + } + pub fn take_error(&mut self) -> Option { self.shared.error.lock().ok().and_then(|mut e| e.take()) } diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index 6101324f91..b17d586886 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -66,7 +66,7 @@ mod track; feature = "ffv1", feature = "vp8-decode" ))] -pub use track::TrackDecoder; +pub use track::{TrackDecoder, TrackDecoderOptions}; #[cfg(any(feature = "apv-decode", feature = "apv-encode"))] pub mod apv; diff --git a/crates/video/src/track.rs b/crates/video/src/track.rs index d89eeaeac7..fa7be7e515 100644 --- a/crates/video/src/track.rs +++ b/crates/video/src/track.rs @@ -92,16 +92,33 @@ enum Inner { /// } /// # Ok(()) } /// ``` +/// Options for [`TrackDecoder::with_options`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TrackDecoderOptions { + /// Worker threads for codecs that decode in parallel (`None` uses the codec default; + /// `Some(1)` decodes on the calling thread). Values of `0` are clamped to `1`. + pub threads: Option, + /// Draft mode (approximate, for reduced-resolution playback only; never for export). + pub draft: bool, +} + pub struct TrackDecoder { inner: Inner, codec: CodecId, + threads: Option, + draft: bool, /// Frames finished by a call that then failed, which the next call returns first. held: Vec, } impl std::fmt::Debug for TrackDecoder { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("TrackDecoder").field("codec", &self.codec).field("held", &self.held.len()).finish_non_exhaustive() + f.debug_struct("TrackDecoder") + .field("codec", &self.codec) + .field("threads", &self.threads) + .field("draft", &self.draft) + .field("held", &self.held.len()) + .finish_non_exhaustive() } } @@ -114,7 +131,20 @@ impl TrackDecoder { /// allowed, is [`VideoError::Malformed`]. Unsupported codec features are /// [`VideoError::Unsupported`]. pub fn new(params: &CodecParams) -> Result { - Ok(TrackDecoder { inner: Inner::new(params)?, codec: params.codec, held: Vec::new() }) + Self::with_options(params, TrackDecoderOptions::default()) + } + + /// Like [`TrackDecoder::new`], capped at `threads` worker threads (`1` decodes on the calling + /// thread; `0` is clamped to `1`) for codecs that decode in parallel. + pub fn with_threads(params: &CodecParams, threads: usize) -> Result { + Self::with_options(params, TrackDecoderOptions { threads: Some(threads), draft: false }) + } + + /// Like [`TrackDecoder::new`], with explicit threading and draft options. + pub fn with_options(params: &CodecParams, options: TrackDecoderOptions) -> Result { + let threads = options.threads.map(|t| t.max(1)); + let normalized = TrackDecoderOptions { threads, draft: options.draft }; + Ok(TrackDecoder { inner: Inner::new(params, normalized)?, codec: params.codec, threads, draft: options.draft, held: Vec::new() }) } /// The track's codec, as `params` gave it. @@ -122,6 +152,44 @@ impl TrackDecoder { self.codec } + /// The explicit worker-thread cap, or `None` when using the codec's default. + pub fn threads(&self) -> Option { + self.threads + } + + /// Whether draft mode is enabled (for reduced-resolution playback only; never for export). + pub fn draft(&self) -> bool { + self.draft + } + + /// Toggle draft mode (skipping non-reference loop/deblocking filters on codecs that support + /// it). Approximate, for reduced-resolution playback only; never use for export. + pub fn set_draft(&mut self, on: bool) { + self.draft = on; + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, .. } => dec.set_draft(on), + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, .. } => dec.set_draft(on), + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => dec.set_draft(on), + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, .. } => dec.set_draft(on), + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(_) => {} + #[cfg(feature = "prores")] + Inner::ProRes => {} + #[cfg(feature = "dnx")] + Inner::Dnx => {} + #[cfg(feature = "apv-decode")] + Inner::Apv => {} + #[cfg(feature = "ffv1")] + Inner::Ffv1(_) => {} + #[cfg(feature = "vp8-decode")] + Inner::Vp8(_) => {} + } + } + /// Decode one packet (an access unit, a VP9 frame or superframe, an AV1 temporal unit) with /// its presentation timestamp. Returns the frames that became ready for display, in display /// order; a decoder that reorders or decodes on worker threads returns a packet's frame from a @@ -247,7 +315,8 @@ impl TrackDecoder { #[cfg(feature = "hevc-decode")] Inner::Hevc { dec, config } => { // The HEVC decoder has no reset of its own: a new one starts from nothing. - let mut fresh = Box::new(hevc::decode::Decoder::new()); + let mut fresh = Box::new(self.threads.map_or_else(hevc::decode::Decoder::new, hevc::decode::Decoder::with_threads)); + fresh.set_draft(self.draft); configure_hevc(&mut fresh, config)?; *dec = fresh; Ok(()) @@ -260,7 +329,8 @@ impl TrackDecoder { #[cfg(feature = "av1-decode")] Inner::Av1 { dec, config_obus } => { // The AV1 decoder has no reset of its own: a new one starts from nothing. - let mut fresh = Box::new(av1::decode::Decoder::new()); + let mut fresh = Box::new(self.threads.map_or_else(av1::decode::Decoder::new, av1::decode::Decoder::with_threads)); + fresh.set_draft(self.draft); configure_av1(&mut fresh, config_obus)?; *dec = fresh; Ok(()) @@ -335,35 +405,45 @@ impl TrackDecoder { } impl Inner { - fn new(params: &CodecParams) -> Result { + fn new(params: &CodecParams, options: TrackDecoderOptions) -> Result { let codec = params.codec; let extradata = ¶ms.extradata; - let _ = extradata; + let _ = (extradata, options); match codec { #[cfg(feature = "h264-decode")] CodecId::H264 => { - let mut dec = Box::new(h264::decode::Decoder::new()); + let mut dec = Box::new(options.threads.map_or_else(h264::decode::Decoder::new, h264::decode::Decoder::with_threads)); + dec.set_draft(options.draft); configure_h264(&mut dec, extradata)?; Ok(Inner::H264 { dec, config: extradata.to_vec() }) } #[cfg(feature = "hevc-decode")] CodecId::Hevc => { - let mut dec = Box::new(hevc::decode::Decoder::new()); + let mut dec = Box::new(options.threads.map_or_else(hevc::decode::Decoder::new, hevc::decode::Decoder::with_threads)); + dec.set_draft(options.draft); configure_hevc(&mut dec, extradata)?; Ok(Inner::Hevc { dec, config: extradata.to_vec() }) } #[cfg(feature = "vp9-decode")] - CodecId::Vp9 => Ok(Inner::Vp9(Box::default())), + CodecId::Vp9 => { + let mut dec = Box::new(options.threads.map_or_else(vp9::decode::Decoder::new, vp9::decode::Decoder::with_threads)); + dec.set_draft(options.draft); + Ok(Inner::Vp9(dec)) + } #[cfg(feature = "av1-decode")] CodecId::Av1 => { let config_obus = av1c_config_obus(extradata)?.to_vec(); - let mut dec = Box::new(av1::decode::Decoder::new()); + let mut dec = Box::new(options.threads.map_or_else(av1::decode::Decoder::new, av1::decode::Decoder::with_threads)); + dec.set_draft(options.draft); configure_av1(&mut dec, &config_obus)?; Ok(Inner::Av1 { dec, config_obus }) } #[cfg(feature = "mpeg2-decode")] CodecId::Mpeg2Video => { let mut dec = Box::new(mpeg2::Decoder::new()); + if let Some(threads) = options.threads { + dec.set_threads(threads > 1); + } if !extradata.is_empty() { check_mpeg2_config(extradata)?; dec.decode(extradata, 0)?; diff --git a/crates/video/src/track/tests.rs b/crates/video/src/track/tests.rs index 42d3ab861d..d9da7fe724 100644 --- a/crates/video/src/track/tests.rs +++ b/crates/video/src/track/tests.rs @@ -389,3 +389,85 @@ fn new_codec_errors_keep_their_category() { #[cfg(feature = "vp8-decode")] assert!(matches!(VideoError::from(crate::vp8::Error::Invalid("header".into())), VideoError::Malformed(_))); } + +#[test] +#[allow(irrefutable_let_patterns, clippy::cognitive_complexity)] +fn track_decoder_options_and_draft_persist_across_reset() { + #[allow(unused_variables)] + let opts = TrackDecoderOptions { threads: Some(0), draft: true }; + #[cfg(feature = "h264-decode")] + { + let mut dec = TrackDecoder::with_options(¶ms(CodecId::H264, &[]), opts).unwrap(); + assert_eq!(dec.threads(), Some(1)); + assert!(dec.draft()); + if let Inner::H264 { dec: inner, .. } = &dec.inner { + assert_eq!(inner.threads(), 1); + assert!(inner.draft()); + } else { + panic!("expected H264 inner"); + } + dec.reset().unwrap(); + assert!(dec.draft()); + if let Inner::H264 { dec: inner, .. } = &dec.inner { + assert_eq!(inner.threads(), 1); + assert!(inner.draft()); + } + dec.set_draft(false); + assert!(!dec.draft()); + if let Inner::H264 { dec: inner, .. } = &dec.inner { + assert!(!inner.draft()); + } + let dec2 = TrackDecoder::with_threads(¶ms(CodecId::H264, &[]), 2).unwrap(); + assert_eq!(dec2.threads(), Some(2)); + assert!(!dec2.draft()); + if let Inner::H264 { dec: inner, .. } = &dec2.inner { + let expected = if cfg!(all(feature = "threads", not(target_arch = "wasm32"))) { 2 } else { 1 }; + assert_eq!(inner.threads(), expected); + assert!(!inner.draft()); + } + } + #[cfg(feature = "hevc-decode")] + { + let mut dec = TrackDecoder::with_options(¶ms(CodecId::Hevc, &[]), opts).unwrap(); + assert_eq!(dec.threads(), Some(1)); + assert!(dec.draft()); + if let Inner::Hevc { dec: inner, .. } = &dec.inner { + assert!(inner.draft()); + } + dec.reset().unwrap(); + assert!(dec.draft()); + if let Inner::Hevc { dec: inner, .. } = &dec.inner { + assert!(inner.draft()); + } + } + #[cfg(feature = "av1-decode")] + { + let mut dec = TrackDecoder::with_options(¶ms(CodecId::Av1, &[]), opts).unwrap(); + assert_eq!(dec.threads(), Some(1)); + assert!(dec.draft()); + if let Inner::Av1 { dec: inner, .. } = &dec.inner { + assert!(inner.draft()); + } + dec.reset().unwrap(); + assert!(dec.draft()); + if let Inner::Av1 { dec: inner, .. } = &dec.inner { + assert!(inner.draft()); + } + } + #[cfg(feature = "vp9-decode")] + { + let mut dec = TrackDecoder::with_options(¶ms(CodecId::Vp9, &[]), opts).unwrap(); + assert_eq!(dec.threads(), Some(1)); + assert!(dec.draft()); + if let Inner::Vp9(inner) = &dec.inner { + assert_eq!(inner.threads(), 1); + assert!(inner.draft()); + } + dec.reset().unwrap(); + assert!(dec.draft()); + if let Inner::Vp9(inner) = &dec.inner { + assert_eq!(inner.threads(), 1); + assert!(inner.draft()); + } + } +} diff --git a/crates/video/src/vp9/decode/decoder.rs b/crates/video/src/vp9/decode/decoder.rs index 1a0af2ed59..5432994ef9 100644 --- a/crates/video/src/vp9/decode/decoder.rs +++ b/crates/video/src/vp9/decode/decoder.rs @@ -164,6 +164,11 @@ impl Decoder { self.draft = on; } + #[cfg(test)] + pub(crate) fn draft(&self) -> bool { + self.draft + } + /// Decode one chunk (a frame or a superframe, as stored in one IVF / WebM / MP4 sample). /// Returns the pictures finished so far, in order; each carries the `pts` of the chunk that /// showed it. With frame threads a picture may come out of a later call or [`Self::flush`]. From 3dff4793f1a5bd1f99a4fe3280d48f515158dff3 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 20:36:43 -0500 Subject: [PATCH 74/79] craft-develop, craft-color-transform: deduplicate spline, add 1024-entry compose_len, spaces, and warm-green WB test (#2464) * craft-develop, craft-color-transform: deduplicate spline, add 1024-entry Lut1::compose_len, spaces, and warm-green WB test * cct: check bradford identity and matrix tolerance in warm-green WB test * style(color-transform): fix clippy needless_range_loop in cct test --- Cargo.lock | 1 + crates/color-transform/src/cct.rs | 20 +++ crates/color-transform/src/curve.rs | 41 ++++++ crates/color-transform/src/lib.rs | 4 +- crates/color-transform/src/space.rs | 17 +++ crates/develop/Cargo.toml | 1 + crates/develop/README.md | 2 +- crates/develop/src/color/mod.rs | 2 +- crates/develop/src/color/spline.rs | 206 ---------------------------- 9 files changed, 85 insertions(+), 209 deletions(-) delete mode 100644 crates/develop/src/color/spline.rs diff --git a/Cargo.lock b/Cargo.lock index 79eb278cda..3c7c6a1e91 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1794,6 +1794,7 @@ dependencies = [ name = "craft-develop" version = "0.1.0" dependencies = [ + "craft-color-transform", "craft-develop-model", "craft-render-parity", "proptest", diff --git a/crates/color-transform/src/cct.rs b/crates/color-transform/src/cct.rs index 1f81cdb19f..413ca5e6e1 100644 --- a/crates/color-transform/src/cct.rs +++ b/crates/color-transform/src/cct.rs @@ -240,4 +240,24 @@ mod tests { assert_eq!(xy_to_temp_tint(p), (6500.0, 0.0), "{p:?}"); } } + + /// Pins the current behavior for warm, strongly green illuminants (e.g. 2000–3500 K with high + /// positive tint) where the source white's Bradford blue cone response is `<= 0.0`. The + /// checked Bradford path currently returns `Mat3::IDENTITY` there (so `wb_matrix` is + /// `REC2020.from_xyz() * REC2020.to_xyz()`, i.e. identity within `f64` rounding) rather than + /// inverting blue; final `#587` process-version policy for this region remains open. + #[test] + fn warm_green_wb_with_non_positive_cone_response_returns_identity() { + for (t, tint) in [(2000.0, 30.0), (2500.0, 60.0), (3000.0, 100.0), (3500.0, 125.0)] { + let src = temp_tint_to_xy(t, tint); + assert_eq!(crate::bradford(src, REC2020.white), Mat3::IDENTITY, "{t} K tint {tint}"); + let m = wb_matrix(&REC2020, src); + for (i, row) in m.0.iter().enumerate() { + for (j, &val) in row.iter().enumerate() { + let want = if i == j { 1.0 } else { 0.0 }; + assert!((val - want).abs() < 1e-12, "{t} K tint {tint} [{i}][{j}] = {val}"); + } + } + } + } } diff --git a/crates/color-transform/src/curve.rs b/crates/color-transform/src/curve.rs index cdf135cd5c..5a7d482b2c 100644 --- a/crates/color-transform/src/curve.rs +++ b/crates/color-transform/src/curve.rs @@ -225,6 +225,32 @@ impl Lut1 { } } + /// Resample this table to `n` evenly spaced entries over `0..1` (2 to [`MAX_LUT`]). + pub fn resample(&self, n: usize) -> Lut1 { + let n = n.clamp(2, MAX_LUT); + if self.v.len() == n { + return self.clone(); + } + Lut1::from_fn(n, |x| self.eval(x)) + } + + /// `self ∘ inner` sampled at `n` evenly spaced entries over `0..1` (2 to [`MAX_LUT`]). + /// + /// Preserves fixed-size GPU LUT contracts (such as 1,024-entry shader tables) where + /// [`Lut1::compose`] would expand to the common refinement grid. When `inner` is empty it + /// resamples `self` to `n` entries; when `inner` already has `n` entries it evaluates `self` + /// directly at each of `inner`'s samples. + pub fn compose_len(&self, inner: &Lut1, n: usize) -> Lut1 { + let n = n.clamp(2, MAX_LUT); + if inner.v.is_empty() { + return self.resample(n); + } + if inner.v.len() == n { + return Lut1 { v: inner.v.iter().map(|&x| self.eval(x)).collect() }; + } + Lut1::from_fn(n, |x| self.eval(inner.eval(x))) + } + pub fn is_identity(&self) -> bool { let n = self.v.len(); n >= 2 && self.v.iter().enumerate().all(|(i, &y)| (y - i as f32 / (n - 1) as f32).abs() < 1e-6) @@ -319,6 +345,21 @@ mod tests { assert_eq!(a.compose(&Lut1 { v: vec![] }), a); } + #[test] + fn compose_len_preserves_fixed_gpu_lut_size() { + const N: usize = 1024; + let a = Lut1::from_fn(N, |x| x * x); + let b = Lut1::from_fn(N, f32::sqrt); + let c = a.compose_len(&b, N); + assert_eq!(c.v.len(), N); + assert!((c.eval(0.3) - 0.3).abs() < 2e-3); + assert_eq!(a.compose_len(&Lut1 { v: vec![] }, N), a); + let small = Lut1::from_fn(17, f32::sqrt); + let d = a.compose_len(&small, N); + assert_eq!(d.v.len(), N); + assert!((d.eval(0.3) - a.eval(small.eval(0.3))).abs() < 2e-3); + } + /// A short `inner` does not drop the outer table's points between its own. #[test] fn composing_with_a_short_table_keeps_the_outer_curve() { diff --git a/crates/color-transform/src/lib.rs b/crates/color-transform/src/lib.rs index 7708cd75eb..1c37910009 100644 --- a/crates/color-transform/src/lib.rs +++ b/crates/color-transform/src/lib.rs @@ -18,4 +18,6 @@ pub mod oklab; mod space; pub mod tonemap; -pub use space::{BRADFORD, D50, D65, DISPLAY_P3, Mat3, REC601_525, REC601_625, REC2020, RgbSpace, SRGB, Xy, bradford, bradford_xyz}; +pub use space::{ + ADOBE_RGB, BRADFORD, D50, D65, DISPLAY_P3, Mat3, PROPHOTO, REC601_525, REC601_625, REC2020, RgbSpace, SRGB, Xy, bradford, bradford_xyz, +}; diff --git a/crates/color-transform/src/space.rs b/crates/color-transform/src/space.rs index c0c1da3826..d067d878a5 100644 --- a/crates/color-transform/src/space.rs +++ b/crates/color-transform/src/space.rs @@ -118,6 +118,11 @@ pub const REC601_525: RgbSpace = RgbSpace { r: Xy::new(0.630, 0.340), g: Xy::new pub const REC2020: RgbSpace = RgbSpace { r: Xy::new(0.708, 0.292), g: Xy::new(0.170, 0.797), b: Xy::new(0.131, 0.046), white: D65 }; /// The DCI-P3 primaries with a D65 white (SMPTE EG 432-1). pub const DISPLAY_P3: RgbSpace = RgbSpace { r: Xy::new(0.680, 0.320), g: Xy::new(0.265, 0.690), b: Xy::new(0.150, 0.060), white: D65 }; +/// ProPhoto RGB (ROMM RGB, ISO 22028-2) primaries with a D50 white. +pub const PROPHOTO: RgbSpace = + RgbSpace { r: Xy::new(0.734699, 0.265301), g: Xy::new(0.159597, 0.840403), b: Xy::new(0.036598, 0.000105), white: D50 }; +/// The 1998 Adobe RGB primaries with a D65 white. +pub const ADOBE_RGB: RgbSpace = RgbSpace { r: Xy::new(0.64, 0.33), g: Xy::new(0.21, 0.71), b: Xy::new(0.15, 0.06), white: D65 }; impl From for RgbSpace { fn from(p: Primaries) -> RgbSpace { @@ -292,4 +297,16 @@ mod tests { let m: [[f64; 3]; 3] = read.to_xyz().into(); assert_eq!(Mat3::from(m), read.to_xyz()); } + + #[test] + fn prophoto_and_adobe_rgb_map_white_and_roundtrip() { + for sp in [PROPHOTO, ADOBE_RGB] { + let w = sp.to_space(&REC2020).apply([1.0, 1.0, 1.0]); + assert!(w.iter().all(|c| (c - 1.0).abs() < 1e-3), "{sp:?} -> {w:?}"); + } + let a = SRGB.to_space(&PROPHOTO); + let b = PROPHOTO.to_space(&SRGB); + let v = b.apply(a.apply([0.2, 0.5, 0.9])); + assert!((v[0] - 0.2).abs() < 1e-9 && (v[1] - 0.5).abs() < 1e-9 && (v[2] - 0.9).abs() < 1e-9); + } } diff --git a/crates/develop/Cargo.toml b/crates/develop/Cargo.toml index 0ded6bc383..6d78859832 100644 --- a/crates/develop/Cargo.toml +++ b/crates/develop/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true workspace = true [dependencies] +craft-color-transform = { workspace = true } craft-develop-model = { workspace = true } serde = { workspace = true } diff --git a/crates/develop/README.md b/crates/develop/README.md index 561e408c18..6cab634280 100644 --- a/crates/develop/README.md +++ b/crates/develop/README.md @@ -12,7 +12,7 @@ craft-develop = { git = "https://github.com/storytold/craft-libs", rev = ", - ys: Vec, - ms: Vec, -} - -impl MonotoneCurve { - /// Build from points; sorts by x, merges duplicates. Fewer than two points → identity. - pub fn new(points: &[(f64, f64)]) -> MonotoneCurve { - let mut p: Vec<(f64, f64)> = points.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect(); - p.sort_by(|a, b| a.0.total_cmp(&b.0)); - p.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9); - if p.len() < 2 { - p = vec![(0.0, 0.0), (1.0, 1.0)]; - } - let n = p.len(); - let xs: Vec = p.iter().map(|q| q.0).collect(); - let ys: Vec = p.iter().map(|q| q.1).collect(); - let d: Vec = (0..n - 1).map(|i| (ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i])).collect(); - let mut ms = vec![0.0; n]; - ms[0] = d[0]; - ms[n - 1] = d[n - 2]; - for i in 1..n - 1 { - ms[i] = if d[i - 1] * d[i] <= 0.0 { 0.0 } else { (d[i - 1] + d[i]) / 2.0 }; - } - // Fritsch–Carlson limiter where the data is monotone within a segment. - for i in 0..n - 1 { - if d[i] == 0.0 { - ms[i] = 0.0; - ms[i + 1] = 0.0; - continue; - } - let a = ms[i] / d[i]; - let b = ms[i + 1] / d[i]; - let s = a * a + b * b; - if s > 9.0 { - let t = 3.0 / s.sqrt(); - ms[i] = t * a * d[i]; - ms[i + 1] = t * b * d[i]; - } - } - MonotoneCurve { xs, ys, ms } - } - - pub fn identity() -> MonotoneCurve { - MonotoneCurve::new(&[(0.0, 0.0), (1.0, 1.0)]) - } - - pub fn eval(&self, x: f64) -> f64 { - // NaN passes both bound checks below and would send the search past either end - if x.is_nan() { - return x; - } - let n = self.xs.len(); - if x <= self.xs[0] { - return self.ys[0] + self.ms[0] * (x - self.xs[0]).min(0.0) * 0.0; - } - if x >= self.xs[n - 1] { - return self.ys[n - 1]; - } - let i = match self.xs.binary_search_by(|v| v.total_cmp(&x)) { - Ok(i) => return self.ys[i], - Err(i) => i - 1, - }; - let h = self.xs[i + 1] - self.xs[i]; - let t = (x - self.xs[i]) / h; - let (t2, t3) = (t * t, t * t * t); - (2.0 * t3 - 3.0 * t2 + 1.0) * self.ys[i] - + (t3 - 2.0 * t2 + t) * h * self.ms[i] - + (-2.0 * t3 + 3.0 * t2) * self.ys[i + 1] - + (t3 - t2) * h * self.ms[i + 1] - } - - /// Sample into a LUT of `n` entries (at least 2) over `0..1`. - pub fn to_lut(&self, n: usize) -> Lut1 { - let n = n.max(2); - Lut1 { v: (0..n).map(|i| self.eval(i as f64 / (n - 1) as f64) as f32).collect() } - } - - pub fn points(&self) -> Vec<(f64, f64)> { - self.xs.iter().copied().zip(self.ys.iter().copied()).collect() - } -} - -/// A 1-D lookup table over `0..1` with linear interpolation; inputs outside clamp. -#[derive(Clone, Debug, PartialEq)] -pub struct Lut1 { - pub v: Vec, -} - -impl Lut1 { - /// At least 2 entries, like [`Lut1::from_fn`]. - pub fn identity(n: usize) -> Lut1 { - Lut1::from_fn(n, |x| x) - } - /// `f` sampled at `n` evenly spaced points over `0..1` (at least 2). - pub fn from_fn(n: usize, f: impl Fn(f32) -> f32) -> Lut1 { - let n = n.max(2); - Lut1 { v: (0..n).map(|i| f(i as f32 / (n - 1) as f32)).collect() } - } - /// `v` is public, so a table shorter than 2 entries is read as constant (1) or the identity (0). - #[inline] - pub fn eval(&self, x: f32) -> f32 { - let x = x.clamp(0.0, 1.0); - let n = self.v.len(); - if n < 2 { - return self.v.first().copied().unwrap_or(x); - } - let f = x * (n - 1) as f32; - let i = (f as usize).min(n - 2); - let t = f - i as f32; - self.v[i] + (self.v[i + 1] - self.v[i]) * t - } - /// `self ∘ inner` (apply `inner` first). - pub fn compose(&self, inner: &Lut1) -> Lut1 { - Lut1 { v: inner.v.iter().map(|&x| self.eval(x)).collect() } - } - pub fn is_identity(&self) -> bool { - let n = self.v.len(); - self.v.iter().enumerate().all(|(i, &y)| (y - i as f32 / (n - 1) as f32).abs() < 1e-6) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn identity_curve() { - let c = MonotoneCurve::identity(); - for i in 0..=10 { - let x = i as f64 / 10.0; - assert!((c.eval(x) - x).abs() < 1e-12); - } - assert!(c.to_lut(256).is_identity()); - } - - #[test] - fn passes_through_points_and_is_monotone() { - let pts = [(0.0, 0.0), (0.25, 0.15), (0.5, 0.5), (0.75, 0.88), (1.0, 1.0)]; - let c = MonotoneCurve::new(&pts); - for (x, y) in pts { - assert!((c.eval(x) - y).abs() < 1e-12); - } - let mut prev = -1.0; - for i in 0..=1000 { - let y = c.eval(i as f64 / 1000.0); - assert!(y >= prev - 1e-12); - prev = y; - } - } - - #[test] - fn no_overshoot_on_flat_segment() { - let c = MonotoneCurve::new(&[(0.0, 0.0), (0.4, 0.5), (0.6, 0.5), (1.0, 1.0)]); - for i in 400..=600 { - let y = c.eval(i as f64 / 1000.0); - assert!((y - 0.5).abs() < 1e-9, "{y}"); - } - } - - #[test] - fn lut_compose() { - let a = Lut1::from_fn(1024, |x| x * x); - let b = Lut1::from_fn(1024, |x| x.sqrt()); - let c = a.compose(&b); - assert!((c.eval(0.3) - 0.3).abs() < 2e-3); - } - - #[test] - fn nan_input_and_short_luts_do_not_panic() { - let c = MonotoneCurve::new(&[(0.0, 0.0), (0.5, 0.6), (1.0, 1.0)]); - assert!(c.eval(f64::NAN).is_nan()); - assert!(c.eval(-f64::NAN).is_nan()); - for n in [0, 1] { - assert_eq!(c.to_lut(n).v.len(), 2, "{n}"); - assert!(Lut1::identity(n).is_identity(), "{n}"); - assert_eq!(Lut1::from_fn(n, |x| x).v.len(), 2, "{n}"); - } - assert_eq!(Lut1 { v: vec![] }.eval(0.3), 0.3); - assert_eq!(Lut1 { v: vec![] }.eval(-1.0), 0.0, "inputs outside 0..1 clamp, as for any table"); - assert_eq!(Lut1 { v: vec![] }.eval(2.0), 1.0); - assert_eq!(Lut1 { v: vec![0.7] }.eval(0.3), 0.7); - } - - proptest::proptest! { - #[test] - fn monotone_for_increasing_data(ys in proptest::collection::vec(0.0f64..1.0, 3..8)) { - let mut ys = ys; ys.sort_by(|a, b| a.total_cmp(b)); - let n = ys.len(); - let pts: Vec<(f64, f64)> = ys.iter().enumerate().map(|(i, y)| (i as f64 / (n - 1) as f64, *y)).collect(); - let c = MonotoneCurve::new(&pts); - let mut prev = f64::MIN; - for i in 0..=200 { let y = c.eval(i as f64 / 200.0); proptest::prop_assert!(y >= prev - 1e-9); prev = y; } - } - } -} From 5c0d5999bd806c74a75e074af94075cf7a8a8890 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 21:08:56 -0500 Subject: [PATCH 75/79] Expose bounded ZIP directory records for catalog selection (#2474) * zip: expose bounded central directory record listing * Preserve original ZIP central directory name bytes --- crates/zip/src/lenient.rs | 14 ++++- crates/zip/src/lenient/file.rs | 112 ++++++++++++++++++++++++++++----- crates/zip/src/seekable.rs | 12 ++++ 3 files changed, 118 insertions(+), 20 deletions(-) diff --git a/crates/zip/src/lenient.rs b/crates/zip/src/lenient.rs index 20da277cdd..70ce7253f8 100644 --- a/crates/zip/src/lenient.rs +++ b/crates/zip/src/lenient.rs @@ -170,16 +170,21 @@ fn recover_zip64_record(data: &[u8], loc: usize, disk_entries: u64, total: u64, /// Parse the central directory, keeping at most `max_entries`. pub fn parse(data: &[u8], max_entries: usize) -> Result { - parse_directory(data, max_entries, None) + parse_directory(data, max_entries, None, None) } /// Search the validated directory while retaining only the requested entry. pub fn has_entry(data: &[u8], name: &str) -> bool { - parse_directory(data, 1, Some(name)).is_ok_and(|archive| !archive.entries.is_empty()) + parse_directory(data, 1, Some(name), None).is_ok_and(|archive| !archive.entries.is_empty()) } /// List directory entries, optionally retaining only a matching decoded name. -fn parse_directory(data: &[u8], max_entries: usize, name_filter: Option<&str>) -> Result { +fn parse_directory( + data: &[u8], + max_entries: usize, + name_filter: Option<&str>, + mut raw_records: Option<&mut Vec<(usize, Vec)>>, +) -> Result { let r = Reader::new(data); let eocd = find_eocd(data).ok_or(ZipError::NotZip)?; let mut disk = u32::from(r.u16_le(eocd + 4).ok_or(ZipError::Truncated("end record"))?); @@ -349,6 +354,9 @@ fn parse_directory(data: &[u8], max_entries: usize, name_filter: Option<&str>) - if entry_disk != 0 { return Err(ZipError::Unsupported("multi-volume ZIP archives".into())); } + if let Some(records) = raw_records.as_deref_mut() { + records.push((pos, name_bytes.to_vec())); + } let name = unicode_name.map(str::to_owned).unwrap_or_else(|| decode_name(name_bytes, flags)).replace('\\', "/"); if name_filter.is_none_or(|wanted| wanted == name) { entries.push(ZipEntry { diff --git a/crates/zip/src/lenient/file.rs b/crates/zip/src/lenient/file.rs index fc50dfd26f..6d6b67afbf 100644 --- a/crates/zip/src/lenient/file.rs +++ b/crates/zip/src/lenient/file.rs @@ -14,6 +14,55 @@ const ZIP64_RECORD: u64 = 56; /// The entry named `name` (not a folder), decompressed to at most `max_bytes` and checked against /// its CRC-32. `None`: the archive has no such entry. pub fn read_named_entry(file: &mut (impl Read + Seek), name: &str, max_bytes: u64) -> Result>, ZipError> { + let (directory, prefix, _) = read_directory(file, MAX_DIRECTORY)?; + let archive = zip::parse(&directory, usize::MAX)?; + let Some(mut entry) = archive.entries.into_iter().find(|e| e.name == name && !e.is_dir) else { return Ok(None) }; + if entry.compressed_size > max_bytes.saturating_add(1 << 16) { + return Err(ZipError::TooLarge(max_bytes)); + } + let at = entry.local_header_offset.checked_add(prefix).ok_or(ZipError::Corrupt("local header offset".into()))?; + let header = read_at(file, at, 30)?; + let fields = Reader::new(&header); + let name_len = u64::from(fields.u16_le(26).ok_or(ZipError::Truncated("local header"))?); + let extra_len = u64::from(fields.u16_le(28).ok_or(ZipError::Truncated("local header"))?); + let local_len = (30 + name_len + extra_len).checked_add(entry.compressed_size).ok_or(ZipError::Corrupt("entry size".into()))?; + let local = read_at(file, at, local_len)?; + entry.local_header_offset = 0; + zip::read_entry(&local, &entry, max_bytes).map(Some) +} + +/// The original bytes and absolute offset of one central record, before name decoding. +#[derive(Debug, PartialEq, Eq)] +pub struct DirectoryRecordName { + pub name: Vec, + pub offset: u64, +} + +/// List original central records in order, retaining repeats and reading only bounded metadata. +pub fn directory_record_names( + file: &mut (impl Read + Seek), + max_directory_bytes: u64, + max_entries: usize, +) -> Result, ZipError> { + let (directory, _, start) = read_directory(file, max_directory_bytes.min(MAX_DIRECTORY))?; + let mut names = Vec::new(); + let archive = zip::parse_directory(&directory, max_entries, None, Some(&mut names))?; + if archive.truncated || u64::try_from(names.len()).ok() != Some(archive.declared_entries) { + return Err(ZipError::Truncated("directory entries")); + } + names + .into_iter() + .map(|(relative, name)| { + let offset = u64::try_from(relative) + .ok() + .and_then(|relative| start.checked_add(relative)) + .ok_or_else(|| ZipError::Corrupt("directory record offset overflows".into()))?; + Ok(DirectoryRecordName { name, offset }) + }) + .collect() +} + +fn read_directory(file: &mut (impl Read + Seek), max_directory_bytes: u64) -> Result<(Vec, u64, u64), ZipError> { let len = file.seek(SeekFrom::End(0)).map_err(io)?; let tail_start = len.saturating_sub(zip::EOCD_SEARCH as u64); let tail = read_at(file, tail_start, len - tail_start)?; @@ -58,8 +107,8 @@ pub fn read_named_entry(file: &mut (impl Read + Seek), name: &str, max_bytes: u6 Some((record_at, size, offset, record)) => (record_at, size, offset, saturated.then_some((record, locator))), None => (end_at, u64::from(size), u64::from(classic_offset), None), }; - if size > MAX_DIRECTORY { - return Err(ZipError::TooLarge(MAX_DIRECTORY)); + if size > max_directory_bytes { + return Err(ZipError::TooLarge(max_directory_bytes)); } // The directory ends where the end records start; anything before its stated offset is a // prepended stub, as `zip::parse` allows. @@ -80,21 +129,7 @@ pub fn read_named_entry(file: &mut (impl Read + Seek), name: &str, max_bytes: u6 put(&mut end, 16, &[0; 4])?; } directory.extend_from_slice(&end); - // `MAX_DIRECTORY` already bounds how many entries there can be. - let archive = zip::parse(&directory, usize::MAX)?; - let Some(mut entry) = archive.entries.into_iter().find(|e| e.name == name && !e.is_dir) else { return Ok(None) }; - if entry.compressed_size > max_bytes.saturating_add(1 << 16) { - return Err(ZipError::TooLarge(max_bytes)); - } - let at = entry.local_header_offset.checked_add(prefix).ok_or(ZipError::Corrupt("local header offset".into()))?; - let header = read_at(file, at, 30)?; - let fields = Reader::new(&header); - let name_len = u64::from(fields.u16_le(26).ok_or(ZipError::Truncated("local header"))?); - let extra_len = u64::from(fields.u16_le(28).ok_or(ZipError::Truncated("local header"))?); - let local_len = (30 + name_len + extra_len).checked_add(entry.compressed_size).ok_or(ZipError::Corrupt("entry size".into()))?; - let local = read_at(file, at, local_len)?; - entry.local_header_offset = 0; - zip::read_entry(&local, &entry, max_bytes).map(Some) + Ok((directory, prefix, start)) } /// Overwrite `bytes` at `at` in a record read from the file. @@ -129,6 +164,49 @@ mod tests { read_named_entry(&mut Cursor::new(bytes.to_vec()), name, 1 << 20) } + #[test] + fn directory_listing_preserves_repeated_names_and_enforces_limits() { + let bytes = crate::lenient::testkit::zip_stored(&[("notes.txt", b"first"), ("notes.txt", b"second"), ("index.txt", b"index")]); + let strict = crate::SeekableArchive::open( + Cursor::new(&bytes), + crate::SeekableLimits { max_entries: 3, max_metadata_bytes: 4096, max_total_bytes: 64 }, + ) + .unwrap(); + assert!(strict.has_duplicate_names()); + assert_eq!(strict.len(), 2); + let records = directory_record_names(&mut Cursor::new(&bytes), 4096, 3).unwrap(); + assert_eq!(records.iter().map(|r| r.name.as_slice()).collect::>(), [b"notes.txt".as_slice(), b"notes.txt", b"index.txt"]); + assert_eq!(strict.index_for_central_record(records[2].offset), Some(1)); + assert!(matches!(directory_record_names(&mut Cursor::new(&bytes), 8, 3), Err(ZipError::TooLarge(8)))); + assert!(directory_record_names(&mut Cursor::new(&bytes), 4096, 2).is_err()); + } + + #[test] + fn unicode_path_alias_does_not_replace_the_original_record_name() { + use std::io::Write; + let raw = "catalog.lrcat"; + let alias = "Café.lrcat"; + let mut extra = vec![1]; + extra.extend_from_slice(&zip::crc32(raw.as_bytes()).to_le_bytes()); + extra.extend_from_slice(alias.as_bytes()); + let mut opts = ::zip::write::FullFileOptions::default().compression_method(::zip::CompressionMethod::Stored); + opts.add_extra_field(0x7075, extra, false).unwrap(); + let mut writer = ::zip::ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file(raw, opts).unwrap(); + writer.write_all(b"catalog").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let records = directory_record_names(&mut Cursor::new(&bytes), 4096, 1).unwrap(); + assert_eq!(records[0].name, raw.as_bytes()); + assert_eq!(read(&bytes, alias).unwrap().as_deref(), Some(b"catalog".as_slice())); + let mut strict = crate::SeekableArchive::open( + Cursor::new(&bytes), + crate::SeekableLimits { max_entries: 1, max_metadata_bytes: 4096, max_total_bytes: 64 }, + ) + .unwrap(); + assert_eq!(strict.entry_name(0).unwrap().as_deref(), Some(alias)); + assert_eq!(strict.index_for_central_record(records[0].offset), Some(0)); + } + /// The same archive with a ZIP64 end record and locator before its classic end record, whose /// fields at these offsets are saturated (entry counts and disk numbers 2 bytes, others 4). fn as_zip64(archive: &[u8], saturate: &[usize]) -> Vec { diff --git a/crates/zip/src/seekable.rs b/crates/zip/src/seekable.rs index dfed9d643b..478e928bd0 100644 --- a/crates/zip/src/seekable.rs +++ b/crates/zip/src/seekable.rs @@ -79,6 +79,18 @@ impl SeekableArchive { self.zip.is_empty() } + /// Whether the central directory contains repeated raw names. The strict index keeps one + /// entry per raw name, so `len` alone cannot distinguish these from unique records. + pub fn has_duplicate_names(&self) -> bool { + self.zip.has_duplicate_names() + } + + /// Locate a surviving entry by the absolute offset of its central directory record, + /// without decoding its name or reading the local entry header. + pub fn index_for_central_record(&self, offset: u64) -> Option { + (0..self.zip.len()).find(|&i| self.zip.by_index_data(i).is_ok_and(|e| e.central_header_start() == offset)) + } + /// The name at `index`, copied on demand. pub fn entry_name(&mut self, index: usize) -> Result, Error> { if index >= self.zip.len() { From 359b72eebcd78579c715f607121e4811a9187232 Mon Sep 17 00:00:00 2001 From: Terra854 Date: Fri, 20 Nov 2026 10:30:46 +0800 Subject: [PATCH 76/79] docs: compare SQLite readers for #778 (#2443) --- docs/sqlite-reader-parity.md | 172 +++++++++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 docs/sqlite-reader-parity.md diff --git a/docs/sqlite-reader-parity.md b/docs/sqlite-reader-parity.md new file mode 100644 index 0000000000..fdf3411255 --- /dev/null +++ b/docs/sqlite-reader-parity.md @@ -0,0 +1,172 @@ +# SQLite reader comparison + +This comparison addresses the LightCraft and Craft Anything SQLite item in [#778](https://github.com/storytold/craft-libs/issues/778#issuecomment-7022490467). + +## Readers and results + +- LightCraft's Lightroom importer checks the WAL and passes the validated committed prefix to its file-backed page reader. The probe calls that reader directly with a complete, committed WAL produced by SQLite. [LightCraft baseline `78b57565`](https://github.com/storytold/lightcraft/blob/78b575658a61d17bd392b4b81b64c92c8beecbac/crates/engine/src/lightroom_catalog.rs#L512-L530) +- Craft Anything's `db_sqlite_show` reads the main-file image and checks for a WAL sidecar so it can disclose a potentially older view. The probe calls the same parser and row-pagination method as the tool. [Craft Anything baseline `df227090`](https://github.com/storytold/craft-anything/blob/df2270904c36d6904883ba4442fb80fb383ed350/crates/engine/src/tools/database_tools.rs#L49-L93) + +The fixture is one table with 512-byte pages. SQLite queries verified the seven stored values: row ID 1, integer −8,388,607, real 1.25, null, label `Päris`, 6,000 ASCII `x` characters, and bytes `00 ff`. The text spans overflow pages. An update changes the label to `committed`. + +| Input | LightCraft import reader | Craft Anything inspection reader | +| --- | --- | --- | +| Same pre-update main image | `Päris` | `Päris` | +| Same main image with SQLite's committed WAL available | `committed` after the caller supplies the committed prefix | Main-file view remains `Päris` | +| Same checkpointed main image | `committed` | `committed` | +| Overflow text in every tested view | All 6,000 bytes | First 4,096 bytes, marked truncated | +| BLOB in every tested view | Exact `00 ff` bytes | Length 2 and SHA-256 prefix `06eb7d6a69ee19e5` | + +The scalar values other than the updated label agreed across every view. Both pinned reader modules compiled and all five probe calls passed on Windows with Rust 1.99.0 and Python 3.14.4 using SQLite 3.50.4. The WAL was 7,536 bytes. These are module-level checks. The production WAL checksum scanner, app frontends, malformed database recovery, and schema-default edge cases were outside this run. + +## Candidate shared boundary + +Start with bounded varint decoding and serial-type widths over borrowed bytes. The reader sources already have independently implemented versions of these mechanics. Before adopting a helper, add boundary fixtures for ninth-byte varints, failed reads and offset handling, reserved serial types, and truncated values. Both readers assemble overflow data, but their caps and treatment of partial data need separate parity evidence before that code moves. [LightCraft reader](https://github.com/storytold/lightcraft/blob/78b575658a61d17bd392b4b81b64c92c8beecbac/crates/engine/src/lightroom_sqlite.rs) · [Craft Anything reader](https://github.com/storytold/craft-anything/blob/df2270904c36d6904883ba4442fb80fb383ed350/crates/formats/src/sqlite.rs) + +Keep snapshot selection and caller validation with the Lightroom importer. Keep schema defaults, pagination, text previews and BLOB presentation with Craft Anything. Coordinate a consumer change against the current catalog bounds and old-row default work. [LightCraft #3674](https://github.com/storytold/lightcraft/pull/3674) · [Craft Anything #1349](https://github.com/storytold/craft-anything/pull/1349) + +## Reproduce + +Place the three repositories under one parent directory and check out the two app revisions above. In a scratch directory at `craft-libs/target/sqlite-reader-parity`, save the three blocks below as `generate.py`, `Cargo.toml` and `src/main.rs`. Run from that scratch directory. Use a new fixture path on each run. + +```text +python generate.py fixtures +cargo run --quiet -- fixtures +``` + +### Fixture generator + +```python +from pathlib import Path +import sqlite3 +import sys + +root = Path(sys.argv[1]) +root.mkdir(parents=True, exist_ok=False) +live = root / "live.db" +with sqlite3.connect(live) as connection: + connection.execute("PRAGMA page_size=512") + assert connection.execute("PRAGMA journal_mode=WAL").fetchone() == ("wal",) + connection.execute("PRAGMA wal_autocheckpoint=0") + connection.execute( + "CREATE TABLE samples(id INTEGER PRIMARY KEY, n INTEGER, r REAL," + " missing, label TEXT, overflow TEXT, binary BLOB)" + ) + expected = (1, -8388607, 1.25, None, "Päris", "x" * 6000, b"\0\xff") + connection.execute("INSERT INTO samples VALUES (?,?,?,?,?,?,?)", expected) + connection.commit() + assert connection.execute("SELECT * FROM samples").fetchone() == expected + assert connection.execute("PRAGMA page_size").fetchone() == (512,) + assert connection.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone() == (0, 0, 0) + (root / "base.db").write_bytes(live.read_bytes()) + + connection.execute("UPDATE samples SET label='committed'") + connection.commit() + committed = expected[:4] + ("committed",) + expected[5:] + assert connection.execute("SELECT * FROM samples").fetchone() == committed + wal = live.with_name(live.name + "-wal").read_bytes() + assert len(wal) >= 32 + 24 + 512 and (len(wal) - 32) % (24 + 512) == 0 + assert int.from_bytes(wal[-(512 + 20):-(512 + 16)], "big") > 0 + (root / "committed.wal").write_bytes(wal) + assert connection.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone() == (0, 0, 0) + (root / "checkpoint.db").write_bytes(live.read_bytes()) + assert connection.execute("SELECT * FROM samples").fetchone() == committed +print("SQLite", sqlite3.sqlite_version, "| 512-byte pages |", len(wal), "WAL bytes") +``` + +### Runner manifest + +```toml +[package] +name = "sqlite-parity-probe" +version = "0.1.0" +edition = "2024" + +[dependencies] +serde = { version = "=1.0.229", features = ["derive"] } +sha2 = "=0.10.9" + +[workspace] +``` + +### Runner + +```rust +#[path = "../../../../lightcraft/crates/engine/src/lightroom_sqlite.rs"] +mod light; +#[path = "../../../../craft-anything/crates/formats/src/sqlite.rs"] +mod inspect; + +use inspect::{CellValue, SqliteDb}; +use light::{Database, FileSource, Value}; +use std::fs; +use std::path::Path; + +#[allow(dead_code)] +#[derive(Debug)] +enum FormatError { + TooLarge(String), + Unsupported(String), + Truncated(String), + Malformed(String), +} + +fn light_row(main: &Path, wal: &[u8], label: &str) { + let database = Database::open_file_with_wal(FileSource::open(main).unwrap(), wal).unwrap(); + let table = database.live_tables().unwrap().into_iter().find(|table| table.name == "samples").unwrap(); + let rows = database.read_table(table.rootpage, 7).unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!( + rows[0].values, + [ + Value::Integer(1), + Value::Integer(-8388607), + Value::Real(1.25), + Value::Null, + Value::Text(label.to_owned()), + Value::Text("x".repeat(6000)), + Value::Blob(vec![0, 255]), + ] + ); + database.ensure_unchanged().unwrap(); + println!("LightCraft: {label}; all 7 values; full 6000-byte text and 2-byte BLOB"); +} + +fn inspector_row(main: &Path, label: &str) { + let bytes = fs::read(main).unwrap(); + let database = SqliteDb::parse(&bytes).unwrap(); + let table = database.find_object("samples").unwrap(); + let page = database.read_rows(table.rootpage, 0, 2); + assert_eq!(page.rows.len(), 1); + assert_eq!(page.rows[0].rowid, Some(1)); + assert_eq!( + page.rows[0].values, + [ + CellValue::Int(1), + CellValue::Int(-8388607), + CellValue::Real(1.25), + CellValue::Null, + CellValue::Text { text: label.to_owned(), truncated: false }, + CellValue::Text { text: "x".repeat(4096), truncated: true }, + CellValue::Blob { len: 2, sha256_prefix: "06eb7d6a69ee19e5".into() }, + ] + ); + println!("Craft Anything: {label}; all 7 values; 4096-byte projection and BLOB digest"); +} + +fn main() { + let fixture_arg = std::env::args_os().nth(1).expect("fixture directory"); + let fixtures = Path::new(&fixture_arg); + let base = fixtures.join("base.db"); + let checkpoint = fixtures.join("checkpoint.db"); + let wal = fs::read(fixtures.join("committed.wal")).unwrap(); + println!("Main image"); + light_row(&base, &[], "Päris"); + inspector_row(&base, "Päris"); + println!("Committed WAL overlay"); + light_row(&base, &wal, "committed"); + println!("Checkpointed control"); + light_row(&checkpoint, &[], "committed"); + inspector_row(&checkpoint, "committed"); +} +``` From 4b4d5f7a9d126ff20d7c4a453726e43dc15c13cd Mon Sep 17 00:00:00 2001 From: Elvis33LE <67311580+Elvis33LE@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:30:51 +0100 Subject: [PATCH 77/79] fix(exr): stage contained data windows in display canvas (#2033) --- crates/image-codecs/src/codecs/exr.rs | 77 ++++++++++++++++++- crates/image-codecs/src/exr_stream.rs | 87 ++++++++++++++++++---- crates/image-codecs/tests/it/exr_stream.rs | 64 ++++++++++++++++ 3 files changed, 209 insertions(+), 19 deletions(-) diff --git a/crates/image-codecs/src/codecs/exr.rs b/crates/image-codecs/src/codecs/exr.rs index 87c9617799..19e390018f 100644 --- a/crates/image-codecs/src/codecs/exr.rs +++ b/crates/image-codecs/src/codecs/exr.rs @@ -99,7 +99,8 @@ pub(super) fn read_meta(bytes: &[u8], limits: &Limits) -> Result Result= display.position.0 + && data.1 >= display.position.1 + && i64::from(data.0) + size.0 as i64 <= i64::from(display.position.0) + display.size.0 as i64 + && i64::from(data.1) + size.1 as i64 <= i64::from(display.position.1) + display.size.1 as i64; + if contained && (selected.is_none() || selected == Some(index)) { + let sw = u32::try_from(display.size.0).unwrap_or(u32::MAX); + let sh = u32::try_from(display.size.1).unwrap_or(u32::MAX); + limits.check_bytes(sw, sh, 16)?; + } } if total > limits.max_alloc { return Err(CodecError::LimitExceeded(format!("{total} bytes across {} parts exceed max_alloc {}", meta.headers.len(), limits.max_alloc))); @@ -238,6 +250,65 @@ fn layer_to_image(layer: &Layer>) -> Result Result { + let data = header.own_attributes.layer_position; + let display = header.shared_attributes.display_window; + let (dw, dh) = (header.layer_size.0 as i64, header.layer_size.1 as i64); + let (sw, sh) = (display.size.0 as i64, display.size.1 as i64); + if data.0 == display.position.0 && data.1 == display.position.1 && dw == sw && dh == sh { + return Ok(image); + } + if data.0 < display.position.0 + || data.1 < display.position.1 + || i64::from(data.0) + dw > i64::from(display.position.0) + sw + || i64::from(data.1) + dh > i64::from(display.position.1) + sh + { + return Ok(image); + } + let (w, h) = (u32::try_from(sw).map_err(err)?, u32::try_from(sh).map_err(err)?); + limits.check_bytes(w, h, 16)?; + let x = usize::try_from(data.0 - display.position.0).map_err(err)?; + let y = usize::try_from(data.1 - display.position.1).map_err(err)?; + let nc = image.layout().channels(); + let npx = usize::try_from(w).map_err(err)?.checked_mul(usize::try_from(h).map_err(err)?).ok_or_else(|| err("EXR stage size"))?; + let src_w = image.width() as usize; + if let Some(source) = image.to_f16_samples() { + let mut pixels = Vec::new(); + let len = npx.checked_mul(nc).ok_or_else(|| err("EXR stage allocation"))?; + pixels.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded("EXR stage allocation".into()))?; + pixels.resize(len, f16::ZERO); + for row in 0..image.height() as usize { + let src = row * src_w * nc; + let dst = ((y + row) * w as usize + x) * nc; + pixels + .get_mut(dst..dst + src_w * nc) + .ok_or_else(|| err("EXR stage row"))? + .copy_from_slice(source.get(src..src + src_w * nc).ok_or_else(|| err("EXR source row"))?); + } + image = Image::from_f16(w, h, image.layout(), &pixels)?; + } else if let Some(source) = image.to_f32_samples() { + let mut pixels = Vec::new(); + let len = npx.checked_mul(nc).ok_or_else(|| err("EXR stage allocation"))?; + pixels.try_reserve_exact(len).map_err(|_| CodecError::LimitExceeded("EXR stage allocation".into()))?; + pixels.resize(len, 0.0_f32); + for row in 0..image.height() as usize { + let src = row * src_w * nc; + let dst = ((y + row) * w as usize + x) * nc; + pixels + .get_mut(dst..dst + src_w * nc) + .ok_or_else(|| err("EXR stage row"))? + .copy_from_slice(source.get(src..src + src_w * nc).ok_or_else(|| err("EXR source row"))?); + } + image = Image::from_f32(w, h, image.layout(), &pixels)?; + } else { + return Err(err("EXR sample conversion")); + } + image + .warnings + .push(DecodeWarning::DisplayWindowStage { stage: (w, h), origin: (i32::try_from(x).map_err(err)?, i32::try_from(y).map_err(err)?) }); + Ok(image) +} + pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result { let meta = read_meta(bytes, limits)?; @@ -249,7 +320,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result } let pick = pick_part(&meta); - let mut img = layer_to_image(&read_layer(bytes, pick)?)?; + let mut img = stage_image(layer_to_image(&read_layer(bytes, pick)?)?, &meta.headers[pick], limits)?; if meta.headers.len() > 1 { let total = u32::try_from(meta.headers.len()).ok(); img.warnings.push(DecodeWarning::MoreParts { total }); @@ -285,7 +356,7 @@ pub(crate) fn decode_part(bytes: &[u8], index: usize, limits: &Limits) -> Result if index >= meta.headers.len() { return Err(err(format!("part index {index} is out of range ({} parts)", meta.headers.len()))); } - layer_to_image(&read_layer(bytes, index)?) + stage_image(layer_to_image(&read_layer(bytes, index)?)?, &meta.headers[index], limits) } /// Decodes the named channels of one flat part (exact names as the file stores them, e.g. diff --git a/crates/image-codecs/src/exr_stream.rs b/crates/image-codecs/src/exr_stream.rs index 6ffa95c53b..e350a45279 100644 --- a/crates/image-codecs/src/exr_stream.rs +++ b/crates/image-codecs/src/exr_stream.rs @@ -97,7 +97,7 @@ pub struct Info { pub blocks: usize, } -/// Interleaved little-endian F32, GrayA or RGBA, at source resolution. +/// Interleaved little-endian F32, GrayA or RGBA, at staged output coordinates. pub struct Band { pub x: u32, pub y: u32, @@ -118,6 +118,9 @@ pub struct Decoder { chunks_start: u64, raw_limit: usize, rows: usize, + source_width: usize, + origin: (i32, i32), + staged: bool, } impl Decoder { @@ -133,7 +136,18 @@ impl Decoder { if meta.headers.len() != 1 || header.deep || !matches!(header.blocks, BlockDescription::ScanLines) { return Err(unsupported("streaming requires a single flat scanline part")); } - let (w, h) = (header.layer_size.0, header.layer_size.1); + let (source_w, source_h) = (header.layer_size.0, header.layer_size.1); + let dw = header.own_attributes.layer_position; + let display = header.shared_attributes.display_window; + let (w, h, origin, staged) = if dw.0 >= display.position.0 + && dw.1 >= display.position.1 + && i64::from(dw.0) + source_w as i64 <= i64::from(display.position.0) + display.size.0 as i64 + && i64::from(dw.1) + source_h as i64 <= i64::from(display.position.1) + display.size.1 as i64 + { + (display.size.0, display.size.1, (dw.0 - display.position.0, dw.1 - display.position.1), true) + } else { + (source_w, source_h, (0, 0), false) + }; if w == 0 || h == 0 || w > 1 << 18 || h > 1 << 18 { return Err(limit("EXR dimensions exceed the streaming limit of 262144")); } @@ -162,16 +176,21 @@ impl Decoder { let has_alpha = selected.last().copied().flatten().is_some(); let channels = (0..list.len()).map(|i| selected.iter().position(|s| *s == Some(i))).collect(); let rows = header.max_block_pixel_size().1; - let expected = h.div_ceil(rows.max(1)); + let expected = source_h.div_ceil(rows.max(1)); if rows == 0 || header.chunk_count != expected || expected > MAX_CHUNKS { return Err(limit("EXR block count exceeds the streaming budget")); } - let raw_limit = w + let raw_limit = source_w .checked_mul(rows) .and_then(|n| n.checked_mul(header.channels.bytes_per_pixel)) .filter(|n| *n <= BLOCK_BYTES) .ok_or_else(|| limit("EXR compression block exceeds 64 MiB"))?; - let output = (w as u64).saturating_mul(rows as u64).saturating_mul(selected.len() as u64 * 4); + if staged { + crate::Limits::default().check_bytes(w as u32, h as u32, 16)?; + } + let band_rows = rows.min(source_h); + let source_output = (source_w as u64).saturating_mul(band_rows as u64).saturating_mul(selected.len() as u64 * 4); + let staged_output = (w as u64).saturating_mul(band_rows as u64).saturating_mul(selected.len() as u64 * 4); let info = Info { width: w as u32, height: h as u32, @@ -179,7 +198,7 @@ impl Decoder { has_alpha, all_half, blocks: expected, - working_bytes: (raw_limit as u64).saturating_mul(8).saturating_add(output.saturating_mul(2)).saturating_add(1 << 20), + working_bytes: (raw_limit as u64).saturating_mul(8).saturating_add(source_output).saturating_add(staged_output).saturating_add(1 << 20), }; let chunks_start = source .stream_position() @@ -202,10 +221,25 @@ impl Decoder { // Check the bounded offset table before rejecting a large declared image. // A truncated file with an oversized data window is malformed; a complete // file above the streaming area limit is rejected before any pixel decode. - if (w as u64).saturating_mul(h as u64) > 1 << 30 { + if (source_w as u64).saturating_mul(source_h as u64) > 1 << 30 { return Err(limit("EXR pixel count exceeds the streaming limit of 1073741824")); } - Ok(Self { source, meta, info, offsets, seen: vec![false; expected], channels, next: 0, file_len, chunks_start, raw_limit, rows }) + Ok(Self { + source, + meta, + info, + offsets, + seen: vec![false; expected], + channels, + next: 0, + file_len, + chunks_start, + raw_limit, + rows, + source_width: source_w, + origin, + staged, + }) } pub fn info(&self) -> Info { @@ -230,11 +264,11 @@ impl Decoder { return Err(invalid("EXR compressed block length")); } let header = self.meta.headers.first().ok_or_else(|| invalid("missing header"))?; - let row = i64::from(y) - i64::from(header.own_attributes.layer_position.1); - if row < 0 || row as u64 >= u64::from(self.info.height) || !(row as usize).is_multiple_of(self.rows) { + let source_row = i64::from(y) - i64::from(header.own_attributes.layer_position.1); + if source_row < 0 || source_row as usize >= header.layer_size.1 || !(source_row as usize).is_multiple_of(self.rows) { return Err(invalid("EXR block coordinate")); } - let seen = self.seen.get_mut(row as usize / self.rows).ok_or_else(|| invalid("EXR block coordinate"))?; + let seen = self.seen.get_mut(source_row as usize / self.rows).ok_or_else(|| invalid("EXR block coordinate"))?; if *seen { return Err(invalid("duplicate EXR block")); } @@ -256,10 +290,10 @@ impl Decoder { .map_err(|_| invalid("invalid EXR compression block"))? .map_err(invalid)?; let (w, h) = (block.index.pixel_size.0, block.index.pixel_size.1); - if w != self.info.width as usize + if w != self.source_width || block.index.pixel_position.0 != 0 - || block.index.pixel_position.1 != row as usize - || h != self.rows.min(self.info.height as usize - row as usize) + || block.index.pixel_position.1 != source_row as usize + || h != self.rows.min(header.layer_size.1 - source_row as usize) { return Err(invalid("EXR block shape")); } @@ -272,7 +306,9 @@ impl Decoder { let mut data = Vec::new(); data.try_reserve_exact(count).map_err(|_| limit("EXR output allocation"))?; data.resize(count, 0); - if !self.info.has_alpha { + if self.info.has_alpha { + // Transparent black stage padding is already zeroed. + } else { for pixel in data.chunks_exact_mut(nc * 4) { pixel.get_mut((nc - 1) * 4..).ok_or_else(|| invalid("alpha sample"))?.copy_from_slice(&1_f32.to_le_bytes()); } @@ -297,7 +333,26 @@ impl Decoder { pixel.get_mut(channel * 4..channel * 4 + 4).ok_or_else(|| invalid("EXR channel"))?.copy_from_slice(&value.to_le_bytes()); } } + let stage_y = if self.staged { source_row as i32 + self.origin.1 } else { source_row as i32 }; + let mut staged = Vec::new(); + let staged_len = self.info.width as usize * h * nc * 4; + staged.try_reserve_exact(staged_len).map_err(|_| limit("EXR stage allocation"))?; + staged.resize(staged_len, 0); + if !self.info.has_alpha { + for pixel in staged.chunks_exact_mut(nc * 4) { + pixel.get_mut((nc - 1) * 4..).ok_or_else(|| invalid("alpha sample"))?.copy_from_slice(&1_f32.to_le_bytes()); + } + } + let x = if self.staged { usize::try_from(self.origin.0).map_err(invalid)? } else { 0 }; + for y in 0..h { + let src = y * self.source_width * nc * 4; + let dst = (y * self.info.width as usize + x) * nc * 4; + staged + .get_mut(dst..dst + self.source_width * nc * 4) + .ok_or_else(|| invalid("EXR stage row"))? + .copy_from_slice(data.get(src..src + self.source_width * nc * 4).ok_or_else(|| invalid("EXR source row"))?); + } self.next += 1; - Ok(Some(Band { x: 0, y: row as u32, width: w as u32, height: h as u32, data })) + Ok(Some(Band { x: 0, y: u32::try_from(stage_y).map_err(invalid)?, width: self.info.width, height: h as u32, data: staged })) } } diff --git a/crates/image-codecs/tests/it/exr_stream.rs b/crates/image-codecs/tests/it/exr_stream.rs index a3a6503f48..ab338e6cff 100644 --- a/crates/image-codecs/tests/it/exr_stream.rs +++ b/crates/image-codecs/tests/it/exr_stream.rs @@ -48,6 +48,70 @@ fn change_window(bytes: &mut [u8], width: i32, height: i32) { bytes[at + 12..at + 16].copy_from_slice(&(height - 1).to_le_bytes()); } +fn cropped_exr(display_size: usize, origin: (i32, i32), alpha: bool) -> Vec { + use exr::prelude::{ + AnyChannel, AnyChannels, Blocks, Compression, Encoding, FlatSamples, ImageAttributes, IntegerBounds, Layer, LayerAttributes, LineOrder, + WritableImage, + }; + let mut channels = vec![ + AnyChannel::new("R", FlatSamples::F16(vec![f16::from_f32(0.25); 4])), + AnyChannel::new("G", FlatSamples::F16(vec![f16::from_f32(0.5); 4])), + AnyChannel::new("B", FlatSamples::F16(vec![f16::from_f32(0.75); 4])), + ]; + if alpha { + channels.push(AnyChannel::new("A", FlatSamples::F16(vec![f16::ONE; 4]))); + } + let channels = AnyChannels::sort(channels.into_iter().collect()); + let layer = Layer::new( + (2, 2), + LayerAttributes { layer_position: exr::math::Vec2(origin.0, origin.1), ..Default::default() }, + Encoding { compression: Compression::Uncompressed, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing }, + channels, + ); + let image = exr::image::Image::from_layers(ImageAttributes::new(IntegerBounds::new((0, 0), (display_size, display_size))), vec![layer]); + let mut out = Cursor::new(Vec::new()); + image.write().to_buffered(&mut out).unwrap(); + out.into_inner() +} + +#[test] +fn contained_display_stage_matches_whole_decode_and_preserves_half_samples() { + let bytes = cropped_exr(4, (1, 1), true); + let whole = decode(&bytes).unwrap(); + assert_eq!(whole.dimensions(), (4, 4)); + assert_eq!(whole.sample_type(), SampleType::F16); + assert!(matches!(whole.warnings.first(), Some(DecodeWarning::DisplayWindowStage { stage: (4, 4), origin: (1, 1) }))); + let mut stream = Decoder::new(Cursor::new(&bytes), &|| false).unwrap(); + let expected = whole.convert(ChannelLayout::Rgba, SampleType::F32); + let mut actual = vec![0; expected.data().len()]; + while let Some(band) = stream.next_band(&|| false).unwrap() { + assert_eq!((band.x, band.width), (0, 4)); + let start = band.y as usize * 4 * 16; + actual[start..start + band.data.len()].copy_from_slice(&band.data); + } + // Stream API emits F32 RGBA; compare values after widening the whole-file half samples. + assert_eq!(actual, expected.data()); + for p in actual[..4 * 16].as_chunks::<16>().0 { + assert_eq!(f32::from_le_bytes(p[12..16].try_into().unwrap()), 0.0); + } +} + +#[test] +fn oversized_contained_display_stage_is_rejected_by_both_decoders() { + let bytes = cropped_exr(262_145, (0, 0), true); + assert!(matches!(decode(&bytes), Err(CodecError::LimitExceeded(_)))); + assert!(matches!(Decoder::new(Cursor::new(bytes), &|| false), Err(CodecError::LimitExceeded(_)))); +} + +#[test] +fn opaque_display_padding_does_not_overwrite_rgb_channels() { + let image = decode(&cropped_exr(4, (1, 1), false)).unwrap(); + assert_eq!(image.layout(), ChannelLayout::Rgb); + let samples = image.to_f16_samples().unwrap(); + assert!(samples[..3].iter().all(|sample| *sample == f16::ZERO)); + assert_eq!(samples[15..18], [f16::from_f32(0.25), f16::from_f32(0.5), f16::from_f32(0.75)]); +} + #[test] fn enormous_header_is_not_a_whole_image_allocation() { let mut bytes = fixture(ChannelLayout::Rgb, SampleType::F16, ExrCompression::Zip16); From 38b4001816f894ce848a6ac31b6afbef6e0944c6 Mon Sep 17 00:00:00 2001 From: mtlcl410 <2368091+mtlcl410@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:57:10 +0800 Subject: [PATCH 78/79] MIDI: imported SMF SysEx packets retain their payloads and timing on export (#2077) * Preserve SMF SysEx packet payloads and timing across MIDI round trips * Order cross-track note-offs before SysEx when writing format zero * Diagnose truncated SysEx and guard merged packet streams * Validate emitted event order around split SysEx * Preserve real split boundaries when exporting SMF SysEx * Preserve same-tick SysEx order and require real termination --- crates/midi/Cargo.toml | 2 +- crates/midi/README.md | 22 ++- crates/midi/src/lib.rs | 14 +- crates/midi/src/sequence.rs | 25 ++- crates/midi/src/smf.rs | 253 +++++++++++++++++++++++++++---- crates/midi/tests/it/lenient.rs | 2 +- crates/midi/tests/it/main.rs | 1 + crates/midi/tests/it/sequence.rs | 11 +- crates/midi/tests/it/smf.rs | 6 +- crates/midi/tests/it/sysex.rs | 212 ++++++++++++++++++++++++++ 10 files changed, 496 insertions(+), 52 deletions(-) create mode 100644 crates/midi/tests/it/sysex.rs diff --git a/crates/midi/Cargo.toml b/crates/midi/Cargo.toml index a25b5d6fd5..21cb60d965 100644 --- a/crates/midi/Cargo.toml +++ b/crates/midi/Cargo.toml @@ -11,7 +11,7 @@ repository.workspace = true workspace = true [features] -# Serialize / Deserialize on the model types (Note, CtrlEvent, CtrlKind, Sequence). +# Serialize / Deserialize on the model types (Note, CtrlEvent, CtrlKind, SysExEvent, Sequence). serde = ["dep:serde"] [dependencies] diff --git a/crates/midi/README.md b/crates/midi/README.md index 584bd567e0..2076a193b8 100644 --- a/crates/midi/README.md +++ b/crates/midi/README.md @@ -16,14 +16,15 @@ app reads or writes them. - `Note`: pitch, note-on velocity, release velocity, channel, start and length in ticks. - `CtrlEvent`: a channel event at a tick: control change, pitch bend (centred, -8192..=8191), channel pressure, polyphonic pressure or program change. -- `Sequence`: the notes and channel events of one track, with sorting, range queries and +- `SysExEvent`: one F0 or F7 System Exclusive packet, with its tick and exact payload bytes. +- `Sequence`: the notes, channel events and SysEx packets of one track, with sorting, range queries and duplicate removal. - `Smf`: the file: its format, its tracks (`SmfTrack`: a name and a `Sequence`) and the file-wide tempo, meter, marker and key-signature lists. `Smf::default()` is an empty format-1 file. All ticks are at `PPQ` (960) per quarter note, whatever the file's division. The `serde` feature -derives `Serialize` and `Deserialize` on `Note`, `CtrlEvent`, `CtrlKind` and `Sequence`. +derives `Serialize` and `Deserialize` on `Note`, `CtrlEvent`, `CtrlKind`, `SysExEvent` and `Sequence`. ## Reading @@ -34,9 +35,12 @@ derives `Serialize` and `Deserialize` on `Note`, `CtrlEvent`, `CtrlKind` and `Se - pairs note-ons with note-offs: running status, note-on with velocity 0 as note-off, overlapping notes of one pitch first in first out, an unmatched note-off ignored, a note still sounding at the end of its track closed there, a zero-length note given one tick; -- folds the leading conductor track of a format-1 file (no notes, no channel events) into the - file-wide lists; its name is not kept; -- skips unknown chunks, unknown meta events and System Exclusive events; +- folds the leading conductor track of a format-1 file when it has no notes, channel events, + or SysEx packets. Its track name is discarded when folded. A leading track carrying setup + SysEx remains a track, with its name and packets, while tempo and meter stay file-wide. +- retains F0 and F7 packets in `Sequence::sysex` with exact payloads and ticks, up to + `MAX_SYSEX_BYTES` (16 MiB) and 262,144 packets per file. The separate `source_timed` reader skips them. +- skips unknown chunks and unknown meta events. - accepts a header track count that differs from the number of `MTrk` chunks and reads every chunk present. @@ -74,6 +78,14 @@ pitch that overlap are trimmed so that the file reads back with the same starts, start together the longer is written. An invalid tempo, a meter denominator that is not a power of two, more than 65535 tracks or a gap beyond the 28-bit delta limit is an error. +Same-tick events normally write as note-offs, SysEx, controllers, then note-ons. +A split SysEx message opens after same-tick channel events and continues before channel +events on later ticks. Same-tick packets from that track retain their order, including +packets following the split. Interleaving a transmittable event within an actual split +returns a write error, including when merging tracks. Exhausting continuation packets +without a terminating F7 leaves the split open for this check. Meta events may appear between packets. A legacy +F0 with no continuation is exported with its original payload and tick. + ## Sources and clean room Written from the public Standard MIDI Files 1.0 specification (the MIDI Association). No other diff --git a/crates/midi/src/lib.rs b/crates/midi/src/lib.rs index b2464dce87..599f9c7c52 100644 --- a/crates/midi/src/lib.rs +++ b/crates/midi/src/lib.rs @@ -1,11 +1,11 @@ //! MIDI file formats. //! -//! - [`Note`], [`CtrlEvent`] and [`Sequence`]: the neutral model, the notes and channel events of +//! - [`Note`], [`CtrlEvent`], [`SysExEvent`] and [`Sequence`]: the neutral model, including notes, channel events and SysEx packets of //! one track, in ticks at [`PPQ`] (960) ticks per quarter note. //! - [`read_smf`] / [`write_smf`]: Standard MIDI File reading (format 0/1, format 2 best-effort) //! and writing (format 0 or 1, 960 PPQ). [`read_smf_lenient`] reads what makes sense of a //! damaged file and says what it could not. The reader treats its input as hostile: every length is -//! checked, variable-length quantities are bounded and track and event counts are capped. +//! checked, variable-length quantities are bounded and track/event counts and retained SysEx payload bytes are capped. //! //! Written from the public Standard MIDI Files 1.0 specification. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -18,10 +18,10 @@ mod smf; pub mod source_timed; pub mod sync; -pub use sequence::{CtrlEvent, CtrlKind, Note, Sequence}; +pub use sequence::{CtrlEvent, CtrlKind, Note, Sequence, SysExEvent}; pub use smf::{ - LenientRead, MAX_EVENTS, MAX_TRACKS, MAX_WARNINGS, Smf, SmfTrack, TimedEvent, encode_meta_event, read_smf, read_smf_lenient, write_smf, - write_timed_smf, + LenientRead, MAX_EVENTS, MAX_SYSEX_BYTES, MAX_TRACKS, MAX_WARNINGS, Smf, SmfTrack, TimedEvent, encode_meta_event, read_smf, read_smf_lenient, + write_smf, write_timed_smf, }; /// Ticks per quarter note used throughout the model. @@ -46,6 +46,10 @@ pub enum MidiError { TooManyEvents(usize), #[error("too many tracks (limit {0})")] TooManyTracks(usize), + #[error("SysEx payload exceeds the file limit of {0} bytes")] + SysExTooLarge(usize), + #[error("MIDI file has more than {0} SysEx packets")] + TooManySysExPackets(usize), #[error("cannot write MIDI file: {0}")] Write(String), } diff --git a/crates/midi/src/sequence.rs b/crates/midi/src/sequence.rs index 5dcdd38749..0641524bca 100644 --- a/crates/midi/src/sequence.rs +++ b/crates/midi/src/sequence.rs @@ -54,6 +54,17 @@ pub struct CtrlEvent { pub value: i32, } +/// A source SMF SysEx packet. `status` distinguishes F0 from F7 continuation/escape events. +/// `data` is the exact length-delimited payload, including a terminating F7 when present. +/// Packets are retained separately: joining them would lose their timing and escape semantics. +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +pub struct SysExEvent { + pub tick: i64, + pub status: u8, + pub data: Vec, +} + /// The MIDI content of a region or track. #[derive(Debug, Clone, Default, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] @@ -62,6 +73,9 @@ pub struct Sequence { pub notes: Vec, /// Controller events, sorted by tick after [`Sequence::sort`]. pub ctrls: Vec, + /// SysEx packets, stably sorted by tick. Absent in older serialized sequences. + #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Vec::is_empty"))] + pub sysex: Vec, } fn kind_key(k: CtrlKind) -> (u8, u8) { @@ -75,22 +89,19 @@ fn kind_key(k: CtrlKind) -> (u8, u8) { } impl Sequence { - /// Sorts notes by `(start, pitch, channel, length, velocity)` and controller events by tick + /// Sorts notes by `(start, pitch, channel, length, velocity)` and controller/SysEx events by tick /// (stable, so same-tick events keep their order). pub fn sort(&mut self) { self.notes.sort_by_key(|a| (a.start, a.pitch, a.channel, a.length, a.velocity)); self.ctrls.sort_by_key(|c| c.tick); + self.sysex.sort_by_key(|e| e.tick); } - /// The last tick covered by any note end or controller event (0 when empty). + /// The last tick covered by any note end, controller or SysEx packet (0 when empty). pub fn end_tick(&self) -> i64 { let n = self.notes.iter().map(Note::end).max(); let c = self.ctrls.iter().map(|c| c.tick).max(); - match (n, c) { - (Some(a), Some(b)) => a.max(b), - (Some(a), None) | (None, Some(a)) => a, - (None, None) => 0, - } + n.into_iter().chain(c).chain(self.sysex.iter().map(|e| e.tick)).max().unwrap_or(0) } /// Notes whose start lies in the half-open range `[start, end)`. diff --git a/crates/midi/src/smf.rs b/crates/midi/src/smf.rs index 801cdd3003..681bbfd5ed 100644 --- a/crates/midi/src/smf.rs +++ b/crates/midi/src/smf.rs @@ -2,12 +2,35 @@ use std::collections::VecDeque; -use crate::{CtrlEvent, CtrlKind, MidiError, Note, PPQ, Sequence}; +use crate::{CtrlEvent, CtrlKind, MidiError, Note, PPQ, Sequence, SysExEvent}; /// Maximum number of events (across all tracks) [`read_smf`] will parse. pub const MAX_EVENTS: usize = 5_000_000; /// Maximum number of track chunks [`read_smf`] will accept. pub const MAX_TRACKS: usize = 4096; +/// Most retained SysEx payload bytes across one file, checked before copying hostile input. +pub const MAX_SYSEX_BYTES: usize = 16 * 1024 * 1024; + +// Bound packet metadata independently of the payload, including empty F7 escape events. +const MAX_SYSEX_PACKETS: usize = 262_144; + +struct SysexBudget { + bytes: usize, + packets: usize, +} + +impl SysexBudget { + fn new() -> Self { + Self { bytes: MAX_SYSEX_BYTES, packets: MAX_SYSEX_PACKETS } + } + + fn charge(&mut self, bytes: usize) -> Result<(), MidiError> { + let remaining = self.bytes.checked_sub(bytes).ok_or(MidiError::SysExTooLarge(MAX_SYSEX_BYTES))?; + self.packets = self.packets.checked_sub(1).ok_or(MidiError::TooManySysExPackets(MAX_SYSEX_PACKETS))?; + self.bytes = remaining; + Ok(()) + } +} /// Release velocity used when a note ends with a note-on of velocity 0 (per the spec, a /// note-on with velocity 0 is a note-off with velocity 64). @@ -190,7 +213,7 @@ pub const MAX_WARNINGS: usize = 32; /// for where the track's events ended; /// - bytes that are no chunk are skipped up to the next `MTrk`, and trailing bytes are ignored; /// - past [`MAX_TRACKS`] tracks the rest is left out; this and the event limit set -/// [`LenientRead::over_limit`]; +/// [`LenientRead::over_limit`], as does exceeding either SysEx limit; /// - lyrics are counted in a warning (they are not kept); a format-2 file gets a warning that its /// tracks are read side by side. pub fn read_smf_lenient(bytes: &[u8]) -> Result { @@ -210,7 +233,7 @@ pub struct LenientRead { pub instruments: Vec, /// The last tick any track reaches: its End of Track, or where its events stop. pub end: i64, - /// Whether the file goes past [`MAX_EVENTS`] events or [`MAX_TRACKS`] tracks, so what lies past + /// Whether the file goes past the event, track, SysEx payload or SysEx packet limit, so what lies past /// the limit was left out. It is set even when the warnings are already full, so a caller that /// refuses such files (as [`read_smf`] does) can tell without reading the warnings. pub over_limit: bool, @@ -268,6 +291,7 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec>) -> Result<(Smf, Ex let mut globals = Globals { tempos: Vec::new(), meters: Vec::new(), markers: Vec::new(), key_sigs: Vec::new() }; let (mut tracks, mut instruments) = (Vec::new(), Vec::new()); let mut event_budget = MAX_EVENTS; + let mut sysex_budget = SysexBudget::new(); let (mut end, mut seen, mut lyrics) = (0i64, 0usize, 0usize); let mut over_limit = false; @@ -323,13 +347,13 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec>) -> Result<(Smf, Ex warn(&mut warnings, format!("track {seen} is shorter than its length says")); cur.pos = bytes.len(); } - let read = read_track(body, body_at, conv, &mut globals, &mut event_budget); + let read = read_track(body, body_at, conv, &mut globals, &mut event_budget, &mut sysex_budget); lyrics += read.lyrics; end = end.max(read.end); match read.stop { Some(e) if !lenient => return Err(e), Some(e) => { - over_limit |= matches!(e, MidiError::TooManyEvents(_)); + over_limit |= matches!(e, MidiError::TooManyEvents(_) | MidiError::SysExTooLarge(_) | MidiError::TooManySysExPackets(_)); warn(&mut warnings, format!("track {seen} {}: what came before is kept", stop_reason(&e))); } None if !read.ended && lenient => warn(&mut warnings, format!("track {seen} has no End of Track: what came before is kept")), @@ -361,7 +385,9 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec>) -> Result<(Smf, Ex let globals_present = !(globals.tempos.is_empty() && globals.meters.is_empty() && globals.markers.is_empty() && globals.key_sigs.is_empty()); if format == 1 && (tracks.len() > 1 || globals_present) - && tracks.first().is_some_and(|t| t.sequence.notes.is_empty() && t.sequence.ctrls.is_empty() && (tracks.len() > 1 || t.name.is_empty())) + && tracks.first().is_some_and(|t| { + t.sequence.notes.is_empty() && t.sequence.ctrls.is_empty() && t.sequence.sysex.is_empty() && (tracks.len() > 1 || t.name.is_empty()) + }) { tracks.remove(0); instruments.remove(0); @@ -382,6 +408,8 @@ fn read(bytes: &[u8], mut warnings: Option<&mut Vec>) -> Result<(Smf, Ex /// Why a track's events stopped, in words for a warning. fn stop_reason(e: &MidiError) -> &'static str { match e { + MidiError::SysExTooLarge(_) => "exceeds the retained SysEx payload limit", + MidiError::TooManySysExPackets(_) => "exceeds the retained SysEx packet count limit", MidiError::TooManyEvents(_) => "holds more events than are read: the rest was left out", MidiError::Invalid { reason, .. } if reason.starts_with("data byte") || reason.starts_with("system") || reason.starts_with("status") => { "holds a byte that is no event" @@ -428,10 +456,10 @@ struct TrackState { lyrics: usize, } -fn read_track(body: &[u8], base: usize, conv: TickConv, g: &mut Globals, budget: &mut usize) -> TrackRead { +fn read_track(body: &[u8], base: usize, conv: TickConv, g: &mut Globals, budget: &mut usize, sysex_budget: &mut SysexBudget) -> TrackRead { let mut cur = Cursor { data: body, pos: 0, base }; let mut st = TrackState { name: None, instrument: None, seq: Sequence::default(), open: vec![VecDeque::new(); 16 * 128], tick: 0, lyrics: 0 }; - let result = track_events(&mut cur, conv, g, budget, &mut st); + let result = track_events(&mut cur, conv, g, budget, sysex_budget, &mut st); let TrackState { name, instrument, mut seq, mut open, tick, lyrics } = st; // Close hanging notes at the end of the track (or where its events stopped). for (key, stack) in open.iter_mut().enumerate() { @@ -452,7 +480,14 @@ fn read_track(body: &[u8], base: usize, conv: TickConv, g: &mut Globals, budget: } /// Reads a track's events; `Ok(true)` when an End of Track ends them, `Ok(false)` when the data does. -fn track_events(cur: &mut Cursor, conv: TickConv, g: &mut Globals, budget: &mut usize, st: &mut TrackState) -> Result { +fn track_events( + cur: &mut Cursor, + conv: TickConv, + g: &mut Globals, + budget: &mut usize, + sysex_budget: &mut SysexBudget, + st: &mut TrackState, +) -> Result { let mut file_tick: u64 = 0; let mut running: Option = None; @@ -522,7 +557,11 @@ fn track_events(cur: &mut Cursor, conv: TickConv, g: &mut Globals, budget: &mut 0xF0 | 0xF7 => { running = None; let len = cur.vlq()?; - cur.bytes(usize::try_from(len).unwrap_or(usize::MAX))?; + let len = usize::try_from(len).unwrap_or(usize::MAX); + let data = cur.bytes(len)?; + sysex_budget.charge(len)?; + let data = data.to_vec(); + st.seq.sysex.push(SysExEvent { tick, status, data }); } 0x80..=0xEF => { running = Some(status); @@ -610,7 +649,21 @@ pub struct TimedEvent { pub bytes: Vec, } -type WEvent = TimedEvent; +struct WEvent { + event: TimedEvent, + split: Option, +} + +enum SplitPacket { + Start(usize), + Continue(usize), +} + +impl WEvent { + fn new(tick: u64, order: u8, bytes: Vec) -> Self { + Self { event: TimedEvent { tick, order, bytes }, split: None } + } +} /// Encode an SMF meta event, without its delta time. pub fn encode_meta_event(kind: u8, data: &[u8]) -> Result, MidiError> { @@ -656,7 +709,8 @@ pub fn write_timed_smf(format: u16, division: u16, tracks: Vec>, out.extend_from_slice(&format.to_be_bytes()); out.extend_from_slice(&count.to_be_bytes()); out.extend_from_slice(&division.to_be_bytes()); - for track in tracks { + for mut track in tracks { + track.sort_by_key(|e| (e.tick, e.order)); write_track_policy(&mut out, track, clamp_deltas, false)?; } Ok(out) @@ -673,16 +727,49 @@ fn meta(kind: u8, data: &[u8]) -> Result, MidiError> { Ok(b) } -fn write_track(out: &mut Vec, events: Vec) -> Result<(), MidiError> { - write_track_policy(out, events, false, true) +fn write_track(out: &mut Vec, mut events: Vec) -> Result<(), MidiError> { + events.sort_by_key(|e| (e.event.tick, e.event.order)); + check_split_sysex_order(&events)?; + write_track_policy(out, events.into_iter().map(|e| e.event), false, true) } -fn write_track_policy(out: &mut Vec, mut events: Vec, clamp_deltas: bool, running_status: bool) -> Result<(), MidiError> { - events.sort_by_key(|e| (e.tick, e.order)); +// Check the actual emitted order and the source of each continuation. +fn check_split_sysex_order(events: &[WEvent]) -> Result<(), MidiError> { + let mut active = None; + let mut unterminated = false; + for event in events { + let status = event.event.bytes.first().copied(); + let terminated = event.event.bytes.last() == Some(&0xF7); + match (&event.split, active) { + (Some(SplitPacket::Start(track)), None) => { + active = Some(*track); + unterminated = true; + } + (Some(SplitPacket::Continue(track)), Some(owner)) if *track == owner => { + if terminated { + active = None; + unterminated = false; + } + } + (None, _) if status == Some(0xFF) => {} // Meta events are local to the file. + (None, None) if status == Some(0xF0) => unterminated = !terminated, + (None, None) if status != Some(0xF7) || !unterminated => {} + _ => return Err(MidiError::Write("event ordering would interleave split SysEx packets".into())), + } + } + Ok(()) +} + +fn write_track_policy( + out: &mut Vec, + events: impl IntoIterator, + clamp_deltas: bool, + running_status: bool, +) -> Result<(), MidiError> { let mut body = Vec::new(); let mut last_tick = 0u64; let mut running: Option = None; - for e in &events { + for e in events { let delta = e.tick - last_tick; push_vlq(&mut body, if clamp_deltas { delta.min(MAX_VLQ) } else { delta })?; last_tick = e.tick; @@ -717,21 +804,21 @@ fn conductor_events(smf: &Smf) -> Result, MidiError> { } let us = (60_000_000.0 / bpm).round().clamp(1.0, f64::from(0x00FF_FFFFu32)) as u32; let [_, a, b, c] = us.to_be_bytes(); - ev.push(WEvent { tick: clamp_tick(t), order: 0, bytes: meta(0x51, &[a, b, c])? }); + ev.push(WEvent::new(clamp_tick(t), 0, meta(0x51, &[a, b, c])?)); } for &(t, num, den) in &smf.meters { if den == 0 || !den.is_power_of_two() { return Err(MidiError::Write(format!("meter denominator {den} is not a power of two"))); } let dd = den.trailing_zeros() as u8; - ev.push(WEvent { tick: clamp_tick(t), order: 1, bytes: meta(0x58, &[num, dd, 24, 8])? }); + ev.push(WEvent::new(clamp_tick(t), 1, meta(0x58, &[num, dd, 24, 8])?)); } for &(t, sf, minor) in &smf.key_sigs { let sf = sf.clamp(-7, 7); - ev.push(WEvent { tick: clamp_tick(t), order: 2, bytes: meta(0x59, &[sf as u8, u8::from(minor)])? }); + ev.push(WEvent::new(clamp_tick(t), 2, meta(0x59, &[sf as u8, u8::from(minor)])?)); } for (t, text) in &smf.markers { - ev.push(WEvent { tick: clamp_tick(*t), order: 3, bytes: meta(0x06, text.as_bytes())? }); + ev.push(WEvent::new(clamp_tick(*t), 3, meta(0x06, text.as_bytes())?)); } Ok(ev) } @@ -778,11 +865,23 @@ fn trim_overlaps(notes: &[Note], ends: &mut [u64], dropped: &mut [bool]) { /// Track 1 is a conductor track holding tempos, meters, key signatures and markers; every /// [`SmfTrack`] follows as its own track, with its name when it is not empty. Format 0 is one track holding all of that. Negative ticks are clamped to 0, data values are /// clamped to their MIDI ranges, and note-on velocity 0 is written as 1 (0 would mean -/// note-off). At each tick note-offs are written before controllers, then note-ons. +/// note-off). At each tick the default order is note-offs, SysEx, controllers, then note-ons. +/// Split SysEx starts after same-tick channel events and continues before channel events on +/// later ticks. Later SysEx packets on the opening tick follow the split in source order. +/// An unterminated legacy F0 with no continuation retains its original bytes. /// /// Errors: invalid tempo (non-finite or <= 0 bpm), meter denominator that is not a power of two -/// (1..=128), more than 65535 tracks, or a gap between events beyond the 28-bit delta limit. +/// (1..=128), more than 65535 tracks, a gap beyond the 28-bit delta limit, an invalid +/// SysEx status, ordering that interrupts split SysEx in either format, or more than +/// [`MAX_SYSEX_BYTES`] bytes of SysEx payloads or 262,144 SysEx packets. pub fn write_smf(smf: &Smf) -> Result, MidiError> { + let mut sysex_budget = SysexBudget::new(); + for event in smf.tracks.iter().flat_map(|t| &t.sequence.sysex) { + if !matches!(event.status, 0xF0 | 0xF7) { + return Err(MidiError::Write("SysEx status must be F0 or F7".into())); + } + sysex_budget.charge(event.data.len())?; + } // The conductor track is omitted when there is nothing to put in it and no content tracks, so an // empty `Smf` is written as a file with zero tracks and reads back as zero tracks. let has_conductor = @@ -803,10 +902,10 @@ pub fn write_smf(smf: &Smf) -> Result, MidiError> { write_track(&mut out, std::mem::take(&mut merged))?; } - for track in &smf.tracks { + for (track_index, track) in smf.tracks.iter().enumerate() { let mut ev = Vec::new(); if !track.name.is_empty() { - ev.push(WEvent { tick: 0, order: 0, bytes: meta(0x03, track.name.as_bytes())? }); + ev.push(WEvent::new(0, 0, meta(0x03, track.name.as_bytes())?)); } let notes = &track.sequence.notes; let mut ends: Vec = notes.iter().map(|n| clamp_tick(n.end()).max(clamp_tick(n.start).saturating_add(1))).collect(); @@ -820,8 +919,8 @@ pub fn write_smf(smf: &Smf) -> Result, MidiError> { let pitch = n.pitch.min(127); let start = clamp_tick(n.start); let end = ends.get(i).copied().unwrap_or(start.saturating_add(1)); - ev.push(WEvent { tick: start, order: 3, bytes: vec![0x90 | ch, pitch, n.velocity.clamp(1, 127)] }); - ev.push(WEvent { tick: end, order: 1, bytes: vec![0x80 | ch, pitch, n.release_velocity.min(127)] }); + ev.push(WEvent::new(start, 4, vec![0x90 | ch, pitch, n.velocity.clamp(1, 127)])); + ev.push(WEvent::new(end, 1, vec![0x80 | ch, pitch, n.release_velocity.min(127)])); } for c in &track.sequence.ctrls { let ch = c.channel & 0x0F; @@ -836,8 +935,9 @@ pub fn write_smf(smf: &Smf) -> Result, MidiError> { vec![0xE0 | ch, (v & 0x7F) as u8, ((v >> 7) & 0x7F) as u8] } }; - ev.push(WEvent { tick: clamp_tick(c.tick), order: 2, bytes }); + ev.push(WEvent::new(clamp_tick(c.tick), 3, bytes)); } + append_sysex_events(&mut ev, track_index, &track.sequence.sysex)?; if single { merged.extend(ev); } else { @@ -850,10 +950,107 @@ pub fn write_smf(smf: &Smf) -> Result, MidiError> { Ok(out) } +fn append_sysex_events(events: &mut Vec, track: usize, packets: &[SysExEvent]) -> Result<(), MidiError> { + let mut ordered: Vec<_> = packets.iter().collect(); + ordered.sort_by_key(|packet| clamp_tick(packet.tick)); + let mut packets = ordered.into_iter().peekable(); + let mut opening_tick = None; + while let Some(packet) = packets.next() { + let tick = clamp_tick(packet.tick); + let starts_split = packet.status == 0xF0 && packet.data.last() != Some(&0xF7) && packets.peek().is_some_and(|next| next.status == 0xF7); + if !starts_split { + // Later packets at the opening tick keep their position after the split. + let order = if opening_tick == Some(tick) { 5 } else { 2 }; + events.push(encode_sysex(packet, order)?); + continue; + } + + // Start after channel events. Subsequent ticks continue before channel events. + opening_tick = Some(tick); + let mut start = encode_sysex(packet, 5)?; + start.split = Some(SplitPacket::Start(track)); + events.push(start); + while let Some(packet) = packets.next_if(|next| next.status == 0xF7) { + let terminated = packet.data.last() == Some(&0xF7); + // Same-tick continuations stay after their own F0 in source order. + let order = if clamp_tick(packet.tick) == tick { 5 } else { 0 }; + let mut continuation = encode_sysex(packet, order)?; + continuation.split = Some(SplitPacket::Continue(track)); + events.push(continuation); + if terminated { + break; + } + } + } + Ok(()) +} + +fn encode_sysex(packet: &SysExEvent, order: u8) -> Result { + let mut bytes = vec![packet.status]; + push_vlq(&mut bytes, packet.data.len() as u64)?; + bytes.extend_from_slice(&packet.data); + Ok(WEvent::new(clamp_tick(packet.tick), order, bytes)) +} + #[cfg(test)] +// Test fixtures assert successful parses; production code keeps the crate's unwrap denial. +#[allow(clippy::unwrap_used)] mod tests { use super::*; + #[test] + fn bounds_zero_payload_sysex_packet_storage() { + let mut body = [0, 0xF7, 0].repeat(262_145); + body.extend_from_slice(&[0, 0xFF, 0x2F, 0]); + let mut bytes = b"MThd\0\0\0\x06\0\0\0\x01\x03\xC0MTrk".to_vec(); + bytes.extend_from_slice(&(body.len() as u32).to_be_bytes()); + bytes.extend_from_slice(&body); + assert_eq!(read_smf(&bytes), Err(MidiError::TooManySysExPackets(MAX_SYSEX_PACKETS))); + let report = read_smf_lenient(&bytes).unwrap(); + assert!(report.over_limit); + assert_eq!(report.smf.tracks[0].sequence.sysex.len(), 262_144); + } + + #[test] + fn reports_truncated_sysex_before_the_payload_budget() { + let body = [0, 0xF0, 0xFF, 0xFF, 0xFF, 0x7F, 1, 2, 3]; + let mut bytes = b"MThd\0\0\0\x06\0\0\0\x01\x03\xC0MTrk".to_vec(); + bytes.extend_from_slice(&(body.len() as u32).to_be_bytes()); + bytes.extend_from_slice(&body); + assert!(matches!(read_smf(&bytes), Err(MidiError::Truncated(_)))); + let report = read_smf_lenient(&bytes).unwrap(); + assert!(!report.over_limit); + assert!(!report.warnings.is_empty()); + } + + #[test] + fn refuses_to_interleave_split_sysex_when_merging_tracks() { + let mut smf = Smf { format: 0, ..Smf::default() }; + for sysex in [ + vec![SysExEvent { tick: 0, status: 0xF0, data: vec![0x43, 0x10] }, SysExEvent { tick: 10, status: 0xF7, data: vec![0x4C, 0xF7] }], + vec![SysExEvent { tick: 5, status: 0xF0, data: vec![0x41, 0xF7] }], + ] { + smf.tracks.push(SmfTrack { name: String::new(), sequence: Sequence { sysex, ..Sequence::default() } }); + } + assert!(matches!(write_smf(&smf), Err(MidiError::Write(message)) if message.contains("interleave"))); + smf.format = 1; + assert!(write_smf(&smf).is_ok()); + } + + #[test] + fn imported_xg_reset_survives_an_smf_round_trip() { + let event = [0xF0, 8, 0x43, 0x10, 0x4C, 0, 0, 0x7E, 0, 0xF7]; + let mut body = vec![0]; + body.extend_from_slice(&event); + body.extend_from_slice(&[0, 0xFF, 0x2F, 0]); + let mut bytes = b"MThd\0\0\0\x06\0\0\0\x01\x03\xC0MTrk".to_vec(); + bytes.extend_from_slice(&(body.len() as u32).to_be_bytes()); + bytes.extend_from_slice(&body); + let parsed = read_smf(&bytes).unwrap(); + let written = write_smf(&parsed).unwrap(); + assert!(written.windows(event.len()).any(|part| part == event), "the imported XG System On was discarded"); + } + #[test] fn vlq_round_trip() { for v in [0u64, 0x40, 0x7F, 0x80, 0x2000, 0x3FFF, 0x4000, 0x1F_FFFF, 0x20_0000, MAX_VLQ] { diff --git a/crates/midi/tests/it/lenient.rs b/crates/midi/tests/it/lenient.rs index 0556c3859c..e328115458 100644 --- a/crates/midi/tests/it/lenient.rs +++ b/crates/midi/tests/it/lenient.rs @@ -170,7 +170,7 @@ fn damaged_files_never_panic() { #[test] fn format_0_is_written_as_one_track_and_reads_back() { let note = |pitch, channel, start| Note { pitch, velocity: 100, release_velocity: 64, channel, start, length: 480 }; - let track = |name: &str, n: Note| SmfTrack { name: name.into(), sequence: Sequence { notes: vec![n], ctrls: vec![] } }; + let track = |name: &str, n: Note| SmfTrack { name: name.into(), sequence: Sequence { notes: vec![n], ..Default::default() } }; let smf = Smf { format: 0, tracks: vec![track("A", note(60, 0, 0)), track("B", note(64, 1, 960))], diff --git a/crates/midi/tests/it/main.rs b/crates/midi/tests/it/main.rs index 45f95c70ca..cc7865d4ad 100644 --- a/crates/midi/tests/it/main.rs +++ b/crates/midi/tests/it/main.rs @@ -4,3 +4,4 @@ mod lenient; mod sequence; mod smf; mod sync; +mod sysex; diff --git a/crates/midi/tests/it/sequence.rs b/crates/midi/tests/it/sequence.rs index 01185e08b9..c89537930d 100644 --- a/crates/midi/tests/it/sequence.rs +++ b/crates/midi/tests/it/sequence.rs @@ -18,6 +18,7 @@ fn sequence_helpers() { CtrlEvent { tick: 500, channel: 0, kind: CtrlKind::Cc(1), value: 3 }, CtrlEvent { tick: 500, channel: 0, kind: CtrlKind::Cc(2), value: 4 }, ], + ..Default::default() }; assert_eq!(seq.end_tick(), 500); seq.sort(); @@ -39,7 +40,11 @@ fn sequence_helpers() { #[cfg(feature = "serde")] #[test] fn sequence_serde_round_trip() { - let seq = Sequence { notes: vec![n(60, 0, 1)], ctrls: vec![CtrlEvent { tick: 1, channel: 0, kind: CtrlKind::PolyPressure(60), value: 9 }] }; + let seq = Sequence { + notes: vec![n(60, 0, 1)], + ctrls: vec![CtrlEvent { tick: 1, channel: 0, kind: CtrlKind::PolyPressure(60), value: 9 }], + ..Default::default() + }; let json = serde_json::to_string(&seq).unwrap(); assert_eq!(serde_json::from_str::(&json).unwrap(), seq); } @@ -53,7 +58,7 @@ fn remove_duplicates_handles_a_large_same_tick_controller_group() { .iter() .flat_map(|&pass| keys.iter().map(move |&(channel, cc)| CtrlEvent { tick: 7, channel, kind: CtrlKind::Cc(cc), value: pass })) .collect(); - let mut seq = Sequence { notes: Vec::new(), ctrls }; + let mut seq = Sequence { notes: Vec::new(), ctrls, ..Default::default() }; let start = std::time::Instant::now(); assert_eq!(seq.remove_duplicates(), keys.len()); assert!(start.elapsed() < std::time::Duration::from_secs(10), "{:?}", start.elapsed()); @@ -105,7 +110,7 @@ fn remove_duplicates_matches_a_per_tick_rescan_on_mixed_ticks() { let r = next(); ctrls.push(CtrlEvent { tick: (r % 6) as i64 - 2, channel: (r >> 16) as u8 % 3, kind: kinds(r >> 24), value: (round * 100 + i) as i32 }); } - let mut seq = Sequence { notes: Vec::new(), ctrls: ctrls.clone() }; + let mut seq = Sequence { notes: Vec::new(), ctrls: ctrls.clone(), ..Default::default() }; let removed = seq.remove_duplicates(); let expected = reference(ctrls.clone()); assert_eq!(seq.ctrls, expected, "round {round}"); diff --git a/crates/midi/tests/it/smf.rs b/crates/midi/tests/it/smf.rs index cd2915607a..0d481525a7 100644 --- a/crates/midi/tests/it/smf.rs +++ b/crates/midi/tests/it/smf.rs @@ -57,13 +57,14 @@ fn round_trip() { CtrlEvent { tick: 50, channel: 2, kind: CtrlKind::ChannelPressure, value: 77 }, CtrlEvent { tick: 60, channel: 2, kind: CtrlKind::PolyPressure(61), value: 12 }, ], + ..Default::default() }; seq.sort(); let smf = Smf { format: 1, tracks: vec![ SmfTrack { name: "Piano".into(), sequence: seq.clone() }, - SmfTrack { name: "Bass ♪".into(), sequence: Sequence { notes: vec![note(36, 100, 50)], ctrls: vec![] } }, + SmfTrack { name: "Bass ♪".into(), sequence: Sequence { notes: vec![note(36, 100, 50)], ..Default::default() } }, ], tempos: vec![(0, 120.0), (3840, 90.0)], meters: vec![(0, 4, 4), (3840, 6, 8)], @@ -118,7 +119,7 @@ fn write_rejects_bad_values() { let bad_meter = Smf { meters: vec![(0, 4, 3)], ..Default::default() }; assert!(write_smf(&bad_meter).is_err()); let huge_gap = Smf { - tracks: vec![SmfTrack { name: String::new(), sequence: Sequence { notes: vec![note(60, 0x1000_0000, 10)], ctrls: vec![] } }], + tracks: vec![SmfTrack { name: String::new(), sequence: Sequence { notes: vec![note(60, 0x1000_0000, 10)], ..Default::default() } }], ..Default::default() }; assert!(write_smf(&huge_gap).is_err()); @@ -341,6 +342,7 @@ proptest! { let mut seq = Sequence { notes: notes.iter().map(|&(pitch, velocity, channel, start, length)| Note { pitch, velocity, release_velocity: 64, channel, start, length }).collect(), ctrls: vec![], + ..Default::default() }; seq.remove_duplicates(); let smf = Smf { format: 1, tracks: vec![SmfTrack { name: "t".into(), sequence: seq.clone() }], ..Default::default() }; diff --git a/crates/midi/tests/it/sysex.rs b/crates/midi/tests/it/sysex.rs new file mode 100644 index 0000000000..dd229af921 --- /dev/null +++ b/crates/midi/tests/it/sysex.rs @@ -0,0 +1,212 @@ +use craft_midi::{MAX_SYSEX_BYTES, MidiError, Sequence, SysExEvent, read_smf, read_smf_lenient, write_smf}; + +fn file(format: u16, bodies: &[Vec]) -> Vec { + let mut bytes = b"MThd\0\0\0\x06".to_vec(); + bytes.extend_from_slice(&format.to_be_bytes()); + bytes.extend_from_slice(&(bodies.len() as u16).to_be_bytes()); + bytes.extend_from_slice(&960u16.to_be_bytes()); + for body in bodies { + bytes.extend_from_slice(b"MTrk"); + bytes.extend_from_slice(&(body.len() as u32).to_be_bytes()); + bytes.extend_from_slice(body); + } + bytes +} + +#[test] +fn sysex_only_first_track_is_not_folded_into_the_conductor() { + let bytes = file(1, &[vec![0, 0xF0, 2, 0x43, 0xF7, 0, 0xFF, 0x2F, 0], vec![0, 0x90, 60, 100, 1, 0x80, 60, 64, 0, 0xFF, 0x2F, 0]]); + let smf = read_smf(&bytes).unwrap(); + assert_eq!(smf.tracks.len(), 2); + assert_eq!(smf.tracks[0].sequence.sysex[0].data, [0x43, 0xF7]); + let back = read_smf(&write_smf(&smf).unwrap()).unwrap(); + assert_eq!(back, smf); +} + +#[test] +fn split_f0_f7_and_escape_packets_keep_bytes_and_ticks_in_both_readers() { + let bytes = file(0, &[vec![0, 0xF0, 3, 0x43, 0x10, 0x4C, 0x87, 0x40, 0xF7, 5, 0, 0, 0x7E, 0, 0xF7, 0, 0xF7, 1, 0xF8, 0, 0xFF, 0x2F, 0]]); + let smf = read_smf(&bytes).unwrap(); + let packets = &smf.tracks[0].sequence.sysex; + assert_eq!(packets.iter().map(|p| (p.tick, p.status)).collect::>(), [(0, 0xF0), (960, 0xF7), (960, 0xF7)]); + assert_eq!(packets[2].data, [0xF8]); + assert_eq!(smf.tracks[0].sequence.end_tick(), 960); + assert_eq!(read_smf_lenient(&bytes).unwrap().smf, smf); + assert_eq!(read_smf(&write_smf(&smf).unwrap()).unwrap(), smf); +} + +#[test] +fn truncated_packet_is_not_invented_by_lenient_import() { + let bytes = file(0, &[vec![0, 0xF0, 1, 0x43, 0, 0xF7, 4, 0xF7]]); + assert!(read_smf(&bytes).is_err()); + let read = read_smf_lenient(&bytes).unwrap(); + assert_eq!(read.smf.tracks[0].sequence.sysex.len(), 1); + assert!(!read.warnings.is_empty()); +} + +#[test] +fn sysex_limit_is_shared_across_tracks_and_reported_by_lenient_import() { + let mut body = vec![0, 0xF0, 0x88, 0x80, 0x80, 0]; // 16 MiB VLQ + body.resize(body.len() + MAX_SYSEX_BYTES, 0x01); + body.extend_from_slice(&[0, 0xFF, 0x2F, 0]); + let bytes = file(1, &[body, vec![0, 0xF7, 1, 0xF7, 0, 0xFF, 0x2F, 0]]); + assert_eq!(read_smf(&bytes), Err(MidiError::SysExTooLarge(MAX_SYSEX_BYTES))); + assert!(read_smf_lenient(&bytes).unwrap().over_limit); +} + +#[test] +fn same_tick_setup_packets_precede_program_changes_and_notes() { + let mut smf = craft_midi::Smf::default(); + let mut sequence = Sequence::default(); + sequence.sysex.push(SysExEvent { tick: 0, status: 0xF0, data: vec![0x43, 0xF7] }); + sequence.ctrls.push(craft_midi::CtrlEvent { tick: 0, channel: 0, kind: craft_midi::CtrlKind::Program, value: 5 }); + sequence.notes.push(craft_midi::Note { start: 0, length: 960, channel: 0, pitch: 60, velocity: 100, release_velocity: 64 }); + smf.tracks.push(craft_midi::SmfTrack { name: String::new(), sequence }); + let bytes = write_smf(&smf).unwrap(); + let packet = bytes.windows(4).position(|w| w == [0xF0, 2, 0x43, 0xF7]).unwrap(); + let program = bytes.windows(2).position(|w| w == [0xC0, 5]).unwrap(); + let note = bytes.windows(3).position(|w| w == [0x90, 60, 100]).unwrap(); + assert!(packet < program && program < note); +} + +#[test] +fn format_zero_cross_track_note_off_precedes_sysex_at_the_same_tick() { + for reverse in [false, true] { + let mut packets = Sequence::default(); + packets.sysex.push(SysExEvent { tick: 960, status: 0xF0, data: vec![0x43, 0xF7] }); + packets.sysex.push(SysExEvent { tick: 960, status: 0xF7, data: vec![0xF8] }); + let mut notes = Sequence::default(); + notes.notes.push(craft_midi::Note { start: 0, length: 960, channel: 0, pitch: 60, velocity: 100, release_velocity: 64 }); + notes.notes.push(craft_midi::Note { start: 960, length: 960, channel: 0, pitch: 64, velocity: 100, release_velocity: 64 }); + notes.ctrls.push(craft_midi::CtrlEvent { tick: 960, channel: 0, kind: craft_midi::CtrlKind::Program, value: 5 }); + let mut tracks = + vec![craft_midi::SmfTrack { name: String::new(), sequence: packets }, craft_midi::SmfTrack { name: String::new(), sequence: notes }]; + if reverse { + tracks.reverse(); + } + let bytes = write_smf(&craft_midi::Smf { format: 0, tracks, ..Default::default() }).unwrap(); + let position = |message: &[u8]| bytes.windows(message.len()).position(|w| w == message).unwrap(); + let off = position(&[0x80, 60, 64]); + let first = position(&[0xF0, 2, 0x43, 0xF7]); + let second = position(&[0xF7, 1, 0xF8]); + let program = position(&[0xC0, 5]); + let on = position(&[0x90, 64, 100]); + assert!( + off < first && first < second && second < program && program < on, + "cross-track order must be note-off, stable SysEx packets, controllers, note-on (reverse={reverse})" + ); + } +} + +#[test] +fn writer_rejects_invalid_status_and_excess_payload() { + let mut smf = craft_midi::Smf::default(); + smf.tracks.push(craft_midi::SmfTrack::default()); + smf.tracks[0].sequence.sysex.push(SysExEvent { tick: 0, status: 0x90, data: vec![] }); + assert!(write_smf(&smf).is_err()); + let event = &mut smf.tracks[0].sequence.sysex[0]; + event.status = 0xF0; + event.data.resize(MAX_SYSEX_BYTES + 1, 0); + assert_eq!(write_smf(&smf), Err(MidiError::SysExTooLarge(MAX_SYSEX_BYTES))); +} + +#[cfg(feature = "serde")] +#[test] +fn old_sequences_load_and_sysex_packets_survive_json() { + let old: Sequence = serde_json::from_str(r#"{"notes":[],"ctrls":[]}"#).unwrap(); + assert!(old.sysex.is_empty()); + assert_eq!(serde_json::to_string(&old).unwrap(), r#"{"notes":[],"ctrls":[]}"#); + let mut sequence = old; + sequence.sysex.push(SysExEvent { tick: 10, status: 0xF0, data: vec![0x43, 0xF7] }); + sequence.sysex.push(SysExEvent { tick: 10, status: 0xF7, data: vec![] }); + sequence.sort(); + assert_eq!(serde_json::from_str::(&serde_json::to_string(&sequence).unwrap()).unwrap(), sequence); + assert_eq!(sequence.remove_duplicates(), 0, "stateful packets must not be deduplicated"); + assert_eq!(sequence.sysex.len(), 2); +} + +#[test] +fn rejects_a_format_zero_channel_event_inside_split_sysex() { + let sysex = vec![0, 0xF0, 1, 0x43, 10, 0xF7, 2, 0x10, 0xF7, 0, 0xFF, 0x2F, 0]; + for (program_tick, valid_merge) in [(5, false), (10, true), (11, true)] { + let program = vec![program_tick, 0xC0, 7, 0, 0xFF, 0x2F, 0]; + let mut smf = read_smf(&file(1, &[sysex.clone(), program])).unwrap(); + assert!(write_smf(&smf).is_ok()); + smf.format = 0; + assert_eq!(write_smf(&smf).is_ok(), valid_merge); + } +} + +#[test] +fn split_sysex_closes_before_a_same_tick_note_off() { + let body = vec![0, 0x90, 60, 100, 5, 0xF0, 1, 0x43, 5, 0xF7, 2, 0x10, 0xF7, 0, 0x80, 60, 64, 0, 0xFF, 0x2F, 0]; + for format in [0, 1] { + let smf = read_smf(&file(format, std::slice::from_ref(&body))).unwrap(); + let bytes = write_smf(&smf).unwrap(); + assert!(bytes.windows(8).any(|w| w == [0xF7, 2, 0x10, 0xF7, 0, 0x80, 60, 64])); + assert_eq!(read_smf(&bytes).unwrap(), smf); + } +} + +#[test] +fn split_sysex_opens_after_a_same_tick_program_change() { + for gap in [0, 10] { + let body = vec![0, 0xC0, 7, 0, 0xF0, 1, 0x43, gap, 0xF7, 2, 0x10, 0xF7, 0, 0xFF, 0x2F, 0]; + for format in [0, 1] { + let smf = read_smf(&file(format, std::slice::from_ref(&body))).unwrap(); + let bytes = write_smf(&smf).unwrap(); + assert!(bytes.windows(10).any(|w| w == [0xC0, 7, 0, 0xF0, 1, 0x43, gap, 0xF7, 2, 0x10])); + assert_eq!(read_smf(&bytes).unwrap(), smf); + } + } +} + +#[test] +fn legacy_f0_packets_without_a_continuation_survive_export() { + let body = vec![0, 0xF0, 4, 0x7E, 0x7F, 0x09, 1, 5, 0x90, 60, 100, 5, 0x80, 60, 64, 0, 0xFF, 0x2F, 0]; + for format in [0, 1] { + let smf = read_smf(&file(format, std::slice::from_ref(&body))).unwrap(); + assert_eq!(read_smf(&write_smf(&smf).unwrap()).unwrap(), smf); + } + + // A new F0 starts its own message even when the previous packet had no terminator. + let control_and_setup = vec![5, 0xB0, 7, 90, 5, 0xF0, 2, 0x41, 0xF7, 0, 0xFF, 0x2F, 0]; + let mut smf = read_smf(&file(1, &[body, control_and_setup])).unwrap(); + smf.format = 0; + let written = read_smf(&write_smf(&smf).unwrap()).unwrap(); + let sequence = &written.tracks[0].sequence; + assert_eq!(sequence.sysex, [smf.tracks[0].sequence.sysex[0].clone(), smf.tracks[1].sequence.sysex[0].clone()]); + assert_eq!(sequence.notes, smf.tracks[0].sequence.notes); + assert_eq!(sequence.ctrls, smf.tracks[1].sequence.ctrls); +} + +#[test] +fn later_same_tick_sysex_packets_keep_their_source_order() { + let body = vec![0, 0xC0, 7, 0, 0xF0, 1, 0x43, 0, 0xF7, 2, 0x10, 0xF7, 0, 0xF0, 2, 0x41, 0xF7, 0, 0xFF, 0x2F, 0]; + for format in [0, 1] { + let smf = read_smf(&file(format, std::slice::from_ref(&body))).unwrap(); + let bytes = write_smf(&smf).unwrap(); + assert_eq!(read_smf(&bytes).unwrap(), smf); + assert!(bytes.windows(body.len()).any(|window| window == body)); + } +} + +#[test] +fn nonterminating_continuations_still_block_later_channel_events() { + for format in [0, 1] { + for terminated in [false, true] { + let mut body = vec![0, 0xF0, 1, 0x43, 10, 0xF7, 1 + u8::from(terminated), 0x10]; + if terminated { + body.push(0xF7); + } + body.extend([10, 0xC0, 7, 0, 0xFF, 0x2F, 0]); + let smf = read_smf(&file(format, &[body])).unwrap(); + let result = write_smf(&smf); + if terminated { + assert_eq!(read_smf(&result.unwrap()).unwrap(), smf); + } else { + assert!(matches!(result, Err(MidiError::Write(message)) if message.contains("interleave"))); + } + } + } +} From c8087acbd9711315eefc2790949b7acf915da011 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 21:57:15 -0500 Subject: [PATCH 79/79] hayro*: port pdfcraft vendor/hayro* patches (#2472) * hayro*: port pdfcraft vendor/hayro* patches (storytold/craft-libs#778) * hayro-syntax: fix test and merge compile errors from port * fix(hayro-syntax): avoid moving params.control in lzw_flate test * fix(hayro-syntax): include early_change in lzw_flate test * hayro*: fix hayro-interpret compile errors and hayro-syntax test failures * hayro*: fix duplicate char_code_to_unicode and super::LETTER in test * hayro-syntax: fix predictor cancellation and ArrayIter parse failure tests * hayro-syntax: restore bit-level PNG predictor fallback when control is set * hayro-syntax: support Checkpoints cancellation inside unfilter_png * hayro-interpret: remove duplicate blob::tests and require hayro-syntax 0.7.2 * hayro-interpret: cast MAX_COLOR_SPACE_DEPTH u32 as usize in test * hayro: drop unvendored vello_cpu set_max_coverage/coverage_full calls * hayro-interpret: restore interpret_form_contents call and TextPass order * hayro-interpret: split ExtendedWarning out of InterpreterWarning for vectorcraft compatibility * hayro-interpret: clone extended_warning_sink before ImageXObject::new closure * hayro-interpret: restore OP/op/OPM ExtGState handling for overprint * hayro-interpret: restore DecodeLimits and truncation reporting in decode_content * hayro: restore on_plate DefaultColorSpaces bypass and cmyk_luminosity soft mask --- crates/pdf/src/raster.rs | 1 + vendor/hayro-cmap/src/bcmap/mod.rs | 2 + vendor/hayro-cmap/src/lib.rs | 202 +- vendor/hayro-cmap/src/parse.rs | 24 +- vendor/hayro-interpret/Cargo.lock | 19 +- vendor/hayro-interpret/Cargo.toml | 2 +- vendor/hayro-interpret/src/cache.rs | 203 ++- vendor/hayro-interpret/src/cmyk_group.rs | 100 + vendor/hayro-interpret/src/cmyk_inverse.rs | 118 ++ vendor/hayro-interpret/src/color.rs | 512 ++++-- vendor/hayro-interpret/src/context.rs | 341 ++-- vendor/hayro-interpret/src/convert.rs | 30 + vendor/hayro-interpret/src/device.rs | 68 +- vendor/hayro-interpret/src/encode.rs | 106 +- vendor/hayro-interpret/src/font/blob.rs | 152 +- vendor/hayro-interpret/src/font/cid.rs | 262 ++- vendor/hayro-interpret/src/font/mod.rs | 147 +- .../hayro-interpret/src/font/standard_font.rs | 54 +- vendor/hayro-interpret/src/font/true_type.rs | 454 ++++- vendor/hayro-interpret/src/font/type1.rs | 62 +- vendor/hayro-interpret/src/font/type3.rs | 140 +- vendor/hayro-interpret/src/interpret/mod.rs | 345 +++- vendor/hayro-interpret/src/interpret/path.rs | 312 +++- vendor/hayro-interpret/src/interpret/state.rs | 12 +- vendor/hayro-interpret/src/lib.rs | 3 + vendor/hayro-interpret/src/ocg.rs | 105 +- vendor/hayro-interpret/src/pattern.rs | 24 + vendor/hayro-interpret/src/soft_mask.rs | 32 +- vendor/hayro-interpret/src/types.rs | 2 +- vendor/hayro-interpret/src/x_object.rs | 377 +++- vendor/hayro-jbig2/src/segment.rs | 49 +- vendor/hayro-syntax/src/content/mod.rs | 189 +- vendor/hayro-syntax/src/content/ops.rs | 41 + vendor/hayro-syntax/src/crypto/mod.rs | 77 +- vendor/hayro-syntax/src/data.rs | 11 +- .../src/filter/cancellation_tests.rs | 4 +- vendor/hayro-syntax/src/filter/ccitt.rs | 12 +- vendor/hayro-syntax/src/filter/jbig2.rs | 148 +- vendor/hayro-syntax/src/filter/jpx.rs | 241 ++- vendor/hayro-syntax/src/filter/lzw_flate.rs | 759 ++++++-- vendor/hayro-syntax/src/filter/mod.rs | 21 +- vendor/hayro-syntax/src/object/array.rs | 46 +- vendor/hayro-syntax/src/object/dict.rs | 25 +- vendor/hayro-syntax/src/object/mod.rs | 6 +- vendor/hayro-syntax/src/object/ref.rs | 9 +- vendor/hayro-syntax/src/object/stream.rs | 83 +- vendor/hayro-syntax/src/object/tuple.rs | 4 + vendor/hayro-syntax/src/page.rs | 91 +- vendor/hayro-syntax/src/pdf.rs | 51 +- vendor/hayro-syntax/src/xref.rs | 470 ++++- vendor/hayro/src/lib.rs | 18 +- vendor/hayro/src/renderer.rs | 1623 +++++++++++++---- 52 files changed, 6974 insertions(+), 1215 deletions(-) create mode 100644 vendor/hayro-interpret/src/cmyk_group.rs create mode 100644 vendor/hayro-interpret/src/cmyk_inverse.rs diff --git a/crates/pdf/src/raster.rs b/crates/pdf/src/raster.rs index 9b170d1f19..e9dc13f35b 100644 --- a/crates/pdf/src/raster.rs +++ b/crates/pdf/src/raster.rs @@ -143,6 +143,7 @@ pub fn render_into<'a>( options.background[2], options.background[3], ), + ..Default::default() }; catch_unwind(AssertUnwindSafe(|| hayro::render_into(page, cache, &settings, &rs, buffer))).map_err(|_| Error::BackendPanic)?; if cancelled() { diff --git a/vendor/hayro-cmap/src/bcmap/mod.rs b/vendor/hayro-cmap/src/bcmap/mod.rs index e20c45903f..182dff2c60 100644 --- a/vendor/hayro-cmap/src/bcmap/mod.rs +++ b/vendor/hayro-cmap/src/bcmap/mod.rs @@ -410,6 +410,8 @@ fn parse_bf_segment( entries.push(BfRange { range: Range { start, end }, dst_base, + // PdfCraft patch (4): a binary CMap doesn't record the length. + code_len: 0, }); prev_end = Some(end); diff --git a/vendor/hayro-cmap/src/lib.rs b/vendor/hayro-cmap/src/lib.rs index 2ef3c6d190..ebf5b6adac 100644 --- a/vendor/hayro-cmap/src/lib.rs +++ b/vendor/hayro-cmap/src/lib.rs @@ -359,8 +359,9 @@ const MAX_NESTING_DEPTH: u32 = 16; #[derive(Debug, Clone)] pub struct CMap { metadata: Metadata, - // Note that we don't actually use this, because Acrobat _seems_ to ignore - // it, too. + // Note that the CID lookup doesn't check this, because Acrobat _seems_ to + // ignore it, too. PdfCraft patch (4): the `bfchar` fallback of + // `lookup_cid_code` does check it (see there). _codespace_ranges: Vec, cid_ranges: PartitionedRanges, notdef_ranges: PartitionedRanges, @@ -449,7 +450,20 @@ impl CMap { // See pdfjs_bug920426, it uses bf chars for encoding the characters // of a text-showing operator, so try that as well. We don't want to // recurse though, only check the bf chars of this level. - if let Some(BfString::Char(lookup)) = self.lookup_bf_string_inner(code, false) { + // + // PdfCraft patch (4): bf entries don't record how many bytes their code + // has, so the fallback only applies when the codespace ranges give + // the code `byte_len` bytes (ISO 32000-2 §9.7.6.2). Otherwise the + // first byte of `` matched a `<00fe>` entry and a two-byte code + // drew as two glyphs. A CMap with no codespace ranges anywhere uses + // the length the entry's own source code was written with instead. + let length_fits = match self.codespace_allows(code, byte_len, 0) { + Some(allowed) => allowed, + None => self.bf_code_has_length(code, byte_len), + }; + if length_fits + && let Some(BfString::Char(lookup)) = self.lookup_bf_string_inner(code, false) + { return Some(lookup as u32); } @@ -459,6 +473,40 @@ impl CMap { .and_then(|b| b.lookup_cid_code(code, byte_len)) } + /// PdfCraft patch (4): whether this level's bf entry for `code` was written with `byte_len` + /// bytes (`<00fe>` is a two-byte code, not the one-byte ``), or doesn't record its length. + /// Used where no codespace range gives the code its length. + fn bf_code_has_length(&self, code: u32, byte_len: u8) -> bool { + find_in_ranges(&self.bf_entries, code) + .is_some_and(|entry| entry.code_len == 0 || entry.code_len == byte_len) + } + + /// PdfCraft patch (4): whether a code of `byte_len` bytes lies in a codespace range of that + /// length (each byte within the range's bounds for its position, ISO + /// 32000-2 §9.7.6.2). A CMap without codespace ranges defers to its base, + /// and with none anywhere the answer is `None`. + fn codespace_allows(&self, code: u32, byte_len: u8, depth: u32) -> Option { + if self._codespace_ranges.is_empty() { + return match &self.base { + Some(base) if depth < MAX_NESTING_DEPTH => { + base.codespace_allows(code, byte_len, depth.saturating_add(1)) + } + _ => None, + }; + } + + Some(self._codespace_ranges.iter().any(|range| { + range.number_bytes == byte_len + && (0..u32::from(byte_len)).all(|i| { + // `byte_len` is at most 4 here (the range's own length), + // so `shift` is at most 24. + let shift = (u32::from(byte_len) - 1 - i) * 8; + let byte = |v: u32| v.checked_shr(shift).map_or(0, |b| b & 0xFF); + byte(range.low) <= byte(code) && byte(code) <= byte(range.high) + }) + })) + } + /// Look up a bf string in the cmap. This is usually /// used for mapping character codes to Unicode codepoints in a /// `ToUnicode` cmap. @@ -584,6 +632,9 @@ impl PartitionedRanges { pub(crate) struct BfRange { pub(crate) range: Range, pub(crate) dst_base: Vec, + /// PdfCraft patch (4): how many bytes the entry's source code was written with (1 to 4), + /// or 0 where that isn't recorded (a binary CMap). + pub(crate) code_len: u8, } impl HasRange for BfRange { @@ -594,7 +645,6 @@ impl HasRange for BfRange { /// A codespace range defining valid character code byte sequences. #[derive(Debug, Clone)] -#[allow(dead_code)] pub(crate) struct CodespaceRange { pub(crate) number_bytes: u8, pub(crate) low: u32, @@ -1128,6 +1178,96 @@ endbfchar ); } + /// Parse `body` after the metadata of [`PREAMBLE`] but without its + /// codespace ranges. + fn parse_without_codespace(body: &[u8]) -> CMap { + let mut data = Vec::new(); + data.extend_from_slice( + br#"/CIDSystemInfo 3 dict dup begin + /Registry (Adobe) def + /Ordering (Identity) def + /Supplement 0 def +end def +/CMapName /Test def +"#, + ); + data.extend_from_slice(body); + CMap::parse(&data, |_| None).unwrap() + } + + /// PdfCraft patch (4) test: a `bfchar` entry used as a CID mapping matches only + /// codes of the length the codespace ranges give it (ISO 32000-2 §9.7.6.2). + #[test] + fn bfchar_cid_fallback_takes_the_codespace_length() { + let cmap = parse_without_codespace( + br#" +1 begincodespacerange +<0000> +endcodespacerange +2 beginbfchar +<0020> <0020> +<2041> <0042> +endbfchar +"#, + ); + // The first byte of <2041> alone is not a code of this CMap. + assert_eq!(cmap.lookup_cid_code(0x20, 1), None); + assert_eq!(cmap.lookup_cid_code(0x2041, 2), Some(0x42)); + assert_eq!(cmap.lookup_cid_code(0x0020, 2), Some(0x20)); + // ToUnicode-style lookups are unchanged. + assert_eq!(cmap.lookup_bf_string(0x20), Some(BfString::Char(' '))); + } + + /// PdfCraft patch (4) test: mixed codespaces give each code its own length, + /// byte by byte, and a CMap without codespace ranges keeps the fallback. + #[test] + fn bfchar_cid_fallback_checks_each_byte_of_the_codespace() { + let cmap = parse_without_codespace( + br#" +2 begincodespacerange +<00> <80> +<8140> <9FFC> +endcodespacerange +3 beginbfchar +<41> <0041> +<8141> <0100> +<8220> <0101> +endbfchar +"#, + ); + assert_eq!(cmap.lookup_cid_code(0x41, 1), Some(0x41)); + assert_eq!(cmap.lookup_cid_code(0x8141, 2), Some(0x100)); + // 0x8220 lies numerically between 0x8140 and 0x9FFC, but its second + // byte 0x20 is below 0x40. + assert_eq!(cmap.lookup_cid_code(0x8220, 2), None); + + let no_codespace = parse_without_codespace(b"1 beginbfchar <20> <0020> endbfchar\n"); + assert_eq!(no_codespace.lookup_cid_code(0x20, 1), Some(0x20)); + } + + /// PdfCraft patch (4) test: without codespace ranges, a `bfchar` entry used as a CID + /// mapping matches only codes of the length its source was written with, so the first + /// byte of `` is not taken for `<00fe>`. + #[test] + fn bfchar_cid_fallback_without_codespace_takes_the_source_length() { + let cmap = parse_without_codespace( + br#" +2 beginbfchar +<00fe> <0041> + <0042> +endbfchar +1 beginbfrange +<0100> <0102> <0050> +endbfrange +"#, + ); + assert_eq!(cmap.lookup_cid_code(0xfe, 1), None); + assert_eq!(cmap.lookup_cid_code(0xfe96, 2), Some(0x42)); + assert_eq!(cmap.lookup_cid_code(0x00fe, 2), Some(0x41)); + assert_eq!(cmap.lookup_cid_code(0x0101, 2), Some(0x51)); + assert_eq!(cmap.lookup_cid_code(0x0101, 3), None); + } + #[test] fn stream_cut_off_inside_a_block_keeps_the_entries_before_it() { let cmap = parse_with_preamble(b"1 beginbfchar <41> <0058>\n<42> <00"); @@ -1176,6 +1316,60 @@ endbfchar assert!(cmap.lookup_bf_string(0x41).is_some()); } + // PdfCraft patch (3): a token the scanner can't read (a stray `>` after a CMap name, a name + // with spaces in it) is stepped over, so the mappings after it are still read; at most + // `MAX_SKIPPED` of them per CMap. + + #[test] + fn mappings_after_an_unreadable_token_are_read() { + for header in [ + &b"/CMapName /Adobe-Identity-UC> def"[..], + b"/CMapName /-usr-share-fonts-Panton Family - Panton.otf,000-UTF16 def", + ] { + let mut data = header.to_vec(); + data.extend_from_slice( + b"\n1 beginbfchar <41> <0058> endbfchar\n1 beginbfrange <50> <52> <0061> endbfrange", + ); + let cmap = parse_with_preamble(&data); + assert_eq!(cmap.lookup_bf_string(0x41), Some(BfString::Char('X'))); + assert_eq!(cmap.lookup_bf_string(0x51), Some(BfString::Char('b'))); + } + } + + #[test] + fn a_number_run_into_an_operator_does_not_start_its_mappings() { + // `1beginbfchar` is one token, not `1` and `beginbfchar`: the pairs after it are not + // mappings, and the well-formed block after them still reads. + let cmap = parse_with_preamble( + b"1beginbfchar <41> <0058> endbfchar\n1 beginbfchar <42> <0059> endbfchar", + ); + assert_eq!(cmap.lookup_bf_string(0x41), None); + assert_eq!(cmap.lookup_bf_string(0x42), Some(BfString::Char('Y'))); + } + + /// A CMap with `count` unreadable tokens, each after a space, before one `bfchar` mapping. + fn mapping_after_unreadable_tokens(count: usize) -> Option { + let mut data = PREAMBLE.to_vec(); + data.extend_from_slice(&b" >".repeat(count)); + data.extend_from_slice(b"\n1 beginbfchar <41> <0058> endbfchar"); + CMap::parse(&data, |_| None) + } + + #[test] + fn the_scan_steps_over_at_most_max_skipped_unreadable_tokens() { + let limit = parse::MAX_SKIPPED; + let cmap = mapping_after_unreadable_tokens(limit).expect("read up to the limit"); + assert_eq!(cmap.lookup_bf_string(0x41), Some(BfString::Char('X'))); + // One more ends the scan before the mapping, and a CMap with no mappings fails. + assert!(mapping_after_unreadable_tokens(limit + 1).is_none()); + } + + #[test] + fn a_cmap_of_unreadable_tokens_only_reports_failure() { + assert!(CMap::parse(b"> ) >", |_| None).is_none()); + assert!(CMap::parse(&b" >".repeat(4 * parse::MAX_SKIPPED), |_| None).is_none()); + } + #[test] fn bad_bfchar_code_keeps_later_entries_aligned() { // The malformed 5-byte code still has a destination object; both diff --git a/vendor/hayro-cmap/src/parse.rs b/vendor/hayro-cmap/src/parse.rs index a936209275..6bebf1b047 100644 --- a/vendor/hayro-cmap/src/parse.rs +++ b/vendor/hayro-cmap/src/parse.rs @@ -15,6 +15,9 @@ struct Context { get_cmap: F, } +/// PdfCraft patch (3): most unreadable tokens one CMap may step over before its scan stops. +pub(crate) const MAX_SKIPPED: usize = 1024; + pub(crate) fn parse_inner<'a>( data: &[u8], get_cmap: impl Fn(CMapName<'_>) -> Option<&'a [u8]> + Clone + 'a, @@ -61,10 +64,20 @@ pub(crate) fn parse_inner<'a>( // must see failure rather than an empty map, so its encoding fallback // paths run exactly as they did before the tolerant-usecmap change. let mut usecmap_failed = false; + let mut skipped = 0usize; while !scanner.at_end() { - let Ok(obj) = scanner.parse_object() else { + // PdfCraft patch (3): a token that can't be read (a stray `>` after a CMap name, a + // name with spaces in it, both written into ToUnicode CMaps) is stepped over, so the + // mappings after it are still read; it used to end the scan before any of them. + // At most `MAX_SKIPPED` such tokens: a failed read may scan to the end of the data (an + // unclosed string), so a stream of them would cost its length squared. + let Ok(obj) = scanner.parse_object_or_skip() else { truncated = true; - break; + skipped += 1; + if skipped > MAX_SKIPPED { + break; + } + continue; }; let Object::Name(name) = &obj else { continue }; @@ -333,6 +346,8 @@ fn parse_bf_char( let _ = scanner.parse_object(); continue; }; + // PdfCraft patch (4): 1 to 4 (`extract_u32_code` checked). + let code_len = u8::try_from(ctx.buf.len()).unwrap_or(0); let Ok(dst) = scanner.parse_string() else { continue }; if dst.decode_into(&mut ctx.buf).is_err() { continue } let Some(dst_base) = decode_be(&ctx.buf) else { continue }; @@ -343,6 +358,7 @@ fn parse_bf_char( end: code, }, dst_base, + code_len, }); } } @@ -367,6 +383,8 @@ fn parse_bf_range( let _ = scanner.parse_object(); continue; }; + // PdfCraft patch (4): 1 to 4 (`extract_u32_code` checked). + let code_len = u8::try_from(ctx.buf.len()).unwrap_or(0); let Some(end) = read_u32_code(scanner, &mut ctx.buf) else { // Skip the destination object as well to stay aligned. let _ = scanner.parse_object(); @@ -383,6 +401,7 @@ fn parse_bf_range( entries.push(BfRange { range: Range { start, end }, dst_base, + code_len, }); } Object::Array(array) => { @@ -403,6 +422,7 @@ fn parse_bf_range( end: code, }, dst_base, + code_len, }); } } diff --git a/vendor/hayro-interpret/Cargo.lock b/vendor/hayro-interpret/Cargo.lock index c10e174988..fee8cbd0f9 100644 --- a/vendor/hayro-interpret/Cargo.lock +++ b/vendor/hayro-interpret/Cargo.lock @@ -146,9 +146,9 @@ dependencies = [ [[package]] name = "font-types" -version = "0.11.3" +version = "0.12.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" dependencies = [ "bytemuck", ] @@ -297,6 +297,12 @@ dependencies = [ "autocfg", ] +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "phf" version = "0.13.1" @@ -387,12 +393,13 @@ dependencies = [ [[package]] name = "read-fonts" -version = "0.39.2" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81" +checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8" dependencies = [ "bytemuck", "font-types", + "once_cell", ] [[package]] @@ -415,9 +422,9 @@ checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e" [[package]] name = "skrifa" -version = "0.42.1" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564" +checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f" dependencies = [ "bytemuck", "read-fonts", diff --git a/vendor/hayro-interpret/Cargo.toml b/vendor/hayro-interpret/Cargo.toml index 8141e63df3..a3b936176c 100644 --- a/vendor/hayro-interpret/Cargo.toml +++ b/vendor/hayro-interpret/Cargo.toml @@ -59,7 +59,7 @@ version = "0.1.0" default-features = false [dependencies.hayro-syntax] -version = "0.7.0" +version = "0.7.2" features = [ "std", "images", diff --git a/vendor/hayro-interpret/src/cache.rs b/vendor/hayro-interpret/src/cache.rs index d2be754309..b3fc0d5fa0 100644 --- a/vendor/hayro-interpret/src/cache.rs +++ b/vendor/hayro-interpret/src/cache.rs @@ -1,17 +1,19 @@ use crate::util::hash128; +use crate::{InterpreterWarning, WarningSinkFn}; use hayro_syntax::object::{Array, Dict, MaybeRef, Name, Null, ObjRef, Object, Stream}; use kurbo::Affine; use std::any::Any; use std::collections::HashMap; use std::collections::hash_map::Entry; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; type CacheMap = HashMap>>; -/// The objects read from a document, by key. PdfCraft patch (#3020): the second field counts -/// the ICC profiles read through it ([`Cache::icc_profile_reads`]). +/// The objects read from a document, by key. PdfCraft patch (48): the second field counts the +/// ICC profiles read through it ([`Cache::icc_profile_reads`]). PdfCraft patch (80): the third +/// counts the `/Indexed` lookup tables read ([`Cache::indexed_lookup_reads`]). #[derive(Clone)] -pub(crate) struct Cache(Arc>, Arc); +pub(crate) struct Cache(Arc>, Arc, Arc); impl Default for Cache { fn default() -> Self { Self::new() @@ -20,20 +22,35 @@ impl Default for Cache { impl Cache { pub(crate) fn new() -> Self { - Self(Arc::new(Mutex::new(HashMap::new())), Arc::default()) + Self( + Arc::new(Mutex::new(HashMap::new())), + Arc::default(), + Arc::default(), + ) } - /// PdfCraft patch (#3020): count one ICC profile read, the color space of an `/ICCBased` + /// PdfCraft patch (48): count one ICC profile read, the colour space of an `/ICCBased` /// profile no entry held yet being built from it. pub(crate) fn count_icc_profile_read(&self) { self.1.fetch_add(1, Ordering::Relaxed); } - /// PdfCraft patch (#3020): how many ICC profiles were read through this cache. + /// PdfCraft patch (48): how many ICC profiles were read through this cache. pub(crate) fn icc_profile_reads(&self) -> usize { self.1.load(Ordering::Relaxed) } + /// PdfCraft patch (80): count one `/Indexed` lookup table read (a stream decoded or a + /// string copied). + pub(crate) fn count_indexed_lookup_read(&self) { + self.2.fetch_add(1, Ordering::Relaxed); + } + + /// PdfCraft patch (80): how many `/Indexed` lookup tables were read through this cache. + pub(crate) fn indexed_lookup_reads(&self) -> usize { + self.2.load(Ordering::Relaxed) + } + pub(crate) fn get_or_insert_with( &self, id: u128, @@ -69,6 +86,17 @@ impl Cache { /// them; when an insert would pass the budget the whole map is dropped (a fresh epoch), which /// only costs re-decoding, and an image larger than the whole budget is never kept. The budget /// caps memory per interpreter cache. A poisoned lock decodes without the cache. +/// +/// PdfCraft patch (91): a decode that fails is kept too, as the warnings it reported, so an +/// image drawn again and again that doesn't decode (damaged data, a JPX or JBIG2 stream its +/// decoder refuses) isn't decoded again at every draw: a later draw reports the same warnings +/// and gets nothing, as the decode did. A failure counts [`FAILED_DECODE_BYTES`] towards the +/// budget, so failures can't grow the map without bound either. A failure that may come from +/// what the page had left (its JBIG2 allowance, `ContentTruncated`) isn't kept: another page, +/// or the same page drawn again, starts with a fresh allowance. One that left out a JBIG2 mask +/// for a limit its stream reaches by itself is kept, with the image it takes along (patch 73, +/// [`note_stream_limited`]): decoding them again would only refuse them again, and an image of +/// any size under such a mask was decoded again at every draw. #[derive(Clone)] pub(crate) struct DecodedImageCache { inner: Arc>, @@ -88,8 +116,8 @@ pub(crate) struct DecodedImageCache { /// - whether it is decoded as a mask, a stencil mask, raster or mask output, interpolation, /// the decode target size (only for an image a JPX stream decodes, which is the only /// decode that reads it: PdfCraft patch 32), and preview or final quality; -/// - the default color space drawn in place of the image's device space, if any (the cache -/// key of its object, PdfCraft patch #3018): the same image can be drawn by resources with a +/// - the default colour space drawn in place of the image's device space, if any (the cache +/// key of its object, PdfCraft patch 38): the same image can be drawn by resources with a /// `/DefaultRGB` and by resources without one. /// /// A transfer function (graphics state `/TR`) also changes the pixels and has no cheap key, so @@ -108,14 +136,71 @@ pub(crate) struct DecodedImageKey { pub(crate) default_space: Option, pub(crate) target: Option<(u32, u32)>, pub(crate) preview: bool, + /// PdfCraft patch (82): the size a soft mask far larger than where it is drawn was averaged + /// down to (`ImageXObject::decoded_soft_mask`), `None` for a mask kept at its own size. + pub(crate) shrunk_to: Option<(u32, u32)>, +} + +/// PdfCraft patch (91): what the budget charges for a failed decode, about what its key and +/// entry take in the map. +const FAILED_DECODE_BYTES: usize = 128; + +/// PdfCraft patch (91): with the warnings of a failure kept, that it left out a JBIG2 mask for a +/// limit its stream reaches by itself ([`note_stream_limited`]); no warning's flag. +const STREAM_LIMITED: u8 = 128; + +std::thread_local! { + static LEFT_OUT_BY_STREAM_LIMIT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// PdfCraft patch (73): note, wherever a decode reports `ContentTruncated` for an image or a kept +/// failure replays it, whether that left out a JBIG2 mask for a limit its stream reaches by itself +/// (`hayro_syntax::jbig2_limited_by_stream`): its failure, and the failure of the image it takes +/// along, is then the stream's to keep, since decoding it again refuses it again. +pub(crate) fn note_stream_limited(limited: bool) { + LEFT_OUT_BY_STREAM_LIMIT.with(|left_out| left_out.set(limited)); +} + +fn stream_limited() -> bool { + LEFT_OUT_BY_STREAM_LIMIT.with(std::cell::Cell::get) +} + +/// PdfCraft patch (91): what a [`DecodedImageCache`] keeps for a key. +enum DecodedEntry { + /// The decoded image. + Decoded(Box), + /// The decode failed, reporting these warnings ([`warning_bit`] flags). + Failed(u8), +} + +/// PdfCraft patch (91): `warning` as a flag in a set of warnings. +fn warning_bit(warning: InterpreterWarning) -> u8 { + match warning { + InterpreterWarning::UnsupportedFont => 1, + InterpreterWarning::ImageDecodeFailure => 2, + InterpreterWarning::ContentTruncated => 4, + } +} + +/// PdfCraft patch (91): the warnings in a set of [`warning_bit`] flags. +fn warnings_in(bits: u8) -> impl Iterator { + [ + InterpreterWarning::UnsupportedFont, + InterpreterWarning::ImageDecodeFailure, + InterpreterWarning::ContentTruncated, + ] + .into_iter() + .filter(move |warning| bits & warning_bit(*warning) != 0) } #[derive(Default)] struct DecodedImageCacheInner { - map: HashMap>>, + map: HashMap, bytes: usize, /// PdfCraft patch (32): how many keyed decodes ran (cache misses). decodes: usize, + /// PdfCraft patch (82): how many of `decodes` were of masks (keys with `mask_output`). + mask_decodes: usize, } impl DecodedImageCache { @@ -132,6 +217,15 @@ impl DecodedImageCache { self.inner.lock().map(|locked| locked.decodes).unwrap_or(0) } + /// PdfCraft patch (82): how many of [`Self::decodes`] were of soft masks and `/Mask` images, + /// for tests. 0 when the lock is poisoned. + pub(crate) fn mask_decodes(&self) -> usize { + self.inner + .lock() + .map(|locked| locked.mask_decodes) + .unwrap_or(0) + } + /// The same cache, for a preview (`true`) or a final render. pub(crate) fn for_render(&self, preview: bool) -> Self { Self { @@ -140,44 +234,77 @@ impl DecodedImageCache { } } - /// The decoded image for `key`, from the cache or from `f`. `None` as the key decodes - /// without the cache. + /// The decoded image for `key`, from the cache or from `f`, which decodes reporting its + /// warnings to the sink it is handed. `None` as the key decodes without the cache. + /// PdfCraft patch (91): `sink` gets the warnings of the decode, or those of the failed + /// decode kept for `key`. pub(crate) fn get_or_insert_with( &self, key: Option, budget: usize, size_of: impl FnOnce(&T) -> usize, - f: impl FnOnce() -> Option, + sink: &WarningSinkFn, + f: impl FnOnce(&WarningSinkFn) -> Option, ) -> Option { - let Some(key) = key else { return f() }; - // Fast path: a hit clones the pixels without decoding. + let Some(key) = key else { return f(sink) }; + // Fast path: a hit clones the pixels without decoding, and a kept failure reports its + // warnings again without decoding. let hit = match self.inner.lock() { - Ok(locked) => locked - .map - .get(&key) - .and_then(|val| val.as_ref()) - .and_then(|val| val.downcast_ref::().cloned()), + Ok(locked) => match locked.map.get(&key) { + Some(DecodedEntry::Decoded(val)) => val.downcast_ref::().cloned().map(Ok), + Some(DecodedEntry::Failed(bits)) => Some(Err(*bits)), + None => None, + }, // A thread panicked while holding the lock: decode without the cache. - Err(_) => return f(), + Err(_) => return f(sink), }; - if let Some(hit) = hit { - return Some(hit); + match hit { + Some(Ok(hit)) => return Some(hit), + Some(Err(bits)) => { + note_stream_limited(bits & STREAM_LIMITED != 0); + warnings_in(bits).for_each(|warning| sink(warning)); + return None; + } + None => {} } - // Miss: decode without holding the lock (decoding must never deadlock the cache). - let val = f(); + // Miss: decode without holding the lock (decoding must never deadlock the cache), + // noting the warnings it reports. + let reported = Arc::new(AtomicU8::new(0)); + let recording: WarningSinkFn = { + let (reported, sink) = (reported.clone(), sink.clone()); + Arc::new(move |warning| { + reported.fetch_or(warning_bit(warning), Ordering::Relaxed); + sink(warning); + }) + }; + let val = f(&recording); + let reported = reported.load(Ordering::Relaxed); let Ok(mut locked) = self.inner.lock() else { return val; }; locked.decodes = locked.decodes.saturating_add(1); - // Another thread may have decoded it meanwhile: keep the first copy. - if let Some(existing) = locked.map.get(&key) - && let Some(existing) = existing.as_ref().and_then(|val| val.downcast_ref::()) - { - return Some(existing.clone()); + if key.mask_output { + locked.mask_decodes = locked.mask_decodes.saturating_add(1); } + // Another thread may have decoded it meanwhile: keep the first copy. + match locked.map.get(&key) { + Some(DecodedEntry::Decoded(existing)) => { + if let Some(existing) = existing.downcast_ref::() { + return Some(existing.clone()); + } + } + Some(DecodedEntry::Failed(_)) if val.is_none() => return None, + _ => {} + } + let truncated = reported & warning_bit(InterpreterWarning::ContentTruncated) != 0; let size = match &val { Some(v) => size_of(v), - None => 0, + // A failure the page's JBIG2 allowance may have caused isn't the image's to keep, nor + // one a JBIG2 decode's work did, which may be the page's too. + None if hayro_syntax::page_jbig2_work_spent() || (truncated && !stream_limited()) => { + return None; + } + None => FAILED_DECODE_BYTES, }; if size > budget { return val; @@ -186,12 +313,16 @@ impl DecodedImageCache { locked.map.clear(); locked.bytes = 0; } + let entry = match &val { + Some(val) => DecodedEntry::Decoded(Box::new(val.clone())), + // Here only when a limit of its stream refused the mask that left it out (above). + None if truncated => DecodedEntry::Failed(reported | STREAM_LIMITED), + None => DecodedEntry::Failed(reported), + }; + // An entry replaced (a failure another thread kept) isn't given back: the budget + // errs towards a fresh epoch. locked.bytes = locked.bytes.saturating_add(size); - locked.map.insert( - key, - val.clone() - .map(|val| Box::new(val) as Box), - ); + locked.map.insert(key, entry); val } } diff --git a/vendor/hayro-interpret/src/cmyk_group.rs b/vendor/hayro-interpret/src/cmyk_group.rs new file mode 100644 index 0000000000..f791895798 --- /dev/null +++ b/vendor/hayro-interpret/src/cmyk_group.rs @@ -0,0 +1,100 @@ +//! PdfCraft patch (70): an isolated transparency group that blends in `DeviceCMYK`. +//! +//! ISO 32000-2 §11.3.4: a group's elements blend in the group's colour space, and the +//! components of a subtractive space are complemented before the blend function and +//! complemented back after it. The renderer composites in RGB, which gives other colours +//! wherever a blend mode meets CMYK artwork: `0 1 0 0 k` (magenta) under `0 0 0 1 k` (black) +//! with `/BM /Difference` is green when blended in CMYK (`|(1,0,1,1) − (1,1,1,0)|` +//! complemented back is `1 0 1 0`) and magenta when blended in RGB. +//! +//! An *isolated* group starts from a transparent backdrop of its own (§11.4.7), so its +//! interior can be computed apart from the page and handed back as finished pixels. A device +//! that can blend in CMYK takes such a group through [`Device::draw_isolated_cmyk_group`] and +//! interprets it with [`CmykGroup::interpret`] as often as it needs; every other device, and a +//! device that declines, gets the group's contents as before. + +use crate::InterpreterSettings; +use crate::context::{Context, InterpreterCache}; +use crate::device::Device; +use crate::interpret::state::{ClipType, State}; +use crate::x_object::{FormXObject, interpret_form_contents}; +use hayro_syntax::object::dict::keys::{CS, GROUP}; +use hayro_syntax::object::{Dict, Name}; +use hayro_syntax::page::Resources; +use hayro_syntax::xref::XRef; +use kurbo::{Affine, Rect, Shape}; +use std::ops::Deref; + +/// An isolated, non-knockout transparency group whose blending colour space is `DeviceCMYK`, +/// captured where it is painted (PdfCraft patch (70); see the module documentation). +pub struct CmykGroup<'a, 'b> { + form: &'b FormXObject<'a>, + resources: &'b Resources<'a>, + /// The graphics state the group's contents start with: the state at `Do`, after the + /// form's `/Matrix`, with the group's own opacity, soft mask and blend mode already taken + /// by the layer the group is composited through. + state: State<'a>, + root_transform: Affine, + bbox: Rect, + interpreter_cache: InterpreterCache<'a>, + settings: InterpreterSettings, + xref: &'a XRef, + nesting_depth: u32, +} + +impl<'a, 'b> CmykGroup<'a, 'b> { + pub(crate) fn new(form: &'b FormXObject<'a>, resources: &'b Resources<'a>, context: &Context<'a>) -> Self { + let mut state = context.get().clone(); + // The clips in force belong to the device the group is composited onto; contents + // interpreted on their own push and pop only the clips they set themselves. + state.clips = Vec::::new(); + Self { + form, + resources, + state, + root_transform: context.root_transform(), + bbox: context.bbox(), + interpreter_cache: context.interpreter_cache.clone(), + settings: context.settings.clone(), + xref: context.xref, + nesting_depth: context.nesting_depth(), + } + } + + /// The device-space box the group can paint: its `/BBox` under the current transform, + /// within the area being drawn. + pub fn device_bbox(&self) -> Rect { + let [x0, y0, x1, y1] = self.form.bbox; + let user = Rect::new(x0 as f64, y0 as f64, x1 as f64, y1 as f64); + let device = (self.state.ctm * user.to_path(0.1)).bounding_box(); + device.intersect(self.bbox) + } + + /// Interpret the group's contents into `device`, with device space moved by `offset` + /// (so a device covering only [`Self::device_bbox`] can start at its corner). + pub fn interpret(&self, device: &mut impl Device<'a>, offset: (f64, f64)) { + let shift = Affine::translate((-offset.0, -offset.1)); + let mut state = self.state.clone(); + state.ctm = shift * state.ctm; + let mut context = Context::new_with( + shift * self.root_transform, + shift.transform_rect_bbox(self.bbox), + &self.interpreter_cache, + self.xref, + self.settings.clone(), + state, + self.nesting_depth, + ); + interpret_form_contents(self.resources, self.form, &mut context, device); + } +} + +/// Whether `form`'s transparency group blends in `DeviceCMYK`: it says so in its `/CS`. +pub(crate) fn blends_in_device_cmyk(form: &Dict<'_>) -> bool { + form.get::>(GROUP).and_then(|g| g.get::>(CS)).is_some_and(|cs| matches!(cs.deref(), b"DeviceCMYK" | b"CMYK")) +} + +/// Whether `form`'s transparency group names a blending colour space of its own (`/CS`). +pub(crate) fn names_a_blending_space(form: &Dict<'_>) -> bool { + form.get::>(GROUP).is_some_and(|g| g.contains_key(CS)) +} diff --git a/vendor/hayro-interpret/src/cmyk_inverse.rs b/vendor/hayro-interpret/src/cmyk_inverse.rs new file mode 100644 index 0000000000..74804f92a7 --- /dev/null +++ b/vendor/hayro-interpret/src/cmyk_inverse.rs @@ -0,0 +1,118 @@ +//! PdfCraft patch (104): an sRGB colour as the process ink that draws back to it through the +//! CMYK profile pages are drawn with, for an additive colour painted into a `DeviceCMYK` +//! blending space (ISO 32000-2 §11.3.4). +//! +//! Black is `K = 0.4 · k₀² + 0.6 · k₀⁸` with `k₀ = 1 − max(r, g, b)`, light in the mid tones +//! and full for black; cyan, magenta and yellow are then solved for by Newton's method at that +//! black, clamped to the ink range. A colour inside the profile's gamut draws as itself; one +//! outside it lands where the clamped solve stops. The curve matches Acrobat's output for the +//! greys, black and red measured in a CMYK page group, plain and under a blend mode; +//! §10.4.2.4's black generation and undercolour removal is for a device without a profile. + +use moxcms::{ColorProfile, Layout, TransformF32Executor, TransformOptions}; +use std::cell::Cell; +use std::sync::{Arc, LazyLock}; + +use crate::color::CMYK_PROFILE; + +/// The weight of `k₀²` in the black ink; the rest is on `k₀⁸`. +const BLACK_GENERATION: f32 = 0.4; +/// Newton steps; each costs four profile evaluations. +const MAX_STEPS: usize = 12; +/// Close enough: well under one 8-bit level. +const TOLERANCE: f32 = 0.5 / 255.0; +/// The finite-difference step for the Jacobian. +const STEP: f32 = 0.02; + +static FORWARD: LazyLock>> = LazyLock::new(|| { + ColorProfile::new_from_slice(CMYK_PROFILE) + .ok()? + .create_transform_f32( + Layout::Rgba, + &ColorProfile::new_srgb(), + Layout::Rgb, + TransformOptions::default(), + ) + .ok() +}); + +/// The process ink `[C, M, Y, K]` (0 = no ink) that the CMYK profile draws as `rgb`; for a +/// colour outside its gamut, where the clamped solve stops. `None` when the +/// profile can't be evaluated or `rgb` isn't finite. +/// +/// The last colour converted on this thread is kept, as a run of fills (the glyphs of a +/// line of text) usually shares one colour. +pub(crate) fn srgb_to_cmyk(rgb: [f32; 3]) -> Option<[f32; 4]> { + if !rgb.iter().all(|v| v.is_finite()) { + return None; + } + let rgb = rgb.map(|v| v.clamp(0.0, 1.0)); + let key = rgb.map(f32::to_bits); + if let Some((last, ink)) = LAST.get() + && last == key + { + return Some(ink); + } + let ink = solve_ink(rgb)?; + LAST.set(Some((key, ink))); + Some(ink) +} + +thread_local! { + static LAST: Cell> = const { Cell::new(None) }; +} + +fn solve_ink(rgb: [f32; 3]) -> Option<[f32; 4]> { + let forward: &TransformF32Executor = FORWARD.as_ref()?.as_ref(); + let k0 = 1.0 - rgb[0].max(rgb[1]).max(rgb[2]); + let k = BLACK_GENERATION * k0 * k0 + (1.0 - BLACK_GENERATION) * k0.powi(8); + let eval = |cmy: [f32; 3]| draw(forward, [cmy[0], cmy[1], cmy[2], k]); + + let mut cmy = rgb.map(|v| 1.0 - v); + for _ in 0..MAX_STEPS { + let drawn = eval(cmy)?; + let residual: [f32; 3] = std::array::from_fn(|i| drawn[i] - rgb[i]); + if residual.iter().all(|r| r.abs() < TOLERANCE) { + break; + } + // Column `j` of the Jacobian: how the drawn colour moves with ink `j`. + let mut columns = [[0.0_f32; 3]; 3]; + for (j, column) in columns.iter_mut().enumerate() { + let step = if cmy[j] <= 1.0 - STEP { STEP } else { -STEP }; + let mut moved = cmy; + moved[j] += step; + let shifted = eval(moved)?; + *column = std::array::from_fn(|i| (shifted[i] - drawn[i]) / step); + } + let Some(delta) = solve(columns, residual.map(|r| -r)) else { + break; + }; + cmy = std::array::from_fn(|i| (cmy[i] + delta[i]).clamp(0.0, 1.0)); + } + Some([cmy[0], cmy[1], cmy[2], k]) +} + +fn draw(forward: &TransformF32Executor, cmyk: [f32; 4]) -> Option<[f32; 3]> { + let mut out = [0.0_f32; 3]; + forward.transform(&cmyk, &mut out).ok()?; + out.iter().all(|v| v.is_finite()).then_some(out) +} + +/// `x` with `A x = b`, `A` given by its columns (Cramer's rule). `None` when `A` is +/// singular or the result isn't finite. +fn solve(a: [[f32; 3]; 3], b: [f32; 3]) -> Option<[f32; 3]> { + let det = |[c0, c1, c2]: [[f32; 3]; 3]| { + c0[0] * (c1[1] * c2[2] - c2[1] * c1[2]) - c1[0] * (c0[1] * c2[2] - c2[1] * c0[2]) + + c2[0] * (c0[1] * c1[2] - c1[1] * c0[2]) + }; + let d = det(a); + if !d.is_finite() || d.abs() < 1e-9 { + return None; + } + let x: [f32; 3] = std::array::from_fn(|j| { + let mut m = a; + m[j] = b; + det(m) / d + }); + x.iter().all(|v| v.is_finite()).then_some(x) +} diff --git a/vendor/hayro-interpret/src/color.rs b/vendor/hayro-interpret/src/color.rs index 48141a9d52..8b9aaefb34 100644 --- a/vendor/hayro-interpret/src/color.rs +++ b/vendor/hayro-interpret/src/color.rs @@ -28,6 +28,22 @@ pub type ColorComponents = SmallVec<[f32; 4]>; std::thread_local! { // PdfCraft patch (34): see `tint_transform_runs`. static TINT_TRANSFORM_RUNS: core::cell::Cell = const { core::cell::Cell::new(0) }; + // PdfCraft patch (55): see `note_color_fallback`. + static COLOR_FALLBACK: core::cell::Cell = const { core::cell::Cell::new(false) }; +} + +/// PdfCraft patch (55): record that a colour could not be computed and was painted in a +/// fallback colour, reported as `InterpreterWarning::ColorFallback` when the content stream +/// being interpreted ends. Per thread, like the page's other budgets: one page is interpreted +/// on one thread. +pub(crate) fn note_color_fallback() { + COLOR_FALLBACK.with(|fell_back| fell_back.set(true)); +} + +/// PdfCraft patch (55): whether a colour fell back since the last call (or since the page +/// started), clearing it, so each fallback is reported once. +pub(crate) fn take_color_fallback() -> bool { + COLOR_FALLBACK.with(|fell_back| fell_back.replace(false)) } /// PdfCraft patch (34): how many colours this thread has run through a Separation or DeviceN @@ -124,10 +140,10 @@ pub(crate) enum ColorSpaceType { Plate(PlateSpace), } -/// PdfCraft patch (#3020): what the color space read from an `/ICCBased` profile stream is -/// cached by. hayro keyed it by the stream dictionary's bytes alone, so two different profiles -/// with the same `/N` and `/Length` shared whichever was read first, and colors in the second -/// were drawn through the first. +/// PdfCraft patch (48): what the colour space read from an `/ICCBased` profile stream is cached +/// by. hayro keyed it by the stream dictionary's bytes alone, so two different profiles with the +/// same `/N` and `/Length` shared whichever was read first, and colours in the second were +/// drawn through the first. #[derive(Hash)] enum IccProfileKey<'a> { /// The stream object a space names, looked up without reading the stream: an object holds @@ -140,10 +156,10 @@ enum IccProfileKey<'a> { Content { dict: u128, data: &'a [u8] }, } -/// PdfCraft patch (#3020): the object of the `/ICCBased` profile `stream` that `array` names, -/// or `None` for a stream written directly in the array (its dictionary lies within the -/// array's bytes). Such a stream has no object of its own: its dictionary reports the object -/// that holds the array, which every other stream written there reports too. +/// PdfCraft patch (48): the object of the `/ICCBased` profile `stream` that `array` names, or +/// `None` for a stream written directly in the array (its dictionary lies within the array's +/// bytes). Such a stream has no object of its own: its dictionary reports the object that +/// holds the array, which every other stream written there reports too. fn icc_stream_object(array: &Array<'_>, stream: &Stream<'_>) -> Option { let dict = stream.dict(); if array.data().as_ptr_range().contains(&dict.data().as_ptr()) { @@ -152,23 +168,24 @@ fn icc_stream_object(array: &Array<'_>, stream: &Stream<'_>) -> Option, cache: &Cache, depth: u8) -> Option { + fn new(object: Object<'_>, cache: &Cache, depth: u32) -> Option { if depth >= MAX_COLOR_SPACE_DEPTH { - warn!("color space nesting depth exceeded"); - + warn!("colour spaces nest past the limit of {MAX_COLOR_SPACE_DEPTH} levels"); return None; } Self::new_inner(object, cache, depth) } - fn new_inner(object: Object<'_>, cache: &Cache, depth: u8) -> Option { + fn new_inner(object: Object<'_>, cache: &Cache, depth: u32) -> Option { if let Object::Name(name) = object { return Self::new_from_name(&name); } else if let Object::Array(color_array) = object { @@ -181,8 +198,11 @@ impl ColorSpaceType { let dict = icc_stream.dict(); let num_components = dict.get::(N)?; - // PdfCraft patch (#3020): cached by what the profile is read from (see + // PdfCraft patch (48): cached by what the profile is read from (see // `IccProfileKey`), not by the stream dictionary's bytes alone. + // PdfCraft patch (74): what's kept is what the profile itself reads as. What + // it falls back to depends on how deep it was met, and kept with the profile + // a page could build a chain past the limit on spaces already read. let read = || { let data = icc_stream.raw_data(); let content = IccProfileKey::Content { @@ -191,40 +211,37 @@ impl ColorSpaceType { }; cache.get_or_insert_with(hash128(&content), || { cache.count_icc_profile_read(); - if let Some(decoded) = icc_stream.decoded().ok().as_ref() { - ICCProfile::new(decoded, num_components) - .map(|icc| { - // TODO: For SVG and PNG we can assume that the output color space is - // sRGB. If we ever implement PDF-to-PDF, we probably want to - // let the user pass the native color type and don't make this optimization - // if it's not sRGB. - if icc.is_srgb() { - Self::DeviceRgb - } else { - Self::ICCBased(icc) - } - }) - .or_else(|| { - dict.get::>(ALTERNATE) - .and_then(|o| Self::new(o, cache, depth + 1)) - }) - .or_else(|| match dict.get::(N) { - Some(1) => Some(Self::DeviceGray), - Some(3) => Some(Self::DeviceRgb), - Some(4) => Some(Self::DeviceCmyk), - _ => None, - }) - } else { - None - } + let decoded = icc_stream.decoded().ok()?; + Some(ICCProfile::new(&decoded, num_components).map(|icc| { + // TODO: For SVG and PNG we can assume that the output color space is + // sRGB. If we ever implement PDF-to-PDF, we probably want to + // let the user pass the native color type and don't make this optimization + // if it's not sRGB. + if icc.is_srgb() { + Self::DeviceRgb + } else { + Self::ICCBased(icc) + } + })) }) }; - return match icc_stream_object(&color_array, &icc_stream) { + let profile = match icc_stream_object(&color_array, &icc_stream) { Some(object) => { cache.get_or_insert_with(hash128(&IccProfileKey::Object(object)), read) } None => read(), }; + return profile? + .or_else(|| { + dict.get::>(ALTERNATE) + .and_then(|o| Self::new(o, cache, depth + 1)) + }) + .or_else(|| match dict.get::(N) { + Some(1) => Some(Self::DeviceGray), + Some(3) => Some(Self::DeviceRgb), + Some(4) => Some(Self::DeviceCmyk), + _ => None, + }); } CALCMYK => return Some(Self::DeviceCmyk), CALGRAY => { @@ -243,7 +260,7 @@ impl ColorSpaceType { return Some(Self::Lab(Lab::new(&lab_dict)?)); } INDEXED | I => { - return Some(Self::Indexed(Indexed::new(&color_array, cache, depth)?)); + return Some(Self::Indexed(Indexed::new(&color_array, cache, depth, false)?)); } SEPARATION => { return Some(Self::Separation(Separation::new(&color_array, cache, depth)?)); @@ -252,10 +269,11 @@ impl ColorSpaceType { return Some(Self::DeviceN(DeviceN::new(&color_array, cache, depth)?)); } PATTERN => { - let _ = iter.next::>(); + // PdfCraft patch (72): the family is already read. Reading a name here too took + // the underlying space when it was a name or a reference. let cs = iter .next::>() - .and_then(|o| ColorSpace::new_nested(o, cache, depth + 1)) + .and_then(|o| ColorSpace::within(o, cache, depth + 1)) .unwrap_or(ColorSpace::device_rgb()); return Some(Self::Pattern(cs)); } @@ -288,14 +306,30 @@ pub struct ColorSpace(Arc); impl ColorSpace { /// Create a new color space from the given object. pub(crate) fn new(object: Object<'_>, cache: &Cache) -> Option { - Self::new_nested(object, cache, 0) + Self::within(object, cache, 0) } - /// PdfCraft patch: a color space found `depth` levels inside others. - fn new_nested(object: Object<'_>, cache: &Cache, depth: u8) -> Option { + /// A colour space named by another, `depth` levels down. + fn within(object: Object<'_>, cache: &Cache, depth: u32) -> Option { Some(Self(Arc::new(ColorSpaceType::new(object, cache, depth)?))) } + /// PdfCraft patch (80): as `new`, except that an `/Indexed` space with no lookup table is + /// built (marked tableless) rather than unreadable, for the image and colour operators to + /// handle it (see `Indexed::new`). Every other space is read as by `new`. + pub(crate) fn new_allowing_tableless(object: Object<'_>, cache: &Cache) -> Option { + if let Object::Array(array) = &object + && array + .flex_iter() + .next::>() + .is_some_and(|family| matches!(family.deref(), INDEXED | I)) + { + return Indexed::new(array, cache, 0, true) + .map(|indexed| Self(Arc::new(ColorSpaceType::Indexed(indexed)))); + } + Self::new(object, cache) + } + /// Create a new color space from the name. pub(crate) fn new_from_name(name: &Name<'_>) -> Option { ColorSpaceType::new_from_name(name).map(|c| Self(Arc::new(c))) @@ -343,6 +377,18 @@ impl ColorSpace { } } + /// PdfCraft patch (80): whether this is an indexed colour space that broke ISO 32000-2 + /// §8.6.6.3 and was recovered (see `Indexed::new`). + pub(crate) fn is_recovered_indexed(&self) -> bool { + matches!(self.0.as_ref(), ColorSpaceType::Indexed(i) if i.recovered && !i.tableless) + } + + /// PdfCraft patch (80): whether this is an indexed colour space with no lookup table (see + /// `Indexed::new`), which only `ColorSpace::new_allowing_tableless` builds. + pub(crate) fn is_tableless_indexed(&self) -> bool { + matches!(self.0.as_ref(), ColorSpaceType::Indexed(i) if i.tableless) + } + /// Get the default decode array for the color space. pub(crate) fn default_decode_arr(&self, n: f32) -> SmallVec<[(f32, f32); 4]> { match self.0.as_ref() { @@ -429,7 +475,7 @@ impl ColorSpace { .unwrap_or(AlphaColor::BLACK) } - /// PdfCraft patch (#3018): whether this space can be the default color space of `family` + /// PdfCraft patch (38): whether this space can be the default colour space of `family` /// (ISO 32000-2 §8.6.5.6): it has as many components as the device space and is not a /// Lab, Indexed or Pattern space. Nor is a device space: a default that names one is /// ignored, so substitution never recurses. @@ -446,8 +492,8 @@ impl ColorSpace { } } -/// PdfCraft patch (#3018): a device color space (ISO 32000-2 §8.6.4), which the resources' -/// default color space for it replaces wherever content selects it (§8.6.5.6). +/// PdfCraft patch (38): a device colour space (ISO 32000-2 §8.6.4), which the resources' +/// default colour space for it replaces wherever content selects it (§8.6.5.6). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum DeviceFamily { Gray, @@ -456,9 +502,9 @@ pub(crate) enum DeviceFamily { } impl DeviceFamily { - /// The device space a color space operand names: `/DeviceGray`, `/DeviceRGB` or + /// The device space a colour space operand names: `/DeviceGray`, `/DeviceRGB` or /// `/DeviceCMYK` (or an abbreviation read as one), alone or at the head of an array. `None` - /// for any other space, including the ICC-based and calibrated ones drawn as device color + /// for any other space, including the ICC-based and calibrated ones drawn as device colour /// here (an sRGB profile, `/CalCMYK`): they are not device spaces. pub(crate) fn of_object(object: &Object<'_>) -> Option { match object { @@ -508,19 +554,17 @@ impl DeviceFamily { } } -/// PdfCraft patch (#3018): the default color spaces (`/DefaultGray`, `/DefaultRGB` and +/// PdfCraft patch (38): the default colour spaces (`/DefaultGray`, `/DefaultRGB` and /// `/DefaultCMYK`, ISO 32000-2 §8.6.5.6) of the resources content is drawn with, each read the /// first time the content selects its device space. Like any named resource, a default comes -/// from the resources in scope: a form XObject without `/Resources` draws in its page's -/// defaults, one with `/Resources` only in its own. -/// -/// On a plate (patch 35) device color keeps its device space: plates separate DeviceCMYK -/// by its components, with nonzero overprint mode, and a DefaultCMYK profile would route it -/// through the CMYK simulation (patch 36) instead. Defaults change how device color looks, -/// not which inks it is printed with. +/// from those resources' `/ColorSpace` or from the resources they inherit: a form XObject +/// without one of its own draws in its page's. pub(crate) struct DefaultColorSpaces<'r, 'a> { resources: &'r Resources<'a>, cache: Cache, + /// On a plate (patch 35) device color keeps its device space: plates separate DeviceCMYK + /// by its components, with nonzero overprint mode, and a DefaultCMYK profile would route it + /// through the CMYK simulation (patch 36) instead. on_plate: bool, gray: OnceCell>, rgb: OnceCell>, @@ -540,8 +584,8 @@ impl<'r, 'a> DefaultColorSpaces<'r, 'a> { } /// The default for `family`, with the cache key of the object it was read from. `None` - /// when the resources have none, or theirs is not a color space that can stand in for - /// the device space, or on a plate: device color is then drawn as it is. + /// when the resources have none, or theirs is not a colour space that can stand in for + /// the device space, or on a plate: device colour is then drawn as it is. pub(crate) fn get(&self, family: DeviceFamily) -> Option<(ColorSpace, u128)> { if self.on_plate { return None; @@ -565,7 +609,7 @@ impl<'r, 'a> DefaultColorSpaces<'r, 'a> { .clone() } - /// The color space content that selects `family` draws in: its default, else the device + /// The colour space content that selects `family` draws in: its default, else the device /// space itself. pub(crate) fn device(&self, family: DeviceFamily) -> ColorSpace { self.get(family) @@ -1029,54 +1073,144 @@ impl ToRgb for Lab { #[derive(Debug, Clone)] pub(crate) struct Indexed { + /// `hival + 1` entries of the base's component count each; entries from `present` on are + /// zeros and are drawn black (see `convert_f32`). values: Vec>, hival: u8, base: Box, + /// PdfCraft patch (80): how many entries the lookup table holds in full (at most + /// `hival + 1`). An index at or past it is drawn black. + present: usize, + /// PdfCraft patch (80): the space broke ISO 32000-2 §8.6.6.3 and was recovered (see + /// `Indexed::new`). + recovered: bool, + /// PdfCraft patch (80): the space has no lookup table at all (see `Indexed::new`). + tableless: bool, } impl Indexed { - fn new(array: &Array<'_>, cache: &Cache, depth: u8) -> Option { + /// PdfCraft patch (80): ISO 32000-2 §8.6.6.3 says `hival` "shall be an integer" no greater + /// than 255 and the lookup table "shall be m × (hival + 1) bytes long", but not how a reader + /// recovers when a file breaks this. Most readers draw such a space, and so does this: + /// - a real `hival` is truncated toward zero (upstream read it so too); + /// - a `hival` past 255 is taken as 255; + /// - a lookup table shorter than m × (hival + 1) bytes keeps the entries it holds in full, + /// and an index past them is drawn black, after conversion, whatever the base space (zero + /// bytes would be white in DeviceCMYK, Separation and DeviceN, and blue in Lab). + /// + /// Any of these sets `recovered`, which the drawing paths report. A `hival` below zero (once + /// truncated), or not a number, has no reading: the space cannot be read, as upstream, and + /// `has_unusable_hival` lets the image path report it. + /// + /// A lookup that is missing, or neither a string nor a stream that decodes, is no table at + /// all. Upstream could not read such a space either. With `allow_tableless` it is built, + /// marked `tableless`, so that the image path can skip the image with a warning and the + /// colour operators can fall back as upstream; without it, it is `None` as upstream. + fn new(array: &Array<'_>, cache: &Cache, depth: u32, allow_tableless: bool) -> Option { let mut iter = array.flex_iter(); // Skip name let _ = iter.next::>()?; - let base_color_space = ColorSpace::new_nested(iter.next::>()?, cache, depth + 1)?; - let hival = iter.next::()?.min(u8::MAX as u32) as u8; + let base_color_space = ColorSpace::within(iter.next::>()?, cache, depth + 1)?; + let (hival, hival_recovered) = indexed_hival(iter.next::()?)?; - let values = { - let data = iter - .next::>() - .and_then(|s| s.decoded().ok()) - .or_else(|| { - iter.next::>() - .map(|s| Cow::Owned(s.to_vec())) - })?; + // At most 255 components (a `u8`), and at most 256 entries. + let num_components = usize::from(base_color_space.num_components()); + let entries = usize::from(hival) + 1; - let num_components = base_color_space.num_components(); - - let mut byte_iter = data.iter().copied(); - - let mut vals = vec![]; - for _ in 0..=hival { - let mut temp = vec![]; - - for _ in 0..num_components { - temp.push(byte_iter.next()? as f32 / 255.0); - } - - vals.push(temp); - } - - vals - }; + // PdfCraft patch (80): read once and then by type, so a string lookup given by an + // indirect reference is found (a failed stream read had already consumed the + // reference). + let data = iter + .next::>() + .and_then(|o| indexed_lookup(o, cache)); + let tableless = data.is_none(); + if tableless && !allow_tableless { + return None; + } + let data: &[u8] = data.as_deref().unwrap_or_default(); + let present = data + .len() + .checked_div(num_components) + .unwrap_or(0) + .min(entries); + let mut bytes = data.iter().copied(); + let values: Vec> = (0..entries) + .map(|entry| { + (0..num_components) + .map(|_| { + if entry < present { + f32::from(bytes.next().unwrap_or(0)) / 255.0 + } else { + 0.0 + } + }) + .collect() + }) + .collect(); Some(Self { values, hival, base: Box::new(base_color_space), + present, + recovered: hival_recovered || present < entries, + tableless, }) } } +/// PdfCraft patch (80): an Indexed space's `hival` (ISO 32000-2 §8.6.6.3) as drawn, and whether +/// it had to be recovered: a real is truncated toward zero and a value past 255 is taken as 255. +/// `None` for a value below zero once truncated, or one that is not finite. +fn indexed_hival(number: object::Number) -> Option<(u8, bool)> { + let value = number.as_f64(); + let whole = value.trunc(); + // NaN fails this test too. + if !(whole >= 0.0 && whole.is_finite()) { + return None; + } + let clamped = whole.min(f64::from(u8::MAX)); + // `clamped` is a whole number in 0..=255, so the cast is exact. + Some((clamped as u8, clamped != value)) +} + +/// PdfCraft patch (80): whether `object` is an `/Indexed` colour space array whose `hival` has no +/// reading (below zero, or not a number), which `Indexed::new` cannot recover. Reads the array's +/// first and third entries only; the lookup table is not touched. +pub(crate) fn has_unusable_hival(object: &Object<'_>) -> bool { + let Object::Array(array) = object else { + return false; + }; + let mut iter = array.flex_iter(); + if !iter + .next::>() + .is_some_and(|family| matches!(family.deref(), INDEXED | I)) + { + return false; + } + let _base = iter.next::>(); + iter.next::() + .and_then(indexed_hival) + .is_none() +} + +/// PdfCraft patch (80): an Indexed space's lookup table, a byte string or a stream (ISO 32000-2 +/// §8.6.6.3), with a stream's filters applied. `None` for any other object or a stream that +/// cannot be decoded. A stream that decodes to nothing although it holds data counts as one that +/// cannot be decoded: the Flate decoder recovers what it can from a broken stream, and here +/// recovered nothing. Each call is counted on `cache` (`Cache::indexed_lookup_reads`). +fn indexed_lookup<'a>(lookup: Object<'a>, cache: &Cache) -> Option> { + cache.count_indexed_lookup_read(); + match lookup { + Object::Stream(s) => s + .decoded() + .ok() + .filter(|d| !d.is_empty() || s.raw_data().is_empty()), + Object::String(s) => Some(Cow::Owned(s.to_vec())), + _ => None, + } +} + impl ToRgb for Indexed { fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> { let mut indexed = vec![0.0; input.len() * self.base.num_components() as usize]; @@ -1090,50 +1224,103 @@ impl ToRgb for Indexed { output.copy_from_slice(&self.values[idx]); } - self.base.convert_f32(&indexed, output, true) + self.base.convert_f32(&indexed, output, true)?; + + // PdfCraft patch (80): an index past the entries the table holds is drawn black, in + // whatever space the base is (see `Indexed::new`). + if self.present <= usize::from(self.hival) { + for (input, rgb) in input.iter().copied().zip(output.chunks_exact_mut(3)) { + let idx = (input.clamp(0.0, self.hival as f32) + 0.5) as usize; + if idx >= self.present { + rgb.fill(0); + } + } + } + + Some(()) } } #[derive(Debug, Clone)] pub(crate) struct Separation { alternate_space: ColorSpace, - tint_transform: Function, + /// PdfCraft patch (55): `None` when the tint transform cannot be read (see + /// `eval_tint_transform`). + tint_transform: Option, is_none_separation: bool, /// PdfCraft patch (35): the colorant the space paints, for separations. colorant: Colorant, + /// PdfCraft patch (66): the colourant is the special name `All`. + is_all: bool, +} + +/// PdfCraft patch (55): `tint_transform` run on the tints of one colour, or, when it cannot be +/// read or evaluated, the initial colour of `alternate_space` (black in every device space), with +/// the fallback recorded. hayro already fell back this way when evaluation failed, silently; a +/// transform it could not read made the whole colour space unreadable, and the space's +/// paints were drawn in DeviceGray from their first tint instead (white for a full tint). +fn eval_tint_transform( + tint_transform: Option<&Function>, + alternate_space: &ColorSpace, + tints: &[f32], +) -> ColorComponents { + tint_transform + .and_then(|f| f.eval(tints.to_smallvec())) + .unwrap_or_else(|| { + note_color_fallback(); + alternate_space.initial_color() + }) } impl Separation { - fn new(array: &Array<'_>, cache: &Cache, depth: u8) -> Option { + fn new(array: &Array<'_>, cache: &Cache, depth: u32) -> Option { let mut iter = array.flex_iter(); // Skip `/Separation` let _ = iter.next::>()?; let name = iter.next::>()?; - let alternate_space = ColorSpace::new_nested(iter.next::>()?, cache, depth + 1)?; - let tint_transform = Function::new(&iter.next::>()?)?; - // Either I did something wrong, or no other viewers properly handles - // `All`, so let's just ignore it as well. + let alternate_space = ColorSpace::within(iter.next::>()?, cache, depth + 1)?; + // PdfCraft patch (55): an unreadable tint transform keeps the space (see + // `eval_tint_transform`). + let tint_transform = iter.next::>().and_then(|f| Function::new(&f)); let is_none_separation = name.as_str() == "None"; let colorant = Colorant::from_name(name.deref()); + // PdfCraft patch (66): `All` names every colourant of the output device at once + // (ISO 32000-2 §8.6.6.4), so its tints never go through the alternate space. + let is_all = name.as_str() == "All"; Some(Self { alternate_space, tint_transform, is_none_separation, colorant, + is_all, }) } } impl ToRgb for Separation { fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> { + if self.is_all { + // PdfCraft patch (66): §8.6.6.4: the tint applies to every colourant, and on an + // additive device it is complemented first, so tint t is the gray 1 − t on each of + // R, G and B whatever the alternate space and tint transform say. + for (tint, rgb) in input.iter().zip(output.chunks_exact_mut(3)) { + // `clamp` keeps NaN, and `f32_to_u8`'s cast saturates it to 0. + let gray = f32_to_u8(1.0 - tint.clamp(0.0, 1.0)); + rgb.copy_from_slice(&[gray, gray, gray]); + } + return Some(()); + } count_tint_transform_runs(input.len()); + // PdfCraft patch (55): see `eval_tint_transform`. let evaluated = input .iter() .flat_map(|n| { - self.tint_transform - .eval(smallvec![*n]) - .unwrap_or(self.alternate_space.initial_color()) + eval_tint_transform( + self.tint_transform.as_ref(), + &self.alternate_space, + &[*n], + ) }) .collect::>(); self.alternate_space.convert_f32(&evaluated, output, false) @@ -1148,14 +1335,16 @@ impl ToRgb for Separation { pub(crate) struct DeviceN { alternate_space: ColorSpace, num_components: u8, - tint_transform: Function, + /// PdfCraft patch (55): `None` when the tint transform cannot be read (see + /// `eval_tint_transform`). + tint_transform: Option, is_none: bool, /// PdfCraft patch (35): the colorant of each component, for separations. colorants: Vec, } impl DeviceN { - fn new(array: &Array<'_>, cache: &Cache, depth: u8) -> Option { + fn new(array: &Array<'_>, cache: &Cache, depth: u32) -> Option { let mut iter = array.flex_iter(); // Skip `/DeviceN` let _ = iter.next::>()?; @@ -1166,8 +1355,10 @@ impl DeviceN { .collect::>(); let num_components = u8::try_from(names.len()).ok()?; let all_none = names.iter().all(|n| n.as_str() == "None"); - let alternate_space = ColorSpace::new_nested(iter.next::>()?, cache, depth + 1)?; - let tint_transform = Function::new(&iter.next::>()?)?; + let alternate_space = ColorSpace::within(iter.next::>()?, cache, depth + 1)?; + // PdfCraft patch (55): an unreadable tint transform keeps the space (see + // `eval_tint_transform`). + let tint_transform = iter.next::>().and_then(|f| Function::new(&f)); if num_components == 0 { return None; @@ -1197,12 +1388,11 @@ impl ToRgb for DeviceN { fn convert_f32(&self, input: &[f32], output: &mut [u8], _: bool) -> Option<()> { let colours = input.len().checked_div(usize::from(self.num_components)); count_tint_transform_runs(colours.unwrap_or(0)); + // PdfCraft patch (55): see `eval_tint_transform`. let evaluated = input .chunks_exact(self.num_components as usize) .flat_map(|n| { - self.tint_transform - .eval(n.to_smallvec()) - .unwrap_or(self.alternate_space.initial_color()) + eval_tint_transform(self.tint_transform.as_ref(), &self.alternate_space, n) }) .collect::>(); self.alternate_space.convert_f32(&evaluated, output, false) @@ -1423,6 +1613,18 @@ fn f32_to_u8(val: f32) -> u8 { (val * 255.0 + 0.5) as u8 } +// PdfCraft patch (63). +/// The `/DeviceCMYK` to `/DeviceGray` conversion of ISO 32000-2 §10.4.2.3, +/// `gray = 1.0 - min(1.0, 0.3 c + 0.59 m + 0.11 y + k)`, which §11.5.3 also gives for the +/// luminosity of a soft mask whose group is in `/DeviceCMYK`. A missing component counts as +/// zero, and each component is clamped to `[0, 1]` first (`NaN` and infinities read as zero). +pub(crate) fn device_cmyk_to_gray(cmyk: &[f32]) -> f32 { + let component = |i: usize| clamp_component(cmyk.get(i).copied().unwrap_or(0.0), 0.0, 1.0); + let ink = 0.3 * component(0) + 0.59 * component(1) + 0.11 * component(2) + component(3); + // Every component is in [0, 1], so `ink` is not negative and the result is in [0, 1]. + 1.0 - ink.min(1.0) +} + /// Clamp an input-derived colour component to `[lo, hi]` without panicking on /// NaN or on a reversed range. Non-finite values map to zero. fn clamp_component(value: f32, lo: f32, hi: f32) -> f32 { @@ -1465,6 +1667,46 @@ impl Color { .to_rgba(&self.components, self.opacity, false) } + /// PdfCraft patch (70): the colour as process ink tints `[C, M, Y, K]` (0 = no ink) and + /// its opacity, for blending in a `DeviceCMYK` transparency group (ISO 32000-2 §11.3.4). + /// + /// `DeviceCMYK` gives its components. `DeviceGray` is black ink alone, `K = 1 − gray` + /// (§10.4.2.2). PdfCraft patch (104): an additive colour (`DeviceRGB`, `CalRGB`, `Lab`, a + /// three-component ICCBased colour) is the ink that draws back to it through the CMYK + /// profile. `None` for every other space, ICCBased CMYK included (it keeps its own + /// profile), and the caller draws it as before. + pub fn ink_tints(&self) -> Option<([f32; 4], f32)> { + let c = |i: usize| { + self.components + .get(i) + .copied() + .unwrap_or(0.0) + .clamp(0.0, 1.0) + }; + let tints = match self.color_space.0.as_ref() { + ColorSpaceType::DeviceCmyk => [c(0), c(1), c(2), c(3)], + ColorSpaceType::DeviceGray => [0.0, 0.0, 0.0, 1.0 - c(0)], + ColorSpaceType::DeviceRgb | ColorSpaceType::CalRgb(_) | ColorSpaceType::Lab(_) => { + self.ink_from_srgb()? + } + ColorSpaceType::ICCBased(icc) if icc.0.number_components == 3 => { + self.ink_from_srgb()? + } + _ => return None, + }; + Some((tints, self.opacity.clamp(0.0, 1.0))) + } + + fn ink_from_srgb(&self) -> Option<[f32; 4]> { + // `to_rgba` turns a non-finite component into some finite colour, which is not the + // colour's ink, so such a colour has no tints. + if self.components.iter().any(|c| !c.is_finite()) { + return None; + } + let [r, g, b, _] = self.to_rgba().components(); + crate::cmyk_inverse::srgb_to_cmyk([r, g, b]) + } + /// Create a color from RGBA. pub fn from_rgba(rgba: AlphaColor) -> Self { let c = rgba.components(); @@ -2133,7 +2375,8 @@ impl ColorSpace { }; count_tint_transform_runs(1); function - .eval(components.iter().copied().collect()) + .as_ref() + .and_then(|f| f.eval(components.iter().copied().collect())) .unwrap_or(alternate.initial_color()) } @@ -2501,9 +2744,11 @@ impl ToRgb for PlateSpace { } } -static CMYK_TRANSFORM: LazyLock = LazyLock::new(|| { - ICCProfile::new(include_bytes!("../assets/CGATS001Compat-v2-micro.icc"), 4).unwrap() -}); +/// The CMYK profile pages are drawn with. +pub(crate) const CMYK_PROFILE: &[u8] = include_bytes!("../assets/CGATS001Compat-v2-micro.icc"); + +static CMYK_TRANSFORM: LazyLock = + LazyLock::new(|| ICCProfile::new(CMYK_PROFILE, 4).unwrap()); pub(crate) trait ToRgb { fn convert_sample(&self, input: &[f32], output: &mut [u8], manual_scale: bool) -> Option<()> { @@ -2681,7 +2926,7 @@ impl ColorSpace { _ => return None, }; if alternate.is_device_cmyk() - && let Some(cmyk) = transform.eval(components.clone()) + && let Some(cmyk) = transform.as_ref().and_then(|f| f.eval(components.clone())) && let [c, m, y, k] = cmyk[..] { return Some(SpotAlternate::Cmyk([c, m, y, k].map(unit))); @@ -2911,7 +3156,7 @@ mod nesting_tests { #[test] fn nested_color_spaces_stop_at_the_depth_limit() { - let deepest = usize::from(MAX_COLOR_SPACE_DEPTH) - 1; + let deepest = (MAX_COLOR_SPACE_DEPTH as usize) - 1; assert!(chain_space(1).is_some()); assert!(chain_space(deepest).is_some(), "the base at the deepest allowed level resolves"); assert!(chain_space(deepest + 1).is_none()); @@ -2922,3 +3167,36 @@ mod nesting_tests { assert!(chain_space(100_000).is_none()); } } + +#[cfg(test)] +mod device_cmyk_gray_tests { + use super::device_cmyk_to_gray; + + fn assert_close(cmyk: &[f32], expected: f32) { + let got = device_cmyk_to_gray(cmyk); + assert!( + (got - expected).abs() < 1e-5, + "{cmyk:?}: gray {got}, expected {expected}" + ); + } + + #[test] + fn each_ink_darkens_by_its_iso_weight() { + assert_close(&[0.0, 0.0, 0.0, 0.0], 1.0); + assert_close(&[0.0, 0.0, 0.0, 1.0], 0.0); + assert_close(&[0.0, 0.0, 0.0, 0.5], 0.5); + assert_close(&[1.0, 0.0, 0.0, 0.0], 0.7); + assert_close(&[0.0, 1.0, 0.0, 0.0], 0.41); + assert_close(&[0.0, 0.0, 1.0, 0.0], 0.89); + assert_close(&[0.5, 0.5, 0.5, 0.25], 0.25); + } + + #[test] + fn ink_past_full_coverage_is_black_and_bad_components_read_as_zero() { + assert_close(&[1.0, 1.0, 1.0, 1.0], 0.0); + assert_close(&[0.0, 0.0, 0.0, 1.5], 0.0); + assert_close(&[2.0, -1.0, f32::NAN, f32::INFINITY], 0.7); + assert_close(&[], 1.0); + assert_close(&[0.0, 0.0], 1.0); + } +} diff --git a/vendor/hayro-interpret/src/context.rs b/vendor/hayro-interpret/src/context.rs index caa1c2bdd3..7997e9c0de 100644 --- a/vendor/hayro-interpret/src/context.rs +++ b/vendor/hayro-interpret/src/context.rs @@ -5,7 +5,7 @@ use crate::font::{Font, StandardFont}; use crate::interpret::state::{ClipType, State, TextStateFont}; use crate::ocg::OcgState; use crate::util::{BezPathExt, Float64Ext}; -use crate::{ClipPath, Device, FillRule, InterpreterSettings, StrokeProps}; +use crate::{ClipPath, Device, FillRule, InterpreterSettings, InterpreterWarning, StrokeProps}; use hayro_syntax::content::ops::Transform; use hayro_syntax::object::Dict; use hayro_syntax::object::Name; @@ -37,6 +37,12 @@ std::thread_local! { // PdfCraft patch (18): whether this page's content budget ran out, reported as // `InterpreterWarning::ContentTruncated`. static CONTENT_TRUNCATED: core::cell::Cell = const { core::cell::Cell::new(false) }; + // PdfCraft patch (89): the form XObjects being drawn on this page, outermost first, across + // the contexts of the tiling patterns, Type 3 glyphs, soft masks and groups painted while + // they draw. A form already on it draws itself and is skipped. Its length is bounded by the + // nesting limits: every form on it is nested in the ones before it. + static FORMS_DRAWING: RefCell> = + const { RefCell::new(Vec::new()) }; } /// PdfCraft patch: decoded content-stream bytes one page may hold at once: its contents, and @@ -96,6 +102,37 @@ pub(crate) fn decode_content<'a>(stream: &Stream<'a>) -> Option usize { + CONTENT_LEFT.with(core::cell::Cell::get) +} + +/// PdfCraft patch (87): `len` bytes of content held within the page's [`MAX_PAGE_CONTENT`] +/// until dropped, as [`DecodedContent`] holds what it decoded: content kept from an earlier +/// decode (a cached Type 3 glyph procedure) counts as it did when it was decoded. +pub(crate) struct HeldContent(usize); + +impl Drop for HeldContent { + fn drop(&mut self) { + let held = self.0; + CONTENT_LEFT.with(|c| c.set(c.get().saturating_add(held).min(MAX_PAGE_CONTENT))); + } +} + +/// PdfCraft patch (87): hold `len` bytes of content within what is left of the page's +/// [`MAX_PAGE_CONTENT`]. `None`, and the page reported truncated, when they don't fit, as +/// [`decode_content`] skips content the budget can't hold. +pub(crate) fn hold_content(len: usize) -> Option { + let left = content_left(); + if left == 0 || left < len { + CONTENT_TRUNCATED.with(|truncated| truncated.set(true)); + warn!("page content budget exceeded"); + return None; + } + charge_content(len); + Some(HeldContent(len)) +} + /// PdfCraft patch: count `len` bytes held for the rest of the page (its own contents). pub(crate) fn charge_content(len: usize) { CONTENT_LEFT.with(|c| c.set(c.get().saturating_sub(len))); @@ -133,6 +170,22 @@ pub struct InterpreterCache<'a> { /// PdfCraft patch: decoded images, shared by every render through this cache so a tile /// no longer decodes its page's images again. pub(crate) decoded_cache: DecodedImageCache, + /// PdfCraft patch (87): what the Type 3 fonts of this cache keep of their decoded glyph + /// procedures, together (see `font::type3`). + pub(crate) type3_procs: Rc, +} + +/// PdfCraft patch (87): decoded Type 3 glyph procedure bytes all the fonts of one +/// [`InterpreterCache`] keep together. Fonts live as long as the cache, so the bound is on the +/// cache, not on each font: a document can have thousands of Type 3 fonts. +pub(crate) const MAX_CACHED_TYPE3_PROCS: usize = 32 << 20; + +/// PdfCraft patch (87): the decoded glyph procedure bytes the Type 3 fonts of a cache keep, +/// and how many procedures they decoded. +#[derive(Default)] +pub(crate) struct Type3Procs { + pub(crate) held: core::cell::Cell, + pub(crate) decodes: core::cell::Cell, } impl<'a> Default for InterpreterCache<'a> { @@ -148,21 +201,42 @@ impl<'a> InterpreterCache<'a> { font_cache: Rc::new(RefCell::new(HashMap::new())), object_cache: Cache::new(), decoded_cache: DecodedImageCache::new(), + type3_procs: Rc::default(), } } + /// PdfCraft patch (87): how many Type 3 glyph procedures the fonts of this cache decoded, + /// for diagnostics and tests. A procedure kept from an earlier copy of its glyph isn't + /// decoded again. + pub fn type3_proc_decodes(&self) -> usize { + self.type3_procs.decodes.get() + } + /// PdfCraft patch (32): how many images were decoded through this cache (its misses, not /// counting images that are never cached), for diagnostics and tests. pub fn decoded_image_decodes(&self) -> usize { self.decoded_cache.decodes() } - /// PdfCraft patch (#3020): how many `/ICCBased` profiles were read through this cache, for + /// PdfCraft patch (82): how many of [`Self::decoded_image_decodes`] were of soft masks and + /// `/Mask` images, for diagnostics and tests. + pub fn decoded_mask_decodes(&self) -> usize { + self.decoded_cache.mask_decodes() + } + + /// PdfCraft patch (48): how many `/ICCBased` profiles were read through this cache, for /// diagnostics and tests. A profile used again, by the same stream object or by a copy with /// the same dictionary and bytes, is read once. pub fn icc_profile_reads(&self) -> usize { self.object_cache.icc_profile_reads() } + + /// PdfCraft patch (80): how many `/Indexed` lookup tables were read through this cache, for + /// diagnostics and tests. A colour space named by a resource is built, and its table read, + /// once however many images or colours use it. + pub fn indexed_lookup_reads(&self) -> usize { + self.object_cache.indexed_lookup_reads() + } } /// A per-page interpretation context that borrows shared data from an [`InterpreterCache`]. @@ -183,6 +257,15 @@ pub struct Context<'a> { /// a limit was reached, the clip count to return to at its `Q`. saved_bytes: usize, skipped_saves: Vec, + /// PdfCraft patch (68): the `num_states` at which the nested content stream (a form, an + /// appearance, a glyph or pattern cell) being interpreted started, or 0 in page content. A + /// `Q` there has no `q` of its own stream to match (see `stream_floor_reached`). + stream_floor: usize, + // PdfCraft patch (63). + /// This is the content of a luminosity soft mask whose group colour space is `/DeviceCMYK`, + /// so a `/DeviceCMYK` fill or stroke colour paints as its gray (ISO 32000-2 §11.5.3, + /// §10.4.2.3) rather than through the CMYK profile used for display. + pub(crate) luminosity_in_device_cmyk: bool, } /// PdfCraft patch: most graphics states saved at once. Every `q` copies the current state, dash @@ -192,9 +275,6 @@ const MAX_SAVED_STATES: usize = 4096; const MAX_SAVED_STATE_BYTES: usize = 64 << 20; /// Roughly what a saved copy of `state` holds. -/// PdfCraft patch (51): the sums saturate, so a huge dash array or clip list counts as over the -/// bound rather than wrapping on a 32-bit target. The pending text-clip outlines (text render -/// modes 4–7) are copied with the state too, so they count. fn state_bytes(state: &State<'_>) -> usize { size_of::>() .saturating_add( @@ -223,6 +303,12 @@ impl<'a> Context<'a> { NESTED_PAINTS.with(|n| n.set(0)); CONTENT_LEFT.with(|c| c.set(MAX_PAGE_CONTENT)); CONTENT_TRUNCATED.with(|truncated| truncated.set(false)); + // PdfCraft patch (89): no form of another page is being drawn. + FORMS_DRAWING.with(|forms| forms.borrow_mut().clear()); + // PdfCraft patch (73): and fresh JBIG2 decoding, which every image of it shares. + hayro_syntax::set_page_jbig2_work(settings.jbig2_work); + // PdfCraft patch (55): a fallback left over from another page is not this page's. + crate::color::take_color_fallback(); crate::encode::reset_mesh_budget(); Self::new_with(initial_transform, bbox, cache, xref, settings, state, 0) @@ -240,7 +326,7 @@ impl<'a> Context<'a> { let mut ocg_state = { let root_ref = xref.root_id(); xref.get::>(root_ref) - .map(|catalog| OcgState::from_catalog(&catalog)) + .map(|catalog| OcgState::from_catalog(&catalog, xref, settings.view_auto_state)) .unwrap_or_default() }; // PdfCraft patch: apply viewer layer toggles. @@ -263,6 +349,58 @@ impl<'a> Context<'a> { nesting_depth, saved_bytes: 0, skipped_saves: Vec::new(), + stream_floor: 0, + luminosity_in_device_cmyk: false, + } + } + + /// PdfCraft patch (89): begins drawing the form `id`; `false` when that form is already + /// being drawn, so drawing it again would never end (ISO 32000-2 §8.10.1: a form is a + /// self-contained description; one that contains itself describes nothing finite). The + /// skip is reported as `InterpreterWarning::ContentTruncated`. A form without an object + /// number can't be told apart and is only bounded by the nesting limits. + /// + /// The forms being drawn are those of this page's context and of every context painting + /// inside it (a tiling pattern, a Type 3 glyph, a soft mask or a group), so a form that + /// reaches itself through one of those is skipped too, while a form drawn again after it + /// has finished draws as usual. + pub(crate) fn enter_form( + &mut self, + id: Option, + ) -> bool { + let Some(id) = id else { + return true; + }; + // The stack is never borrowed across a call, so the borrow succeeds; if it didn't, + // the form draws, bounded by the nesting limits as before this patch. + let entered = FORMS_DRAWING.with(|forms| { + let Ok(mut forms) = forms.try_borrow_mut() else { + return None; + }; + if forms.contains(&id) { + return Some(false); + } + forms.push(id); + Some(true) + }); + if entered == Some(false) { + warn!("form XObject draws itself; the inner drawing is skipped"); + CONTENT_TRUNCATED.with(|truncated| truncated.set(true)); + return false; + } + true + } + + /// PdfCraft patch (89): ends drawing a form begun with `enter_form`. + pub(crate) fn leave_form(&mut self, id: Option) { + if let Some(id) = id { + FORMS_DRAWING.with(|forms| { + if let Ok(mut forms) = forms.try_borrow_mut() + && forms.last() == Some(&id) + { + forms.pop(); + } + }); } } @@ -445,6 +583,8 @@ impl<'a> Context<'a> { self.get_mut().ctm *= transform; } + /// PdfCraft patch (80): an `/Indexed` resource with no lookup table is built, marked + /// tableless, for the image and colour operators to handle (see `Indexed::new`). pub(crate) fn get_color_space( &mut self, resources: &Resources<'_>, @@ -454,7 +594,10 @@ impl<'a> Context<'a> { self.interpreter_cache .object_cache .get_or_insert_with(cs_object.cache_key(), || { - ColorSpace::new(cs_object.clone(), &self.interpreter_cache.object_cache) + ColorSpace::new_allowing_tableless( + cs_object.clone(), + &self.interpreter_cache.object_cache, + ) }) } @@ -462,6 +605,25 @@ impl<'a> Context<'a> { self.get().graphics_state.stroke_props.clone() } + /// PdfCraft patch (68): starts a nested content stream at the current depth and returns the + /// floor of the stream it runs inside, for `leave_stream`. + pub(crate) fn enter_stream(&mut self) -> usize { + let depth = self.num_states(); + std::mem::replace(&mut self.stream_floor, depth) + } + + /// PdfCraft patch (68): ends a content stream begun with `enter_stream`. + pub(crate) fn leave_stream(&mut self, outer_floor: usize) { + self.stream_floor = outer_floor; + } + + /// PdfCraft patch (68): every `q` of the current content stream has been matched, so a `Q` + /// now would restore a state its caller saved (a stream balances its own `q` and `Q`, + /// ISO 32000-2 §8.4.2, §8.10.1). + pub(crate) fn stream_floor_reached(&self) -> bool { + self.num_states() <= self.stream_floor + } + pub(crate) fn num_states(&self) -> usize { // PdfCraft patch: saves not kept still count, so callers restore back past them. self.states.len().saturating_add(self.skipped_saves.len()) @@ -508,6 +670,12 @@ impl<'a> Context<'a> { .clone() }; + // PdfCraft patch (90): tell the caller a Type 3 font lacks the /Widths it requires, + // so the spacing taken from its glyph procedures can be reported. + if resolved.as_ref().is_some_and(Font::type3_widths_missing) { + (self.settings.extended_warning_sink)(crate::ExtendedWarning::Type3WidthsMissing); + } + if let Some(resolved) = resolved { Some(TextStateFont::Font(resolved)) } else { @@ -523,13 +691,13 @@ pub(crate) fn path_as_rect(path: &BezPath) -> Option { return None; } - // PdfCraft patch (35), PdfCraft #3327: the points have to trace the rectangle, not merely - // reach its corners. The length check above admits one MoveTo and four LineTo as well as the - // intended one MoveTo, three LineTo and one ClosePath, and asking only that each corner of - // the bounding box was visited says nothing about the order or the steps between: a - // five-point polyline whose ends reached every corner of its own bounding box was painted as - // that box, and a clip of that shape was discarded. Four distinct points, each step along one - // axis, the last point back at the first: that is a rectangle and nothing else is. + // PdfCraft patch: the points have to trace the rectangle, not merely reach its corners. The + // length check above admits one MoveTo and four LineTo as well as the intended one MoveTo, + // three LineTo and one ClosePath, and asking only that each corner of the bounding box was + // visited says nothing about the order or the steps between: a five-point polyline whose + // ends reached every corner of its own bounding box was painted as that box, and a clip of + // that shape was discarded. Four distinct points, each step along one axis, the last point + // back at the first: that is a rectangle and nothing else is. let mut points: Vec = Vec::with_capacity(5); let mut closed = false; for (idx, el) in path.elements().iter().enumerate() { @@ -554,16 +722,16 @@ pub(crate) fn path_as_rect(path: &BezPath) -> Option { } // Exactly equal, not nearly: `is_nearly_equal` allows a 256th of a path unit, and the matrix - // is applied after this, so a large `cm` turns that into whole device units: a path that only - // nearly closes would be painted as the rectangle, with a side it does not have. A - // rectangle's coordinates are equal in the content stream, so nothing that is one loses the - // fast path by this; a path that misses takes the general route and is painted as written. + // is applied after this, so a `cm` of 10,000 turns that into tens of device units -- a path + // that only nearly closes would be painted as the rectangle, with a side it does not have. + // A rectangle's coordinates are equal in the content stream, not approximately equal, so + // nothing that is one loses the fast path by this; a path that misses takes the general route + // and is painted as written (#3327 review). let same = |a: Point, b: Point| a.x == b.x && a.y == b.y; // `m l l l l`: the fourth line goes back to the start, which `m l l l h` does with ClosePath. if !closed { - match (points.first(), points.get(4)) { - (Some(first), Some(last)) if points.len() == 5 && same(*first, *last) => {} - _ => return None, + if points.len() != 5 || !same(points[4], points[0]) { + return None; } points.pop(); } @@ -573,7 +741,7 @@ pub(crate) fn path_as_rect(path: &BezPath) -> Option { // Distinct, so a degenerate path is not one, and each step along one axis only: the four // points of an axis-aligned rectangle, in order round it. for (i, p) in points.iter().enumerate() { - let q = points.get((i + 1) % 4)?; + let q = points[(i + 1) % 4]; let along_x = p.y == q.y && p.x != q.x; let along_y = p.x == q.x && p.y != q.y; if !(along_x || along_y) { @@ -587,55 +755,8 @@ pub(crate) fn path_as_rect(path: &BezPath) -> Option { Some(path.fast_bounding_box()) } -/// PdfCraft patch (35) tests: only a path that traces an axis-aligned rectangle is one. -#[cfg(test)] -mod path_as_rect_tests { - use super::*; - - fn path(points: &[(f64, f64)], close: bool) -> BezPath { - let mut path = BezPath::new(); - for (i, p) in points.iter().enumerate() { - if i == 0 { - path.move_to(*p); - } else { - path.line_to(*p); - } - } - if close { - path.close_path(); - } - path - } - - #[test] - fn an_open_polyline_through_every_corner_is_not_a_rectangle() { - // VectorCraft #2920: the zigzag's ends reach all four corners; its peak reaches none. - let zigzag = [(80.0, 38.0), (80.0, 21.75), (60.571, 29.875), (40.0, 21.75), (40.0, 38.0)]; - assert_eq!(path_as_rect(&path(&zigzag, false)), None); - } - - #[test] - fn corners_visited_out_of_order_are_not_a_rectangle() { - let bow_tie = [(10.0, 10.0), (50.0, 40.0), (10.0, 40.0), (50.0, 10.0)]; - assert_eq!(path_as_rect(&path(&bow_tie, true)), None); - } - - #[test] - fn a_path_that_only_nearly_closes_is_not_a_rectangle() { - let open = [(10.0, 10.0), (50.0, 10.0), (50.0, 40.0), (10.0, 40.0), (10.0, 10.001)]; - assert_eq!(path_as_rect(&path(&open, false)), None); - } - - #[test] - fn closed_rectangles_are_rectangles() { - let expected = Some(Rect::new(10.0, 10.0, 50.0, 40.0)); - let closed = [(10.0, 10.0), (50.0, 10.0), (50.0, 40.0), (10.0, 40.0)]; - assert_eq!(path_as_rect(&path(&closed, true)), expected); - let back_to_start = [(10.0, 10.0), (10.0, 40.0), (50.0, 40.0), (50.0, 10.0), (10.0, 10.0)]; - assert_eq!(path_as_rect(&path(&back_to_start, false)), expected); - } -} - +/// PdfCraft patch tests (ported from craft-libs): the graphics-state stack is bounded by count +/// and by bytes, and every `q` still pairs with its `Q`. #[cfg(test)] mod saved_state_tests { use super::*; @@ -643,7 +764,10 @@ mod saved_state_tests { use hayro_syntax::Pdf; fn pdf() -> Pdf { - let objects = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Count 0 /Kids [] >>"]; + let objects = [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Count 0 /Kids [] >>", + ]; let mut out = b"%PDF-1.7\n".to_vec(); let mut offsets = Vec::new(); for (i, body) in objects.iter().enumerate() { @@ -655,32 +779,34 @@ mod saved_state_tests { for offset in offsets { out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes()); } - out.extend_from_slice(format!("trailer\n<< /Size 3 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes()); + out.extend_from_slice( + format!("trailer\n<< /Size 3 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes(), + ); Pdf::new(out).expect("synthetic pdf") } - #[test] - fn repeated_saves_of_a_large_state_stay_bounded_and_balanced() { - let pdf = pdf(); - let cache = InterpreterCache::new(); - let mut ctx = Context::new(Affine::IDENTITY, Rect::new(0.0, 0.0, 100.0, 100.0), &cache, pdf.xref(), InterpreterSettings::default()); - ctx.get_mut().graphics_state.stroke_props.dash_array = crate::types::dash_array((0..crate::types::MAX_DASH_ENTRIES).map(|i| i as f32 + 1.0)); - for _ in 0..20_000 { + fn triangle() -> BezPath { + let mut path = BezPath::new(); + path.move_to((10.0, 10.0)); + path.line_to((90.0, 10.0)); + path.line_to((50.0, 90.0)); + path.close_path(); + path + } + + /// Saves `saves` more times, checks a clip added after the last save goes at its `Q`, and unwinds. + fn save_and_unwind(ctx: &mut Context<'_>, saves: usize) { + let before = ctx.num_states(); + for _ in 0..saves { ctx.save_state(); } assert!(ctx.states.len() <= MAX_SAVED_STATES); assert!(ctx.saved_bytes <= MAX_SAVED_STATE_BYTES); - assert_eq!(ctx.num_states(), 20_001, "every q still counts"); + assert_eq!(ctx.num_states(), before + saves, "every q still counts"); - // A clip added after a save that was not kept is removed by its Q. let mut device = DummyDevice; - let mut triangle = BezPath::new(); - triangle.move_to((10.0, 10.0)); - triangle.line_to((90.0, 10.0)); - triangle.line_to((50.0, 90.0)); - triangle.close_path(); let clips = ctx.get().clips.len(); - ctx.push_clip_path(triangle, FillRule::NonZero, &mut device); + ctx.push_clip_path(triangle(), FillRule::NonZero, &mut device); assert_eq!(ctx.get().clips.len(), clips + 1); ctx.restore_state(&mut device); assert_eq!(ctx.get().clips.len(), clips); @@ -689,31 +815,36 @@ mod saved_state_tests { ctx.restore_state(&mut device); } assert_eq!(ctx.states.len(), 1); + assert!(ctx.skipped_saves.is_empty()); assert_eq!(ctx.saved_bytes, 0); } #[test] - fn pending_text_clip_outlines_count_toward_the_saved_bytes() { + fn repeated_saves_stay_bounded_and_balanced() { let pdf = pdf(); let cache = InterpreterCache::new(); - let mut ctx = Context::new(Affine::IDENTITY, Rect::new(0.0, 0.0, 100.0, 100.0), &cache, pdf.xref(), InterpreterSettings::default()); - let empty = state_bytes(ctx.get()); - ctx.get_mut().text_state.clip_paths.move_to((0.0, 0.0)); - for i in 0..100_000 { - ctx.get_mut().text_state.clip_paths.line_to((f64::from(i), 1.0)); - } - assert!(state_bytes(ctx.get()) >= empty + 100_000 * size_of::()); - for _ in 0..20_000 { + let bbox = Rect::new(0.0, 0.0, 100.0, 100.0); + let settings = InterpreterSettings::default(); + let mut ctx = Context::new(Affine::IDENTITY, bbox, &cache, pdf.xref(), settings); + + // A small state reaches the count limit. + save_and_unwind(&mut ctx, 20_000); + + // A large one (a 64 Ki-entry dash array, 256 KiB a copy) reaches the byte limit first. + ctx.get_mut().graphics_state.stroke_props.dash_array = (0..1 << 16).map(|_| 2.0).collect(); + ctx.save_state(); + assert_eq!(ctx.states.len(), 2); + while ctx.skipped_saves.is_empty() { ctx.save_state(); } - assert!(ctx.saved_bytes <= MAX_SAVED_STATE_BYTES); - } + assert!(ctx.states.len() < MAX_SAVED_STATES); + save_and_unwind(&mut ctx, 1000); - #[test] - fn an_overlong_dash_array_strokes_solid() { - let max = crate::types::MAX_DASH_ENTRIES; - assert_eq!(crate::types::dash_array((0..max).map(|_| 2.0)).len(), max); - assert!(crate::types::dash_array((0..max + 1).map(|_| 2.0)).is_empty()); - assert_eq!(crate::types::dash_array([0.0, 3.0].into_iter()).as_slice(), &[0.01, 3.0]); + // Once unwound, a kept save restores what changed after it. + let mut device = DummyDevice; + ctx.save_state(); + ctx.pre_concat_affine(Affine::scale(2.0)); + ctx.restore_state(&mut device); + assert_eq!(ctx.get().ctm, Affine::IDENTITY); } } diff --git a/vendor/hayro-interpret/src/convert.rs b/vendor/hayro-interpret/src/convert.rs index e768911415..0380f04b76 100644 --- a/vendor/hayro-interpret/src/convert.rs +++ b/vendor/hayro-interpret/src/convert.rs @@ -28,3 +28,33 @@ pub(crate) fn convert_line_join(lc: LineJoin) -> kurbo::Join { _ => kurbo::Join::Miter, } } + +/// PdfCraft patch (61): the line width to keep for a `w` operand or an ExtGState `/LW`. ISO +/// 32000-2 §8.4.3.2 makes 0 "the thinnest line that can be rendered at device resolution" but +/// says nothing of a negative width; it is drawn as 0, as is one that isn't finite, so no device +/// sees a width below zero. +pub(crate) fn convert_line_width(width: f32) -> f32 { + if width.is_finite() && width > 0.0 { + width + } else { + 0.0 + } +} + +/// PdfCraft patch (61): the dash array to keep for a `d` operator or an ExtGState `/D`. ISO +/// 32000-2 §8.4.3.6 requires numbers that "shall be nonnegative and not all zero". A pattern that +/// breaks that (all zero, a negative or a non-finite entry) is kept as `[]`, a solid line, rather +/// than cut into dashes the zero-entry workaround below would make a hundredth of a point long. +pub(crate) fn convert_dash_array( + dashes: impl Iterator, +) -> smallvec::SmallVec<[f32; 4]> { + let dashes: smallvec::SmallVec<[f32; 4]> = dashes.collect(); + if dashes.iter().any(|d| !d.is_finite() || *d < 0.0) || dashes.iter().all(|d| *d == 0.0) { + return smallvec::SmallVec::new(); + } + // kurbo apparently cannot properly deal with dashes that are exactly 0. + dashes + .into_iter() + .map(|d| if d == 0.0 { 0.01 } else { d }) + .collect() +} diff --git a/vendor/hayro-interpret/src/device.rs b/vendor/hayro-interpret/src/device.rs index 32a7f92fba..6630130f02 100644 --- a/vendor/hayro-interpret/src/device.rs +++ b/vendor/hayro-interpret/src/device.rs @@ -1,3 +1,4 @@ +use crate::cmyk_group::CmykGroup; use crate::font::Glyph; use crate::soft_mask::SoftMask; use crate::{BlendMode, ClipPath, Image}; @@ -73,53 +74,64 @@ pub trait Device<'a> { fn begin_annotations(&mut self) {} /// PdfCraft patch (29): the page's annotations are done; what follows is page content. fn end_annotations(&mut self) {} - /// Knockout patch (pdfcraft #2974): the transparency group just pushed is a knockout group - /// (`/K true`): each of its elements composites with the group's initial backdrop, not with the - /// elements drawn before it in the group (ISO 32000-2, knockout groups), until the matching - /// `pop_transparency_group`. + /// PdfCraft patch (39): the transparency group just pushed is a knockout group (`/K true`): + /// each of its elements composites with the group's initial backdrop, not with the + /// elements drawn before it in the group (ISO 32000-2, knockout groups), until the + /// matching `pop_transparency_group`. fn set_knockout(&mut self) {} - /// Knockout patch (pdfcraft #2974): an element whose shape is `shape` (device space) is about - /// to be drawn into a transparency group of its own. In a knockout group (`set_knockout`) the - /// element replaces what the group drew under its shape, so a device clears that first; the - /// element's layer then composites over the cleared area as usual. + /// PdfCraft patch (39): an element whose shape is `shape` (device space) is about to be + /// drawn into a transparency group of its own. In a knockout group (`set_knockout`) the + /// element replaces what the group drew under its shape, so a device clears that first; + /// the element's layer then composites over the cleared area as usual. fn knockout_shape(&mut self, _shape: &BezPath) {} - /// Knockout patch (pdfcraft #2974): whether `knockout_shape` would clear anything now, that is - /// whether the innermost transparency group is a knockout group. Lets the interpreter skip work - /// it only needs for the clear. + /// PdfCraft patch (39): whether `knockout_shape` would clear anything now, that is whether + /// the innermost transparency group is a knockout group. Lets the interpreter skip work it + /// only needs for the clear. fn in_knockout_group(&mut self) -> bool { false } - /// Knockout patch (pdfcraft #2974): `image`, an unmasked raster image, is about to be drawn - /// with `transform` in a knockout group. A device that will draw it (it isn't skipped and it + /// PdfCraft patch (39): `image`, an unmasked raster image, is about to be drawn with + /// `transform` in a knockout group. A device that will draw it (it isn't skipped and it /// decodes) clears what the group drew under its placement rectangle first, so the image - /// replaces it. Decided by the device, at the size it draws the image, so the draw reuses that - /// decode. + /// replaces it. Decided by the device, at the size it draws the image, so the draw reuses + /// that decode. fn knockout_image(&mut self, _image: &crate::RasterImage<'_>, _transform: Affine) {} - /// Knockout patch (pdfcraft #2974): whether a transparency group drawn now is an element of a - /// knockout group that the device wants cleared under the group's shape first. If so the + /// PdfCraft patch (39): whether a transparency group drawn now is an element of a knockout + /// group that the device wants cleared under the group's shape first. If so the /// interpreter draws the group's content once between `begin_knockout_erase` and /// `end_knockout_erase`, in which every paint clears what is under its shape instead of /// painting, and then draws the group as usual, in a layer of its own. fn knockout_erase_wanted(&mut self) -> bool { false } - /// Knockout patch (pdfcraft #2974): see `knockout_erase_wanted`. + /// PdfCraft patch (39): see `knockout_erase_wanted`. fn begin_knockout_erase(&mut self) {} - /// Knockout patch (pdfcraft #2974): see `knockout_erase_wanted`. + /// PdfCraft patch (39): see `knockout_erase_wanted`. fn end_knockout_erase(&mut self) {} - /// Knockout patch (pdfcraft #4898): the knockout group just pushed (`set_knockout`) is drawn - /// once per blend mode its elements use, each pass into a layer of its own composited with - /// that mode. In this pass only elements whose blend mode is `mode` paint; every other - /// element clears what is under its shape, as it would replace it. Each pixel then holds the - /// last element covering it in exactly one pass, which composites it with the group's - /// backdrop in that element's own blend mode (#870). + /// PdfCraft patch (67): the knockout group just pushed (`set_knockout`) is drawn once per + /// blend mode its elements use, each pass into a layer of its own composited with that + /// mode. In this pass only elements whose blend mode is `mode` paint; every other element + /// clears what is under its shape, as it would replace it. Each pixel then holds the last + /// element covering it in exactly one pass, which composites it with the group's backdrop + /// in that element's own blend mode (#4886). fn begin_knockout_pass(&mut self, _mode: BlendMode) {} - /// Knockout patch (pdfcraft #4898): ends the pass `begin_knockout_pass` started, before the - /// layer is popped. Returns the other blend modes the pass's elements used, each once. A - /// device that doesn't track them returns none, and the group is drawn in one Normal pass. + /// PdfCraft patch (67): ends the pass `begin_knockout_pass` started, before the layer is + /// popped. Returns the other blend modes the pass's elements used, each once. A device + /// that doesn't track them returns none, and the group is drawn in one Normal pass. fn end_knockout_pass(&mut self) -> Vec { Vec::new() } + /// PdfCraft patch (70): draw the contents of an isolated transparency group that blends + /// in `DeviceCMYK` (ISO 32000-2 §11.3.4), already inside the layer it is composited + /// through. Return `true` when the device drew them; on `false` (the default) the + /// interpreter draws the contents into the device as for any other group. + fn draw_isolated_cmyk_group(&mut self, _group: &CmykGroup<'a, '_>) -> bool { + false + } + /// PdfCraft patch (70): an isolated transparency group that names a blending colour space + /// other than `DeviceCMYK` is about to be drawn. A device drawing an enclosing group in CMYK + /// can no longer draw that group right, since this one blends in its own space. + fn group_blends_outside_device_cmyk(&mut self) {} /// Craft patch (flatten): the overprint parameters for the paints that follow, until the /// next call: `op` (`fill`, for fills, glyph fills and images), `OP` (`stroke`) and `OPM` /// (`mode`, 0 or 1; ISO 32000-2 §8.6.7). Called where `set_blend_mode` is called for a diff --git a/vendor/hayro-interpret/src/encode.rs b/vendor/hayro-interpret/src/encode.rs index 314d133fae..fcffab2b31 100644 --- a/vendor/hayro-interpret/src/encode.rs +++ b/vendor/hayro-interpret/src/encode.rs @@ -18,7 +18,7 @@ pub struct EncodedShadingPattern { pub(crate) shading_type: EncodedShadingType, pub(crate) opacity: f32, pub(crate) transfer_function: Option, - /// PdfCraft patch (#3296): where the shading can paint at all, in device space: for a mesh + /// PdfCraft patch (35): where the shading can paint at all, in device space: for a mesh /// (types 4–7), the pixels its triangles touched when it was encoded (empty when none /// lies in the area); `None` for the shading types that paint everywhere (function-based, /// axial, radial). The renderer samples a texture only there, and skips a mesh that @@ -57,7 +57,7 @@ impl ShadingPattern { /// Mesh shadings are sampled pixel by pixel, and only there (see `TriangleSampler`). pub fn encode_within(&self, area: Option) -> EncodedShadingPattern { let base_transform; - // PdfCraft patch (#3296): see `EncodedShadingPattern::extent`. + // PdfCraft patch (35): see `EncodedShadingPattern::extent`. let mut extent = None; let shading_type = match self.shading.shading_type.as_ref() { @@ -230,7 +230,8 @@ fn encode_axial_shading( } /// PdfCraft patch: pixel visits one mesh shading may make, per pixel of the area it is drawn in -/// and per triangle. Sampling walks each triangle's bounding box (rounded out to whole pixels), +/// and per triangle. Sampling walks each triangle's bounding box (rounded out to whole pixels; +/// patch 99: only the columns of each row the triangle can reach), /// so triangles far off the page (a fuzzed patch decoded onto ±40000) asked for 65536 × 65536 /// samples, and many triangles covering the same pixels repeat the work. A triangle's box is /// about twice its area, and a sub-pixel triangle's box is at most 2 × 2 pixels. @@ -268,7 +269,7 @@ struct TriangleSampler { map: FxHashMap<(u16, u16), ColorComponents>, area: kurbo::Rect, visits_left: u64, - /// PdfCraft patch (#3296): the pixels sampled so far, as `(x0, y0, x1, y1)` inclusive. + /// PdfCraft patch (35): the pixels sampled so far, as `(x0, y0, x1, y1)` inclusive. touched: Option<(u16, u16, u16, u16)>, } @@ -288,7 +289,7 @@ impl TriangleSampler { } } - /// PdfCraft patch (#3296): the device-space rectangle covering every pixel sampled so far + /// PdfCraft patch (35): the device-space rectangle covering every pixel sampled so far /// (whole pixels), or an empty rectangle when no triangle touched the area. fn extent(&self) -> kurbo::Rect { match self.touched { @@ -350,27 +351,55 @@ impl TriangleSampler { } self.visits_left = self.visits_left.saturating_add(MESH_VISITS_PER_TRIANGLE); + let (columns_start, columns_end) = (bbox.x0.floor() as u16, bbox.x1.ceil() as u16); for y in (bbox.y0.floor() as u16)..(bbox.y1.ceil() as u16) { - for x in (bbox.x0.floor() as u16)..(bbox.x1.ceil() as u16) { - if self.visits_left == 0 { - warn!("mesh shading visit budget exceeded; the rest is not drawn"); + // PdfCraft patch (99): only the columns where this row's sample points (the + // corner and the centre, at heights `y` and `y + 0.5`) can lie in the triangle, + // not the whole box. A thin triangle lying across the pixel grid has a box many + // times its area (the cells of a narrow curved band of patches, cut into a fixed + // 19 × 19 grid, are a few pixels long and a fraction of one wide, at every angle), + // and walking the box spent the visit budget before the last patches: painted + // through a path the size of its own box, a rainbow of tensor patches lost its + // inner bands. A box two columns wide or less is walked whole (no row of it is + // narrower by more than a column, which isn't worth finding), and a row with no + // column still costs a visit, so the walk stays within the budget however tall + // the triangle is. + let columns = if columns_end.saturating_sub(columns_start) <= 2 { + columns_start..columns_end + } else { + let top = f64::from(y); + match x_extent_between(&t, top - SPAN_SLACK, top + 0.5 + SPAN_SLACK) { + // Pixel `x` samples at `x` and `x + 0.5`; the casts saturate. + Some((lo, hi)) => { + let start = (lo - 0.5 - SPAN_SLACK).floor() as u16; + let end = ((hi + SPAN_SLACK).floor() as u16).saturating_add(1); + columns_start.max(start)..columns_end.min(end) + } + None => 0..0, + } + }; + if columns.is_empty() { + if !self.take_visit() { + return false; + } + continue; + } + for x in columns { + if !self.take_visit() { return false; } - self.visits_left -= 1; let corner = Point::new(x as f64, y as f64); let sampled = if t.contains_point(corner) { self.map.insert((x, y), t.interpolate(corner)); true } else if t.covers(Point::new(x as f64 + 0.5, y as f64 + 0.5)) { - // PdfCraft patch (#3035): a pixel whose corner no triangle holds strictly (it + // PdfCraft patch (36): a pixel whose corner no triangle holds strictly (it // lies on an edge two triangles share, or on the mesh's side) still belongs - // to the triangle that covers its center, edges included. Testing only the + // to the triangle that covers its centre, edges included. Testing only the // corner left a white seam along every shared edge. Such a pixel takes the - // color at its corner, as every other pixel does (where MuPDF's colors + // colour at its corner, as every other pixel does (where MuPDF's colours // agree), unless a triangle that holds the corner gives it one. - self.map - .entry((x, y)) - .or_insert_with(|| t.interpolate(corner)); + self.map.entry((x, y)).or_insert_with(|| t.interpolate(corner)); true } else { false @@ -385,6 +414,53 @@ impl TriangleSampler { } true } + + /// Spend one visit; `false` (with a warning) when none is left. + fn take_visit(&mut self) -> bool { + if self.visits_left == 0 { + warn!("mesh shading visit budget exceeded; the rest is not drawn"); + return false; + } + self.visits_left -= 1; + true + } +} + +/// PdfCraft patch (99): how far past a row's sample points the triangle's extent is still +/// walked, in pixels. A sample a little outside the triangle can still pass `covers`, whose +/// tolerance is relative to the triangle's size (1e-9 of it, under 1e-4 pixel on a 65536-pixel +/// canvas); this is wider than that and than the rounding of the extent itself. A triangle +/// whose corners all but coincide (two of them 1e-13 pixel apart, its area 1e-14) can pass +/// `covers` for points well outside it, through rounding in its barycentric division; the +/// box walk took such points, the extent leaves them out. +const SPAN_SLACK: f64 = 1e-3; + +/// PdfCraft patch (99): the least and greatest x of the part of `t` between the heights `y0` +/// and `y1`, or `None` when no part of it is there: the ends of that part are the triangle's +/// corners inside the band and the points where its edges cross the band's two lines. +fn x_extent_between(t: &Triangle, y0: f64, y1: f64) -> Option<(f64, f64)> { + let corners = [t.p0.point, t.p1.point, t.p2.point]; + let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY); + let mut add = |x: f64| { + lo = lo.min(x); + hi = hi.max(x); + }; + for (a, b) in corners.iter().zip(corners.iter().cycle().skip(1)) { + if (y0..=y1).contains(&a.y) { + add(a.x); + } + // A level edge lies along the band or misses it; its corners are taken above. + if a.y != b.y { + for line in [y0, y1] { + let s = (line - a.y) / (b.y - a.y); + if (0.0..=1.0).contains(&s) { + add(a.x + s * (b.x - a.x)); + } + } + } + } + // NaN corners add nothing (every comparison fails), so this is `None` for them. + (lo <= hi).then_some((lo, hi)) } /// The triangle `v0`, `v1`, `v2` with its points mapped through `transform` (its colours as diff --git a/vendor/hayro-interpret/src/font/blob.rs b/vendor/hayro-interpret/src/font/blob.rs index 53501e5ac3..2dd1ecf1c0 100644 --- a/vendor/hayro-interpret/src/font/blob.rs +++ b/vendor/hayro-interpret/src/font/blob.rs @@ -5,6 +5,7 @@ use skrifa::instance::{LocationRef, Size}; use skrifa::metrics::GlyphMetrics; use skrifa::outline::{DrawSettings, Engine, HintingInstance, HintingOptions, Target}; use skrifa::raw::TableProvider; +use skrifa::raw::model::pen::NullPen; use skrifa::raw::ps::cff::{CffFontRef, Subfont, charset::Charset, v1::Cff}; use skrifa::raw::ps::string::Sid; use skrifa::raw::ps::type1::Type1Font; @@ -52,7 +53,8 @@ impl Type1FontBlob { #[derive(Clone)] pub(crate) struct CffFontBlob(Arc, Arc>); -/// PdfCraft patch (50): glyph name to glyph id, built on first use. +/// PdfCraft patch: (see vendor/README.md hayro-interpret (50)) glyph name to glyph id, built on +/// first use. type GlyphNames = HashMap, GlyphId>; impl Debug for CffFontBlob { @@ -66,18 +68,23 @@ impl CffFontBlob { let font = CffFontRef::new(data.as_ref().as_ref(), 0, None).ok()?; let cff = Cff::read(ReadFontData::new(data.as_ref().as_ref())).ok()?; let charset = font.charset(); + // PdfCraft patch (93): a font dict that cannot be read (a CID font's FDArray entry + // emptied by a subsetter, with no Private DICT) leaves only the glyphs it selects + // missing. The font is dropped only when no font dict is usable. let subfonts = (0..font.num_subfonts()) .map(|index| font.subfont(index, &[]).ok()) - .collect::>>()?; + .collect::>(); + if !subfonts.iter().any(Option::is_some) { + return None; + } - let yoke = Yoke::, FontData>::attach_to_cart(data.clone(), |data| { + // PdfCraft patch (93): the subfonts read above own their data, so they move into the + // yoke instead of being read again. + let yoke = Yoke::, FontData>::attach_to_cart(data.clone(), move |data| { let bytes = data.as_ref(); let font = CffFontRef::new(bytes, 0, None).unwrap(); let cff = Cff::read(ReadFontData::new(bytes)).unwrap(); let charset = font.charset(); - let subfonts = (0..font.num_subfonts()) - .map(|index| font.subfont(index, &[]).unwrap()) - .collect(); CFFYoke { font, cff, @@ -86,7 +93,7 @@ impl CffFontBlob { } }); - let _ = (cff, charset, subfonts); + let _ = (cff, charset); Some(Self(Arc::new(yoke), Arc::new(OnceLock::new()))) } @@ -104,7 +111,7 @@ impl CffFontBlob { fn subfont(&self, glyph: GlyphId) -> Option<&Subfont> { let index = self.font().subfont_index(glyph)? as usize; - self.0.as_ref().get().subfonts.get(index) + self.0.as_ref().get().subfonts.get(index)?.as_ref() } pub(crate) fn outline_glyph(&self, glyph: GlyphId) -> BezPath { @@ -120,6 +127,18 @@ impl CffFontBlob { path.take() } + /// PdfCraft patch (see vendor/README.md hayro-interpret (77)): the glyph's own advance from + /// its charstring, in thousandths of an em like [`Self::outline_glyph`], or `None` when the + /// charstring can't be read or gives no usable width. + pub(crate) fn advance_width(&self, glyph: GlyphId) -> Option { + let subfont = self.subfont(glyph)?; + self.font() + .draw(subfont, glyph, &[], Some(UNITS_PER_EM), &mut NullPen) + .ok() + .flatten() + .filter(|width| width.is_finite() && *width > 0.0) + } + pub(crate) fn glyph_names(&self) -> Vec<(GlyphId, String)> { let Some(charset) = self.charset() else { return Vec::new(); @@ -137,9 +156,8 @@ impl CffFontBlob { } pub(crate) fn glyph_index_by_name(&self, name: &str) -> Option { - // PdfCraft patch (50): called for every character code of a font, so the charset is - // read once. The first glyph of a name wins, as it did when the charset was searched - // in order. + // Called for every character code of a font, so the charset is read once. The first + // glyph of a name wins, as it did when the charset was searched in order. self.1 .get_or_init(|| { let mut names = GlyphNames::new(); @@ -170,6 +188,13 @@ impl CffFontBlob { self.font().num_glyphs() } + /// PdfCraft patch (69): the `CFF ` table of an OpenType font, for a `FontFile3` of + /// subtype `OpenType` (ISO 32000-2 §9.9) under a simple font. + pub(crate) fn from_open_type(data: &[u8]) -> Option { + let cff = FontRef::new(data).ok()?.cff().ok()?; + Self::new(Arc::new(cff.offset_data().as_ref().to_vec())) + } + pub(crate) fn is_cid(&self) -> bool { self.font().is_cid() } @@ -190,13 +215,53 @@ impl Debug for OpenTypeFontBlob { } } +/// PdfCraft patch (83): a copy of the font with its `head.indexToLocFormat` set to the format its +/// `loca` table is in, when the field holds neither 0 (short offsets) nor 1 (long), or `None` when +/// it needs no change. The glyph outline reader takes only 1 as long, so a font whose field reads +/// 256 (the value's bytes swapped) had its long `loca` read as short offsets: every glyph came +/// out wrong, and a line of text set in it drew boxes (pdf.js `issue2537r.pdf`). The `loca` +/// table's length decides: room for `numGlyphs + 1` offsets of 4 bytes is long, room for only +/// that many of 2 bytes short (a table may carry padding after its offsets), and a table too +/// short for either is left as it is. +fn with_loca_format_fixed(data: &[u8], index: u32) -> Option> { + use skrifa::raw::types::Tag; + const HEAD: Tag = Tag::new(b"head"); + const LOCA: Tag = Tag::new(b"loca"); + // The `indexToLocFormat` field's offset in `head`. + const FORMAT_AT: usize = 50; + let f = FontRef::from_index(data, index).ok()?; + let format = f.head().ok()?.index_to_loc_format(); + if format == 0 || format == 1 { + return None; + } + let offsets = usize::from(f.maxp().ok()?.num_glyphs()).checked_add(1)?; + let loca_len = f.table_data(LOCA)?.len(); + let long = if loca_len >= offsets.checked_mul(4)? { + true + } else if loca_len >= offsets.checked_mul(2)? { + false + } else { + return None; + }; + let head_at = f.table_directory.table_records().iter().find(|r| r.tag() == HEAD)?.offset() as usize; + let at = head_at.checked_add(FORMAT_AT)?; + let mut fixed = data.to_vec(); + fixed.get_mut(at..at.checked_add(2)?)?.copy_from_slice(&i16::from(long).to_be_bytes()); + Some(fixed) +} + impl OpenTypeFontBlob { pub(crate) fn new(data: FontData, index: u32) -> Option { + // PdfCraft patch (83): see `with_loca_format_fixed`. + let data = match with_loca_format_fixed(data.as_ref().as_ref(), index) { + Some(fixed) => Arc::new(fixed) as FontData, + None => data, + }; // Check first whether the font is valid so we can unwrap in the closure. let f = FontRef::from_index(data.as_ref().as_ref(), index).ok()?; // Reject fonts with invalid post table version, fixes pdf.js issue 9462. Not sure if there // is a better fix, for some reason skrifa accepts the font which is completely invalid. - // PdfCraft patch (49): also accept 1.0, 2.0 and 3.0 with the two 16-bit halves swapped + // PdfCraft patch: also accept 1.0, 2.0 and 3.0 with the two 16-bit halves swapped // (`00 00 00 03` for 3.0), as ScanSoft PDF Create! writes it into every font it embeds // (#2946). Rejecting those fonts drew their text with a substitute that has no such glyphs. let invalid = f.post().is_ok_and(|p| { @@ -279,10 +344,10 @@ impl OpenTypeFontBlob { return glyph_names; }; - // PdfCraft patch (49): a version written with its halves swapped (`00 00 00 02`, - // accepted in `new`) is read as the version it means, from a copy of the table with the - // version written correctly: read-fonts reads a 2.0 table's name index only under - // version 2.0, so otherwise its glyph names were never found (#2946). + // PdfCraft patch: a version written with its halves swapped (`00 00 00 02`, accepted in + // `new`) is read as the version it means, from a copy of the table with the version + // written correctly: read-fonts reads a 2.0 table's name index only under version 2.0, + // so otherwise its glyph names were never found (#2946). let repaired = match post.version().to_be_bytes() { [0, 0, 0, n @ 1..=3] => self .font_ref() @@ -296,9 +361,9 @@ impl OpenTypeFontBlob { }), _ => None, }; - let repaired_post = repaired - .as_deref() - .and_then(|b| skrifa::raw::tables::post::Post::read(ReadFontData::new(b)).ok()); + let repaired_post = repaired.as_deref().and_then(|b| { + skrifa::raw::tables::post::Post::read(ReadFontData::new(b)).ok() + }); let post = repaired_post.as_ref().unwrap_or(&post); match post.version().to_major_minor() { (1, 0) => { @@ -378,7 +443,8 @@ struct CFFYoke<'a> { font: CffFontRef<'a>, cff: Cff<'a>, charset: Option>, - subfonts: Vec, + /// PdfCraft patch (93): `None` for a font dict that could not be read. + subfonts: Vec>, } #[cfg(test)] @@ -477,49 +543,5 @@ mod tests { assert!(Arc::ptr_eq(&blob.1, &shared.1), "clones share one name map"); assert_eq!(shared.glyph_index_by_name("Alpha"), Some(GlyphId::new(1))); } - - /// An sfnt with only a `post` table of the given version, naming three glyphs `.notdef`, - /// `A` (a standard name) and `W.cv07` (a name of its own) when the version is 2.0. - fn font_with_post(version: [u8; 4]) -> FontData { - let mut post = version.to_vec(); - post.extend_from_slice(&[0; 28]); - post.extend_from_slice(&3u16.to_be_bytes()); - for index in [0u16, 36, 258] { - post.extend_from_slice(&index.to_be_bytes()); - } - post.push(6); - post.extend_from_slice(b"W.cv07"); - let mut font = vec![0, 1, 0, 0, 0, 1, 0, 16, 0, 0, 0, 0]; - font.extend_from_slice(b"post"); - font.extend_from_slice(&[0; 4]); - font.extend_from_slice(&28u32.to_be_bytes()); - font.extend_from_slice(&(post.len() as u32).to_be_bytes()); - font.extend(post); - Arc::new(font) - } - - #[test] - fn a_post_version_with_swapped_halves_is_read_as_the_version_it_means() { - for (swapped, correct) in [([0, 0, 0, 1], [0, 1, 0, 0]), ([0, 0, 0, 3], [0, 3, 0, 0])] { - assert!(OpenTypeFontBlob::new(font_with_post(correct), 0).is_some()); - assert!( - OpenTypeFontBlob::new(font_with_post(swapped), 0).is_some(), - "{swapped:?} is accepted" - ); - } - let names = |version| { - OpenTypeFontBlob::new(font_with_post(version), 0) - .unwrap() - .glyph_names() - }; - let correct = names([0, 2, 0, 0]); - assert_eq!(correct.get("A"), Some(&GlyphId::new(1))); - assert_eq!(correct.get("W.cv07"), Some(&GlyphId::new(2))); - assert_eq!( - names([0, 0, 0, 2]), - correct, - "a swapped 2.0 table names its glyphs" - ); - assert!(OpenTypeFontBlob::new(font_with_post([0, 9, 0, 0]), 0).is_none()); - } } + diff --git a/vendor/hayro-interpret/src/font/cid.rs b/vendor/hayro-interpret/src/font/cid.rs index db40d5a716..68b36e325c 100644 --- a/vendor/hayro-interpret/src/font/cid.rs +++ b/vendor/hayro-interpret/src/font/cid.rs @@ -16,10 +16,12 @@ use kurbo::{BezPath, Vec2}; use skrifa::attribute::Style; use skrifa::charmap::MapVariant; use skrifa::raw::collections::int_set::Domain; +use skrifa::raw::tables::post::DEFAULT_GLYPH_NAMES; use skrifa::{FontRef, GlyphId, MetadataProvider}; use std::collections::HashMap; use std::ops::Deref; use std::sync::Arc; +use std::sync::OnceLock; #[derive(Debug)] pub(crate) struct Type0Font { @@ -42,6 +44,9 @@ pub(crate) struct Type0Font { /// Whether the `to_unicode` map is a UCS2 `CMap` (CID-indexed) rather than /// a `ToUnicode` `CMap` (code-indexed). to_unicode_is_cid_indexed: bool, + /// PdfCraft patch (84): the character collection's UCS2 CMap (by CID), for the codes the + /// font's own `/ToUnicode` gives nothing for, whether or not its program is embedded. + ucs2: Option, /// PdfCraft patch: whether the CIDs belong to an Adobe character collection (Japan1, GB1, /// CNS1, Korea1), whose glyph numbering no substitute other than a CID-keyed CFF font shares. adobe_collection: bool, @@ -50,6 +55,11 @@ pub(crate) struct Type0Font { /// such text as the code's Unicode value; the identity CMap the name resolves to maps codes /// to CIDs only and gave no text at all. identity_to_unicode: bool, + /// PdfCraft patch: an Arial or a Times New Roman the PDF doesn't embed, as a TrueType CID + /// font (`CIDFontType2`) whose CIDs aren't of an Adobe character collection. Its CIDToGIDMap + /// gives glyph indexes in the author's font, which numbers its first 258 glyphs in the + /// standard Macintosh order of the TrueType `post` table (#5889, #6449). + mac_glyph_order: bool, } impl Type0Font { @@ -86,7 +96,9 @@ impl Type0Font { if let Some((standard, _)) = select_standard_font(dict, &font_descriptor) { (FontQuery::Standard(standard), true) } else { - let mut query = FallbackFontQuery::new(dict); + // PdfCraft patch: the style comes from the descendant's descriptor. + let mut query = + FallbackFontQuery::with_descriptor(dict, Some(font_descriptor.clone())); query.character_collection = character_collection.clone(); warn!( @@ -129,18 +141,24 @@ impl Type0Font { .is_some_and(|n| matches!(n.as_ref(), b"Identity-H" | b"Identity-V")); let mut to_unicode_is_cid_indexed = false; + // PdfCraft patch (84): the character collection's UCS2 CMap (ISO 32000-2 §9.10.2), CID + // to Unicode, for a font of an Adobe collection whether or not its program is embedded. + let mut ucs2 = character_collection + .as_ref() + .and_then(|cc| cc.family.ucs2_cmap()) + .and_then(|name| (cmap_resolver)(name)) + .map(|data| Ucs2 { + data, + resolver: cmap_resolver.clone(), + map: OnceLock::new(), + }); // If there is no ToUnicode map, try to get the UCS2 CMap. if fallback && to_unicode.is_none() - && let Some(cc) = character_collection.as_ref() - && let Some(ucs2_name) = cc.family.ucs2_cmap() - && let Some(data) = (cmap_resolver)(ucs2_name) + && let Some(ucs2_cmap) = ucs2.take().and_then(|u| u.parse()) { - let resolver = cmap_resolver.clone(); - if let Some(ucs2_cmap) = CMap::parse(data, move |n| (resolver)(n)) { - to_unicode = Some(ucs2_cmap); - to_unicode_is_cid_indexed = true; - } + to_unicode = Some(ucs2_cmap); + to_unicode_is_cid_indexed = true; } let adobe_collection = character_collection @@ -151,6 +169,17 @@ impl Type0Font { .get::>(BASE_FONT) .map(|n| strip_subset_prefix(n.as_str()).to_string()); + // PdfCraft patch: the descendant names the font program itself; a Type 0 font's own + // `/BaseFont` may carry the CMap's name after it. + let mac_glyph_order = fallback + && !adobe_collection + && descendant_font + .get::>(SUBTYPE) + .is_some_and(|s| s.deref() == CID_FONT_TYPE2) + && descendant_font + .get::>(BASE_FONT) + .is_some_and(|n| numbers_glyphs_in_mac_order(strip_subset_prefix(n.as_str()))); + // Extract font flags from descriptor let font_flags = font_descriptor .get::(FLAGS) @@ -171,8 +200,10 @@ impl Type0Font { font_flags, fallback, to_unicode_is_cid_indexed, + ucs2, adobe_collection, identity_to_unicode, + mac_glyph_order, }) } @@ -196,6 +227,16 @@ impl Type0Font { return glyph; } + // PdfCraft patch: the CID of an Arial or a Times New Roman the PDF doesn't embed names + // one of that font's glyphs, which the substitute draws by that name. Taken as the + // substitute's own glyph index it drew an unrelated glyph: "Low Power" as + // "@ck 'Dck Yf" (#5889), "Salarié(e) du régime" as "Salari²*g+f w't²i lo" (#6449). + if self.mac_glyph_order + && let Some(glyph) = self.map_via_mac_glyph_name(cid) + { + return glyph; + } + // PdfCraft patch: a substitute that isn't CID-keyed numbers its glyphs its own way, so // the CID of an Adobe character collection taken as its glyph index draws an unrelated // glyph. Draw .notdef, as for a CID the font has no glyph for. @@ -285,13 +326,14 @@ impl Type0Font { } FontType::Cff(c) => { // Map codepoint to glyph name via AFL, and then look it up. - if let Some(name) = glyph_names::get_reverse(character) - && let Some(gid) = c.glyph_index_by_name(name) - { - Some(gid) - } else { - None - } + let by_name = |character: char| { + glyph_names::get_reverse(character).and_then(|name| c.glyph_index_by_name(name)) + }; + // PdfCraft patch: a soft hyphen the substitute has no glyph for is its hyphen + // (#5888). Windows exporters map the hyphen glyph of a font they don't embed to + // U+00AD, which ISO 32000-2 Annex D.2 calls typographically the same as the + // hyphen; without this the CID, taken as a glyph index, drew an unrelated glyph. + by_name(character).or_else(|| (character == '\u{00ad}').then(|| by_name('-')).flatten()) } FontType::Type1(_) => { // We could in theory map to a glyph via AFL and then look up @@ -304,6 +346,27 @@ impl Type0Font { } } + /// PdfCraft patch: the substitute's glyph for the author's glyph that `cid` gives, found by + /// that glyph's name in the standard Macintosh order. `None` past the 258 glyphs the order + /// names, and for a substitute that isn't a name-keyed CFF font (the standard substitutes + /// are); .notdef for a name the substitute has no glyph for. + fn map_via_mac_glyph_name(&self, cid: u32) -> Option { + let FontType::Cff(c) = &self.font_type else { + return None; + }; + if c.is_cid() { + return None; + } + let gid = self.cid_to_gid_map.map(u16::try_from(cid).ok()?); + let name = *DEFAULT_GLYPH_NAMES.get(usize::try_from(gid.to_u32()).ok()?)?; + // `.null` and `nonmarkingreturn` draw nothing, and `nonbreakingspace` is a space. + let name = match name { + ".null" | "nonmarkingreturn" | "nonbreakingspace" => "space", + name => name, + }; + Some(c.glyph_index_by_name(name).unwrap_or(GlyphId::NOTDEF)) + } + fn code_to_cid(&self, code: u32) -> Option { for byte_len in 1..=4_u8 { if let Some(cid) = self.encoding.lookup_cid_code(code, byte_len) { @@ -426,6 +489,13 @@ impl Type0Font { } } + /// PdfCraft patch: the code's width w0 (its horizontal displacement, from `/W` or `/DW`) + /// in either writing mode. In vertical writing it is the glyph's extent across the column + /// (ISO 32000-2 §9.7.4.3). + pub(crate) fn code_horizontal_width(&self, code: u32) -> f32 { + self.horizontal_width(self.code_to_cid(code).unwrap_or(0)) + } + fn horizontal_width(&self, cid: u32) -> f32 { self.widths.get(&cid).copied().unwrap_or(self.dw) } @@ -465,7 +535,8 @@ impl Type0Font { /// identity `/ToUnicode` name, when the code is a control or a lone surrogate). pub(crate) fn char_code_to_unicode(&self, code: u32) -> Option { if self.identity_to_unicode { - // Controls and lone surrogates are not text. + // Controls and lone surrogates are not text. The same rule builds the editing + // map, `identity_to_unicode` in crates/fonts/src/pdf.rs: keep both alike. return char::from_u32(code) .filter(|c| !c.is_control()) .map(BfString::Char); @@ -476,13 +547,63 @@ impl Type0Font { } else { code }; - return to_unicode.lookup_bf_string(key); + // PdfCraft patch (85): a `/ToUnicode` written as a CID CMap (`begincidrange` / + // `begincidchar`, whose destinations are numbers) gives the code's Unicode value as + // that number, as glyph lookup already reads it (`map_via_unicode`) and as pdftotext + // and PDFium extract it. ISO 32000-2 §9.10.3 has `beginbfrange` / `beginbfchar` here; + // Word writes CID ranges, and such text extracted nothing. + if let Some(s) = to_unicode.lookup_bf_string(key).or_else(|| { + (1..=4) + .find_map(|len| { + to_unicode + .lookup_cid_code(key, len) + .and_then(|cid| char::from_u32(cid.to_u32())) + }) + .map(BfString::Char) + }) { + return Some(s); + } + } + // PdfCraft patch (84): then the collection's UCS2 CMap, by the code's CID. + if let Some(ucs2) = self.ucs2.as_ref().and_then(Ucs2::cmap) + && let Some(s) = self + .code_to_cid(code) + .and_then(|cid| ucs2.lookup_bf_string(cid)) + { + return Some(s); } None } } +/// PdfCraft patch (84): a collection's UCS2 CMap, parsed the first time a code needs it: a font +/// whose `/ToUnicode` maps every code it shows never parses it. +struct Ucs2 { + data: &'static [u8], + resolver: CMapResolverFn, + map: OnceLock>, +} + +impl Ucs2 { + fn parse(&self) -> Option { + let resolver = self.resolver.clone(); + CMap::parse(self.data, move |n| (resolver)(n)) + } + + fn cmap(&self) -> Option<&CMap> { + self.map.get_or_init(|| self.parse()).as_ref() + } +} + +impl std::fmt::Debug for Ucs2 { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Ucs2") + .field("bytes", &self.data.len()) + .finish_non_exhaustive() + } +} + impl CacheKey for Type0Font { fn cache_key(&self) -> u128 { self.cache_key @@ -592,6 +713,37 @@ fn is_variation_selector(c: char) -> bool { matches!(c, '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}') } +/// PdfCraft patch: whether `name`, a `/BaseFont` without its subset tag, is one of the four +/// faces of Arial or Times New Roman as exporters name them: `ArialMT`, `Arial-BoldMT`, +/// `Arial-ItalicMT`, `Arial-BoldItalicMT`, `TimesNewRomanPSMT`, `TimesNewRomanPS-BoldMT` and so +/// on, or `Arial` or `TimesNewRoman` followed by `,Bold`, `,Italic` or `,BoldItalic`. Both +/// number their first 258 glyphs in the standard Macintosh order. Arial Narrow, Arial Black, +/// Arial Unicode MS and Arial Rounded are other fonts, numbered their own way. Letter case +/// doesn't matter, `MT` included. +fn numbers_glyphs_in_mac_order(name: &str) -> bool { + let (family, style) = name.split_once([',', '-', ' ']).unwrap_or((name, "")); + let style: String = style + .chars() + .filter(|c| !matches!(c, ',' | '-' | ' ')) + .collect(); + ["Arial", "TimesNewRoman", "TimesNewRomanPS"] + .iter() + .any(|f| without_mt(family).eq_ignore_ascii_case(f)) + && ["", "Regular", "Bold", "Italic", "BoldItalic"] + .iter() + .any(|s| without_mt(&style).eq_ignore_ascii_case(s)) +} + +/// PdfCraft patch: `name` without a trailing `MT` in any letter case (Monotype's mark in +/// PostScript names such as `ArialMT`). +fn without_mt(name: &str) -> &str { + name.len() + .checked_sub(2) + .and_then(|stem| Some((name.get(..stem)?, name.get(stem..)?))) + .filter(|(_, suffix)| suffix.eq_ignore_ascii_case("MT")) + .map_or(name, |(stem, _)| stem) +} + /// PdfCraft patch: the largest CID (ISO 32000-2 §9.7.2; CIDs are at most two bytes). const MAX_CID: u32 = 65_535; @@ -689,6 +841,8 @@ fn read_encoding(object: &Object<'_>, cmap_resolver: &CMapResolverFn) -> Option< } } +/// PdfCraft patch test (ported from craft-libs): a /W2 run whose first CID is past `MAX_CID` +/// is skipped and the rest of the table kept. #[cfg(test)] mod tests { use super::read_widths2; @@ -707,3 +861,75 @@ mod tests { assert_eq!(map.len(), 12); } } + +#[cfg(test)] +mod width_tests { + use super::*; + use hayro_syntax::Pdf; + use hayro_syntax::object::ObjectIdentifier; + + /// A PDF whose object 5 is `array`, for what references in it can reach. + fn with_array(array: &str) -> Pdf { + let pdf = format!( + "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n\ + 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\ + 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >> endobj\n\ + 4 0 obj 20 endobj\n5 0 obj {array} endobj\n6 0 obj 22 endobj\n\ + 7 0 obj 7 0 R endobj\n8 0 obj 9 0 R endobj\n9 0 obj 8 0 R endobj\n\ + 10 0 obj 4 0 R endobj\n11 0 obj [500 600] endobj\n12 0 obj [-1000 500 880] endobj\n\ + trailer << /Root 1 0 R >>\n%%EOF\n" + ); + Pdf::new(pdf.into_bytes()).unwrap() + } + + /// `/W` and `/W2` read groups of items, and either kind can start with a reference: taken for + /// the whole group it was lost, with all that followed, and those glyphs fell back to `/DW`. + #[test] + fn a_width_group_can_start_with_a_reference() { + let widths = |array: &str| { + let pdf = with_array(array); + let array = pdf.xref().get::>(ObjectIdentifier::new(5, 0)).unwrap(); + let mut read: Vec<_> = read_widths(&array).unwrap().into_iter().collect(); + read.sort_by_key(|(cid, _)| *cid); + read + }; + let by_list = vec![(20, 500.0), (21, 600.0)]; + assert_eq!(widths("[20 [500 600]]"), by_list); + assert_eq!(widths("[4 0 R [500 600]]"), by_list); + let by_range = vec![(20, 700.0), (21, 700.0), (22, 700.0)]; + assert_eq!(widths("[20 22 700]"), by_range); + assert_eq!(widths("[4 0 R 22 700]"), by_range); + assert_eq!(widths("[4 0 R 6 0 R 700]"), by_range); + assert_eq!(widths("[1 [100] 4 0 R [500 600]]"), vec![(1, 100.0), (20, 500.0), (21, 600.0)], "after a group"); + + let vertical = |array: &str| { + let pdf = with_array(array); + let array = pdf.xref().get::>(ObjectIdentifier::new(5, 0)).unwrap(); + let mut read: Vec<_> = read_widths2(&array).unwrap().into_iter().collect(); + read.sort_by_key(|(cid, _)| *cid); + read + }; + let by_list = vec![(20, [-1000.0, 500.0, 880.0])]; + assert_eq!(vertical("[20 [-1000 500 880]]"), by_list); + assert_eq!(vertical("[4 0 R [-1000 500 880]]"), by_list); + let by_range = vec![(20, [-900.0, 400.0, 800.0]), (21, [-900.0, 400.0, 800.0]), (22, [-900.0, 400.0, 800.0])]; + assert_eq!(vertical("[20 22 -900 400 800]"), by_range); + assert_eq!(vertical("[4 0 R 22 -900 400 800]"), by_range); + + // A group's list can be given by reference too, and a reference to a reference is what it + // names. + let by_list = vec![(20, 500.0), (21, 600.0)]; + assert_eq!(widths("[20 11 0 R]"), by_list); + assert_eq!(widths("[10 0 R [500 600]]"), by_list); + assert_eq!(widths("[10 0 R 11 0 R]"), by_list); + assert_eq!(vertical("[20 12 0 R]"), vec![(20, [-1000.0, 500.0, 880.0])]); + + // A reference that only leads back to itself holds no number, so those glyphs keep `/DW`. + for array in ["[7 0 R [500 600]]", "[8 0 R [500 600]]", "[20 7 0 R 700]", "[7 0 R 8 0 R 700]", "[20 [7 0 R 600]]"] { + assert!(widths(array).is_empty(), "{array}"); + } + for array in ["[7 0 R [-1000 500 880]]", "[8 0 R 22 -900 400 800]", "[20 [7 0 R 500 880]]"] { + assert!(vertical(array).is_empty(), "{array}"); + } + } +} diff --git a/vendor/hayro-interpret/src/font/mod.rs b/vendor/hayro-interpret/src/font/mod.rs index 37f51f8cfe..e87382d976 100644 --- a/vendor/hayro-interpret/src/font/mod.rs +++ b/vendor/hayro-interpret/src/font/mod.rs @@ -87,6 +87,8 @@ impl Glyph<'_> { /// 1. `ToUnicode` cmap /// 2. Glyph name → Unicode (via Adobe Glyph List) /// 3. Unicode naming conventions (e.g., "uni0041", "u0041") + /// 4. PdfCraft patch (100), Type1 and CFF fonts only: a name that only numbers its glyph, as + /// for Type3 fonts below /// /// **For CID Fonts (Type0):** /// 1. `ToUnicode` cmap @@ -94,6 +96,12 @@ impl Glyph<'_> { /// /// **For Type3 Fonts:** /// 1. `ToUnicode` cmap + /// 2. PdfCraft patch: the `/Encoding` glyph name → Unicode (an Annex D.2 alias code reads as + /// the ordinary character) + /// 3. PdfCraft patch: a printable ASCII code (32–126) as itself + /// 4. PdfCraft patch (100): above 126, a name that only numbers its glyph (`C174`) as the + /// code's Latin-1 character, when the number is that code and every numbered name in the + /// font names its own code /// /// Returns `None` if the Unicode value could not be determined. /// @@ -180,6 +188,19 @@ impl OutlineGlyph { self.font.glyph_advance_width(self.char_code) } + /// PdfCraft patch: for a glyph of a vertical-writing Type0 font, its width w0 (the + /// horizontal displacement from `/W` or `/DW`), which is how wide the glyph sits across the + /// column (ISO 32000-2 §9.7.4.3). `None` for horizontal writing, where + /// [`advance_width`](Self::advance_width) gives it. + pub fn vertical_glyph_width(&self) -> Option { + match &self.font { + OutlineFont::Type0(font) if !font.is_horizontal() => { + Some(font.code_horizontal_width(self.char_code)) + } + _ => None, + } + } + /// Get the cache key for this glyph's font. /// /// This identifies the font uniquely, even when `font_data()` returns `None` @@ -217,9 +238,11 @@ impl<'a> Type3Glyph<'a> { .render_glyph(self, transform, glyph_transform, paint, device); } - /// Returns the Unicode code point for this glyph, if available. + /// Returns the Unicode code point for this glyph, if available: the `ToUnicode` cmap, then + /// the `/Encoding` glyph name, a printable ASCII code, and a numbered glyph name at its own + /// code (PdfCraft patches). /// - /// Note: Type3 fonts can only provide Unicode via `ToUnicode` cmap. + /// See [`Glyph::as_unicode`] for details on the fallback chain used. pub fn as_unicode(&self) -> Option { self.font.char_code_to_unicode(self.char_code) } @@ -245,8 +268,14 @@ impl<'a> Font<'a> { font_resolver: &FontResolverFn, cmap_resolver: &CMapResolverFn, ) -> Option { - let f_type = match dict.get::>(SUBTYPE)?.deref() { - TYPE1 | MM_TYPE1 => { + // PdfCraft patch (94): a font dictionary whose `/Subtype` is missing or the empty name + // (`/Subtype /`) is read as a Type 1 font, so its `/BaseFont` still picks the font: a + // `/Courier-Bold` was drawn in the Helvetica fallback (PDFBOX-1988). `/Subtype` is + // required (ISO 32000-2 §9.6.2.1, Table 109); other readers fall back to Type 1 this way. + let subtype = dict.get::>(SUBTYPE); + let subtype: &[u8] = subtype.as_deref().unwrap_or(b""); + let f_type = match subtype { + b"" | TYPE1 | MM_TYPE1 => { FontType::Type1(Rc::new(Type1Font::new(dict, font_resolver, cmap_resolver)?)) } // PDFBOX-5463: PDF viewers seem to accept OpenType as well. @@ -272,6 +301,12 @@ impl<'a> Font<'a> { Some(Self(cache_key, f_type)) } + /// PdfCraft patch (90): whether this is a Type 3 font without `/Widths` (or + /// `/FirstChar`/`/LastChar`), whose glyphs advance by their `d0`/`d1` widths. + pub(crate) fn type3_widths_missing(&self) -> bool { + matches!(&self.1, FontType::Type3(t) if t.widths_missing()) + } + pub(crate) fn new_standard( standard_font: StandardFont, font_resolver: &FontResolverFn, @@ -565,6 +600,13 @@ pub struct FallbackFontQuery { impl FallbackFontQuery { pub(crate) fn new(dict: &Dict<'_>) -> Self { + Self::with_descriptor(dict, dict.get::>(FONT_DESC)) + } + + /// PdfCraft patch: the query for the font `dict` names, with its style read from + /// `descriptor`. A Type 0 font has no font descriptor of its own; its descendant CIDFont + /// has it (ISO 32000-2 §9.7.4.1, §9.7.6.1). + pub(crate) fn with_descriptor(dict: &Dict<'_>, descriptor: Option>) -> Self { let post_script_name = dict .get::>(BASE_FONT) .map(|n| strip_subset_prefix(n.as_str()).to_string()); @@ -574,7 +616,7 @@ impl FallbackFontQuery { ..Default::default() }; - if let Some(descriptor) = dict.get::>(FONT_DESC) { + if let Some(descriptor) = descriptor { data.font_name = dict .get::>(FONT_NAME) .map(|n| strip_subset_prefix(n.as_str()).to_string()); @@ -663,7 +705,7 @@ pub(crate) fn glyph_name_to_unicode(name: &str) -> Option { return unicode_str.chars().next(); } - unicode_from_name(name).or_else(|| { + agl_unicode_from_name(name).or_else(|| { warn!("failed to map glyph name {} to unicode", name); None @@ -713,6 +755,99 @@ pub(crate) fn glyph_name_to_text(name: &str) -> Option { } } +/// PdfCraft patch: the numbers a glyph name that only numbers its glyph gives (`C39`, `G27`, +/// `MT174`: one to three ASCII letters, then one to six decimal or hexadecimal digits), for +/// every split into letters and digits, read in decimal and in hexadecimal (`GA9` is `G` with +/// hex `A9`); nothing for any other name. Everything from the first `.` is dropped first, as +/// `glyph_name_to_text` drops it. +fn glyph_name_numbers(name: &str) -> impl Iterator + '_ { + let base = name.split('.').next().unwrap_or_default(); + (1..=3).flat_map(move |prefix| { + // `from_str_radix` would also take a leading `+`: the number is digits only, and at + // most six of them (a code is under 256, leading zeros as in `C0032`). + let digits = base + .get(..prefix) + .zip(base.get(prefix..)) + .and_then(|(letters, digits)| { + (letters.bytes().all(|b| b.is_ascii_alphabetic()) + && (1..=6).contains(&digits.len()) + && digits.bytes().all(|b| b.is_ascii_hexdigit())) + .then_some(digits) + }); + digits.into_iter().flat_map(|d| { + [10, 16] + .into_iter() + .filter_map(move |radix| u32::from_str_radix(d, radix).ok()) + }) + }) +} + +/// PdfCraft patch: whether every glyph name in a simple font's encoding that only numbers its +/// glyph (see `glyph_name_numbers`) names the very code it sits at, in decimal or hexadecimal. +/// Names the glyph list or its `uni`/`u` forms read are not numbered names. A font whose names +/// number something else (`/Differences [1 /C70 /C105 …]`, a glyph's order in the subset) +/// fails, and so does one where a single name numbers another code: there a name that happens +/// to match its code (`/MT40` at 0x40, `/C1` at 233 beside `/C70` at 70, review on #3239) is a +/// coincidence, not evidence. A subset that counts its glyphs in order of first use from code 1 +/// (`/Differences [1 /C1 /C2 … /C80]`) names its own codes too, but the counter says nothing +/// about the characters (`/C65` is the 65th glyph used, not `A`): a numbered name at a C0 +/// control code (below 32), which no text shows, gives such a counter away and fails the font. +pub(crate) fn numbered_names_name_their_codes<'a>( + names: impl IntoIterator, +) -> bool { + names + .into_iter() + .filter(|(_, name)| { + glyph_names::get(name).is_none() + && unicode_from_name(name).is_none() + && glyph_name_to_text(name).is_none() + }) + .all(|(code, name)| { + let mut numbers = glyph_name_numbers(name).peekable(); + numbers.peek().is_none() || (code >= 0x20 && numbers.any(|n| n == u32::from(code))) + }) +} + +/// PdfCraft patch: the text of a glyph name outside the glyph list that only numbers its glyph +/// (see `glyph_name_numbers`) when that number is the very code the glyph is shown with: the +/// code's Latin-1 character, for codes above 127 too (`C174` reads `®`), as pdftotext, PDFium +/// and MuPDF read it. The name and the code then agree, so nothing is guessed from an +/// encoding table. A number naming another code (`/C1` at 233, review on #3239) and a control +/// character read as nothing. Callers apply it only in a font where +/// `numbered_names_name_their_codes` holds. +pub(crate) fn numbered_glyph_name_at_its_code(name: &str, code: u8) -> Option { + let c = char::from(code); + if c.is_control() { + return None; + } + glyph_name_numbers(name) + .any(|n| n == u32::from(code)) + .then_some(BfString::Char(c)) +} + +/// PdfCraft patch (92): the character a `uniXXXX` or `uXXXX` to `uXXXXXX` glyph name stands +/// for, by the Adobe Glyph List Specification: `uni` and exactly four uppercase hex digits, or +/// `u` and four to six; a value in the surrogate range or past U+10FFFF is no character. The +/// text of a glyph goes by this rule, so `uni65`, `uni20ac` and `u41` read as nothing, as they +/// do in [`glyph_name_to_text`]. +pub(crate) fn agl_unicode_from_name(name: &str) -> Option { + let upper_hex = |d: &str| d.bytes().all(|b| matches!(b, b'0'..=b'9' | b'A'..=b'F')); + let digits = name + .strip_prefix("uni") + .filter(|d| d.len() == 4) + .or_else(|| { + name.strip_prefix('u') + .filter(|d| (4..=6).contains(&d.len())) + }) + .filter(|d| upper_hex(d))?; + u32::from_str_radix(digits, 16) + .ok() + .and_then(char::from_u32) +} + +/// Upstream's lenient reading of a `uni…` or `u…` name (any number of hex digits, either case), +/// kept for finding a glyph in a font: PdfCraft patch (92) reads text by +/// [`agl_unicode_from_name`] instead. pub(crate) fn unicode_from_name(name: &str) -> Option { let convert = |input: &str| u32::from_str_radix(input, 16).ok().and_then(char::from_u32); diff --git a/vendor/hayro-interpret/src/font/standard_font.rs b/vendor/hayro-interpret/src/font/standard_font.rs index 5941160f77..6655ccd3d6 100644 --- a/vendor/hayro-interpret/src/font/standard_font.rs +++ b/vendor/hayro-interpret/src/font/standard_font.rs @@ -4,7 +4,7 @@ use crate::font::generated::{glyph_names, metrics, standard, symbol, zapf_dings} use crate::font::true_type::{Width, read_encoding, read_widths}; use crate::font::{ Encoding, FontData, FontQuery, glyph_name_to_unicode, normalized_glyph_name, stretch_glyph, - strip_subset_prefix, + strip_subset_prefix, unicode_from_name, }; use hayro_syntax::object::Dict; use hayro_syntax::object::Name; @@ -201,6 +201,32 @@ impl StandardFont { } } +/// PdfCraft patch (98): the style names that may follow `Symbol` or `SymbolMT` after a `,` or +/// `-` and still name the Symbol font (any case). +const SYMBOL_STYLES: [&str; 9] = [ + "Bold", + "Italic", + "BoldItalic", + "Oblique", + "BoldOblique", + "Regular", + "Roman", + "Normal", + "Plain", +]; + +/// PdfCraft patch (98): whether `name` (without a subset prefix) is `Symbol` or `SymbolMT`, alone +/// or followed by `,` or `-` and a style from [`SYMBOL_STYLES`]. Another name after the +/// separator (`Symbol-Helvetica`) is a different font. +fn is_symbol_name(name: &str) -> bool { + let (family, style) = match name.split_once([',', '-']) { + Some((family, style)) => (family, Some(style)), + None => (name, None), + }; + matches!(family, "Symbol" | "SymbolMT") + && style.is_none_or(|style| SYMBOL_STYLES.iter().any(|s| s.eq_ignore_ascii_case(style))) +} + enum StandardFontFamily { Helvetica, Courier, @@ -233,6 +259,13 @@ pub(crate) fn select_standard_font( _ => {} } + // PdfCraft patch (98): `SymbolMT` (the name Symbol has as a TrueType font) and the style + // variants `Symbol,Bold`, `SymbolMT,Italic` or `Symbol-Bold` are the Symbol font, drawn with + // its built-in encoding like `Symbol` itself, whatever `/Encoding` and flags they declare. + if is_symbol_name(name) { + return Some((StandardFont::Symbol, true)); + } + // Now, we bruteforce, trying to determine a suitable font based on the // keywords that appear in the name. let lower = name.to_ascii_lowercase(); @@ -328,7 +361,9 @@ impl StandardFontBlob { pub(crate) fn advance_width(&self, glyph: GlyphId) -> Option { match self { - Self::Cff(_) => None, + // PdfCraft patch (77): the stand-in's own advance, so a glyph drawn wider than the + // standard metrics (the € of the bundled stand-ins) is fitted to them. + Self::Cff(blob) => blob.advance_width(glyph), Self::Otf(blob, _) => blob.glyph_metrics().advance_width(glyph), } } @@ -544,6 +579,15 @@ impl StandardKind { return path; }; + // PdfCraft patch (57): a stand-in for a font the document names is narrowed to a + // narrower /Widths advance, so neighbours don't overlap, but never widened: the + // advance already places the next glyph, and widening drew `i` and `l` of a 600-unit + // `Arial,Bold` as solid blocks twice their width. + let should_width = if self.fallback { + should_width.min(actual_width) + } else { + should_width + }; return stretch_glyph(path, should_width, actual_width); } @@ -760,7 +804,11 @@ fn accented_parts(name: &str) -> Option<(&'static str, &'static str, Place)> { .map(|&(_, base, accent, place)| (base, accent, place)) }; by_name(name).or_else(|| { - let c = glyph_name_to_unicode(name)?; + // Drawing keeps upstream's lenient reading of `uni` names; text goes by the glyph list + // specification (PdfCraft patch 92). + let c = glyph_names::get(name) + .and_then(|s| s.chars().next()) + .or_else(|| unicode_from_name(name))?; match COMMA_BELOW_BY_CHAR.iter().find(|(letter, _)| *letter == c) { Some((_, comma_below)) => by_name(comma_below), None => by_name(glyph_names::get_reverse(c)?), diff --git a/vendor/hayro-interpret/src/font/true_type.rs b/vendor/hayro-interpret/src/font/true_type.rs index c650439961..9d84e62528 100644 --- a/vendor/hayro-interpret/src/font/true_type.rs +++ b/vendor/hayro-interpret/src/font/true_type.rs @@ -2,8 +2,8 @@ use crate::font::blob::{CffFontBlob, OpenTypeFontBlob}; use crate::font::generated::{glyph_names, mac_os_roman, mac_roman, standard, win_ansi}; use crate::font::standard_font::StandardKind; use crate::font::{ - Encoding, FallbackFontQuery, FontFlags, glyph_name_to_text, glyph_name_to_unicode, read_to_unicode, - strip_subset_prefix, unicode_from_name, + Encoding, FallbackFontQuery, FontFlags, glyph_name_to_text, glyph_name_to_unicode, + normalized_glyph_name, read_to_unicode, strip_subset_prefix, unicode_from_name, }; use crate::util::OptionLog; use crate::{CMapResolverFn, CacheKey, FontResolverFn}; @@ -18,6 +18,7 @@ use kurbo::BezPath; use skrifa::attribute::Style; use skrifa::raw::TableProvider; use skrifa::raw::tables::cmap::PlatformId; +use skrifa::raw::tables::post::DEFAULT_GLYPH_NAMES; use skrifa::{GlyphId, MetadataProvider}; use std::cell::RefCell; use std::collections::HashMap; @@ -190,11 +191,23 @@ impl TrueTypeFont { } match &self.kind { - // PdfCraft patch (#3169): a name outside the glyph list reads by the glyph list - // specification's full mapping (`f_i`, `hyphen.case`). - Kind::Embedded(e) => e.code_to_unicode_name(code as u8).and_then(|name| { - glyph_name_to_unicode(name).map(BfString::Char).or_else(|| glyph_name_to_text(name)) - }), + Kind::Embedded(e) => { + // PdfCraft patch (79): see `EmbeddedKind::symbolic_text`. + if let Some(text) = e.symbolic_text(code as u8) { + let mut chars = text.chars(); + return Some(match (chars.next(), chars.next()) { + (Some(c), None) => BfString::Char(c), + _ => BfString::String(text.to_string()), + }); + } + // PdfCraft patch (#3169): a name outside the glyph list reads by the glyph list + // specification's full mapping (`f_i`, `hyphen.case`). + e.code_to_unicode_name(code as u8).and_then(|name| { + glyph_name_to_unicode(name) + .map(BfString::Char) + .or_else(|| glyph_name_to_text(name)) + }) + } Kind::Standard(s) => s.char_code_to_unicode(code as u8).map(BfString::Char), } @@ -220,13 +233,19 @@ struct EmbeddedKind { cached_mappings: RefCell>, /// PostScript name from the PDF. postscript_name: Option, + /// PdfCraft patch (79): the text each glyph's `post` table name stands for, for the names + /// that stand for any (`glyph_name_text`). + text_names: HashMap, + /// PdfCraft patch (101): whether the font may take the Mac OS Roman reading at all, worked out + /// once when it is loaded (`EmbeddedKind::mac_roman_name`). + mac_roman_eligible: bool, } impl EmbeddedKind { fn new(dict: &Dict<'_>) -> Option { let descriptor = dict.get::>(FONT_DESC).unwrap_or_default(); - let font_flags = descriptor.get::(FLAGS).and_then(FontFlags::from_bits); + let font_flags = descriptor.get::(FLAGS).map(FontFlags::from_bits_truncate); let (widths, missing_width) = read_widths(dict, &descriptor)?; let (encoding, differences) = read_encoding(dict); @@ -236,6 +255,10 @@ impl EmbeddedKind { .and_then(|d| OpenTypeFontBlob::new(Arc::new(d.to_vec()), 0))?; let glyph_names = base_font.glyph_names(); + let text_names = glyph_names + .iter() + .filter_map(|(name, glyph)| Some((*glyph, glyph_name_text(name)?))) + .collect(); let cff_font_blob = base_font .font_ref() @@ -247,6 +270,27 @@ impl EmbeddedKind { .get::>(BASE_FONT) .map(|n| strip_subset_prefix(n.as_str()).to_string()); + // PdfCraft patch (101): the font names no base encoding, not even one this reader doesn't + // know (which `read_encoding` reads as the built-in one), and isn't Symbol or ZapfDingbats, + // whose built-in encodings aren't Latin (ISO 32000-2 §9.6.6.1). Both as the editor's + // `unicode_map` decides them, Symbol and ZapfDingbats recognised by name as there. + let names_base_encoding = dict.get::>(ENCODING).is_some() + || dict + .get::>(ENCODING) + .is_some_and(|d| d.get::>(BASE_ENCODING).is_some()); + let symbolic_builtin = dict.get::>(BASE_FONT).is_some_and(|n| { + let name = n.as_str(); + let flat: String = name + .rsplit('+') + .next() + .unwrap_or(name) + .chars() + .filter(char::is_ascii_alphanumeric) + .map(|c| c.to_ascii_lowercase()) + .collect(); + flat.contains("symbol") || flat.contains("zapf") || flat.contains("dingbat") + }); + Some(Self { base_font, differences, @@ -258,6 +302,8 @@ impl EmbeddedKind { encoding, cached_mappings: RefCell::new(HashMap::new()), postscript_name, + text_names, + mac_roman_eligible: !names_base_encoding && !symbolic_builtin, }) } @@ -291,16 +337,168 @@ impl EmbeddedKind { // `Encoding::text_alias`. .or_else(|| self.encoding.text_alias(code)) .or_else(|| self.encoding.map_code(code)) + // PdfCraft patch (101): see `EmbeddedKind::mac_roman_name`. + .or_else(|| self.mac_roman_name(code)) // The last resort reads the code as WinAnsi whatever the font said, so it takes the // same aliasing. .or_else(|| Encoding::WinAnsi.text_alias(code)) .or_else(|| win_ansi::get(code)) } + /// PdfCraft patch (79): a symbolic font without an encoding selects its glyphs through its + /// own `cmap`, so its codes need not mean anything in WinAnsi. FrameMaker files distilled + /// with Distiller 3 number them in the Macintosh glyph order, 29 below ASCII, and read as + /// WinAnsi `Solid` came out as `6ROLG` (#3962). The name the `post` table gives the glyph the + /// code selects says what it is, as MuPDF reads it, and as pdfcraft-fonts reads it for the + /// editor. `None` when the font is non-symbolic, has an encoding or a `/Differences` entry + /// for the code, selects no glyph for it, or names it with no text: the code is then read as + /// before. + fn symbolic_text(&self, code: u8) -> Option<&str> { + if self.is_non_symbolic() + || !matches!(self.encoding, Encoding::BuiltIn) + || self.differences.contains_key(&code) + || self.cff_blob.is_some() + { + return None; + } + let glyph = self.map_code(code); + if glyph == GlyphId::NOTDEF { + return None; + } + self.text_names.get(&glyph).map(String::as_str) + } + fn outline_glyph(&self, glyph: GlyphId) -> BezPath { self.base_font.outline_glyph(glyph) } + fn map_unicode_in_cmap(&self, c: char) -> Option { + let cmap = self.base_font.font_ref().cmap().ok()?; + let mut glyph = None; + + for record in cmap.encoding_records() { + if record.platform_id() == PlatformId::Windows + && matches!(record.encoding_id(), 1 | 10) + && let Ok(subtable) = record.subtable(cmap.offset_data()) + { + glyph = glyph + .or_else(|| subtable.map_codepoint(c)) + .filter(|g| *g != GlyphId::NOTDEF); + } + } + + if glyph.is_none() { + for record in cmap.encoding_records() { + if record.platform_id() == PlatformId::Unicode + && let Ok(subtable) = record.subtable(cmap.offset_data()) + { + glyph = glyph + .or_else(|| subtable.map_codepoint(c)) + .filter(|g| *g != GlyphId::NOTDEF); + } + } + } + + glyph + } + + fn map_macintosh_cmap(&self, name: &str, unicode_char: Option) -> Option { + let cmap = self.base_font.font_ref().cmap().ok()?; + let mut glyph = None; + for record in cmap.encoding_records() { + if record.platform_id() == PlatformId::Macintosh + && record.encoding_id() == 0 + && let Ok(subtable) = record.subtable(cmap.offset_data()) + { + glyph = glyph.or_else(|| { + mac_os_roman::get_inverse(name) + .or_else(|| mac_roman::get_inverse(name)) + .or_else(|| { + unicode_char + .and_then(glyph_names::get_reverse) + .and_then(|agl| { + mac_os_roman::get_inverse(agl) + .or_else(|| mac_roman::get_inverse(agl)) + }) + }) + .and_then(|c| subtable.map_codepoint(c)) + .filter(|g| *g != GlyphId::NOTDEF) + }); + } + } + glyph + } + + fn map_name(&self, lookup: &str) -> Option { + let exact_name = self + .glyph_names + .get(lookup) + .copied() + .filter(|g| *g != GlyphId::NOTDEF); + let exact_unicode = glyph_names::get(lookup) + .and_then(|n| n.chars().next()) + .or_else(|| unicode_from_name(lookup)); + + let mut glyph = + if glyph_names::get(lookup).is_some_and(|name| name.chars().nth(1).is_some()) { + exact_name + .or_else(|| exact_unicode.and_then(|c| self.map_unicode_in_cmap(c))) + .or_else(|| self.map_macintosh_cmap(lookup, exact_unicode)) + } else { + exact_unicode + .and_then(|c| self.map_unicode_in_cmap(c)) + .or_else(|| self.map_macintosh_cmap(lookup, exact_unicode)) + .or_else(|| exact_name) + }; + + if glyph.is_none() { + let base_lookup = if !lookup.starts_with('.') { + lookup.split('.').next().unwrap_or(lookup) + } else { + lookup + }; + let unicode_char = exact_unicode.or_else(|| { + glyph_names::get(base_lookup) + .and_then(|n| n.chars().next()) + .or_else(|| unicode_from_name(base_lookup)) + }); + if base_lookup != lookup { + glyph = unicode_char + .and_then(|c| self.map_unicode_in_cmap(c)) + .or_else(|| self.map_macintosh_cmap(base_lookup, unicode_char)); + } + if glyph.is_none() { + glyph = self + .glyph_names + .get(base_lookup) + .copied() + .or_else(|| { + self.glyph_names + .get(normalized_glyph_name(base_lookup)) + .copied() + }) + .or_else(|| { + unicode_char + .and_then(glyph_names::get_reverse) + .and_then(|agl| self.glyph_names.get(agl).copied()) + }) + .or_else(|| { + unicode_char.and_then(|c| { + let cp = c as u32; + self.glyph_names + .get(&format!("uni{cp:04X}")) + .or_else(|| self.glyph_names.get(&format!("u{cp:04X}"))) + .copied() + }) + }) + .or_else(|| glyph_num_string(base_lookup).map(GlyphId::new)) + .filter(|g| *g != GlyphId::NOTDEF); + } + } + + glyph + } + fn map_code(&self, code: u8) -> GlyphId { if let Some(glyph) = self.cached_mappings.borrow().get(&code) { return *glyph; @@ -313,73 +511,51 @@ impl EmbeddedKind { .unwrap_or(GlyphId::NOTDEF); } + // PdfCraft patch: keep glyph selection separate from text extraction. Symbolic + // TrueType fonts ignore Encoding (ISO 32000-1 9.6.6.4); ToUnicode supplies text + // semantics (9.10), not an alternate glyph. Extend only the existing name lookup + // with Unicode cmap records and post-name aliases. Keep the raw symbolic fallback + // and the CFF path unchanged until affected source files justify a different policy. let mut glyph = None; - if self.is_non_symbolic() { let Some(lookup) = self.code_to_name(code) else { return GlyphId::NOTDEF; }; - - if let Ok(cmap) = self.base_font.font_ref().cmap() { - for record in cmap.encoding_records() { - if record.platform_id() == PlatformId::Windows - && record.encoding_id() == 1 - && let Ok(subtable) = record.subtable(cmap.offset_data()) - { - glyph = glyph.or_else(|| { - glyph_names::get(lookup) - .map(|n| n.to_string()) - .or_else(|| unicode_from_name(lookup).map(|n| n.to_string())) - .and_then(|n| n.chars().next()) - .and_then(|c| subtable.map_codepoint(c)) - .filter(|g| *g != GlyphId::NOTDEF) - }); - } - } - - for record in cmap.encoding_records() { - if record.platform_id() == PlatformId::Macintosh - && record.encoding_id() == 0 - && let Ok(subtable) = record.subtable(cmap.offset_data()) - { - glyph = glyph.or_else(|| { - mac_os_roman::get_inverse(lookup) - .or_else(|| mac_roman::get_inverse(lookup)) - .and_then(|c| subtable.map_codepoint(c)) - .filter(|g| *g != GlyphId::NOTDEF) - }); - } - } - } - - if glyph.is_none() { - if let Some(gid) = self.glyph_names.get(lookup) { - glyph = Some(*gid); - } else if let Some(gid) = glyph_num_string(lookup) { - glyph = Some(GlyphId::new(gid)); - } + // An explicit .notdef is a mapping, not permission to draw the raw code. + if lookup != ".notdef" { + glyph = self.map_name(lookup); } } else if let Ok(cmap) = self.base_font.font_ref().cmap() { - for record in cmap.encoding_records() { - if record.platform_id() == PlatformId::Windows - && matches!(record.encoding_id(), 0 | 1) - { - if let Ok(subtable) = record.subtable(cmap.offset_data()) { - for offset in [0x0000_u32, 0xF000, 0xF100, 0xF200] { - glyph = glyph - .or_else(|| subtable.map_codepoint(code as u32 + offset)) - .filter(|g| *g != GlyphId::NOTDEF); + // PdfCraft patch (#4156): the Windows (3, 0) subtable comes first, and the (1, 0) one + // only for codes it doesn't map (ISO 32000-2 §9.6.5.4: "If the font contains a (3, 0) + // subtable" it is used; "Otherwise, if the font contains a (1, 0) subtable"). The + // records are listed by platform ID, so Macintosh came before Windows and a wrong + // (1, 0) table, as SAS writes for its AMT fonts, drew "8" as "p" and "+" as "V". + for windows_pass in [true, false] { + for record in cmap.encoding_records() { + let windows = record.platform_id() == PlatformId::Windows + && matches!(record.encoding_id(), 0 | 1); + if windows != windows_pass { + continue; + } + if windows { + if let Ok(subtable) = record.subtable(cmap.offset_data()) { + for offset in [0x0000_u32, 0xF000, 0xF100, 0xF200] { + glyph = glyph + .or_else(|| subtable.map_codepoint(code as u32 + offset)) + .filter(|g| *g != GlyphId::NOTDEF); + } } + } else if matches!( + record.platform_id(), + PlatformId::Macintosh | PlatformId::Unicode + ) && record.encoding_id() == 0 + && let Ok(subtable) = record.subtable(cmap.offset_data()) + { + glyph = glyph + .or_else(|| subtable.map_codepoint(code)) + .filter(|g| *g != GlyphId::NOTDEF); } - } else if matches!( - record.platform_id(), - PlatformId::Macintosh | PlatformId::Unicode - ) && record.encoding_id() == 0 - && let Ok(subtable) = record.subtable(cmap.offset_data()) - { - glyph = glyph - .or_else(|| subtable.map_codepoint(code)) - .filter(|g| *g != GlyphId::NOTDEF); } } } @@ -390,6 +566,68 @@ impl EmbeddedKind { glyph } + /// PdfCraft patch (101): the Mac OS Roman glyph name a code of a symbolic font without an + /// encoding or glyph names reads as, when two things say the code is Mac OS Roman: + /// + /// - its Macintosh Roman (1, 0) `cmap` subtable selects the glyph the code draws. ISO + /// 32000-2 §9.6.5.4 has single bytes "look up the associated glyph descriptions" there, and + /// has a (3, 0) subtable map "the single-byte codes in the (1, 0) subtable" prepended with + /// 0xF0; + /// - the glyph sits where the standard Macintosh glyph order (the 258 names of a version 1.0 + /// `post` table) puts that character. Fonts distilled from Macintosh originals keep that + /// order and drop the names (`post` version 3.0): pdf.js's issue2017r.pdf draws code 0x88 + /// with glyph 106, `agrave`, Mac OS Roman 0x88. + /// + /// The second test is needed: Windows subsets in the same order carry a (1, 0) subtable too, + /// but their codes are WinAnsi (code 0x92 draws glyph 183, `quoteright`, not Mac OS Roman's + /// `iacute`), and reading every such code as Mac OS Roman turned "USDA’s" into "USDAís". + /// A font that names its glyphs in its `post` table needn't keep the order (a Wingdings subset + /// draws code 0x83 with glyph 101, `Eacute` in the order, which it names `threesans`). + /// `None` when the font is non-symbolic, names a base encoding (one this reader doesn't know + /// too), is Symbol or ZapfDingbats (whose + /// built-in encodings aren't Latin, ISO 32000-2 §9.6.6.1; recognised by name as the editor's + /// `unicode_map` recognises them), is a CFF program, names its glyphs, or either test fails + /// (SAS's AMT fonts carry a wrong (1, 0) table, #4156): the code then reads as before. Glyph + /// selection is unchanged. + fn mac_roman_name(&self, code: u8) -> Option<&'static str> { + if self.is_non_symbolic() + || !self.mac_roman_eligible + || !matches!(self.encoding, Encoding::BuiltIn) + || self.cff_blob.is_some() + || !self.glyph_names.is_empty() + { + return None; + } + let glyph = self.map_code(code); + if glyph == GlyphId::NOTDEF { + return None; + } + let cmap = self.base_font.font_ref().cmap().ok()?; + let mac = cmap.encoding_records().iter().find_map(|record| { + if record.platform_id() == PlatformId::Macintosh && record.encoding_id() == 0 { + record + .subtable(cmap.offset_data()) + .ok()? + .map_codepoint(code) + } else { + None + } + })?; + if mac != glyph { + return None; + } + let standard = match *DEFAULT_GLYPH_NAMES.get(usize::try_from(glyph.to_u32()).ok()?)? { + // The order's name for Mac OS Roman 0xCA; the tables here call it `nbspace`. + "nonbreakingspace" => "nbspace", + name => name, + }; + let name = mac_os_roman::get(code).or_else(|| mac_roman::get(code))?; + if name != standard { + return None; + } + Encoding::MacRoman.text_alias(code).or(Some(name)) + } + fn glyph_width(&self, code: u8) -> f32 { match self.widths.get(code as usize).copied() { Some(Width::Value(w)) => w, @@ -410,6 +648,38 @@ pub(crate) enum Width { Missing, } +/// PdfCraft patch (79): the text a glyph name stands for, by the rules of the Adobe Glyph List +/// specification (ISO 32000-2 §9.10.2): drop any suffix from the first `.` (`a.ss01` is `a`), +/// then each `_`-separated component is a list name, `uni` and groups of exactly four +/// uppercase hex digits, or `u` and four to six. A value in the surrogate range or past +/// U+10FFFF is no character. `None` when any component is none of these (`uni20ac`, `uni65`, +/// `u65`). Each component gives at least one character, so the text is never empty. +fn glyph_name_text(name: &str) -> Option { + // An empty stem (`.notdef`) is no list name and no number, so it gives `None` below. + let stem = name.split('.').next()?; + // `from_str_radix` alone would also take a sign (`uni+041`) and lowercase digits, which the + // specification's forms don't have. + let hex = |h: &str| !h.is_empty() && h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'A'..=b'F')); + let mut out = String::new(); + for part in stem.split('_') { + if let Some(text) = glyph_names::get(part) { + out.push_str(text); + } else if let Some(digits) = part.strip_prefix("uni").filter(|h| hex(h)) { + // A group short of four digits isn't there to take, so `uni041` gives `None`. + for i in (0..digits.len()).step_by(4) { + let unit = digits.get(i..i.saturating_add(4))?; + out.push(char::from_u32(u32::from_str_radix(unit, 16).ok()?)?); + } + } else { + let digits = part + .strip_prefix('u') + .filter(|h| (4..=6).contains(&h.len()) && hex(h))?; + out.push(char::from_u32(u32::from_str_radix(digits, 16).ok()?)?); + } + } + Some(out) +} + pub(crate) fn read_widths(dict: &Dict<'_>, descriptor: &Dict<'_>) -> Option<(Vec, f32)> { let mut widths = Vec::new(); @@ -483,7 +753,7 @@ pub(crate) fn read_encoding(dict: &Dict<'_>) -> (Encoding, HashMap) if let Ok(code) = code.try_into() { map.insert(code, name.as_str().to_string()); } - code += 1; + code = code.saturating_add(1); } _ => {} } @@ -501,3 +771,53 @@ pub(crate) fn read_encoding(dict: &Dict<'_>) -> (Encoding, HashMap) ) } } + +#[cfg(test)] +mod tests { + use super::glyph_name_text; + + /// PdfCraft patch (79): glyph names read by the glyph list specification's rules. + #[test] + fn glyph_names_read_by_the_adobe_glyph_list_rules() { + for (name, expected) in [ + ("a", "a"), + ("a.ss01", "a"), + ("less_equal.liga", "<="), + ("uni0041", "A"), + ("uni00410042", "AB"), + ("u0041", "A"), + ("u1F600", "\u{1F600}"), + ] { + assert_eq!(glyph_name_text(name).as_deref(), Some(expected), "{name}"); + } + for name in [ + "", + ".notdef", + ".alt", + "EMquad", + "uni041", + "uni00410", + "uni004G", + "uni+041", + "u+041", + "uniD800", + "u041", + "u0000041", + "u004G", + "a_EMquad", + // PdfCraft patch (79): the glyph list specification's hex digits are uppercase only. + "uni20ac", + "uni004100e9", + "u1f600", + "u20ac", + "a_uni20ac", + "uni65", + "u65", + "uni+065", + "uDFFF", + "u110000", + ] { + assert_eq!(glyph_name_text(name), None, "{name}"); + } + } +} diff --git a/vendor/hayro-interpret/src/font/type1.rs b/vendor/hayro-interpret/src/font/type1.rs index 3f9bac409e..abb29455a0 100644 --- a/vendor/hayro-interpret/src/font/type1.rs +++ b/vendor/hayro-interpret/src/font/type1.rs @@ -3,7 +3,7 @@ use crate::font::standard_font::{StandardFont, StandardKind, select_standard_fon use crate::font::true_type::{Width, read_encoding, read_widths}; use crate::font::{ Encoding, FallbackFontQuery, glyph_name_to_text, glyph_name_to_unicode, normalized_glyph_name, - read_to_unicode, + numbered_glyph_name_at_its_code, numbered_names_name_their_codes, read_to_unicode, }; use crate::{CMapResolverFn, CacheKey, FontResolverFn}; use hayro_cmap::{BfString, CMap}; @@ -13,10 +13,17 @@ use hayro_syntax::object::dict::keys::{FONT_DESC, FONT_FILE, FONT_FILE3}; use kurbo::BezPath; use skrifa::GlyphId; use std::collections::HashMap; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; #[derive(Debug)] -pub(crate) struct Type1Font(u128, Kind, Option); +pub(crate) struct Type1Font( + u128, + Kind, + Option, + /// PdfCraft patch: whether the font's numbered glyph names all name their own codes + /// (`numbered_names_name_their_codes`), worked out on first use. + OnceLock, +); impl Type1Font { pub(crate) fn new( @@ -50,23 +57,29 @@ impl Type1Font { resolver, )?), to_unicode.clone(), + OnceLock::new(), )) }; let inner = if is_cff(dict) { if let Some(cff) = CffKind::new(dict) { - Self(cache_key, Kind::Cff(cff), to_unicode) + Self(cache_key, Kind::Cff(cff), to_unicode, OnceLock::new()) } else { return fallback(); } } else if is_type1(dict) { if let Some(f) = Type1Kind::new(dict) { - Self(cache_key, Kind::Type1(f), to_unicode) + Self(cache_key, Kind::Type1(f), to_unicode, OnceLock::new()) } else { return fallback(); } } else if let Some(standard) = StandardKind::new(dict, resolver) { - Self(cache_key, Kind::Standard(standard), to_unicode) + Self( + cache_key, + Kind::Standard(standard), + to_unicode, + OnceLock::new(), + ) } else { return fallback(); }; @@ -78,7 +91,7 @@ impl Type1Font { let dict = Dict::default(); let standard = StandardKind::new_with_standard(&dict, font, true, resolver)?; - Some(Self(0, Kind::Standard(standard), None)) + Some(Self(0, Kind::Standard(standard), None, OnceLock::new())) } pub(crate) fn map_code(&self, code: u8) -> GlyphId { @@ -137,15 +150,30 @@ impl Type1Font { } // PdfCraft patch (#3169, #3170): a name outside the glyph list still reads by the // glyph list specification's full mapping (`f_i`, `hyphen.case`). A name that only - // numbers the glyph (`C39`, `c251`) says nothing about the character and reads as - // nothing: the code's StandardEncoding character would be a guess, wrong wherever the - // font's /Encoding puts the glyph elsewhere (review on #3239). - let name = match &self.1 { + // numbers the glyph (`C39`, `c251`) reads as the code's Latin-1 character only when its + // number is that code (`C39` at 39) and every numbered name in the font names its own + // code, as pdftotext, PDFium and MuPDF read it. Anywhere else the number is no + // evidence and reads as nothing: the code's StandardEncoding character would be a + // guess, wrong wherever the font's /Encoding puts the glyph elsewhere (review on #3239). + let name = self.code_to_ps_name(code)?; + glyph_name_to_text(name).or_else(|| { + let own_codes = *self.3.get_or_init(|| { + numbered_names_name_their_codes( + (0..=u8::MAX).filter_map(|c| Some((c, self.code_to_ps_name(c)?))), + ) + }); + own_codes + .then(|| numbered_glyph_name_at_its_code(name, code)) + .flatten() + }) + } + + fn code_to_ps_name(&self, code: u8) -> Option<&str> { + match &self.1 { Kind::Standard(s) => s.code_to_ps_name(code), Kind::Cff(c) => c.code_to_ps_name(code), Kind::Type1(t) => t.code_to_ps_name(code), - }?; - glyph_name_to_text(name) + } } } @@ -291,7 +319,13 @@ impl CffKind { fn new(dict: &Dict<'_>) -> Option { let descriptor = dict.get::>(FONT_DESC)?; let data = descriptor.get::>(FONT_FILE3)?; - let font = CffFontBlob::new(Arc::new(data.decoded().ok()?.to_vec()))?; + let bytes = data.decoded().ok()?.to_vec(); + // PdfCraft patch (69): an OpenType-wrapped program carries its CFF in a table. + let font = if bytes.starts_with(b"OTTO") { + CffFontBlob::from_open_type(&bytes)? + } else { + CffFontBlob::new(Arc::new(bytes))? + }; let (encoding, encodings) = read_encoding(dict); let (widths, missing_width) = read_widths(dict, &descriptor)?; diff --git a/vendor/hayro-interpret/src/font/type3.rs b/vendor/hayro-interpret/src/font/type3.rs index 216f261826..02dafe945c 100644 --- a/vendor/hayro-interpret/src/font/type3.rs +++ b/vendor/hayro-interpret/src/font/type3.rs @@ -1,9 +1,14 @@ use crate::CMapResolverFn; -use crate::context::Context; +use crate::context::{ + Context, HeldContent, MAX_CACHED_TYPE3_PROCS, Type3Procs, content_left, hold_content, +}; use crate::device::Device; use crate::font::glyph_simulator::GlyphSimulator; use crate::font::true_type::{Width, read_encoding, read_widths}; -use crate::font::{Encoding, Glyph, Type3Glyph, UNITS_PER_EM, read_to_unicode}; +use crate::font::{ + Encoding, Glyph, Type3Glyph, UNITS_PER_EM, numbered_glyph_name_at_its_code, + numbered_names_name_their_codes, read_to_unicode, +}; use crate::interpret::state::TextState; use crate::soft_mask::SoftMask; use crate::util::RectExt; @@ -19,12 +24,18 @@ use hayro_syntax::object::dict::keys::{CHAR_PROCS, FONT_BBOX, FONT_MATRIX, RESOU use hayro_syntax::page::Resources; use kurbo::{Affine, BezPath, Rect}; use skrifa::GlyphId; +use std::cell::{OnceCell, RefCell}; use std::collections::HashMap; +use std::rc::Rc; +use std::sync::OnceLock; #[derive(Debug)] pub(crate) struct Type3<'a> { widths: Vec, missing_width: f32, + /// PdfCraft patch (90): the width each code's glyph procedure gives with `d0`/`d1`, read + /// the first time the code is shown in a font without `/Widths`. One cell per code. + proc_widths: Vec>>, encoding: Encoding, encodings: HashMap, dict: Dict<'a>, @@ -33,8 +44,23 @@ pub(crate) struct Type3<'a> { font_bbox: Rect, matrix: Affine, to_unicode: Option, + /// PdfCraft patch (87): glyph procedures already decoded, by glyph name, so a glyph shown + /// again and again (a Type 3 font used as a fill pattern draws one glyph hundreds of + /// thousands of times) isn't inflated again for every copy. Only procedures of at most + /// [`MAX_CACHED_PROC`] bytes are kept, and the fonts of one interpreter cache keep at most + /// `context::MAX_CACHED_TYPE3_PROCS` bytes together. + decoded_procs: RefCell>>, + /// PdfCraft patch: whether the font's numbered glyph names all name their own codes + /// (`numbered_names_name_their_codes`), worked out on first use. + own_code_names: OnceLock, } +/// PdfCraft patch (87): the largest decoded glyph procedure [`Type3`] keeps. +const MAX_CACHED_PROC: usize = 64 << 10; +/// PdfCraft patch (87): what a kept procedure costs the cache besides its bytes and its glyph +/// name (the map entry and the shared allocation's counts), so many empty procedures count too. +const CACHED_PROC_OVERHEAD: usize = 64; + impl<'a> Type3<'a> { pub(crate) fn new(dict: &Dict<'a>, cmap_resolver: &CMapResolverFn) -> Option { let (encoding, encodings) = read_encoding(dict); @@ -71,13 +97,57 @@ impl<'a> Type3<'a> { char_procs, widths, missing_width, + proc_widths: vec![OnceCell::new(); usize::from(u8::MAX) + 1], encodings, matrix, dict: dict.clone(), to_unicode, + decoded_procs: RefCell::new(HashMap::new()), + own_code_names: OnceLock::new(), }) } + /// PdfCraft patch (87): the decoded procedure of glyph `name`, held within the page's + /// content budget while the glyph is painted, whether it was decoded now or kept from an + /// earlier copy, so a page skips the same glyphs either way once the budget is spent. It is + /// decoded the first time and kept, when small enough and while `procs` has room, for the + /// next copies. Only a procedure decoded with more budget left than [`MAX_CACHED_PROC`] is + /// kept, so one the budget may have cut short isn't. + fn decoded_proc( + &self, + name: &str, + program: &Stream<'a>, + procs: &Type3Procs, + ) -> Option<(Rc<[u8]>, HeldContent)> { + let kept = self.decoded_procs.borrow().get(name).cloned(); + if let Some(bytes) = kept { + let held = hold_content(bytes.len())?; + return Some((bytes, held)); + } + let left = content_left(); + // PdfCraft patch: see `context::MAX_PAGE_CONTENT`. + let decoded = crate::context::decode_content(program)?; + procs.decodes.set(procs.decodes.get().saturating_add(1)); + let bytes: Rc<[u8]> = Rc::from(decoded.as_ref()); + drop(decoded); + let held = hold_content(bytes.len())?; + let cost = bytes + .len() + .saturating_add(name.len()) + .saturating_add(CACHED_PROC_OVERHEAD); + let total = procs.held.get().saturating_add(cost); + if left > MAX_CACHED_PROC + && bytes.len() <= MAX_CACHED_PROC + && total <= MAX_CACHED_TYPE3_PROCS + { + procs.held.set(total); + self.decoded_procs + .borrow_mut() + .insert(name.to_string(), bytes.clone()); + } + Some((bytes, held)) + } + pub(crate) fn map_code(&self, code: u8) -> GlyphId { self.encodings .get(&code) @@ -88,13 +158,53 @@ impl<'a> Type3<'a> { } pub(crate) fn glyph_width(&self, code: u8) -> f32 { + // PdfCraft patch (90): /Widths, /FirstChar and /LastChar are required for Type 3 fonts + // (Table 110), but a font without them gave every glyph no advance and its text was drawn on one spot. The glyph + // procedure's `d0`/`d1` operator states the glyph's width too (9.6.4), so such a font + // takes that width, as PDFium does. A font with /Widths is read as before: a code + // outside FirstChar..LastChar has width 0 (Table 110), as in Poppler and MuPDF. let w = match self.widths.get(code as usize).copied() { Some(Width::Value(w)) => w, + _ if self.widths.is_empty() => self.proc_width(code).unwrap_or(self.missing_width), _ => self.missing_width, }; (w * self.matrix.as_coeffs()[0] as f32) * UNITS_PER_EM } + /// PdfCraft patch (90): whether the font has no `/Widths` (or `/FirstChar`/`/LastChar`), so + /// that `glyph_width` falls back on the glyph procedures' `d0`/`d1` widths. + pub(crate) fn widths_missing(&self) -> bool { + self.widths.is_empty() + } + + /// PdfCraft patch (90): the horizontal width `wx` that the glyph procedure for `code` + /// sets with `d0` or `d1`, in glyph space. `None` when the code has no procedure, the + /// procedure sets no width or its width isn't finite. A procedure the page's content + /// budget can't decode isn't remembered, so a later page may still read it. + fn proc_width(&self, code: u8) -> Option { + let cell = self.proc_widths.get(usize::from(code))?; + if let Some(width) = cell.get() { + return *width; + } + let name = self.glyph_simulator.glyph_to_string(self.map_code(code))?; + let program = self.char_procs.get(&name)?; + let decoded = crate::context::decode_content(program)?; + let mut iter = TypedIter::new(decoded.as_ref()); + let mut width = None; + while let Some(op) = iter.next() { + match op { + TypedInstruction::ColorGlyph(d0) => width = Some(d0.0.as_f32()), + TypedInstruction::ShapeGlyph(d1) => width = Some(d1.0.as_f32()), + _ => continue, + } + break; + } + let width = width.filter(|w| w.is_finite()); + // Setting can't fail here: the cell was empty above and nothing in between fills it. + let _ = cell.set(width); + width + } + pub(crate) fn char_code_to_unicode(&self, char_code: u32) -> Option { // PdfCraft patch: upstream only consulted ToUnicode. Many Type3 fonts (e.g. TeX/dvips // bitmap fonts) have none; fall back to the /Encoding glyph names, then to printable @@ -115,9 +225,30 @@ impl<'a> Type3<'a> { name.and_then(crate::font::glyph_name_to_unicode) .or_else(|| (0x20..0x7f).contains(&code).then_some(code as char)) .map(BfString::Char) + // PdfCraft patch (100): above 126, a name that only numbers its glyph reads + // as the code's Latin-1 character when the number is that code and every + // numbered name in the font names its own code (`C174` at 174 reads `®`), + // as in a Type 1 font. + .or_else(|| { + let own_codes = *self.own_code_names.get_or_init(|| { + numbered_names_name_their_codes( + (0..=u8::MAX).filter_map(|c| Some((c, self.code_to_name(c)?))), + ) + }); + name.filter(|_| own_codes) + .and_then(|name| numbered_glyph_name_at_its_code(name, code)) + }) }) } + /// PdfCraft patch: the glyph name `/Encoding` gives a code, as `map_code` reads it. + fn code_to_name(&self, code: u8) -> Option<&str> { + self.encodings + .get(&code) + .map(String::as_str) + .or_else(|| self.encoding.map_code(code)) + } + pub(crate) fn render_glyph( &self, glyph: &Type3Glyph<'a>, @@ -144,9 +275,8 @@ impl<'a> Type3<'a> { let name = self.glyph_simulator.glyph_to_string(glyph.glyph_id)?; let program = self.char_procs.get(&name)?; - // PdfCraft patch: see `context::MAX_PAGE_CONTENT`. - let decoded = crate::context::decode_content(program)?; - let iter = TypedIter::new(decoded.as_ref()); + let (decoded, _held) = self.decoded_proc(&name, program, &glyph.cache.type3_procs)?; + let iter = TypedIter::new(&decoded); let is_shape_glyph = { let mut iter = iter.clone(); diff --git a/vendor/hayro-interpret/src/interpret/mod.rs b/vendor/hayro-interpret/src/interpret/mod.rs index 022c4d1bce..fd80f27ede 100644 --- a/vendor/hayro-interpret/src/interpret/mod.rs +++ b/vendor/hayro-interpret/src/interpret/mod.rs @@ -1,11 +1,12 @@ use crate::{BlendMode, FillRule}; use crate::color::{ColorSpace, DefaultColorSpaces, DeviceFamily}; use crate::context::Context; -use crate::convert::{convert_line_cap, convert_line_join}; +use crate::convert::{convert_dash_array, convert_line_cap, convert_line_join, convert_line_width}; use crate::device::Device; use crate::font::{Font, FontData, FontQuery, StandardFont}; use crate::interpret::path::{ - apply_pending_clip, close_path, fill_path, fill_path_impl, fill_stroke_path, stroke_path, + apply_pending_clip, begin_subpath_after_close, close_path, fill_path, fill_path_impl, + fill_stroke_path, stroke_path, }; use crate::interpret::state::{TextStateFont, handle_gs}; use crate::interpret::text::TextRenderingMode; @@ -18,10 +19,10 @@ use crate::x_object::{ use hayro_syntax::content::TypedIter; use hayro_syntax::content::ops::TypedInstruction; use hayro_syntax::object::dict::keys::{ - ACTUAL_TEXT, ANNOTS, AP, AS, C, CA, F, MCID, N, OC, QUADPOINTS, RECT, SUBTYPE, + ACTUAL_TEXT, ANNOTS, AP, AS, C, CA, F, IRT, MCID, N, OC, QUADPOINTS, RECT, RT, SUBTYPE, }; use hayro_syntax::object::{Array, Dict, Object, Rect, Stream, dict_or_stream}; -use hayro_syntax::page::{ContentReader, Page, Resources}; +use hayro_syntax::page::{ContentReader, Page, Resources, Rotation}; use hayro_syntax::MAX_DECODED_STREAM; use kurbo::{Affine, BezPath, Point, Shape}; use smallvec::smallvec; @@ -44,6 +45,8 @@ pub type CMapResolverFn = Arc) -> Option<&'static [u8]> + Send + Sync>; /// A callback function for resolving warnings during interpretation. pub type WarningSinkFn = Arc; +/// A callback function for extended PdfCraft warnings during interpretation. +pub type ExtendedWarningSinkFn = Arc; #[derive(Clone)] /// Settings that should be applied during the interpretation process. @@ -100,6 +103,9 @@ pub struct InterpreterSettings { /// In certain cases, `hayro` will emit a warning in case an issue was encountered while interpreting /// the PDF file. Providing a callback allows you to catch those warnings and handle them, if desired. pub warning_sink: WarningSinkFn, + /// Optional callback for extended PdfCraft warnings (`ColorFallback`, `MalformedIndexedImage`, + /// `Type3WidthsMissing`) kept separate from [`InterpreterWarning`] for backward compatibility. + pub extended_warning_sink: ExtendedWarningSinkFn, /// Whether annotations should be rendered as well. /// /// Note that this feature is currently not fully implemented yet, so some @@ -111,6 +117,21 @@ pub struct InterpreterSettings { /// PdfCraft patch: viewer overrides for optional content groups (object number, generation, /// visible), applied on top of the document's default configuration (Layers panel toggles). pub ocg_overrides: Arc>, + /// PdfCraft patch (103): apply the default configuration's auto state for the View event + /// (`/AS` usage applications with `/Event /View`, ISO 32000-2 §8.11.4.4) before + /// `ocg_overrides`. On by default: that is the state for viewing. Off for output made for + /// printing, which the View event is not. + pub view_auto_state: bool, + /// PdfCraft patch (105): viewer overrides for annotations (object number, generation, shown), + /// applied in place of their Hidden and NoView flags: what a document's scripts show and + /// hide while it is read (frames of an animation), without changing the document. + pub annotation_overrides: Arc>, + /// PdfCraft patch (106): annotations the viewer draws with a form XObject as their normal + /// appearance (object number and generation of the annotation, then of the form), in their + /// own `/Rect`: a push button a document's script gave another icon (`buttonSetIcon`) while + /// it is read, without changing the document. An override naming an object that isn't a form + /// draws nothing (the script cleared the icon). + pub appearance_overrides: Arc>, /// PdfCraft patch: once this is `true`, interpretation stops before the next content /// operator. What was drawn is then incomplete, so only set it when the output will be /// thrown away (a viewer's render whose result nobody can receive any more). @@ -129,6 +150,10 @@ pub struct InterpreterSettings { /// PdfCraft patch (35): told about each spot ink a paint uses (colours, images, shadings /// and uncoloured patterns), whether or not `plate` is set. pub ink_sink: Option, + /// PdfCraft patch (73): the steps of JBIG2 decoding a page's images may take between them + /// ([`hayro_syntax::MAX_PAGE_JBIG2_WORK`] by default). Images past it aren't drawn, nor images + /// whose masks are past it, each with [`InterpreterWarning::ContentTruncated`]. + pub jbig2_work: u64, } impl Default for InterpreterSettings { @@ -146,13 +171,18 @@ impl Default for InterpreterSettings { #[cfg(not(feature = "embed-cmaps"))] cmap_resolver: Arc::new(|_| None), warning_sink: Arc::new(|_| {}), + extended_warning_sink: Arc::new(|_| {}), render_annotations: true, hide_comments: false, ocg_overrides: Arc::new(Vec::new()), + view_auto_state: true, + annotation_overrides: Arc::new(Vec::new()), + appearance_overrides: Arc::new(Vec::new()), cancelled: None, preview: false, plate: None, ink_sink: None, + jbig2_work: hayro_syntax::MAX_PAGE_JBIG2_WORK, } } } @@ -167,15 +197,48 @@ pub enum InterpreterWarning { /// An image failed to decode. ImageDecodeFailure, /// PdfCraft patch (18): a page content stream was skipped after exhausting its safety budget. + /// Patch (73): or an image was left out for the page's JBIG2 allowance, or because its JBIG2 + /// mask is past the allowance or one of the decoder's limits. ContentTruncated, } +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +/// Extended PdfCraft warnings kept separate from [`InterpreterWarning`] for backward compatibility. +pub enum ExtendedWarning { + /// PdfCraft patch (55): a colour could not be computed (a colour space that cannot be + /// read, or a Separation or DeviceN tint transform that cannot be evaluated) and was painted + /// in a fallback colour. Reported at most once per content stream. + ColorFallback, + /// PdfCraft patch (80): an image's `/Indexed` colour space is malformed (ISO 32000-2 + /// §8.6.6.3). The image was drawn recovered (indices past a short lookup table in black, a + /// `hival` past 255 taken as 255, a real one truncated), or, with a `hival` below zero or not a + /// number, in DeviceGray; with no lookup table at all it was not drawn. + MalformedIndexedImage, + /// PdfCraft patch (90): a Type 3 font without `/Widths` (or `/FirstChar`/`/LastChar`), + /// which ISO 32000-2 Table 110 requires, was selected; its glyphs advance by the widths + /// their glyph procedures set with `d0`/`d1`. Reported each time such a font is selected. + Type3WidthsMissing, +} + +/// PdfCraft patch (73): ends a page's JBIG2 allowance with the page, so that what decodes on its +/// thread afterwards has no page to run out on. +struct PageJbig2Work; + +impl Drop for PageJbig2Work { + fn drop(&mut self) { + hayro_syntax::set_page_jbig2_work(u64::MAX); + } +} + /// interpret the contents of the page and render them into the device. pub fn interpret_page<'a>( page: &Page<'a>, context: &mut Context<'a>, device: &mut impl Device<'a>, ) { + // PdfCraft patch (73): a context used again is another page. + hayro_syntax::set_page_jbig2_work(context.settings.jbig2_work); + let _allowance = PageJbig2Work; let resources = page.resources(); let mut content = page.content_reader(); // PdfCraft patch: the page's own contents count against its content budget too, where they @@ -189,12 +252,60 @@ pub fn interpret_page<'a>( // PdfCraft patch (29): bracket the annotations so devices can tell their paints from // the document's own (the reading-colours setting recolours the document, not comments). device.begin_annotations(); - for annot in annot_arr.iter::>() { + // PdfCraft patch (86): form fields' widgets are drawn after the page's other + // annotations, each group in `/Annots` order, as other readers draw them: a filled + // comment listed after a check box covered the box. ISO 32000-2 doesn't order the two. + // Two passes over the array, so nothing is held for every entry of a long one. + // PdfCraft patch (105): each annotation with its object, so the viewer can show or hide + // it by its object (`annotation_overrides`). An entry that isn't a dictionary is + // skipped; it no longer ends the list. + let xref = context.xref; + for widgets in [false, true] { + let annots = annot_arr.raw_iter().filter_map(|item| match item { + hayro_syntax::object::MaybeRef::Ref(r) => xref.get::>(r.into()).map(|d| (d, Some(r))), + hayro_syntax::object::MaybeRef::NotRef(Object::Dict(d)) => Some((d, None)), + hayro_syntax::object::MaybeRef::NotRef(_) => None, + }); + for (annot, obj) in annots { + if (annot.get::>(SUBTYPE).as_deref() == Some(b"Widget")) != widgets { + continue; + } let flags = annot.get::(F).unwrap_or(0); // Annotation should be hidden (Hidden = bit 2, NoView = bit 6). // PdfCraft patch: NoView was not honoured upstream. - if flags & (2 | 32) != 0 { + // PdfCraft patch (105): the viewer's override, when it has one, decides instead. + let overridden = obj.and_then(|r| { + context + .settings + .annotation_overrides + .iter() + .find(|(num, generation, _)| *num == r.obj_number && *generation == r.gen_number) + .map(|(_, _, shown)| !*shown) + }); + if overridden.unwrap_or(flags & (2 | 32) != 0) { + continue; + } + // PdfCraft patch (56): Invisible (bit 1) hides an annotation of a type that isn't one + // of the standard ones (ISO 32000-2 Table 167), and a popup has no appearance of its + // own (§12.5.6.14): the viewer shows it as a window for its parent, not on the page. + let subtype = annot.get::>(SUBTYPE); + if subtype.as_deref() == Some(b"Popup") + || (flags & 1 != 0 && !subtype.as_deref().is_some_and(is_standard_annotation_type)) + { + continue; + } + // PdfCraft patch (81): a reply of type R (a markup annotation with an `/IRT` to the + // annotation it answers and an `/RT` other than `/Group`; R is the default, so a + // missing, unknown or malformed `/RT` reads as R) is not drawn, whatever its + // appearance or flags: "Interactive PDF processors shall not display replies to an + // annotation individually but together in the form of threaded comments" (ISO 32000-2 + // Table 172). A `/RT /Group` member is part of its group's look and still draws. + // `/IRT` is a markup annotation's entry: a widget, link or pop-up with one still draws. + if !matches!(annot.get::>(SUBTYPE).as_deref(), Some(b"Widget" | b"Link" | b"Popup")) + && annot.get::>(IRT).is_some() + && annot.get::>(RT).as_deref() != Some(b"Group") + { continue; } // PdfCraft patch: "Hide all comments" keeps widgets and links. @@ -206,13 +317,27 @@ pub fn interpret_page<'a>( // PdfCraft patch: `/N` may be a stream or a dictionary of appearance states selected // by `/AS` (checkboxes, radio buttons, …). Upstream only handled the stream form. - let normal = annot.get::>(AP).and_then(|ap| { - ap.get::>(N).or_else(|| { - let states = ap.get::>(N)?; - let state = annot.get::>(AS)?; - states.get::>(state.as_ref()) - }) + // PdfCraft patch (106): the viewer may draw it with another form instead + // (`appearance_overrides`). + // An override naming an object that isn't a form draws nothing: a script cleared the + // button's icon. + let face = obj.and_then(|r| { + context + .settings + .appearance_overrides + .iter() + .find(|(num, generation, _, _)| *num == r.obj_number && *generation == r.gen_number) }); + let normal = match face { + Some(&(_, _, num, generation)) => xref.get::>(hayro_syntax::object::ObjectIdentifier::new(num, generation)), + None => annot.get::>(AP).and_then(|ap| { + ap.get::>(N).or_else(|| { + let states = ap.get::>(N)?; + let state = annot.get::>(AS)?; + states.get::>(state.as_ref()) + }) + }), + }; if let Some(apx) = normal.and_then(|o| FormXObject::new(&o)) { let Some(rect) = annot.get::(RECT) else { continue; @@ -260,6 +385,13 @@ pub fn interpret_page<'a>( annot_rect.x0 - sx * transformed_rect.x0, annot_rect.y0 - sy * transformed_rect.y0, ]); + // PdfCraft patch (59): NoRotate (bit 5) keeps the appearance upright as the page is + // displayed (ISO 32000-2 §12.5.3). + let affine = if flags & 16 != 0 && no_rotate_applies(&annot) { + no_rotate_turn(page.rotation(), &annot_rect) * affine + } else { + affine + }; // PdfCraft patch: a /BBox or /Matrix that collapses the appearance box to a line // or a point leaves nothing to map onto /Rect: the scales above divide by zero, @@ -289,10 +421,72 @@ pub fn interpret_page<'a>( draw_highlight_without_appearance(&annot, context, device); } } + } device.end_annotations(); } } +/// PdfCraft patch (56): whether `subtype` is one of the standard annotation types of +/// ISO 32000-2 Table 171. +fn is_standard_annotation_type(subtype: &[u8]) -> bool { + matches!( + subtype, + b"Text" + | b"Link" + | b"FreeText" + | b"Line" + | b"Square" + | b"Circle" + | b"Polygon" + | b"PolyLine" + | b"Highlight" + | b"Underline" + | b"Squiggly" + | b"StrikeOut" + | b"Caret" + | b"Stamp" + | b"Ink" + | b"Popup" + | b"FileAttachment" + | b"Sound" + | b"Movie" + | b"Screen" + | b"Widget" + | b"PrinterMark" + | b"TrapNet" + | b"Watermark" + | b"3D" + | b"Redact" + | b"Projection" + | b"RichMedia" + ) +} + +/// PdfCraft patch (59): whether the NoRotate flag turns this annotation's appearance. Form fields +/// and links are left in `/Rect`: PdfCraft takes their click targets from it. +fn no_rotate_applies(annot: &Dict<'_>) -> bool { + !matches!( + annot.get::>(SUBTYPE).as_deref(), + Some(b"Widget" | b"Link") + ) +} + +/// PdfCraft patch (59): the user-space turn that keeps a NoRotate annotation upright on a page +/// with `/Rotate`. The page is shown turned clockwise, so the appearance (already fitted to +/// `/Rect`) is turned as far counterclockwise about the rectangle's upper-left corner, which stays +/// where it is on the page (ISO 32000-2 §12.5.3). Its width then runs across the displayed page +/// and its height down from that corner. +fn no_rotate_turn(rotation: Rotation, rect: &kurbo::Rect) -> Affine { + let (cos, sin) = match rotation { + Rotation::None => return Affine::IDENTITY, + Rotation::Horizontal => (0.0, 1.0), + Rotation::Flipped => (-1.0, 0.0), + Rotation::FlippedHorizontal => (0.0, -1.0), + }; + let (x, y) = (rect.x0.min(rect.x1), rect.y0.max(rect.y1)); + Affine::new([cos, sin, -sin, cos, x - (cos * x - sin * y), y - (sin * x + cos * y)]) +} + /// PdfCraft patch: the normal appearance of a Highlight annotation that has none (ISO 32000-2 /// §12.5.6.10), drawn as PdfCraft draws its own highlights (pdfcraft-annot): each /QuadPoints /// quadrilateral filled with /C at /CA opacity, blended with Multiply so the marked-up content @@ -347,7 +541,7 @@ fn draw_highlight_without_appearance<'a>( context.restore_state(device); } -/// PdfCraft patch (#3018): the color space `cs` or `CS` selects by `name`: a device space, else +/// PdfCraft patch (38): the colour space `cs` or `CS` selects by `name`: a device space, else /// the `/ColorSpace` resource `name`. A device space, named directly or by a resource, is /// replaced by its default from `defaults` (ISO 32000-2 §8.6.5.6). fn named_color_space<'a>( @@ -380,8 +574,8 @@ fn interpret_window<'a>( context: &mut Context<'a>, device: &mut impl Device<'a>, ) { - // PdfCraft patch (#3018): the resources' DefaultGray, DefaultRGB and DefaultCMYK replace the - // device spaces that color operators and images select (ISO 32000-2 §8.6.5.6). + // PdfCraft patch (38): the resources' DefaultGray, DefaultRGB and DefaultCMYK replace the + // device spaces that colour operators and images select (ISO 32000-2 §8.6.5.6). let defaults = DefaultColorSpaces::new( resources, &context.interpreter_cache.object_cache, @@ -394,28 +588,36 @@ fn interpret_window<'a>( } match op { TypedInstruction::SaveState(_) => context.save_state(), + // PdfCraft patch (68): in a form or an appearance stream, a `Q` with no `q` of that + // stream to match is ignored, so it cannot pop the states of the content that drew + // it. Page content keeps its old behaviour (`stream_floor` stays 0 there). + TypedInstruction::RestoreState(_) if context.stream_floor_reached() => { + warn!("ignored a `Q` with no matching `q` in its content stream"); + } TypedInstruction::StrokeColorDeviceRgb(s) => { - // PdfCraft patch (#3018): DeviceRGB, or the DefaultRGB that replaces it. + // PdfCraft patch (38): DeviceRGB, or the DefaultRGB that replaces it. context.get_mut().graphics_state.stroke_cs = defaults.device(DeviceFamily::Rgb); context.get_mut().graphics_state.stroke_color = smallvec![s.0.as_f32(), s.1.as_f32(), s.2.as_f32()]; context.get_mut().graphics_state.stroke_pattern = None; } TypedInstruction::StrokeColorDeviceGray(s) => { - // PdfCraft patch (#3018): DeviceGray, or the DefaultGray that replaces it. + // PdfCraft patch (38): DeviceGray, or the DefaultGray that replaces it. context.get_mut().graphics_state.stroke_cs = defaults.device(DeviceFamily::Gray); context.get_mut().graphics_state.stroke_color = smallvec![s.0.as_f32()]; context.get_mut().graphics_state.stroke_pattern = None; } TypedInstruction::StrokeColorCmyk(s) => { - // PdfCraft patch (#3018): DeviceCMYK, or the DefaultCMYK that replaces it. + // PdfCraft patch (38): DeviceCMYK, or the DefaultCMYK that replaces it. context.get_mut().graphics_state.stroke_cs = defaults.device(DeviceFamily::Cmyk); context.get_mut().graphics_state.stroke_color = smallvec![s.0.as_f32(), s.1.as_f32(), s.2.as_f32(), s.3.as_f32()]; context.get_mut().graphics_state.stroke_pattern = None; } TypedInstruction::LineWidth(w) => { - context.get_mut().graphics_state.stroke_props.line_width = w.0.as_f32(); + // PdfCraft patch (61): see `convert_line_width`. + context.get_mut().graphics_state.stroke_props.line_width = + convert_line_width(w.0.as_f32()); } TypedInstruction::LineCap(c) => { context.get_mut().graphics_state.stroke_props.line_cap = convert_line_cap(c); @@ -473,43 +675,41 @@ fn interpret_window<'a>( fill_stroke_path(context, device, FillRule::NonZero); } TypedInstruction::NonStrokeColorDeviceGray(s) => { - // PdfCraft patch (#3018): DeviceGray, or the DefaultGray that replaces it. - context.get_mut().graphics_state.none_stroke_cs = - defaults.device(DeviceFamily::Gray); + // PdfCraft patch (38): DeviceGray, or the DefaultGray that replaces it. + context.get_mut().graphics_state.none_stroke_cs = defaults.device(DeviceFamily::Gray); context.get_mut().graphics_state.non_stroke_color = smallvec![s.0.as_f32()]; context.get_mut().graphics_state.non_stroke_pattern = None; } TypedInstruction::NonStrokeColorDeviceRgb(s) => { - // PdfCraft patch (#3018): DeviceRGB, or the DefaultRGB that replaces it. - context.get_mut().graphics_state.none_stroke_cs = - defaults.device(DeviceFamily::Rgb); + // PdfCraft patch (38): DeviceRGB, or the DefaultRGB that replaces it. + context.get_mut().graphics_state.none_stroke_cs = defaults.device(DeviceFamily::Rgb); context.get_mut().graphics_state.non_stroke_color = smallvec![s.0.as_f32(), s.1.as_f32(), s.2.as_f32()]; context.get_mut().graphics_state.non_stroke_pattern = None; } TypedInstruction::NonStrokeColorCmyk(s) => { - // PdfCraft patch (#3018): DeviceCMYK, or the DefaultCMYK that replaces it. - context.get_mut().graphics_state.none_stroke_cs = - defaults.device(DeviceFamily::Cmyk); + // PdfCraft patch (38): DeviceCMYK, or the DefaultCMYK that replaces it. + context.get_mut().graphics_state.none_stroke_cs = defaults.device(DeviceFamily::Cmyk); context.get_mut().graphics_state.non_stroke_color = smallvec![s.0.as_f32(), s.1.as_f32(), s.2.as_f32(), s.3.as_f32()]; context.get_mut().graphics_state.non_stroke_pattern = None; } TypedInstruction::LineTo(m) => { if !context.path().elements().is_empty() { - let last_point = *context.last_point(); - let mut p = Point::new(m.0.as_f64(), m.1.as_f64()); + begin_subpath_after_close(context); + // PdfCraft patch (61): a segment to the point it starts from is kept as it + // is. Upstream nudged its end a ten-thousandth of a point to the right so + // round caps drew a dot, which also gave butt and square caps a direction + // to draw in; `stroke_path_impl` now handles degenerate subpaths. + let p = Point::new(m.0.as_f64(), m.1.as_f64()); *(context.last_point_mut()) = p; - if last_point == p { - // Add a small delta so that zero width lines can still have a round stroke. - p.x += 0.0001; - } context.path_mut().line_to(p); } } TypedInstruction::CubicTo(c) => { if !context.path().elements().is_empty() { + begin_subpath_after_close(context); let p1 = Point::new(c.0.as_f64(), c.1.as_f64()); let p2 = Point::new(c.2.as_f64(), c.3.as_f64()); let p3 = Point::new(c.4.as_f64(), c.5.as_f64()); @@ -521,6 +721,7 @@ fn interpret_window<'a>( } TypedInstruction::CubicStartTo(c) => { if !context.path().elements().is_empty() { + begin_subpath_after_close(context); let p1 = *context.last_point(); let p2 = Point::new(c.0.as_f64(), c.1.as_f64()); let p3 = Point::new(c.2.as_f64(), c.3.as_f64()); @@ -532,6 +733,7 @@ fn interpret_window<'a>( } TypedInstruction::CubicEndTo(c) => { if !context.path().elements().is_empty() { + begin_subpath_after_close(context); let p2 = Point::new(c.0.as_f64(), c.1.as_f64()); let p3 = Point::new(c.2.as_f64(), c.3.as_f64()); @@ -579,9 +781,22 @@ fn interpret_window<'a>( // Ignore for now. } TypedInstruction::ColorSpaceStroke(c) => { - // PdfCraft patch (#3018): see `named_color_space`. + // PdfCraft patch (38): see `named_color_space`. + // PdfCraft patch (55): a space that cannot be read is drawn in DeviceGray, as + // before, and the fallback is reported. + // PdfCraft patch (80): an Indexed space with no lookup table counts as one that + // cannot be read, as upstream. let cs = named_color_space(c.0, resources, &defaults, context) - .unwrap_or(ColorSpace::device_gray()); + .filter(|cs| !cs.is_tableless_indexed()) + .unwrap_or_else(|| { + crate::color::note_color_fallback(); + ColorSpace::device_gray() + }); + // PdfCraft patch (80): so is an Indexed space drawn recovered (indices past a + // short table drawn black, a `hival` clamped or truncated; see `Indexed::new`). + if cs.is_recovered_indexed() { + crate::color::note_color_fallback(); + } if !cs.is_pattern() { context.get_mut().graphics_state.stroke_pattern = None; @@ -590,9 +805,22 @@ fn interpret_window<'a>( context.get_mut().graphics_state.stroke_cs = cs; } TypedInstruction::ColorSpaceNonStroke(c) => { - // PdfCraft patch (#3018): see `named_color_space`. + // PdfCraft patch (38): see `named_color_space`. + // PdfCraft patch (55): a space that cannot be read is drawn in DeviceGray, as + // before, and the fallback is reported. + // PdfCraft patch (80): an Indexed space with no lookup table counts as one that + // cannot be read, as upstream. let cs = named_color_space(c.0, resources, &defaults, context) - .unwrap_or(ColorSpace::device_gray()); + .filter(|cs| !cs.is_tableless_indexed()) + .unwrap_or_else(|| { + crate::color::note_color_fallback(); + ColorSpace::device_gray() + }); + // PdfCraft patch (80): so is an Indexed space drawn recovered (indices past a + // short table drawn black, a `hival` clamped or truncated; see `Indexed::new`). + if cs.is_recovered_indexed() { + crate::color::note_color_fallback(); + } if !cs.is_pattern() { context.get_mut().graphics_state.non_stroke_pattern = None; @@ -602,9 +830,9 @@ fn interpret_window<'a>( } TypedInstruction::DashPattern(p) => { context.get_mut().graphics_state.stroke_props.dash_offset = p.1.as_f32(); - // PdfCraft patch: bounded, see `types::dash_array`. + // PdfCraft patch (61): see `convert_dash_array`. context.get_mut().graphics_state.stroke_props.dash_array = - crate::types::dash_array(p.0.iter::()); + convert_dash_array(p.0.iter::()); } TypedInstruction::RenderingIntent(_) => { // Ignore for now. @@ -833,10 +1061,11 @@ fn interpret_window<'a>( XObject::new( &s, &context.settings.warning_sink, + Some(&context.settings.extended_warning_sink), &cache, Some(&decoded_cache), transfer_function.clone(), - // PdfCraft patch (#3018): an image in a device space draws in its default. + // PdfCraft patch (38): an image in a device space draws in its default. &defaults, ) }) { @@ -845,15 +1074,35 @@ fn interpret_window<'a>( } TypedInstruction::InlineImage(i) => { let warning_sink = context.settings.warning_sink.clone(); + let extended_warning_sink = context.settings.extended_warning_sink.clone(); let transfer_function = context.get().graphics_state.transfer_function.clone(); let cache = context.interpreter_cache.object_cache.clone(); + // PdfCraft patch (80): an inline image naming a resource colour space that is an + // Indexed space whose `hival` has no reading is reported, as `ImageXObject::new` + // reports one given in place; the image falls back as upstream. Only the array's + // name and `hival` are read here, never its lookup table: a recovered space is + // reported by `ImageXObject::new` from the space it builds through the resource + // cache. A device space name (or its inline abbreviation) never refers to a + // resource (ISO 32000-2 §8.6.8), and `ImageXObject::new` takes it first, so a + // resource of that name is not consulted. + let inline_dict = i.0.dict(); + if inline_dict + .get::>(hayro_syntax::object::dict::keys::CS) + .or_else(|| inline_dict.get::>(hayro_syntax::object::dict::keys::COLORSPACE)) + .filter(|name| ColorSpace::new_from_name(name).is_none()) + .and_then(|name| resources.get_color_space(&name)) + .is_some_and(|cs| crate::color::has_unusable_hival(&cs)) + { + (context.settings.extended_warning_sink)(ExtendedWarning::MalformedIndexedImage); + } // PdfCraft patch: inline images are not cached (see `DecodedImageKey`). - // PdfCraft patch (#3018): an inline image in a device space, named directly or by a + // PdfCraft patch (38): an inline image in a device space, named directly or by a // resource, draws in its default. if let Some(x_object) = ImageXObject::new( i.0, |name| named_color_space(name, resources, &defaults, context), &warning_sink, + Some(&extended_warning_sink), &cache, None, false, @@ -877,7 +1126,7 @@ fn interpret_window<'a>( .get_shading(s.0) .and_then(|o| { let (dict, stream) = dict_or_stream(&o)?; - // PdfCraft patch (#3018): a shading in a device space draws in its default. + // PdfCraft patch (38): a shading in a device space draws in its default. Shading::new( dict, stream, @@ -942,16 +1191,22 @@ pub fn interpret<'a>( let num_states = context.num_states(); context.save_state(); + let outer_floor = context.enter_stream(); interpret_window(&mut ops, resources, context, device); while context.num_states() > num_states { context.restore_state(device); } + context.leave_stream(outer_floor); // PdfCraft patch (18): say that content was skipped, so a truncated page isn't a clean render. if crate::context::content_was_truncated() { (context.settings.warning_sink)(InterpreterWarning::ContentTruncated); } + // PdfCraft patch (55): and that a colour was painted in a fallback colour. + if crate::color::take_color_fallback() { + (context.settings.extended_warning_sink)(ExtendedWarning::ColorFallback); + } } /// PdfCraft patch: the bytes of a window of page content. A window grows only while an instruction @@ -1010,4 +1265,8 @@ fn interpret_content<'a>( if cut || content.truncated() || crate::context::content_was_truncated() { (context.settings.warning_sink)(InterpreterWarning::ContentTruncated); } + // PdfCraft patch (55): and that a colour was painted in a fallback colour. + if crate::color::take_color_fallback() { + (context.settings.extended_warning_sink)(ExtendedWarning::ColorFallback); + } } diff --git a/vendor/hayro-interpret/src/interpret/path.rs b/vendor/hayro-interpret/src/interpret/path.rs index 07d37b2dfe..b6582f41b1 100644 --- a/vendor/hayro-interpret/src/interpret/path.rs +++ b/vendor/hayro-interpret/src/interpret/path.rs @@ -1,12 +1,13 @@ -use crate::color::{Color, ColorSpace, InkUse, Plate}; +use crate::color::{Color, ColorSpace, InkUse, Plate, device_cmyk_to_gray}; use crate::context::{Context, path_as_rect}; use crate::device::Device; use crate::interpret::state::PaintData; use crate::pattern::Pattern; use crate::util::{BezPathExt, Float32Ext}; -use crate::{FillRule, Paint, PathDrawMode, StrokeProps}; -use kurbo::{BezPath, Cap, Join, PathEl}; +use crate::{BlendMode, FillRule, Paint, PathDrawMode, StrokeProps}; +use kurbo::{Affine, BezPath, Cap, Join, PathEl, Point, Rect, Vec2}; use smallvec::smallvec; +use std::borrow::Cow; pub(crate) fn fill_path<'a>( context: &mut Context<'a>, @@ -31,13 +32,62 @@ pub(crate) fn fill_stroke_path<'a>( device: &mut impl Device<'a>, fill_rule: FillRule, ) { - fill_path_impl(context, device, fill_rule, None); - stroke_path_impl(context, device, None); + with_fill_stroke_group(context, device, |context, device| { + fill_path_impl(context, device, fill_rule, None); + stroke_path_impl(context, device, None); + }); apply_pending_clip(context, device); context.path_mut().truncate(0); } +/// PdfCraft patch: when one operator both fills and strokes a path (`B`, `B*`, `b`, `b*`) or +/// paints a glyph in text rendering mode 2 or 6, the fill and stroke form an implicit +/// non-isolated knockout transparency group that is composited as a unit with the current +/// soft mask and blend mode (ISO 32000-2 §11.7.4.4). +pub(crate) fn with_fill_stroke_group<'a, D: Device<'a>>( + context: &mut Context<'a>, + device: &mut D, + f: impl FnOnce(&mut Context<'a>, &mut D), +) { + let gs = &context.get().graphics_state; + let has_pattern = gs.stroke_cs.is_pattern() + || gs.stroke_pattern.is_some() + || gs.none_stroke_cs.is_pattern() + || gs.non_stroke_pattern.is_some(); + let needs_group = context.ocg_state.is_visible() + && !device.in_knockout_group() + && (gs.stroke_alpha < 1.0 + || gs.non_stroke_alpha < 1.0 + || gs.soft_mask.is_some() + || gs.blend_mode != BlendMode::Normal + || has_pattern); + + if !needs_group { + f(context, device); + return; + } + + let soft_mask = context.get_mut().graphics_state.soft_mask.take(); + let blend_mode = std::mem::replace( + &mut context.get_mut().graphics_state.blend_mode, + BlendMode::Normal, + ); + + device.set_soft_mask(None); + device.push_transparency_group(1.0, soft_mask.clone(), blend_mode); + device.set_knockout(); + device.set_blend_mode(BlendMode::Normal); + + f(context, device); + + device.pop_transparency_group(); + context.get_mut().graphics_state.soft_mask = soft_mask.clone(); + context.get_mut().graphics_state.blend_mode = blend_mode; + device.set_soft_mask(soft_mask); + device.set_blend_mode(blend_mode); +} + /// PdfCraft patch: a clip set by `W` / `W*` takes effect once the path-painting operator that /// ends the path has painted it, whichever operator that is (ISO 32000-2 §8.5.4). Upstream /// applied it only on `n`, and otherwise left it pending for some later, unrelated `n`. @@ -45,22 +95,160 @@ pub(crate) fn apply_pending_clip<'a>(context: &mut Context<'a>, device: &mut imp if let Some(rule) = context.clip_mut().take() && !context.path().elements().is_empty() { - let clip_path = context.get().ctm * context.path().clone(); - context.push_clip_path(clip_path, rule, device); + let ctm = context.get().ctm; + // PdfCraft patch (65): a clip that encloses no area keeps the pixels a fill of it marks + // (see `degenerate_fill_area`), as ISO 32000-2 §10.7.4 says of clipping: "the clipping + // region consists of the set of pixels that would be included by a fill operation". + match degenerate_fill_area(context.path(), ctm) { + Some(area) => context.push_clip_path(area, FillRule::NonZero, device), + None => { + let clip_path = ctm * context.path().clone(); + context.push_clip_path(clip_path, rule, device); + } + } } } +/// PdfCraft patch (65): the device-space area a fill marks for a path whose bounding box (user +/// space) has exactly no width or exactly no height, but not both, under `ctm`: one area per +/// subpath (see `degenerate_line_area`), kept as separate subpaths of one path, so a gap between +/// two subpaths on the same line stays unpainted (ISO 32000-2 §10.7.4 marks only the pixels the +/// shape touches). Every area winds the same way, so the non-zero rule paints their union. `None` +/// for a path with area, a path that is a point, or one none of whose subpaths is a line: those +/// paint as before. +pub(crate) fn degenerate_fill_area(path: &BezPath, ctm: Affine) -> Option { + let bbox = path.fast_bounding_box(); + if (bbox.width() == 0.0) == (bbox.height() == 0.0) { + return None; + } + let mut area = BezPath::new(); + let mut add = |subpath: &BezPath| { + if subpath.elements().is_empty() { + return; + } + let Some(mut corners) = degenerate_line_area(subpath.fast_bounding_box(), ctm) else { + return; + }; + // Shoelace: wind every area the same way, so overlapping ones add up under non-zero. + let twice_area: f64 = (0..4) + .map(|i| { + let (p, q) = (corners[i], corners[(i + 1) % 4]); + p.x * q.y - q.x * p.y + }) + .sum(); + if twice_area < 0.0 { + corners.reverse(); + } + area.move_to(corners[0]); + for corner in &corners[1..] { + area.line_to(*corner); + } + area.close_path(); + }; + let mut subpath = BezPath::new(); + for el in path.elements() { + if matches!(el, PathEl::MoveTo(_)) { + add(&subpath); + subpath.truncate(0); + } + subpath.push(*el); + } + add(&subpath); + (!area.elements().is_empty()).then_some(area) +} + +/// PdfCraft patch (65): the corners of the device-space area a fill marks for one subpath whose +/// bounding box `bbox` (user space) has exactly no width or exactly no height, but not both, +/// under `ctm`. ISO 32000-2 §10.7.4 paints "any pixel whose half-open square region intersects +/// the shape, no matter how small the intersection is", and its example says "A zero-width or +/// zero-height rectangle paints a line 1 pixel wide". Such a path encloses no area, so the +/// rasteriser marks nothing: the fill used to fall back to a thinnest-line stroke along the box +/// (half-covering two rows when the line fell on a pixel boundary), and a clip of it hid +/// everything painted after it. A box with area, however thin, is not one of these: scaled up it +/// can cover many pixels. +/// +/// When the line stays within one device row or column (counting a line less than 1/256 of a +/// pixel across as lying exactly along the axis, at its middle), the area is the run of whole +/// pixels it touches, by the half-open rule: from the floor of its low end to the ceiling of its +/// high end, at least one pixel. Otherwise (a rotated or skewed `ctm` that carries it across +/// rows and columns) it is a band one device pixel wide centred on the line, like the thinnest +/// line of §8.4.3.2, so each row or column is marked only where the line runs through it. `None` +/// for a box with area, a point (both sides zero), a non-finite box, or a `ctm` that collapses +/// the line to a point. +fn degenerate_line_area(bbox: Rect, ctm: Affine) -> Option<[Point; 4]> { + let flat_x = bbox.width() == 0.0; + let flat_y = bbox.height() == 0.0; + if flat_x == flat_y { + return None; + } + let a = ctm * Point::new(bbox.x0, bbox.y0); + let b = ctm * Point::new(bbox.x1, bbox.y1); + if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite()) { + return None; + } + let along = b - a; + let length = along.hypot(); + if !length.is_finite() || length <= 0.0 { + return None; + } + let device = Rect::from_points(a, b); + let (x0, x1) = touched_pixels(device.x0, device.x1); + let (y0, y1) = touched_pixels(device.y0, device.y1); + if x1 - x0 <= 1.0 || y1 - y0 <= 1.0 { + return Some([Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)]); + } + let half = Vec2::new(-along.y, along.x) * (0.5 / length); + Some([a + half, b + half, b - half, a - half]) +} + +/// PdfCraft patch (65): the device pixel boundaries `(first, end)` of the pixels a span `lo..=hi` +/// (`lo <= hi`, finite) touches along one axis by the half-open rule, at least one pixel. A span +/// under 1/256 of a pixel is taken at its middle, so a line along a device axis that a CTM's +/// rounding tilts slightly still marks one row or column. +fn touched_pixels(lo: f64, hi: f64) -> (f64, f64) { + let (lo, hi) = if ((hi - lo) as f32).is_nearly_zero() { + let mid = lo + (hi - lo) / 2.0; + (mid, mid) + } else { + (lo, hi) + }; + let first = lo.floor(); + (first, hi.ceil().max(first + 1.0)) +} + pub(crate) fn close_path(context: &mut Context<'_>) { // This is necessary to prevent artifacts (see for example issue 157), // but it does cause some weird lines (maybe conflation artifacts) in // pdftc_900k_0907. - if context.path().elements().last() != Some(&PathEl::ClosePath) && !context.path().is_empty() { + // + // PdfCraft patch (61): a path that is a single `m` is closed too. kurbo's `is_empty` counts + // only segments, so upstream dropped the `h` of `x y m h`, and the single-point closed + // subpath a round cap paints as a dot (ISO 32000-2 §8.5.3.2) became a trailing `m`, which + // paints nothing. + if context.path().elements().last() != Some(&PathEl::ClosePath) + && !context.path().elements().is_empty() + { context.path_mut().close_path(); *(context.last_point_mut()) = *context.sub_path_start(); } } +/// PdfCraft patch (61): call before appending a segment. ISO 32000-2 §8.5.2.1 (Table 58) says `h` +/// "terminates the current subpath. Appending another segment to the current path shall begin a +/// new subpath, even if the new segment begins at the endpoint reached by the h operation." kurbo +/// takes a segment after a `ClosePath` on from the closed subpath's start without a `MoveTo`, so +/// `resolve_degenerate_subpaths` saw the closed subpath and a degenerate one after it (`h` then an +/// `l` to the same point) as one subpath and drew no round dot. A `MoveTo` to the point `h` +/// reached starts the new subpath. +pub(crate) fn begin_subpath_after_close(context: &mut Context<'_>) { + if context.path().elements().last() == Some(&PathEl::ClosePath) { + let p = *context.last_point(); + *(context.sub_path_start_mut()) = p; + context.path_mut().move_to(p); + } +} + pub(crate) fn fill_path_impl<'a>( context: &mut Context<'a>, device: &mut impl Device<'a>, @@ -83,10 +271,22 @@ pub(crate) fn fill_path_impl<'a>( // pdf.js issue 4260: Replace zero-sized paths with a small stroke instead. let bbox = path.fast_bounding_box(); - match ( - (bbox.width() as f32).is_nearly_zero(), - (bbox.height() as f32).is_nearly_zero(), - ) { + // PdfCraft patch (65): see `degenerate_fill_area`. Painted with the non-zero rule: the + // area is one simple shape, whatever rule the path was filled with. + if let Some(area) = degenerate_fill_area(path, base_transform) { + let draw_mode = PathDrawMode::Fill(FillRule::NonZero); + if let Some(rect) = path_as_rect(&area) { + device.draw_rect(&rect, Affine::IDENTITY, &paint, &draw_mode); + } else { + device.draw_path(&area, Affine::IDENTITY, &paint, &draw_mode); + } + return; + } + + // PdfCraft patch (65): only a box with exactly no width or height (by now a point) is + // stroked. A box with area, however thin, is filled as the shape it is: a "nearly zero" + // side scaled up by the CTM can cover many device pixels. + match (bbox.width() == 0.0, bbox.height() == 0.0) { (false, false) => { let draw_mode = PathDrawMode::Fill(fill_rule); if let Some(rect) = path_as_rect(path) { @@ -142,7 +342,16 @@ pub(crate) fn stroke_path_impl<'a>( set_overprint(context, device); let paint = get_paint(context, true); - let path = path.unwrap_or(context.path()); + // PdfCraft patch (61): see `resolve_degenerate_subpaths`. + let path = resolve_degenerate_subpaths( + path.unwrap_or(context.path()), + stroke_props.line_cap, + stroke_props.line_width, + ); + let path = path.as_ref(); + if path.elements().is_empty() { + return; + } let draw_mode = PathDrawMode::Stroke(stroke_props); if let Some(rect) = path_as_rect(path) { @@ -162,6 +371,75 @@ pub(crate) fn set_overprint<'a>(context: &Context<'a>, device: &mut impl Device< ); } +/// PdfCraft patch (61): `path` as `S` strokes it, by ISO 32000-2 §8.5.3.2: "If a subpath is +/// degenerate (consists of a single-point closed path or of two or more points at the same +/// coordinates), the S operator shall paint it only if round line caps have been specified, +/// producing a filled circle centred at the single point." With butt or projecting square caps +/// it "shall produce no output". So with round caps a degenerate subpath becomes a segment +/// centred on its point, a thousandth of the line width long (kurbo draws no cap on a segment of +/// length zero), and is left out for the other caps. The other subpaths, and zero-length dashes +/// of them, are not touched. Borrowed when nothing changes. +pub(crate) fn resolve_degenerate_subpaths( + path: &BezPath, + cap: Cap, + line_width: f32, +) -> Cow<'_, BezPath> { + let elements = path.elements(); + if !subpaths(elements).any(|sub| degenerate_point(sub).is_some()) { + return Cow::Borrowed(path); + } + let mut out = BezPath::new(); + for sub in subpaths(elements) { + match degenerate_point(sub) { + Some(p) if cap == Cap::Round => { + // A hairline (width 0) is widened by the device, so it keeps a length kurbo still + // caps; an enormous width keeps the segment within half a unit. + let half = (f64::from(line_width) * 5e-4).max(5e-5).min(0.5); + out.move_to((p.x - half, p.y)); + out.line_to((p.x + half, p.y)); + } + Some(_) => {} + None => sub.iter().for_each(|el| out.push(*el)), + } + } + Cow::Owned(out) +} + +/// The subpaths of `elements`: each starts at a `MoveTo`, except perhaps the first. +fn subpaths(elements: &[PathEl]) -> impl Iterator { + let mut rest = elements; + std::iter::from_fn(move || { + if rest.is_empty() { + return None; + } + let end = rest + .iter() + .skip(1) + .position(|el| matches!(el, PathEl::MoveTo(_))) + .map_or(rest.len(), |i| i.saturating_add(1)); + let (sub, tail) = rest.split_at_checked(end).unwrap_or((rest, &[])); + rest = tail; + Some(sub) + }) +} + +/// The point a degenerate subpath stays at: one that starts with a `MoveTo` and has at least one +/// segment or a `ClosePath`, every point of which (control points too) is the start point. A lone +/// `MoveTo` (a trailing `m`) is not one: it paints nothing whatever the caps. +fn degenerate_point(sub: &[PathEl]) -> Option { + let (PathEl::MoveTo(start), rest) = sub.split_first()? else { + return None; + }; + let at = |p: &Point| p == start; + let degenerate = !rest.is_empty() + && rest.iter().all(|el| match el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => at(p), + PathEl::QuadTo(a, b) => at(a) && at(b), + PathEl::CurveTo(a, b, c) => at(a) && at(b) && at(c), + PathEl::ClosePath => true, + }); + degenerate.then_some(*start) +} pub(crate) fn get_paint<'a>(context: &Context<'a>, is_stroke: bool) -> Paint<'a> { let data = if is_stroke { context.get().stroke_data() @@ -203,7 +481,13 @@ pub(crate) fn get_paint<'a>(context: &Context<'a>, is_stroke: bool) -> Paint<'a> Paint::Color(Color::new(ColorSpace::device_gray(), smallvec![0.0], 0.0)) } } else { - let color = Color::new(data.color_space, data.color, data.alpha); + // PdfCraft patch (63): see `Context::luminosity_in_device_cmyk`. + let color = if context.luminosity_in_device_cmyk && data.color_space.is_device_cmyk() { + let gray = device_cmyk_to_gray(&data.color); + Color::new(ColorSpace::device_gray(), smallvec![gray], data.alpha) + } else { + Color::new(data.color_space, data.color, data.alpha) + }; if let Some(tf) = &data.transfer_function { Paint::Color(Color::from_rgba(tf.apply(&color.to_rgba()))) diff --git a/vendor/hayro-interpret/src/interpret/state.rs b/vendor/hayro-interpret/src/interpret/state.rs index d6fd263aa8..14b6c748f9 100644 --- a/vendor/hayro-interpret/src/interpret/state.rs +++ b/vendor/hayro-interpret/src/interpret/state.rs @@ -1,7 +1,7 @@ use crate::StrokeProps; use crate::color::{AlphaColor, ColorComponents, ColorSpace}; use crate::context::Context; -use crate::convert::{convert_line_cap, convert_line_join}; +use crate::convert::{convert_dash_array, convert_line_cap, convert_line_join, convert_line_width}; use crate::font::{Font, UNITS_PER_EM}; use crate::function::Function; use crate::interpret::text::TextRenderingMode; @@ -339,7 +339,11 @@ pub(crate) fn handle_gs_single<'a>( ) -> Option<()> { // TODO Can we use constants here somehow? match key.as_str() { - "LW" => context.get_mut().graphics_state.stroke_props.line_width = dict.get::(key)?, + // PdfCraft patch (61): see `convert_line_width`. + "LW" => { + context.get_mut().graphics_state.stroke_props.line_width = + convert_line_width(dict.get::(key)?); + } "LC" => { context.get_mut().graphics_state.stroke_props.line_cap = convert_line_cap(LineCap(dict.get::(key)?)); @@ -422,9 +426,9 @@ pub(crate) fn handle_gs_single<'a>( let dash_phase = iter.next()?.into_number()?.as_f32(); context.get_mut().graphics_state.stroke_props.dash_offset = dash_phase; - // PdfCraft patch: bounded, see `types::dash_array`. + // PdfCraft patch (61): see `convert_dash_array`. context.get_mut().graphics_state.stroke_props.dash_array = - crate::types::dash_array(dash_array.iter::()); + convert_dash_array(dash_array.iter::()); } // PdfCraft patch (35): `OP` sets stroking overprint, and non-stroking overprint too when // the dictionary has no `op` of its own; `OPM` is 0 or 1 (§8.6.7). diff --git a/vendor/hayro-interpret/src/lib.rs b/vendor/hayro-interpret/src/lib.rs index 24c3be2957..03a0f44811 100644 --- a/vendor/hayro-interpret/src/lib.rs +++ b/vendor/hayro-interpret/src/lib.rs @@ -32,6 +32,8 @@ This crate has one optional feature: mod log; mod cache; +mod cmyk_group; +mod cmyk_inverse; mod context; mod convert; mod device; @@ -53,6 +55,7 @@ pub mod shading; pub mod util; pub use cache::CacheKey; +pub use cmyk_group::CmykGroup; pub use context::*; pub use device::*; pub use function::Function; diff --git a/vendor/hayro-interpret/src/ocg.rs b/vendor/hayro-interpret/src/ocg.rs index 3a835a96dd..265e79a077 100644 --- a/vendor/hayro-interpret/src/ocg.rs +++ b/vendor/hayro-interpret/src/ocg.rs @@ -1,8 +1,9 @@ use hayro_syntax::object::dict::keys::{ - BASE_STATE, D, OCGS, OCMD, OCPROPERTIES, OFF, ON, P, TYPE, VE, + AS, BASE_STATE, D, OCGS, OCMD, OCPROPERTIES, OFF, ON, P, TYPE, USAGE, VE, VIEW, VIEW_STATE, }; use hayro_syntax::object::{Array, Dict, MaybeRef, Name, Object, ObjectIdentifier}; -use std::collections::HashSet; +use hayro_syntax::xref::XRef; +use std::collections::{HashMap, HashSet}; pub(crate) struct OcgState { inactive_ocgs: HashSet, @@ -13,13 +14,13 @@ pub(crate) struct OcgState { } impl OcgState { - /// Knockout patch (pdfcraft #4898): the marked-content visibility now, to put back after - /// content that may leave it unbalanced is interpreted once more (`draw_knockout_passes`). + /// PdfCraft patch (67): the marked-content visibility now, to put back after content that + /// may leave it unbalanced is interpreted once more (`draw_knockout_passes`). pub(crate) fn visibility(&self) -> Vec { self.visibility_stack.clone() } - /// Knockout patch (pdfcraft #4898): see `visibility`. + /// PdfCraft patch (67): see `visibility`. pub(crate) fn set_visibility(&mut self, visibility: Vec) { self.visibility_stack = visibility; } @@ -32,7 +33,10 @@ impl OcgState { } } - pub(crate) fn from_catalog(catalog: &Dict<'_>) -> Self { + /// The groups' states as the document opens: the default configuration (`/BaseState`, then + /// `/ON` and `/OFF`), then, when `view_auto_state` is set (PdfCraft patch (103)), the auto + /// state its `/AS` array gives for the View event ([`apply_view_auto_state`]). + pub(crate) fn from_catalog(catalog: &Dict<'_>, xref: &XRef, view_auto_state: bool) -> Self { let Some(oc_properties) = catalog.get::>(OCPROPERTIES) else { return Self::dummy(); }; @@ -85,6 +89,10 @@ impl OcgState { read_ocg_array(ON, true); read_ocg_array(OFF, false); + if view_auto_state { + apply_view_auto_state(&config, xref, &mut inactive); + } + Self { inactive_ocgs: inactive, known_ocgs: known, @@ -167,9 +175,7 @@ impl OcgState { } !self.inactive_ocgs.contains(&id) } - MaybeRef::NotRef(Object::Array(nested)) => { - self.visibility_expression(&nested, depth + 1)? - } + MaybeRef::NotRef(Object::Array(nested)) => self.visibility_expression(&nested, depth + 1)?, _ => return None, }; count = count.saturating_add(1); @@ -220,6 +226,87 @@ impl Default for OcgState { } } +/// PdfCraft patch (103): at most this many usage application dictionaries of an `/AS` array are +/// read; the rest are ignored. +const MAX_AUTO_STATE_APPLICATIONS: usize = 256; +/// PdfCraft patch (103): at most this many `/OCGs` entries are read across all of them. +const MAX_AUTO_STATE_GROUPS: usize = 4096; +/// PdfCraft patch (103): at most this many `/Category` names are read per application. +const MAX_AUTO_STATE_CATEGORIES: usize = 16; + +/// PdfCraft patch (103): apply the configuration's auto state for the View event (ISO 32000-2 +/// §8.11.4.4, Tables 99 and 101). For each usage application dictionary in `/AS` whose `/Event` +/// is `/View`, each group in its `/OCGs` gets a recommended state from each category in its +/// `/Category` that the group's `/Usage` gives one for. A group is ON only if every +/// recommendation it receives, across all such dictionaries, is ON, and OFF otherwise; a group +/// that receives none keeps its configured state. +/// +/// Only the `/View` category (`/ViewState`) is evaluated. `/Zoom`, `/User` and `/Language` need +/// the magnification, user and locale, which the interpreter doesn't know, so they give no +/// recommendation. Malformed entries (not a dictionary, no `/Category`, a `/ViewState` other +/// than ON or OFF) are skipped, and the walk is bounded by the caps above. +fn apply_view_auto_state(config: &Dict<'_>, xref: &XRef, inactive: &mut HashSet) { + let Some(applications) = config.get::>(AS) else { + return; + }; + let mut recommended: HashMap = HashMap::new(); + let mut groups_left = MAX_AUTO_STATE_GROUPS; + for application in applications.raw_iter().take(MAX_AUTO_STATE_APPLICATIONS) { + let application = match application { + MaybeRef::Ref(r) => xref.get::>(r.into()), + MaybeRef::NotRef(Object::Dict(d)) => Some(d), + MaybeRef::NotRef(_) => None, + }; + let Some(application) = application else { + continue; + }; + if application.get::>(b"Event").as_deref() != Some(VIEW) { + continue; + } + let views = application.get::>(b"Category").is_some_and(|categories| { + categories + .raw_iter() + .take(MAX_AUTO_STATE_CATEGORIES) + .any(|c| matches!(c, MaybeRef::NotRef(Object::Name(n)) if n.as_ref() == VIEW)) + }); + if !views { + continue; + } + let Some(groups) = application.get::>(OCGS) else { + continue; + }; + for group in groups.raw_iter() { + if groups_left == 0 { + break; + } + groups_left -= 1; + let Some(r) = group.as_obj_ref() else { + continue; + }; + let id: ObjectIdentifier = r.into(); + let state = xref + .get::>(id) + .and_then(|g| g.get::>(USAGE)) + .and_then(|u| u.get::>(VIEW)) + .and_then(|v| v.get::>(VIEW_STATE)); + let on = match state.as_deref() { + Some(ON) => true, + Some(OFF) => false, + _ => continue, + }; + let entry = recommended.entry(id).or_insert(true); + *entry &= on; + } + } + for (id, on) in recommended { + if on { + inactive.remove(&id); + } else { + inactive.insert(id); + } + } +} + /// PdfCraft patch (40): how deep visibility expressions may nest; deeper ones are malformed. const MAX_VISIBILITY_EXPRESSION_DEPTH: usize = 32; diff --git a/vendor/hayro-interpret/src/pattern.rs b/vendor/hayro-interpret/src/pattern.rs index 0068616150..bc3b99c943 100644 --- a/vendor/hayro-interpret/src/pattern.rs +++ b/vendor/hayro-interpret/src/pattern.rs @@ -23,6 +23,10 @@ use hayro_syntax::xref::XRef; use kurbo::{Affine, BezPath, Rect, Shape}; use std::fmt::{Debug, Formatter}; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// PdfCraft patch (78): the source of [`TilingPattern::instance`]. +static NEXT_TILING_INSTANCE: AtomicU64 = AtomicU64::new(0); /// A PDF pattern. #[derive(Debug, Clone)] @@ -158,6 +162,8 @@ impl CacheKey for ShadingPattern { #[derive(Clone)] pub struct TilingPattern<'a> { cache_key: u128, + /// PdfCraft patch (78): see [`Self::instance`]. + instance: u64, ctx_bbox: Rect, /// The bbox of the tiling pattern. pub bbox: Rect, @@ -259,6 +265,7 @@ impl<'a> TilingPattern<'a> { Some(Self { cache_key, + instance: NEXT_TILING_INSTANCE.fetch_add(1, Ordering::Relaxed), bbox, x_step, y_step, @@ -338,6 +345,23 @@ impl<'a> TilingPattern<'a> { } } +impl TilingPattern<'_> { + /// PdfCraft patch (78): which setting of the pattern (`scn`/`SCN`) this is. Each setting is + /// numbered apart, and its copies keep the number. A coloured pattern's cell depends only on + /// what the setting captured (its stream, resources, settings and the bounding box then in + /// effect) and on the scale it is drawn at, so a renderer can draw the cell once per number + /// and scale for every fill of that setting. An uncoloured pattern's cell also takes the + /// colour and opacity of the paint, which copies can change. + pub fn instance(&self) -> u64 { + self.instance + } + + /// Whether the pattern is coloured (`/PaintType 1`). + pub fn is_coloured(&self) -> bool { + self.is_color + } +} + impl CacheKey for TilingPattern<'_> { fn cache_key(&self) -> u128 { self.cache_key diff --git a/vendor/hayro-interpret/src/soft_mask.rs b/vendor/hayro-interpret/src/soft_mask.rs index 4fdeaac814..6ecd81dbfd 100644 --- a/vendor/hayro-interpret/src/soft_mask.rs +++ b/vendor/hayro-interpret/src/soft_mask.rs @@ -1,4 +1,4 @@ -use crate::color::{CmykSimulation, Color, ColorComponents, ColorSpace, Ink, Plate}; +use crate::color::{CmykSimulation, Color, ColorComponents, ColorSpace, DeviceFamily, Ink, Plate, device_cmyk_to_gray}; use crate::context::{Context, InterpreterCache}; use crate::device::Device; use crate::function::Function; @@ -74,6 +74,9 @@ struct Repr<'a> { transfer_function: Option, settings: InterpreterSettings, background: Color, + // PdfCraft patch (63). + /// A luminosity mask whose group colour space is `/DeviceCMYK`. + luminosity_in_device_cmyk: bool, xref: &'a XRef, nesting_depth: u32, /// Craft patch (CMYK masks): the group's `/CS` is DeviceCMYK. @@ -126,10 +129,17 @@ impl<'a> SoftMask<'a> { // PdfCraft patch: the group's /CS is optional (ISO 32000-2 §11.6.5.2; Chrome/Skia omit // it). Upstream returned None here, silently dropping the whole soft mask. Fall back to // DeviceRGB, the blending space our renderer composites in. - let cs = group + let cs_object = group .dict .get::>(GROUP) - .and_then(|g| g.get::>(CS)) + .and_then(|g| g.get::>(CS)); + // PdfCraft patch (63): the group is composited in `/DeviceCMYK` itself. An ICC-based + // or calibrated group space keeps its own conversion. + let group_in_device_cmyk = cs_object + .as_ref() + .and_then(DeviceFamily::of_object) + .is_some_and(|family| family == DeviceFamily::Cmyk); + let cs = cs_object .and_then(|o| ColorSpace::new(o, &context.interpreter_cache.object_cache)) .unwrap_or_else(ColorSpace::device_rgb); let device_cmyk = cs.is_device_cmyk(); @@ -141,7 +151,19 @@ impl<'a> SoftMask<'a> { LUMINOSITY => { let color = dict .get::(BC) - .map(|c| Color::new(cs, c, 1.0)) + .map(|c| { + // PdfCraft patch (63): a DeviceCMYK backdrop's luminosity is its gray + // (ISO 32000-2 §11.5.3), as for the group's content. + if group_in_device_cmyk && c.len() == 4 { + Color::new( + ColorSpace::device_gray(), + smallvec![device_cmyk_to_gray(&c)], + 1.0, + ) + } else { + Color::new(cs, c, 1.0) + } + }) .unwrap_or(Color::new(ColorSpace::device_gray(), smallvec![0.0], 1.0)); (MaskType::Luminosity, color) @@ -189,6 +211,7 @@ impl<'a> SoftMask<'a> { }, xref: context.xref, background, + luminosity_in_device_cmyk: group_in_device_cmyk && mask_type == MaskType::Luminosity, parent_resources, nesting_depth, device_cmyk, @@ -248,6 +271,7 @@ impl<'a> SoftMask<'a> { state, self.0.nesting_depth, ); + ctx.luminosity_in_device_cmyk = self.0.luminosity_in_device_cmyk; draw_form_xobject(&self.0.parent_resources, &self.0.group, &mut ctx, device); } diff --git a/vendor/hayro-interpret/src/types.rs b/vendor/hayro-interpret/src/types.rs index 7c46cbc833..ecd42d584f 100644 --- a/vendor/hayro-interpret/src/types.rs +++ b/vendor/hayro-interpret/src/types.rs @@ -317,7 +317,7 @@ pub enum GlyphDrawMode { Fill, /// Draw using a stroke. Stroke(StrokeProps), - /// PdfCraft patch (#3116): text that shapes a clip; report it without painting a glyph. + /// PdfCraft patch: text that shapes a clip; report it without painting a glyph. Clip, /// Invisible text (for text extraction but not visual rendering). Invisible, diff --git a/vendor/hayro-interpret/src/x_object.rs b/vendor/hayro-interpret/src/x_object.rs index b2c0f14f57..a772233f28 100644 --- a/vendor/hayro-interpret/src/x_object.rs +++ b/vendor/hayro-interpret/src/x_object.rs @@ -1,4 +1,5 @@ use crate::cache::{Cache, DecodedImageCache, DecodedImageKey}; +use crate::cmyk_group::{CmykGroup, blends_in_device_cmyk, names_a_blending_space}; use crate::color::{ CmykSimulation, ColorComponents, ColorSpace, DefaultColorSpaces, DeviceFamily, InkSpace, InkUse, Plate, ToRgb, @@ -9,7 +10,7 @@ use crate::function::{Function, interpolate}; use crate::interpret::path::{get_paint, set_overprint}; use crate::interpret::state::ActiveTransferFunction; use crate::{BlendMode, CacheKey, ClipPath, Image, Paint, RasterImage, StencilImage}; -use crate::{FillRule, InterpreterWarning, WarningSinkFn, interpret}; +use crate::{ExtendedWarning, ExtendedWarningSinkFn, FillRule, InterpreterWarning, WarningSinkFn, interpret}; use crate::{ImageData, InkImage, LumaData, RgbData}; use hayro_syntax::bit_reader::BitReader; use hayro_syntax::content::TypedIter; @@ -26,6 +27,8 @@ use smallvec::{SmallVec, smallvec}; use std::borrow::Cow; use std::iter; use std::ops::Deref; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; pub(crate) enum XObject<'a> { FormXObject(FormXObject<'a>), @@ -36,6 +39,7 @@ impl<'a> XObject<'a> { pub(crate) fn new( stream: &Stream<'a>, warning_sink: &WarningSinkFn, + extended_warning_sink: Option<&ExtendedWarningSinkFn>, cache: &Cache, decoded_cache: Option<&DecodedImageCache>, transfer_function: Option, @@ -47,6 +51,7 @@ impl<'a> XObject<'a> { stream, |_| None, warning_sink, + extended_warning_sink, cache, decoded_cache, false, @@ -122,6 +127,24 @@ pub(crate) fn draw_form_xobject<'a, 'b>( x_object: &'b FormXObject<'a>, context: &mut Context<'a>, device: &mut impl Device<'a>, +) { + // PdfCraft patch (89): a form already being drawn is not drawn inside itself. A name its + // content uses can reach it again (through its own resources, or the page's, which a form + // with resources of its own still falls back on), and every such level used to run until + // the page's nested-paint budget was spent. + let id = x_object.dict.obj_id(); + if !context.enter_form(id) { + return; + } + draw_form_xobject_once(resources, x_object, context, device); + context.leave_form(id); +} + +fn draw_form_xobject_once<'a, 'b>( + resources: &Resources<'a>, + x_object: &'b FormXObject<'a>, + context: &mut Context<'a>, + device: &mut impl Device<'a>, ) { if !context.ocg_state.is_visible() { return; @@ -140,8 +163,6 @@ pub(crate) fn draw_form_xobject<'a, 'b>( return; } - let iter = TypedIter::new(x_object.decoded.as_ref()); - context.path_mut().truncate(0); context.save_state(); context.pre_concat_affine(x_object.matrix); @@ -237,6 +258,57 @@ pub(crate) fn draw_form_xobject<'a, 'b>( } } + let resources = Resources::from_scope(x_object.resources.clone(), resources.clone()); + + // PdfCraft patch (70): an isolated group blending in DeviceCMYK starts from a backdrop of + // its own, so a device able to blend in CMYK computes its interior apart and composites the + // result through the layer pushed above (see `cmyk_group`). Knockout groups are left out: + // their elements composite with the group's initial backdrop, not with each other. + // An isolated group that names another blending space blends in that space (§11.3.4); a + // device drawing an enclosing group in CMYK is told, so it can decline that group. A + // non-isolated group's /CS is ignored: it blends in its parent's space (ISO 32000-2 + // Table 145, CS), so it stays in the enclosing group's CMYK. + if x_object.is_transparency_group + && x_object.is_isolated + && names_a_blending_space(&x_object.dict) + && !blends_in_device_cmyk(&x_object.dict) + { + device.group_blends_outside_device_cmyk(); + } + + let blended_in_cmyk = own_layer + && x_object.is_isolated + && !x_object.is_knockout + && blends_in_device_cmyk(&x_object.dict) + && device.draw_isolated_cmyk_group(&CmykGroup::new(x_object, &resources, context)); + + if !blended_in_cmyk { + interpret_form_contents(&resources, x_object, context, device); + } + + if own_layer { + device.pop_transparency_group(); + } + + context.pop_root_transform(); + context.restore_state(device); + + if has_oc { + context.ocg_state.end_marked_content(); + } + + context.end_nested_interpretation(); +} + +/// The contents of form `x_object`, in `context` as prepared for them (the form's `/Matrix` +/// applied, its root transform pushed), clipped to its `/BBox`. PdfCraft patch (70): shared by +/// [`draw_form_xobject`] and [`CmykGroup::interpret`]. +pub(crate) fn interpret_form_contents<'a>( + resources: &Resources<'a>, + x_object: &FormXObject<'a>, + context: &mut Context<'a>, + device: &mut impl Device<'a>, +) { device.set_soft_mask(context.get().graphics_state.soft_mask.clone()); device.set_blend_mode(context.get().graphics_state.blend_mode); @@ -253,26 +325,13 @@ pub(crate) fn draw_form_xobject<'a, 'b>( }); interpret( - iter, + TypedIter::new(x_object.decoded.as_ref()), &Resources::from_scope(x_object.resources.clone(), resources.clone()), context, device, ); device.pop_clip_path(); - - if own_layer { - device.pop_transparency_group(); - } - - context.pop_root_transform(); - context.restore_state(device); - - if has_oc { - context.ocg_state.end_marked_content(); - } - - context.end_nested_interpretation(); } /// Knockout patch (pdfcraft #4898): draws a non-isolated knockout group entered at full opacity, @@ -482,6 +541,12 @@ pub(crate) struct ImageXObject<'a> { interpolate: bool, is_mask: bool, is_stencil_mask: bool, + /// PdfCraft patch (73): whether this is a picture's soft mask or `/Mask`, not an image drawn + /// on its own, by `Do` or inline, a stencil mask included. Only a picture's mask refused by a + /// limit takes something out with it, and is reported so. A picture's mask is cached only + /// averaged down (`shrunk_to`), which an image drawn on its own never is, so the two never + /// share an entry and its warnings. + masks_picture: bool, stream: Stream<'a>, transfer_function: Option, warning_sink: WarningSinkFn, @@ -511,6 +576,7 @@ impl<'a> ImageXObject<'a> { stream: &Stream<'a>, resolve_cs: impl FnOnce(&Name<'_>) -> Option, warning_sink: &WarningSinkFn, + extended_warning_sink: Option<&ExtendedWarningSinkFn>, cache: &Cache, decoded_cache: Option<&DecodedImageCache>, mut is_mask: bool, @@ -523,9 +589,11 @@ impl<'a> ImageXObject<'a> { .get::(IM) .or_else(|| dict.get::(IMAGE_MASK)) .unwrap_or(false); + let masks_picture = is_mask; is_mask |= is_stencil_mask; let mut default_space = None; + let mut malformed_indexed = false; let image_cs = if is_mask { // Masks are always single-channel. Some(ColorSpace::device_gray()) @@ -554,6 +622,26 @@ impl<'a> ImageXObject<'a> { }) } }; + // PdfCraft patch (80): an Indexed space that ISO 32000-2 §8.6.6.3 rules out (a short + // lookup table, a `hival` past 255 or with a fraction) is drawn recovered (see + // `Indexed::new`), and reported. The check asks the space that was built, so it reads + // no lookup table of its own (an inline image naming a resource builds it once, through + // the resource cache). + malformed_indexed |= image_cs + .as_ref() + .is_some_and(ColorSpace::is_recovered_indexed); + // PdfCraft patch (80): an Indexed space with no lookup table at all (missing, or not a + // string or a stream that decodes) leaves nothing to draw: the image is skipped, and + // reported. Upstream drew it in DeviceGray. + if image_cs + .as_ref() + .is_some_and(ColorSpace::is_tableless_indexed) + { + if let Some(sink) = extended_warning_sink { + sink(ExtendedWarning::MalformedIndexedImage); + } + return None; + } let interpolate = dict .get::(I) @@ -567,6 +655,10 @@ impl<'a> ImageXObject<'a> { return None; } + if malformed_indexed && let Some(sink) = extended_warning_sink { + sink(ExtendedWarning::MalformedIndexedImage); + } + Some(Self { width, cache: cache.clone(), @@ -580,6 +672,7 @@ impl<'a> ImageXObject<'a> { is_mask, is_stencil_mask, plate: None, + masks_picture, default_space, }) } @@ -597,7 +690,8 @@ impl<'a> ImageXObject<'a> { self.decode_key(cache, true, target_dimension), MAX_DECODED_IMAGE_BYTES, decoded_mask_size, - || decode_mask(self, target_dimension), + &self.warning_sink, + |sink| decode_mask(&self.reporting_to(sink), target_dimension), ) } @@ -608,6 +702,10 @@ impl<'a> ImageXObject<'a> { if self.is_mask { return None; } + // PdfCraft patch (review on #3884): a colour key is matched against the decoded samples + // (`resolve_alpha`), and a JPX decode at a reduced resolution has averaged ones, so an + // image it masks is decoded at full size and resampled with its mask like any other. + let target_dimension = target_dimension.filter(|_| !self.has_colour_key_mask()); // PdfCraft patch: decode once per `DecodedImageKey`; tiles and scales share it. let Some(cache) = &self.decoded_cache else { @@ -617,7 +715,8 @@ impl<'a> ImageXObject<'a> { self.decode_key(cache, false, target_dimension), MAX_DECODED_IMAGE_BYTES, decoded_raster_size, - || decode_raster(self, target_dimension), + &self.warning_sink, + |sink| decode_raster(&self.reporting_to(sink), target_dimension), ) } @@ -649,10 +748,70 @@ impl<'a> ImageXObject<'a> { // PdfCraft patch (32): see `decode_reads_target`. target: if self.decode_reads_target() { target_dimension + } else if self.has_larger_mask() { + target_dimension.map(size_bucket) } else { None }, preview: cache.preview, + shrunk_to: None, + }) + } + + /// PdfCraft patch (82): this soft mask (or `/Mask` image) for an image of `parent` samples + /// drawn at `target_dimension` device pixels. A mask larger than its image and more than + /// [`SOFT_MASK_SHRINK_FACTOR`] times larger than where it is drawn, on a side, is averaged down + /// to that size, and the result is cached at that size: drawn + /// through a form many times (a 2 × 2 image whose mask is 34,862 × 4,332, drawn 40 times on + /// one slide, pdf.js `issue16263.pdf`), it was decoded, copied and drawn at full size each + /// time, about 3.6 s apiece, and the page took minutes. Any other mask decodes as before; a mask + /// no larger than its image keeps its size, so the renderer still samples it onto the image's + /// grid. + pub(crate) fn decoded_soft_mask(&self, target_dimension: Option<(u32, u32)>, parent: (u32, u32)) -> Option { + let larger_than_image = self.width > parent.0 || self.height > parent.1; + let shrink_to = target_dimension.filter(|&(tw, th)| { + larger_than_image + && tw > 0 + && th > 0 + && (u64::from(self.width) > u64::from(tw) * SOFT_MASK_SHRINK_FACTOR + || u64::from(self.height) > u64::from(th) * SOFT_MASK_SHRINK_FACTOR) + }); + // Decoded within the image's own decode, as before: the image's cache entry holds it as + // its alpha, and patch (91) keeps that entry when the mask fails, so a second entry for + // the mask would only count it twice. + let Some((tw, th)) = shrink_to else { + return decode_mask(self, target_dimension); + }; + // Averaged down to the drawn size rounded up to a power of two (`size_bucket`), so draws a + // pixel apart share one mask and the renderer filters the rest, and only on the sides that + // are larger than that. + let (bw, bh) = size_bucket((tw, th)); + let to = (bw.min(self.width).max(1), bh.min(self.height).max(1)); + // Decoded in full and averaged down to `to`. A truncated stream decodes fewer rows than + // the dictionary says: never more target samples than decoded ones on a side. + let from_full = |image: &Self, to: (u32, u32)| { + let full = decode_mask(image, target_dimension)?; + Some(DecodedMask { luma: shrink_luma_within(full.luma, to)? }) + }; + let Some(cache) = &self.decoded_cache else { + return from_full(self, to); + }; + let key = |to| self.decode_key(cache, true, target_dimension).map(|key| DecodedImageKey { shrunk_to: Some(to), ..key }); + // One image drawn at several sizes (rotated and scaled copies on one slide) needs the + // mask at several sizes. Each comes from one intermediate averaged-down mask, cached at + // most `SOFT_MASK_INTERMEDIATE` on a side, so the full mask is decoded once, not once per + // size; a size larger than the intermediate comes from the full mask. + let between = (self.width.min(SOFT_MASK_INTERMEDIATE), self.height.min(SOFT_MASK_INTERMEDIATE)); + if to == between || to.0 > between.0 || to.1 > between.1 { + return cache.get_or_insert_with(key(to), MAX_DECODED_IMAGE_BYTES, decoded_mask_size, &self.warning_sink, |sink| { + from_full(&self.reporting_to(sink), to) + }); + } + cache.get_or_insert_with(key(to), MAX_DECODED_IMAGE_BYTES, decoded_mask_size, &self.warning_sink, |sink| { + let mid = cache.get_or_insert_with(key(between), MAX_DECODED_IMAGE_BYTES, decoded_mask_size, sink, |sink| { + from_full(&self.reporting_to(sink), between) + })?; + Some(DecodedMask { luma: shrink_luma_within(mid.luma, to)? }) }) } @@ -668,6 +827,29 @@ impl<'a> ImageXObject<'a> { || dict.get::>(MASK).is_some_and(|s| uses_jpx(&s)) } + /// PdfCraft patch (82): whether this image has a soft mask (or `/Mask` image) larger than + /// itself, which may be averaged down to the size the image is drawn at + /// (`decoded_soft_mask`): the decoded raster holds it as its alpha, so it depends on that size, + /// to the [`size_bucket`] it is averaged down to. + fn has_larger_mask(&self) -> bool { + let dict = self.stream.dict(); + let larger = |s: &Stream<'_>| { + let d = s.dict(); + // The dimension keys as `ImageXObject::new` reads them, abbreviations first. + let (w, h) = (d.get::(W).or_else(|| d.get::(WIDTH)), d.get::(H).or_else(|| d.get::(HEIGHT))); + w.is_some_and(|w| w > self.width) || h.is_some_and(|h| h > self.height) + }; + dict.get::>(SMASK).is_some_and(|s| larger(&s)) || dict.get::>(MASK).is_some_and(|s| larger(&s)) + } + + /// PdfCraft patch (91): this image, reporting its warnings to `sink`. + fn reporting_to(&self, sink: &WarningSinkFn) -> Self { + Self { + warning_sink: sink.clone(), + ..self.clone() + } + } + pub(crate) fn width(&self) -> u32 { self.width } @@ -680,6 +862,15 @@ impl<'a> ImageXObject<'a> { &self.stream } + /// PdfCraft patch (review on #3884): whether `resolve_alpha` takes this image's alpha from + /// a colour-key `/Mask` array: no `/SMaskInData 1` and no `/SMask` stream before it. + fn has_colour_key_mask(&self) -> bool { + let dict = self.stream.dict(); + dict.get::(SMASK_IN_DATA) != Some(1) + && dict.get::>(SMASK).is_none() + && dict.get::>(MASK).is_some() + } + fn has_mask(&self) -> bool { let dict = self.stream.dict(); @@ -691,6 +882,71 @@ impl<'a> ImageXObject<'a> { /// image pixels shared across tiles and scales. Past it the cache starts a fresh epoch. const MAX_DECODED_IMAGE_BYTES: usize = 64 << 20; +/// PdfCraft patch (82): how many times larger than where it is drawn, on a side, a soft mask must be +/// before it is averaged down to that size (`ImageXObject::decoded_soft_mask`). Below it the mask +/// keeps its own resolution, which the renderer filters as it draws. +const SOFT_MASK_SHRINK_FACTOR: u64 = 2; + +/// PdfCraft patch (82): the largest side of the intermediate mask that every smaller averaged-down +/// size of one soft mask is made from (`ImageXObject::decoded_soft_mask`): 4096 × 4096 one-byte +/// samples are 16 MiB, a quarter of the decoded-image budget, so it stays cached between draws. +const SOFT_MASK_INTERMEDIATE: u32 = 4096; + +/// PdfCraft patch (82): the size a large soft mask is averaged down to for an image drawn at +/// `(w, h)` device pixels: each side rounded up to a power of two. Draws of one image a pixel or so +/// apart (scaled by 0.36 and 0.36167, say) share one averaged mask and one cache entry, and a mask +/// is never averaged below where it is drawn, so the renderer shrinks the rest at most twofold. +fn size_bucket((w, h): (u32, u32)) -> (u32, u32) { + (w.checked_next_power_of_two().unwrap_or(u32::MAX), h.checked_next_power_of_two().unwrap_or(u32::MAX)) +} + +/// PdfCraft patch (82): `luma` averaged down to `to` (no larger than it on either side): each +/// target sample is the mean of the source samples whose centres fall in it. Source sample `x` +/// of `sw`, centred at `x + ½`, falls in target sample `⌊(2x + 1)·tw / 2sw⌋`. The only buffers are +/// the target's sums and counts, reserved fallibly; nothing is sized by the source's width. +fn shrink_luma(luma: LumaData, to: (u32, u32)) -> Option { + let (sw, sh) = (luma.width as usize, luma.height as usize); + let (tw, th) = (to.0 as usize, to.1 as usize); + if sw == 0 || sh == 0 || tw == 0 || th == 0 || tw > sw || th > sh || luma.data.len() != sw.checked_mul(sh)? { + return None; + } + let cells = tw.checked_mul(th)?; + let (mut sums, mut counts): (Vec, Vec) = (Vec::new(), Vec::new()); + sums.try_reserve_exact(cells).ok()?; + counts.try_reserve_exact(cells).ok()?; + sums.resize(cells, 0); + counts.resize(cells, 0); + // The target sample a source sample's centre falls in, along an axis of `src` samples + // shrunk to `dst`. `2·i + 1 < 2·src` and `dst ≤ src ≤ 2^32`, so the product fits a u64. + let centre = |i: usize, src: usize, dst: usize| -> usize { + let at = (2 * i as u64 + 1) * dst as u64 / (2 * src as u64); + (at as usize).min(dst - 1) + }; + for (y, row) in luma.data.chunks_exact(sw).enumerate() { + let base = centre(y, sh, th) * tw; + for (x, &v) in row.iter().enumerate() { + let i = base + centre(x, sw, tw); + if let (Some(sum), Some(count)) = (sums.get_mut(i), counts.get_mut(i)) { + *sum += u64::from(v); + *count += 1; + } + } + } + let data = sums.iter().zip(&counts).map(|(&sum, &count)| if count == 0 { 0 } else { (sum / u64::from(count)) as u8 }).collect(); + Some(LumaData { data, width: to.0, height: to.1, ..luma }) +} + +/// PdfCraft patch (82): `luma` averaged down to `to`, but never to more samples than it has on a +/// side (a truncated stream decodes fewer rows than its dictionary says), and returned as it is +/// when that is its own size. +fn shrink_luma_within(luma: LumaData, to: (u32, u32)) -> Option { + let to = (to.0.min(luma.width).max(1), to.1.min(luma.height).max(1)); + if to == (luma.width, luma.height) { + return Some(luma); + } + shrink_luma(luma, to) +} + /// PdfCraft patch: pixel bytes held by a decoded mask. fn decoded_mask_size(mask: &DecodedMask) -> usize { mask.luma.width as usize * mask.luma.height as usize @@ -700,13 +956,23 @@ fn decoded_mask_size(mask: &DecodedMask) -> usize { /// `/Filter` or its inline abbreviation `/F`. Errs towards `true`: a name the decoder would /// ignore still counts, which only keeps the target in the key as before. fn uses_jpx(stream: &Stream<'_>) -> bool { + uses_filter(stream, JPX_DECODE) +} + +/// PdfCraft patch (73): whether `stream` is JBIG2, so that what the page has left, which all of it +/// shares, says something about why this stream failed. +fn uses_jbig2(stream: &Stream<'_>) -> bool { + uses_filter(stream, JBIG2_DECODE) +} + +fn uses_filter(stream: &Stream<'_>, filter: &[u8]) -> bool { let dict = stream.dict(); - let is_jpx = |name: &Name<'_>| name.deref() == JPX_DECODE; + let is_filter = |name: &Name<'_>| name.deref() == filter; [F, FILTER].into_iter().any(|key| { - dict.get::>(key).is_some_and(|name| is_jpx(&name)) + dict.get::>(key).is_some_and(|name| is_filter(&name)) || dict .get::>(key) - .is_some_and(|filters| filters.iter::>().any(|name| is_jpx(&name))) + .is_some_and(|filters| filters.iter::>().any(|name| is_filter(&name))) }) } @@ -753,7 +1019,16 @@ fn decode_context<'a>( // renderer skips them anyway): a fuzzed `/W 4294967295` stencil mask allocated gigabytes here. // The document's decode limits may set another pixel count. if !image_size_within(obj.width, obj.height, obj.stream.decode_limits().max_image_pixels()) { - (obj.warning_sink)(InterpreterWarning::ImageDecodeFailure); + // PdfCraft patch (73): a picture's JBIG2 mask of a size this bound refuses is one a limit + // refused, as when the decoder refuses it (below), and its size is the stream's own. + // `ImageXObject::new` refuses a size of 0, so this is past the bound. + let limited = obj.masks_picture && uses_jbig2(&obj.stream); + crate::cache::note_stream_limited(limited); + (obj.warning_sink)(if limited { + InterpreterWarning::ContentTruncated + } else { + InterpreterWarning::ImageDecodeFailure + }); return None; } let dict = obj.stream.dict(); @@ -772,10 +1047,31 @@ fn decode_context<'a>( height: obj.height, }; + // PdfCraft patch (73): what refused an image decoded before this one says nothing about it, + // whether or not its filters reach JBIG2. + hayro_syntax::clear_jbig2_limited(); let decoded = obj .stream .decoded_image(&decode_params) - .map_err(|_| (obj.warning_sink)(InterpreterWarning::ImageDecodeFailure)) + .map_err(|_| { + // PdfCraft patch (73): left out for the page's allowance, it is content the page's + // budget skipped, which is reported, and no failure of this image. So is a picture's + // mask one of the decoder's limits refused, which takes the picture with it + // (`decode_raster`). + // Reported so, the decoded-image cache (patch 91) keeps the failure only when the + // limit is one the stream reaches by itself, whatever the page had left. + let limited = obj.masks_picture && hayro_syntax::jbig2_limited(); + let left_out = + (hayro_syntax::page_jbig2_work_spent() || limited) && uses_jbig2(&obj.stream); + crate::cache::note_stream_limited( + left_out && obj.masks_picture && hayro_syntax::jbig2_limited_by_stream(), + ); + (obj.warning_sink)(if left_out { + InterpreterWarning::ContentTruncated + } else { + InterpreterWarning::ImageDecodeFailure + }); + }) .ok()?; let (mut scale_x, mut scale_y) = (1.0, 1.0); @@ -1025,6 +1321,20 @@ fn decode_raster( let mut image = image_data?; + // PdfCraft patch (73): whether the mask, decoded below or kept failed by the decoded-image + // cache, was left out for the page's allowance or a decoder's limit: only those report + // `ContentTruncated` there (`decode_context`). + let left_out = Arc::new(AtomicBool::new(false)); + let sink: WarningSinkFn = { + let (left_out, sink) = (left_out.clone(), obj.warning_sink.clone()); + Arc::new(move |warning| { + if matches!(warning, InterpreterWarning::ContentTruncated) { + left_out.store(true, Ordering::Relaxed); + } + sink(warning); + }) + }; + let obj = &obj.reporting_to(&sink); let alpha = if let Some((alpha, matte_rgb)) = resolve_matte(obj, &ctx.color_space, target_dimension) && alpha.width == ctx.width @@ -1051,6 +1361,18 @@ fn decode_raster( .flatten() }; + // PdfCraft patch (73): a bad mask leaves the image as it is, but one left out for the page's + // allowance, or refused by one of the decoder's limits, takes the image with it. Both are + // reported, and only there is the file not to blame for what the mask would have hidden being + // shown: a scan's colour layer drawn without its JBIG2 mask covers the page in noise (#6722). + // A size or count the file damaged can read as past a limit, and is taken for one: it can't + // be told from a hostile one, and leaving the image out is the safe side. + let dict = obj.stream.dict(); + let mask = dict.get::>(SMASK).or_else(|| dict.get::>(MASK)); + if alpha.is_none() && left_out.load(Ordering::Relaxed) && mask.is_some_and(|m| uses_jbig2(&m)) { + return None; + } + Some(DecodedRaster { image, alpha }) } @@ -1251,9 +1573,10 @@ fn resolve_alpha( .get::>(SMASK) .or_else(|| dict.get::>(MASK)) { - let obj = ImageXObject::new(&s_mask, |_| None, &obj.warning_sink, &obj.cache, obj.decoded_cache.as_ref(), true, None, None)?; + let obj = ImageXObject::new(&s_mask, |_| None, &obj.warning_sink, None, &obj.cache, obj.decoded_cache.as_ref(), true, None, None)?; - decode_mask(&obj, target_dimension).map(|decoded| decoded.luma) + // PdfCraft patch (82): averaged down when far larger than where it is drawn, and cached. + obj.decoded_soft_mask(target_dimension, (width, *height)).map(|decoded| decoded.luma) } else if let Some(color_key_mask) = dict.get::>(MASK) { let mut mask_data = vec![]; @@ -1312,7 +1635,7 @@ fn resolve_matte( let mut matte_rgb = [0_u8; 3]; color_space.convert_f32(&matte, &mut matte_rgb, false); - let mask_obj = ImageXObject::new(&s_mask, |_| None, &obj.warning_sink, &obj.cache, obj.decoded_cache.as_ref(), true, None, None)?; + let mask_obj = ImageXObject::new(&s_mask, |_| None, &obj.warning_sink, None, &obj.cache, obj.decoded_cache.as_ref(), true, None, None)?; let alpha = decode_mask(&mask_obj, target_dimension)?.luma; Some((alpha, matte_rgb)) diff --git a/vendor/hayro-jbig2/src/segment.rs b/vendor/hayro-jbig2/src/segment.rs index 1c6fcf31e5..db720df320 100644 --- a/vendor/hayro-jbig2/src/segment.rs +++ b/vendor/hayro-jbig2/src/segment.rs @@ -8,12 +8,10 @@ use alloc::vec::Vec; use crate::error::{ParseError, Result, SegmentError, bail, err}; use crate::reader::Reader; -/// PdfCraft patch: the most segments one segment may refer to. A crafted long-form -/// header can claim a 29-bit count, which `Vec::with_capacity` below would turn into -/// a multi-gigabyte reservation before a single referred-to number is read — an -/// allocation failure then aborts the process in a way `catch_unwind` cannot contain. -/// Real files refer to a handful of segments, so `u16::MAX` is far beyond any -/// legitimate need. +/// PdfCraft patch: the most segments one segment may refer to. A long-form header can claim a +/// 29-bit count, which `Vec::with_capacity` below would turn into a multi-gigabyte reservation +/// before a single referred-to number is read; the allocation failure aborts the process. Real +/// files refer to a handful of segments. pub(crate) const MAX_REFERRED_TO_SEGMENTS: u32 = u16::MAX as u32; /// "The segment type is a number between 0 and 63, inclusive. Not all values @@ -191,8 +189,8 @@ pub(crate) fn parse_segment_header(reader: &mut Reader<'_>) -> Result MAX_REFERRED_TO_SEGMENTS { bail!(SegmentError::InvalidReferredCount); } @@ -431,26 +429,33 @@ mod tests { assert_eq!(header.data_length, Some(32)); } + /// PdfCraft patch test (ported from craft-libs): a long-form referred-to count over + /// `MAX_REFERRED_TO_SEGMENTS` is refused before its retention bytes are read. #[test] fn test_referred_to_count_is_capped() { use crate::error::DecodeError; - // A long-form header claiming the 29-bit maximum of 536,870,911 - // referred-to segments would otherwise make `Vec::with_capacity` - // reserve ~2 GiB before a single referred-to number is read. - // The first byte is 0xFF: long form, count bits 0x1F; the count is - // 0x1FFFFFFF. - let data = [ - 0x00, 0x01, 0x00, 0x00, // Segment number = 65536 - 0x86, // Flags: type 6, page assoc 1 byte, deferred non-retain - 0xFF, 0xFF, 0xFF, 0xFF, // Long form, count = 536,870,911 - ]; + let header = |count: u32| { + let mut data = vec![ + 0x00, 0x01, 0x00, 0x00, // Segment number = 65536 + 0x86, // Flags: type 6, page assoc 1 byte, deferred non-retain + ]; + // Long form: bits 29-31 are 7, bits 0-28 the count. + data.extend_from_slice(&(0xE000_0000 | count).to_be_bytes()); + parse_segment_header(&mut Reader::new(&data)).unwrap_err() + }; - let mut reader = Reader::new(&data); - let error = parse_segment_header(&mut reader).unwrap_err(); + // The 29-bit maximum, 536,870,911, would reserve about 2 GiB. + for count in [0x1FFF_FFFF, MAX_REFERRED_TO_SEGMENTS + 1] { + assert!(matches!( + header(count), + DecodeError::Segment(SegmentError::InvalidReferredCount) + )); + } + // At the cap the header is read on and ends at its missing retention bytes. assert!(matches!( - error, - DecodeError::Segment(SegmentError::InvalidReferredCount) + header(MAX_REFERRED_TO_SEGMENTS), + DecodeError::Parse(ParseError::UnexpectedEof) )); } } diff --git a/vendor/hayro-syntax/src/content/mod.rs b/vendor/hayro-syntax/src/content/mod.rs index 5b19d50923..41185ee667 100644 --- a/vendor/hayro-syntax/src/content/mod.rs +++ b/vendor/hayro-syntax/src/content/mod.rs @@ -37,12 +37,11 @@ use crate::content::ops::TypedInstruction; use crate::object; use crate::object::dict::{Dict, InlineImageDict}; use crate::object::name::{Name, skip_name_like}; -use crate::object::{Array, Null, Number, Object, Stream}; +use crate::object::{Array, Number, Object, Stream}; use crate::reader::Reader; use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable}; use crate::trivia::{Comment, is_regular_character, is_white_space_character}; use crate::util::find_needle; -use core::array; use core::fmt::{Debug, Formatter}; use core::ops::Deref; use core::marker::PhantomData; @@ -51,8 +50,18 @@ use smallvec::SmallVec; // 6 operands are used for example for ctm or cubic curves, // but anything above should be pretty rare (only for example for // DeviceN color spaces, or invalid PDF files). So we settle on 10. +// PdfCraft patch (28): this is now only how many operands are held inline; see `MAX_OPERANDS`. const OPERANDS_THRESHOLD: usize = 10; +/// PdfCraft patch (28): the most operands one instruction keeps. The stack held ten, and the +/// eleventh operand of an instruction ended the whole content stream, so a DeviceN colour of +/// eleven or more inks (ISO 32000-2 §8.6.6.5 allows "an arbitrary number of colour +/// components") blanked the rest of the page (#4260). An `SCN`/`scn` for the largest DeviceN +/// space the interpreter reads (255 inks) takes 255 numbers and a pattern name. Past this, the +/// oldest operands are dropped: operators read the operands nearest to them (see `shift` in the +/// operator macros), so this is how stray operands below an instruction are already treated. +const MAX_OPERANDS: usize = 256; + impl Debug for Operator<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.0.as_str()) @@ -108,6 +117,15 @@ const MAX_EI_LOOKAHEAD_STEPS: u32 = 256; pub trait ContentTokenizer<'a> { /// Return the next instruction, or `None` after the content stream ends or becomes invalid. fn next_instruction<'b>(&'b mut self) -> Option>; + + /// PdfCraft patch: whether this tokenizer is only judging whether bytes read as content, as + /// the look-ahead past a candidate `EI` does. Such a pass must not recover from a malformed + /// token: its whole purpose is to find out whether the bytes are content, and answering + /// "yes, once the bad parts are skipped" of an inline image's data would cut the image at a + /// false `EI` (#3636 review). + fn judging_only(&self) -> bool { + false + } } /// An iterator over operators in the PDF content streams, providing raw access to the @@ -189,14 +207,28 @@ impl<'a> UntypedIter<'a> { if self.undecided() { return None; } - self.stack.push(object)?; + self.stack.push(object); } else if self.reader.read_without_context::>().is_some() { if self.undecided() { return None; } self.stack.clear(); + } else if self.undecided() { + return None; + } else if !self.lookahead && self.reader.peek_byte() == Some(b'/') && self.skip_bad_token() { + // PdfCraft patch: a name the lexer cannot read -- a malformed `#` escape, as + // in `/C#2 gs` -- used to end the stream, losing the rest of the page. Step + // over it and carry on, as the edit reader and other readers do (#3568). + // + // Only a name. An operand that is well formed but refused by a resource cap + // (a dictionary nested past the limit) still ends the stream, which is what + // `dictionaries_nested_without_keys_are_read_up_to_the_nesting_cap` in + // pdfcraft's renderer asserts: reading on there would draw a page whose + // content was deliberately not parsed. + warn!("skipped an unreadable name in content stream"); + self.stack.clear(); + continue; } else { - self.undecided(); return None; } } else { @@ -209,6 +241,13 @@ impl<'a> UntypedIter<'a> { warn!("failed to read operator in content stream"); + // PdfCraft patch: a stray delimiter (`)`, say) ended the stream here, so + // the rest of the page was lost. Step over it and carry on (#3568). + if !self.lookahead && self.skip_bad_token() { + self.stack.clear(); + continue; + } + self.reader.jump_to_end(); return None; } @@ -254,7 +293,7 @@ impl<'a> UntypedIter<'a> { UnfilteredEnd::Found(end_data, end_after_ei) => { let image_data = stream_data.get(..end_data)?; let stream = Stream::new(image_data, dict.clone()); - self.stack.push(Object::Stream(stream))?; + self.stack.push(Object::Stream(stream)); self.reader.read_bytes(end_after_ei)?; self.reader.skip_white_spaces(); accepted = true; @@ -416,7 +455,7 @@ impl<'a> UntypedIter<'a> { return None; } - self.stack.push(Object::Stream(stream))?; + self.stack.push(Object::Stream(stream)); self.reader.read_bytes(2)?; self.reader.skip_white_spaces(); @@ -436,6 +475,8 @@ impl<'a> UntypedIter<'a> { self.operator = Some(operator); self.committed = self.reader.offset(); + // PdfCraft patch (28): operands in reading order, if some were dropped. + self.stack.settle(); return Some(Instruction { operands: &self.stack, operator: self.operator.as_ref().unwrap(), @@ -473,6 +514,36 @@ impl<'a> UntypedIter<'a> { open_comment.unwrap_or(self.reader.offset()) } + /// PdfCraft patch: step over one token the lexer could not read, so the rest of the stream is + /// still read instead of the page ending there. A delimiter stands alone; anything else runs + /// to the next delimiter or space. At least one byte is always consumed when this returns + /// true, so the loop in `next` cannot spin (#3568). + fn skip_bad_token(&mut self) -> bool { + let before = self.reader.offset(); + match self.reader.peek_byte() { + None => return false, + // Never step over a good token: called where the blanks after the last one have not + // been skipped yet, there is nothing bad here to skip. Skipping ` BT` cost the page + // its second text object while this was being written. + Some(b) if is_white_space_character(b) || b == b'%' => {} + // A name reads to the next delimiter, malformed escapes included. + Some(b'/') => { + let _ = skip_name_like(&mut self.reader, true); + } + // A token of regular characters runs to the next delimiter or space. + Some(b) if is_regular_character(b) => { + self.reader.forward_while(is_regular_character); + } + // A delimiter stands alone. Consuming what follows it would eat the next operator: + // `)BT` cost the page its second text object while this was being written + // (#3636 review). + Some(_) => self.reader.forward(), + } + // Land on the next token, as the end of the loop in `next` does. + self.reader.skip_white_spaces_and_comments(); + self.reader.offset() > before + } + /// PdfCraft patch: whether the instruction being read ran into the end of a window, so it /// cannot be decided yet. Records that more data is needed. fn undecided(&mut self) -> bool { @@ -488,6 +559,10 @@ impl<'a> ContentTokenizer<'a> for UntypedIter<'a> { fn next_instruction<'b>(&'b mut self) -> Option> { self.next() } + + fn judging_only(&self) -> bool { + self.lookahead + } } @@ -546,6 +621,8 @@ where /// Return the next typed instruction. #[allow(clippy::should_implement_trait)] pub fn next(&mut self) -> Option> { + // Read before the instruction borrows the tokenizer. + let judging = self.untyped.judging_only(); let op = self.untyped.next_instruction()?; // TODO: Explore whether dispatching can be made more efficient. match TypedInstruction::dispatch(&op) { @@ -554,22 +631,22 @@ where // operator was used, let's abort completely, otherwise we might end up drawing random stuff. // However, for other operators it could be worth it to just skip it but keep attempting // to read other content operators. + // PdfCraft patch: a path operator whose operands do not fit it contributes nothing to + // the path, so skipping it leaves the path as it was -- the same state the abort + // below used to leave it in, except that the rest of the page is still read. Ending + // the stream here lost every later operator, and with it the rest of the page, its + // text and anything a redaction search would have matched (#3568). None => { - if [ - &b"m"[..], - &b"l"[..], - &b"c"[..], - &b"v"[..], - &b"y"[..], - &b"h"[..], - &b"re"[..], - ] - .contains(&op.operator.0.deref()) + // A pass that is only judging whether bytes read as content must still stop at a + // path operator it cannot dispatch: counting it as a step would let an inline + // image's data pass for a content stream and cut the image at a false `EI` + // (#3636 review). + if judging + && [&b"m"[..], &b"l"[..], &b"c"[..], &b"v"[..], &b"y"[..], &b"h"[..], &b"re"[..]].contains(&op.operator.0.deref()) { - None - } else { - Some(TypedInstruction::Fallback(op.operator)) + return None; } + Some(TypedInstruction::Fallback(op.operator)) } } } @@ -594,8 +671,13 @@ impl<'b, 'a> Instruction<'b, 'a> { pub struct Stack<'a> { // TODO: Explore using an object pool to avoid repeatedly // allocating/deallocating objects. - data: [Object<'a>; OPERANDS_THRESHOLD], - len: usize, + // PdfCraft patch (28): up to `MAX_OPERANDS` operands, the first `OPERANDS_THRESHOLD` inline. + data: SmallVec<[Object<'a>; OPERANDS_THRESHOLD]>, + /// PdfCraft patch (28): once `data` is full, the slot of its oldest operand, which the next + /// operand replaces. Always 0 while the stack is not full, and after `settle`. + oldest: usize, + /// PdfCraft patch (28): whether operands were dropped since the stack was last settled. + dropped: bool, } impl<'a> Default for Stack<'a> { @@ -608,31 +690,57 @@ impl<'a> Stack<'a> { /// Create a new, empty stack. pub fn new() -> Self { Self { - data: array::from_fn(|_| Object::Null(Null)), - len: 0, + data: SmallVec::new(), + oldest: 0, + dropped: false, } } - fn push(&mut self, operand: Object<'a>) -> Option<()> { - if self.len >= OPERANDS_THRESHOLD { - return None; + /// PdfCraft patch (28): push an operand, dropping the oldest once `MAX_OPERANDS` are held + /// (see `MAX_OPERANDS`). It cannot fail: it used to, and the failure ended the content stream. + /// + /// The operands kept are the newest, so the ones nearest the operator -- which are its own. + /// No operator takes anywhere near `MAX_OPERANDS` of them (`scn` takes one per colourant, and + /// ISO 32000 allows a DeviceN space 32), so an instruction preceded by stray operands is + /// applied to its own and the strays fall off the back. + fn push(&mut self, operand: Object<'a>) { + if self.data.len() < MAX_OPERANDS { + self.data.push(operand); + return; } - self.data[self.len] = operand; - self.len += 1; - Some(()) + self.dropped = true; + if let Some(slot) = self.data.get_mut(self.oldest) { + *slot = operand; + } + self.oldest = (self.oldest + 1) % MAX_OPERANDS; + } + + /// PdfCraft patch (28): put the operands back in the order they were read, oldest first, + /// after `push` dropped some. Called before the instruction is handed out. + fn settle(&mut self) { + if self.dropped { + warn!("more than {MAX_OPERANDS} operands before an operator; the oldest were dropped"); + // Cannot panic: operands are dropped only once `data` holds `MAX_OPERANDS`, and + // `oldest` stays below that. + self.data.rotate_left(self.oldest); + self.oldest = 0; + self.dropped = false; + } } fn clear(&mut self) { - self.len = 0; + self.data.clear(); + self.oldest = 0; + self.dropped = false; } fn len(&self) -> usize { - self.len + self.data.len() } fn as_slice(&self) -> &[Object<'a>] { - &self.data[..self.len] + &self.data } fn get<'b, T>(&'b self, index: usize) -> Option @@ -665,11 +773,12 @@ impl Debug for Stack<'_> { impl Clone for Stack<'_> { fn clone(&self) -> Self { - let mut stack = Self::new(); - for item in self.as_slice() { - stack.push(item.clone()).unwrap(); + // PdfCraft patch (28): a plain copy (pushing each operand again could no longer fail). + Self { + data: self.data.clone(), + oldest: self.oldest, + dropped: self.dropped, } - stack } } @@ -1070,12 +1179,12 @@ mod tests { assert_eq!(operators(data), [b"TJ".to_vec(), b"BI".to_vec(), b"q".to_vec(), b"Q".to_vec()]); } - /// PdfCraft patch: bytes above 0x7F after an `EI` candidate don't reject it. #[test] fn an_inline_image_ends_at_its_own_ei_when_later_text_holds_a_non_ascii_byte() { // `(Grüße)` in WinAnsi, then a word holding a capital "EI": both are everyday content, - // and the look-ahead used to read the non-ASCII bytes of the string as image data. - let data = b"BI /W 1 /H 1 /BPC 8 /CS /DeviceGray ID \x00 EI BT /F1 12 Tf (Gr\xFC\xDFe) Tj (EINGANG) Tj ET"; + // and the look-ahead used to read the non-ASCII bytes of the string as image data. The + // image is filtered, so its length isn't known up front and the look-ahead decides. + let data = b"BI /W 1 /H 1 /BPC 8 /CS /DeviceGray /F /AHx ID 00> EI BT /F1 12 Tf (Gr\xFC\xDFe) Tj (EINGANG) Tj ET"; assert_eq!( operators(data), @@ -1090,7 +1199,6 @@ mod tests { ); } - /// PdfCraft patch: `EI` followed by a delimiter ends the image. #[test] fn inline_image_ei_may_be_followed_by_a_delimiter() { let mut image = b"BI /W 16 /H 4 /BPC 8 /CS /G ID ".to_vec(); @@ -1130,7 +1238,6 @@ mod tests { } } - #[test] fn tokenizer_interface_preserves_every_byte_boundary() { let data = b"% comment\n1 -2.5 /Name /A#20B (a\\(b\\) \\101) <4869> [1 2] << /Key (value) >> [(a) 1] TJ BI /W 1 /H 1 /BPC 8 /CS /DeviceGray ID \x00 EI q Q"; diff --git a/vendor/hayro-syntax/src/content/ops.rs b/vendor/hayro-syntax/src/content/ops.rs index b066165841..bf582c36a8 100644 --- a/vendor/hayro-syntax/src/content/ops.rs +++ b/vendor/hayro-syntax/src/content/ops.rs @@ -152,6 +152,47 @@ f assert!(iter.next().is_none()); } + /// PdfCraft patch (28): a twelve-ink DeviceN colour's `scn` keeps all twelve operands, and + /// the instructions after it are still read (#4260). The eleventh operand ended the stream. + #[test] + fn scn_with_twelve_components_keeps_them_all() { + let input = b"1 2 3 4 5 6 7 8 9 10 11 12 scn 0 0 10 10 re f"; + let mut iter = TypedIter::new(input); + + match iter.next() { + Some(TypedInstruction::NonStrokeColorNamed(NonStrokeColorNamed(nums, None))) => { + let expected = (1..=12).map(Number::from_i32).collect::>(); + assert_eq!(nums.as_slice(), expected.as_slice()); + } + other => panic!("unexpected instruction: {other:?}"), + } + assert!(matches!(iter.next(), Some(TypedInstruction::RectPath(_)))); + assert!(matches!(iter.next(), Some(TypedInstruction::FillPathNonZero(_)))); + assert!(iter.next().is_none()); + } + + /// PdfCraft patch (28): past the operand cap the oldest operands are dropped, in order, and + /// the operator reads the ones nearest to it. + #[test] + fn operands_past_the_cap_keep_the_latest_in_order() { + let mut input = String::new(); + for i in 0..600 { + input.push_str(&format!("{i} ")); + } + input.push_str("scn 0 1 0 rg"); + let mut iter = TypedIter::new(input.as_bytes()); + + match iter.next() { + Some(TypedInstruction::NonStrokeColorNamed(NonStrokeColorNamed(nums, None))) => { + let expected = (344..600).map(Number::from_i32).collect::>(); + assert_eq!(nums.as_slice(), expected.as_slice()); + } + other => panic!("unexpected instruction: {other:?}"), + } + assert!(matches!(iter.next(), Some(TypedInstruction::NonStrokeColorDeviceRgb(_)))); + assert!(iter.next().is_none()); + } + #[test] fn scn() { let input = b" diff --git a/vendor/hayro-syntax/src/crypto/mod.rs b/vendor/hayro-syntax/src/crypto/mod.rs index 8e8bfb13bd..759d1b146b 100644 --- a/vendor/hayro-syntax/src/crypto/mod.rs +++ b/vendor/hayro-syntax/src/crypto/mod.rs @@ -74,9 +74,11 @@ pub(crate) enum Decryptor { } #[derive(Debug, Copy, Clone)] -pub(crate) enum DecryptionTarget { +pub(crate) enum DecryptionTarget<'a> { String, Stream, + /// PdfCraft patch (30): a stream that names its own crypt filter. + NamedStream(&'a str), } impl Decryptor { @@ -84,7 +86,7 @@ impl Decryptor { &self, id: ObjectIdentifier, data: &[u8], - target: DecryptionTarget, + target: DecryptionTarget<'_>, ) -> Option> { match self { Self::None => Some(data.to_vec()), @@ -93,6 +95,8 @@ impl Decryptor { let crypt_dict = match target { DecryptionTarget::String => dict.string_filter, DecryptionTarget::Stream => dict.stream_filter, + // `/Identity` isn't in the table, and a name it hasn't got reads as that. + DecryptionTarget::NamedStream(name) => dict.named.get(name).copied().unwrap_or(CryptDictionary::identity(0)), }; match crypt_dict.cfm { @@ -110,6 +114,52 @@ pub(crate) fn get( dict: &Dict<'_>, id: &[u8], password: &[u8], +) -> Result { + match decryptor(dict, id, password) { + // PdfCraft patch (37): a document that encrypts only its embedded files, authorised when + // one is opened (`/AuthEvent /EFOpen`, ISO 32000-2 §7.6.6, Table 25), opens without a + // password: its strings and streams are in the clear, and nothing drawn reads an embedded + // file. + Err(DecryptionError::PasswordProtected) if password.is_empty() && efopen_only(dict) => { + Ok(Decryptor::None) + } + other => other, + } +} + +/// PdfCraft patch (37): whether `dict` has crypt filters (V4 or later) that encrypt, each +/// authorised only when an embedded file is opened (`/AuthEvent /EFOpen`), and neither `/StmF` nor +/// `/StrF` names one. The embedded files use them through `/EFF` or a `/Crypt` filter of their +/// own; earlier handlers (V1, V2) encrypt everything with RC4. +fn efopen_only(dict: &Dict<'_>) -> bool { + if dict.get::(V).is_none_or(|v| v < 4) { + return false; + } + let Some(cf) = dict.get::>(CF) else { + return false; + }; + let mut encrypting = Vec::new(); + for key in cf.keys() { + let Some(filter) = cf.get::>(key.as_ref()) else { + continue; + }; + let method = filter.get::>(CFM).and_then(|n| DecryptorTag::from_name(&n)); + if matches!(method, None | Some(DecryptorTag::None)) { + continue; + } + if filter.get::>(b"AuthEvent").is_none_or(|e| e.as_str() != "EFOpen") { + return false; + } + encrypting.push(key.as_str().to_string()); + } + let names = |key: &[u8]| dict.get::>(key).is_some_and(|n| encrypting.iter().any(|e| e == n.as_str())); + !encrypting.is_empty() && !names(STM_F) && !names(STR_F) +} + +fn decryptor( + dict: &Dict<'_>, + id: &[u8], + password: &[u8], ) -> Result { let filter = dict.get::>(FILTER).ok_or(InvalidEncryption)?; @@ -294,10 +344,12 @@ fn decrypt_rc_aes( with_key(final_key) } -#[derive(Debug, Copy, Clone)] +#[derive(Debug, Clone)] pub(crate) struct DecryptorData { stream_filter: CryptDictionary, string_filter: CryptDictionary, + /// PdfCraft patch (30): `/CF`, for the streams that name a filter of their own. + named: HashMap, } impl DecryptorData { @@ -314,16 +366,23 @@ impl DecryptorData { } } - let stm_f = *mappings - .get(dict.get::>(STM_F)?.as_str()) - .unwrap_or(&CryptDictionary::identity(default_length)); - let str_f = *mappings - .get(dict.get::>(STR_F)?.as_str()) - .unwrap_or(&CryptDictionary::identity(default_length)); + // PdfCraft patch (30): `/Identity` is never an entry of `/CF`, whatever a file puts there, + // and `/StmF` and `/StrF` are optional, naming it by default (ISO 32000-2 Table 20). + mappings.remove("Identity"); + let identity = CryptDictionary::identity(default_length); + let stm_f = dict + .get::>(STM_F) + .and_then(|n| mappings.get(n.as_str()).copied()) + .unwrap_or(identity); + let str_f = dict + .get::>(STR_F) + .and_then(|n| mappings.get(n.as_str()).copied()) + .unwrap_or(identity); Some(Self { stream_filter: stm_f, string_filter: str_f, + named: mappings, }) } } diff --git a/vendor/hayro-syntax/src/data.rs b/vendor/hayro-syntax/src/data.rs index 7d47c4d306..95a0be9c46 100644 --- a/vendor/hayro-syntax/src/data.rs +++ b/vendor/hayro-syntax/src/data.rs @@ -1,5 +1,4 @@ use crate::object::ObjectIdentifier; -use crate::object::Stream; use crate::reader::ReaderContext; use crate::sync::HashMap; use crate::sync::{Arc, Mutex, MutexExt}; @@ -111,6 +110,11 @@ impl Data { Some(self.object_offsets.get().entry(id).or_insert(parsed).clone()) } + /// PdfCraft patch: (hayro-syntax (33)) enter the gate for what an object stream's index depends + /// on, once its data is read and [`Self::get_with`] has let go of it. + pub(crate) fn enter_loading(&self, id: ObjectIdentifier) -> Option> { + self.loading.enter(id) + } /// Get access to the data of a decoded object stream. pub(crate) fn get_with(&self, id: ObjectIdentifier, ctx: &ReaderContext<'_>) -> Option<&[u8]> { // PdfCraft patch: (#307, see vendor/README.md hayro-syntax (10)) register exactly once: @@ -129,7 +133,8 @@ impl Data { let _loading = self.loading.enter(id)?; self.decoded .get_or_init(idx, || { - let stream = ctx.xref().get_with::>(id, ctx)?; + // PdfCraft patch: (hayro-syntax (33)) only ever an object stream. + let stream = ctx.xref().object_stream(id, ctx)?; stream.decoded().ok().map(Cow::into_owned) })? .as_deref() @@ -263,7 +268,7 @@ mod tests { } } -struct LoadGuard<'a>(&'a LoadGate); +pub(crate) struct LoadGuard<'a>(&'a LoadGate); impl Drop for LoadGuard<'_> { fn drop(&mut self) { diff --git a/vendor/hayro-syntax/src/filter/cancellation_tests.rs b/vendor/hayro-syntax/src/filter/cancellation_tests.rs index d072df34cc..80b6c97b8f 100644 --- a/vendor/hayro-syntax/src/filter/cancellation_tests.rs +++ b/vendor/hayro-syntax/src/filter/cancellation_tests.rs @@ -59,9 +59,9 @@ fn flate_stops_inside_stream_decoding() { } let length = 40 * 65535; input.extend_from_slice(&(((length % 65521) as u32) << 16 | 1).to_be_bytes()); - assert_eq!(lzw_flate::flate::decode(&input, &Dict::empty(), usize::MAX).map(|v| v.len()), Some(length)); + assert_eq!(lzw_flate::flate::decode(&input, &Dict::empty(), usize::MAX, None).map(|v| v.len()), Some(length)); let (control, polls) = crate::cancel::stop_at(3); - assert!(lzw_flate::flate::decode_controlled(&input, &Dict::empty(), usize::MAX, Some(&control)).is_none()); + assert!(lzw_flate::flate::decode_controlled(&input, &Dict::empty(), usize::MAX, Some(&control), None).is_none()); assert_eq!(polls.load(Ordering::Relaxed), 3); } diff --git a/vendor/hayro-syntax/src/filter/ccitt.rs b/vendor/hayro-syntax/src/filter/ccitt.rs index a7921a5de1..29a3da40e6 100644 --- a/vendor/hayro-syntax/src/filter/ccitt.rs +++ b/vendor/hayro-syntax/src/filter/ccitt.rs @@ -22,10 +22,14 @@ pub(crate) fn decode( // PdfCraft patch (19): fewer `/Rows` than the image's `/Height` doesn't cut the image short: a // plotter driver wrote `/Rows` equal to `/Columns`, and the rows after it were drawn black // (#3308). The decoder still stops where the data ends. - let rows = params - .get::(ROWS) - .filter(|&rows| rows != 0) - .map_or(image_params.height, |rows| rows.max(image_params.height)); + // PdfCraft patch (41): more `/Rows` than the image's `/Height` doesn't make the decoder go + // past it either: the image is `/Height` rows (ISO 32000-2 Table 87), and a `/Rows` of + // 1,084,975,104 on 2,592 columns had the size check refuse every page of a scan (PDFBOX-771). + // `/Rows` counts only for a stream decoded without an image's height. + let rows = match image_params.height { + 0 => params.get::(ROWS).unwrap_or(0), + height => height, + }; let end_of_block = params.get::(END_OF_BLOCK).unwrap_or(true); // A `/Columns` past `u32::MAX` is refused: truncated, it would wrap to a small width that // passes `ccitt_size_ok` and decode the image at the wrong width. diff --git a/vendor/hayro-syntax/src/filter/jbig2.rs b/vendor/hayro-syntax/src/filter/jbig2.rs index 54751c2fcc..3508314afb 100644 --- a/vendor/hayro-syntax/src/filter/jbig2.rs +++ b/vendor/hayro-syntax/src/filter/jbig2.rs @@ -6,14 +6,138 @@ use crate::object::dict::keys::JBIG2_GLOBALS; use crate::object::stream::{FilterResult, ImageColorSpace, ImageData, ImageDecodeParams}; use alloc::borrow::Cow; use alloc::vec::Vec; + +const MAX_PIXELS: u64 = 1 << 28; use core::iter; -/// PdfCraft patch: most pixels an embedded JBIG2 page may decode to, matching the renderer's -/// `MAX_IMAGE_PIXELS` and `hayro_jbig2`'s region limit. The page header's own dimensions are -/// checked here, before any output is allocated: the image dictionary's smaller ones say nothing -/// about them. -const MAX_PIXELS: u64 = 1 << 28; +/// PdfCraft patch (31): the steps of decoding a page's JBIG2 images may take between them, as many +/// as one may. Each has its own limit, which doesn't bound a page of many made to reach it. That +/// is about 6 s to 17 s, inside a render's watchdog; an image of the largest size costs a quarter of +/// it to decode and a quarter for its page, and ordinary ones are far below that. +pub const MAX_PAGE_JBIG2_WORK: u64 = 1 << 30; +#[cfg(feature = "std")] +std::thread_local! { + // Unbounded until a page says otherwise: what isn't drawing a page has no page to run out on. + static PAGE_WORK_LEFT: core::cell::Cell = const { core::cell::Cell::new(u64::MAX) }; + // PdfCraft patch (31): what refused the image decoded last on this thread, if one of the + // decoder's limits did: `STREAM_LIMIT` or `WORK_LIMIT`, 0 otherwise. + static LIMITED: core::cell::Cell = const { core::cell::Cell::new(0) }; +} + +/// PdfCraft patch (31): a limit the stream reaches by itself, whatever ran before it (a bitmap's +/// size, a dictionary's symbols, the bitmaps retained and the like), so decoding it again is +/// refused again. +#[cfg(feature = "std")] +const STREAM_LIMIT: u8 = 1; +/// PdfCraft patch (31): the decoding work, which may be what the page or run had left. +#[cfg(feature = "std")] +const WORK_LIMIT: u8 = 2; + +/// PdfCraft patch (31): whether the JBIG2 image decoded last on this thread was refused by one of +/// the decoder's limits rather than failing on its data. A soft mask a limit refused hides what +/// its image would show without it: hayro-interpret leaves such an image out, where a mask the +/// file damaged leaves its image whole (#6722). A size or count the file damaged can read as past +/// a limit, and is taken for one: it can't be told from a hostile one, and leaving the image out +/// is the safe side. +#[cfg(feature = "std")] +pub fn jbig2_limited() -> bool { + LIMITED.with(core::cell::Cell::get) != 0 +} + +#[cfg(not(feature = "std"))] +pub fn jbig2_limited() -> bool { + false +} + +/// PdfCraft patch (31): whether the refusal [`jbig2_limited`] reports came from a limit the stream +/// reaches by itself, not from the decoding work, so the same stream is refused again whenever it +/// is decoded. +#[cfg(feature = "std")] +pub fn jbig2_limited_by_stream() -> bool { + LIMITED.with(core::cell::Cell::get) == STREAM_LIMIT +} + +#[cfg(not(feature = "std"))] +pub fn jbig2_limited_by_stream() -> bool { + false +} + +/// PdfCraft patch (31): forget what refused the image decoded last, before decoding another +/// through filters that may fail before JBIG2 is reached. +#[cfg(feature = "std")] +pub fn clear_jbig2_limited() { + LIMITED.with(|limited| limited.set(0)); +} + +#[cfg(not(feature = "std"))] +pub fn clear_jbig2_limited() {} + +#[cfg(feature = "std")] +fn note_limited(error: Option<&hayro_jbig2::DecodeError>) { + let refused = match error { + Some(hayro_jbig2::DecodeError::Overflow(hayro_jbig2::OverflowError::DecodingWork)) => { + WORK_LIMIT + } + Some(e) if e.is_limit() => STREAM_LIMIT, + _ => 0, + }; + LIMITED.with(|limited| limited.set(refused)); +} + +#[cfg(not(feature = "std"))] +fn note_limited(_: Option<&hayro_jbig2::DecodeError>) {} + +/// PdfCraft patch (31): what the JBIG2 images decoded next on this thread may take, for a new page. +#[cfg(feature = "std")] +pub fn set_page_jbig2_work(work: u64) { + PAGE_WORK_LEFT.with(|left| left.set(work)); + clear_jbig2_limited(); +} + +/// Pays for reading `bytes` of a stream and its globals out of what the page has left, or `None`. +/// An image that doesn't decode isn't always kept (not past the page's allowance, nor drawn under a +/// transfer function: hayro-interpret patch 91), so a page drawing it again and again can read it +/// again. +#[cfg(feature = "std")] +fn charge_page_reading(bytes: usize) -> Option<()> { + let mut left = PAGE_WORK_LEFT.with(core::cell::Cell::get); + let charged = hayro_jbig2::charge_reading(&mut left, bytes); + PAGE_WORK_LEFT.with(|cell| cell.set(left)); + charged.ok() +} + +#[cfg(not(feature = "std"))] +fn charge_page_reading(_: usize) -> Option<()> { + Some(()) +} + +/// `image` decoded through `decoder`, spending what the page has left, if there is anything. +#[cfg(feature = "std")] +fn decode_for_page(image: &hayro_jbig2::Image<'_>, decoder: &mut D) -> Option<()> { + let mut left = PAGE_WORK_LEFT.with(core::cell::Cell::get); + let decoded = image.decode_within(decoder, &mut left); + PAGE_WORK_LEFT.with(|cell| cell.set(left)); + note_limited(decoded.as_ref().err()); + decoded.ok() +} + +#[cfg(not(feature = "std"))] +fn decode_for_page(image: &hayro_jbig2::Image<'_>, decoder: &mut D) -> Option<()> { + image.decode(decoder).ok() +} + +/// PdfCraft patch (31): whether the page has nothing left for another image, which then isn't read +/// at all. +#[cfg(feature = "std")] +pub fn page_jbig2_work_spent() -> bool { + PAGE_WORK_LEFT.with(core::cell::Cell::get) == 0 +} + +#[cfg(not(feature = "std"))] +pub fn page_jbig2_work_spent() -> bool { + false +} /// Decode JBIG2 data from a PDF stream. /// /// The `params` dictionary may contain a `JBIG2Globals` entry pointing to @@ -27,6 +151,10 @@ pub(crate) fn decode( image_params: &ImageDecodeParams, limit: usize, ) -> Option> { + if page_jbig2_work_spent() { + return None; + } + // PdfCraft patch: globals are plain segment data. A globals stream filtered as an image // could name further globals of its own, recursing once per stream in the chain. let globals = params @@ -41,7 +169,11 @@ pub(crate) fn decode( }) .and_then(|g| g.decoded().ok()); - let image = hayro_jbig2::Image::new_embedded(data, globals.as_deref()).ok()?; + charge_page_reading(data.len().saturating_add(globals.as_deref().map_or(0, <[u8]>::len)))?; + + let image = hayro_jbig2::Image::new_embedded(data, globals.as_deref()) + .inspect_err(|e| note_limited(Some(e))) + .ok()?; if u64::from(image.width()) * u64::from(image.height()) > MAX_PIXELS { warn!("embedded JBIG2 page is too large"); @@ -103,7 +235,7 @@ pub(crate) fn decode( let writer = BitWriter::new(&mut packed, 1)?; let mut decoder = BitWriterDecoder { writer }; - image.decode(&mut decoder).ok()?; + decode_for_page(&image, &mut decoder)?; (packed, 1) } else { @@ -130,7 +262,7 @@ pub(crate) fn decode( .try_reserve_exact((image.width() as usize).checked_mul(image.height() as usize)?) .ok()?; let mut decoder = Luma8Decoder { output }; - image.decode(&mut decoder).ok()?; + decode_for_page(&image, &mut decoder)?; (decoder.output, 8) }; diff --git a/vendor/hayro-syntax/src/filter/jpx.rs b/vendor/hayro-syntax/src/filter/jpx.rs index b2092eb35a..2b24622426 100644 --- a/vendor/hayro-syntax/src/filter/jpx.rs +++ b/vendor/hayro-syntax/src/filter/jpx.rs @@ -16,15 +16,35 @@ impl ImageColorSpace { } } -/// PdfCraft patch: the most pixels a JPEG 2000 image may decode to, as for JBIG2. +/// PdfCraft patch (47): the most pixels a codestream may decode to (2^28, the renderer's +/// `MAX_IMAGE_PIXELS` and hayro-interpret's `image_size_ok`). Its size comes from the SIZ marker, +/// not the image dictionary, and the decoder allocates it infallibly: a tiny file could ask for +/// tens of gigabytes and abort the process (#5078). +/// +/// It is checked against `Image::width()` x `height()` at full resolution: the SIZ image area, +/// divided by a component subsampling (`XRsiz`, `YRsiz`) that every component shares, the size the +/// decoder allocates each channel and component tile at. Components sampled differently leave the +/// area undivided. So a 2x2-subsampled 32768 x 32768 area decodes to, and counts as, 2^28. const MAX_PIXELS: u64 = 1 << 28; /// PdfCraft patch: the least output `limit` a JPEG 2000 image is held to: the limit comes from the /// image dictionary's size, which a decoder may round differently from the codestream's. const MIN_LIMIT: usize = 64 << 20; -/// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`). +/// Decode a JPEG 2000 image (JP2 file or raw codestream) for an image XObject described by +/// `params`, refusing codestreams over [`MAX_PIXELS`] or `limit` bytes; `None` when it can't be decoded. pub(crate) fn decode(data: &[u8], params: &ImageDecodeParams, limit: usize) -> Option> { + decode_with_pixel_limit(data, params, limit, MAX_PIXELS) +} + +/// [`decode`] with `max_pixels` in place of [`MAX_PIXELS`], so a test can exercise the +/// full-resolution size check on a small image without an attacker-sized allocation. +fn decode_with_pixel_limit( + data: &[u8], + params: &ImageDecodeParams, + limit: usize, + max_pixels: u64, +) -> Option> { use crate::object::stream::ImageColorSpace; let settings = DecodeSettings { @@ -36,21 +56,42 @@ pub(crate) fn decode(data: &[u8], params: &ImageDecodeParams, limit: usize) -> O // indices would be drawn as gray). resolve_palette_indices: params.num_components.is_none(), strict: false, - target_resolution: params.target_dimension, + // PdfCraft patch (review on #3884): `hayro-jpeg2000` 0.3.5 places a reduced resolution's + // samples using the image area's offset on the reference grid unscaled, so with an offset + // it leaves rows out or slices past a row (a panic); such an image is decoded at full size. + target_resolution: params + .target_dimension + .filter(|_| image_area_offset(data) == Some((0, 0))), }; // PdfCraft patch (21): a JP2 colour specification naming an enumerated colour space the // decoder refuses (CIEJab, enum 19, in a veraPDF fixture; YCbCr, PhotoYCC, …) made the whole // image fail, so the page drew blank (#3306). Then it is decoded as if it had no colour // specification, as MuPDF and Poppler draw it: grey, RGB or CMYK by its component count. + // + // PdfCraft patch (47): the header is read at full resolution first, because + // `target_resolution` shrinks `width()` and `height()` but each tile's coefficients are still + // allocated at full size (review on #5086); see `MAX_PIXELS`. + let full_resolution = DecodeSettings { + target_resolution: None, + ..settings + }; let repaired; - let image = match hayro_jpeg2000::Image::new(data, &settings) { - Ok(image) => image, + let (source, full) = match hayro_jpeg2000::Image::new(data, &full_resolution) { + Ok(image) => (data, image), Err(_) => { repaired = without_refused_enumerated_colour(data)?; - hayro_jpeg2000::Image::new(&repaired, &settings).ok()? + let image = hayro_jpeg2000::Image::new(&repaired, &full_resolution).ok()?; + (repaired.as_slice(), image) } }; + if u64::from(full.width()) * u64::from(full.height()) > max_pixels { + return None; + } + let image = match settings.target_resolution { + Some(_) => hayro_jpeg2000::Image::new(source, &settings).ok()?, + None => full, + }; let width = image.width(); let height = image.height(); @@ -84,7 +125,7 @@ pub(crate) fn decode(data: &[u8], params: &ImageDecodeParams, limit: usize) -> O // PdfCraft patch: the decoder sizes its output from the codestream's own dimensions, not the // image dictionary's, and allocates it infallibly. Refuse more than `MAX_PIXELS` pixels or // more than `limit` bytes before decoding, and reserve the buffer fallibly. - if u64::from(width) * u64::from(height) > MAX_PIXELS { + if u64::from(width) * u64::from(height) > max_pixels { return None; } let channels = usize::from(cs.num_components()) + usize::from(has_alpha); @@ -158,6 +199,21 @@ fn has_palette(data: &[u8]) -> bool { .is_some_and(|header| boxes(header).any(|(kind, _, _)| kind == *b"pclr")) } +/// PdfCraft patch (review on #3884): the offset of the image area on the reference grid +/// (`XOsiz`, `YOsiz`) in the SIZ marker segment (ISO 15444-1 A.5.1) of raw codestream or JP2 file +/// `data`, whose codestream is the contents of its `jp2c` box (I.5.4). `None` when it can't be read. +fn image_area_offset(data: &[u8]) -> Option<(u32, u32)> { + const SOC_SIZ: [u8; 4] = [0xff, 0x4f, 0xff, 0x51]; + let codestream = if data.starts_with(&SOC_SIZ) { + data + } else { + let (_, start, end) = boxes(data).find(|&(kind, _, _)| kind == *b"jp2c")?; + data.get(start..end).filter(|c| c.starts_with(&SOC_SIZ))? + }; + // After SOC and SIZ: Lsiz (2), Rsiz (2), Xsiz (4), Ysiz (4), XOsiz (4), YOsiz (4). + let read = |at: usize| Some(u32::from_be_bytes(codestream.get(at..at + 4)?.try_into().ok()?)); + Some((read(16)?, read(20)?)) +} /// The enumerated colour spaces (`EnumCS`, ISO 15444-1 I.5.3.3 and 15444-2 M.11.7.2) the decoder /// handles: CMYK, CIELab, sRGB, greyscale, sYCC, e-sRGB and ROMM-RGB. const DECODED_ENUMERATED: [u32; 7] = [12, 14, 16, 17, 18, 20, 21]; @@ -283,7 +339,7 @@ fn scale( #[cfg(test)] mod tests { - use super::{decode, scale, without_refused_enumerated_colour}; + use super::{decode, decode_with_pixel_limit, image_area_offset, scale, without_refused_enumerated_colour}; use crate::bit_reader::{BitReader, bit_mask}; use crate::object::stream::{ImageColorSpace, ImageDecodeParams}; use alloc::vec::Vec; @@ -445,8 +501,8 @@ mod tests { 0xff, 0xd9, ]; - /// PdfCraft #3179: with no `/ColorSpace` in the image dictionary, the JP2 palette gives the - /// colors. Raw indices (0 and 1) would come back as a gray image, drawn as noise. + /// #3179: with no `/ColorSpace` in the image dictionary, the JP2 palette gives the colours. The + /// raw indices (0 and 1) used to come back as a gray image, drawn as noise. #[test] fn jpx_palette_is_applied_without_a_color_space() { let params = ImageDecodeParams { @@ -463,7 +519,7 @@ mod tests { assert_eq!(&*result.data, &expected[..]); } - /// With an `/Indexed` color space in the dictionary, the PDF supplies the palette, so the raw + /// With an `/Indexed` colour space in the dictionary, the PDF supplies the palette, so the raw /// indices are what the image holds. #[test] fn jpx_palette_indices_stay_raw_for_an_indexed_color_space() { @@ -506,41 +562,152 @@ mod tests { out } - /// PdfCraft #3184: resolved palette colors are 8-bit samples whatever the indices' precision; - /// an image without a palette keeps its own (1 bit here). + /// Review on #3184: resolved palette colours are 8-bit samples whatever the indices' + /// precision; an image without a palette keeps its own (1 bit here). #[test] fn palette_colours_are_eight_bit_and_other_samples_keep_their_precision() { - let params = ImageDecodeParams { - width: 1, - height: 1, - ..ImageDecodeParams::default() - }; - let bpc = |data: &[u8]| { - decode(data, ¶ms, usize::MAX) - .and_then(|r| r.image_data) - .map(|d| d.bits_per_component) - }; + let params = ImageDecodeParams { width: 1, height: 1, ..ImageDecodeParams::default() }; + let bpc = |data: &[u8]| decode(data, ¶ms, usize::MAX).and_then(|r| r.image_data).map(|d| d.bits_per_component); let mut palette = Vec::new(); - for (kind, body) in [ - ( - &b"pclr"[..], - &[0, 2, 3, 7, 7, 7, 255, 0, 0, 64, 128, 192][..], - ), - (b"cmap", &[0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 2]), - ] { + for (kind, body) in [(&b"pclr"[..], &[0, 2, 3, 7, 7, 7, 255, 0, 0, 64, 128, 192][..]), (b"cmap", &[0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 2])] { palette.extend_from_slice(&((8 + body.len()) as u32).to_be_bytes()); palette.extend_from_slice(kind); palette.extend_from_slice(body); } assert_eq!(bpc(&one_bit_jp2(&palette)), Some(8)); assert_eq!(bpc(&one_bit_jp2(&[])), Some(1)); - let one_bit = ImageDecodeParams { - bpc: Some(1), - ..params.clone() + } + + /// A 4x4, one-component, 8-bit codestream whose image area starts at reference-grid point + /// (`x`, `y`): one tile from the grid origin, one decomposition level, reversible wavelet, + /// and an empty packet per resolution, so every sample is 128. + fn one_level_codestream(x: u32, y: u32) -> Vec { + let mut out = alloc::vec![0xff, 0x4f, 0xff, 0x51, 0, 41, 0, 0]; // SOC, SIZ, Lsiz, Rsiz. + for value in [x + 4, y + 4, x, y, x + 4, y + 4, 0, 0] { + out.extend_from_slice(&value.to_be_bytes()); + } + out.extend_from_slice(&[0, 1, 7, 1, 1]); // One component: eight bits, no subsampling. + // COD: LRCP, one layer, no component transform, one decomposition level, 64x64 + // codeblocks, reversible wavelet. QCD: no quantization, four subbands. + out.extend_from_slice(&[0xff, 0x52, 0, 12, 0, 0, 0, 1, 0, 1, 4, 4, 0, 1]); + out.extend_from_slice(&[0xff, 0x5c, 0, 7, 0x40, 0x40, 0x48, 0x48, 0x50]); + // SOT for tile zero, one tile part of 16 bytes, SOD, two empty packets, EOC. + out.extend_from_slice(&[0xff, 0x90, 0, 10, 0, 0, 0, 0, 0, 16, 0, 1, 0xff, 0x93, 0, 0]); + out.extend_from_slice(&[0xff, 0xd9]); + out + } + + #[test] + fn image_area_offset_reads_raw_codestreams_and_jp2_files() { + assert_eq!(image_area_offset(&one_level_codestream(7, 3)), Some((7, 3))); + assert_eq!(image_area_offset(PALETTE_JP2), Some((0, 0))); + let raw = one_level_codestream(7, 3); + for cut in [0, 4, 19, 23] { + assert_eq!(image_area_offset(raw.get(..cut).unwrap()), None, "cut at {cut}"); + } + assert_eq!(image_area_offset(&jp2(1, &[])), None, "a jp2c box too short for SIZ"); + } + + /// Review on #3884: `hayro-jpeg2000` 0.3.5 compares an image area's reference-grid offset + /// (`XOsiz`, `YOsiz`), unscaled, with the coordinates of a reduced resolution, so a hint that + /// skips a level left rows out (offset 7, 7: no reduced row was copied at all) or sliced past + /// the reduced row (offset 7, 0: a panic). With an offset the image is decoded at full size; + /// without one the hint still picks the reduced level. + #[test] + fn jpx_size_hint_is_dropped_only_for_an_offset_image_area() { + for (x, y, expected) in [(7, 0, 4), (0, 7, 4), (7, 7, 4), (0, 0, 2)] { + let params = ImageDecodeParams { + target_dimension: Some((2, 2)), + ..ImageDecodeParams::default() + }; + let result = decode(&one_level_codestream(x, y), ¶ms, usize::MAX).unwrap(); + let image = result.image_data.unwrap(); + assert_eq!((image.width, image.height), (expected, expected), "offset ({x}, {y})"); + assert_eq!(result.data.as_ref(), alloc::vec![128; (expected * expected) as usize], "offset ({x}, {y})"); + } + } + + /// `one_bit_jp2`'s file with the SIZ image and tile sizes set to `xsiz` x `ysiz` (one tile + /// covering the whole image, so the header still parses cheaply), a matching `ihdr`, and + /// `levels` wavelet decomposition levels in COD. With none, a target resolution can't shrink + /// the image (there is no lower resolution to decode); with some, a small target decodes it + /// up to 2^`levels` times smaller on each side. + fn jp2_with_size(xsiz: u32, ysiz: u32, levels: u8) -> Vec { + let jp2_box = |kind: &[u8], body: &[u8]| { + let mut b = ((8 + body.len()) as u32).to_be_bytes().to_vec(); + b.extend_from_slice(kind); + b.extend_from_slice(body); + b }; - let palette_bpc = decode(&one_bit_jp2(&palette), &one_bit, usize::MAX) - .and_then(|r| r.image_data) - .map(|d| d.bits_per_component); - assert_eq!(palette_bpc, Some(8), "/BitsPerComponent 1 with a palette"); + let mut codestream = alloc::vec![0xff, 0x4f, 0xff, 0x51, 0, 41, 0, 0]; + // Xsiz, Ysiz, XOsiz, YOsiz, XTsiz, YTsiz, XTOsiz, YTOsiz: one tile spans the whole image. + for value in [xsiz, ysiz, 0, 0, xsiz, ysiz, 0, 0] { + codestream.extend_from_slice(&value.to_be_bytes()); + } + codestream.extend_from_slice(&[0, 1, 0, 1, 1]); + // COD: Scod, LRCP order, one layer, no MCT, `levels`, 64 x 64 code blocks, 5/3 wavelet. + codestream.extend_from_slice(&[0xff, 0x52, 0, 12, 0, 0, 0, 1, 0, levels, 4, 4, 0, 1]); + // QCD: no quantization, one exponent per subband (3 per level and the lowest band). + let subbands = 3 * usize::from(levels) + 1; + codestream.extend_from_slice(&[0xff, 0x5c, 0, (3 + subbands) as u8, 0x40]); + codestream.extend(core::iter::repeat_n(0x40, subbands)); + // One tile part holding an empty packet (one zero byte) per resolution level. + let packets = usize::from(levels) + 1; + codestream.extend_from_slice(&[0xff, 0x90, 0, 10, 0, 0]); + codestream.extend_from_slice(&((14 + packets) as u32).to_be_bytes()); + codestream.extend_from_slice(&[0, 1, 0xff, 0x93]); + codestream.extend(core::iter::repeat_n(0, packets)); + codestream.extend_from_slice(&[0xff, 0xd9]); + let mut ihdr = ysiz.to_be_bytes().to_vec(); + ihdr.extend_from_slice(&xsiz.to_be_bytes()); + ihdr.extend_from_slice(&[0, 1, 0, 7, 0, 0]); + let mut header = jp2_box(b"ihdr", &ihdr); + header.extend(jp2_box(b"colr", &[1, 0, 0, 0, 0, 0, 16])); + let mut out = alloc::vec![0, 0, 0, 12, b'j', b'P', b' ', b' ', 0x0d, 0x0a, 0x87, 0x0a]; + out.extend(jp2_box(b"ftyp", b"jp2 \0\0\0\0jp2 ")); + out.extend(jp2_box(b"jp2h", &header)); + out.extend(jp2_box(b"jp2c", &codestream)); + out + } + + /// #5078: a `/Width 1 /Height 1` image whose codestream SIZ declares more than 2^28 pixels + /// is refused before the decoder makes its full-resolution, infallible allocation (tens of + /// gigabytes from a tiny file, which aborts the process), with or without a small target + /// resolution, since a target shrinks the reported size but not the per-tile buffers: with + /// four decomposition levels a 1 x 1 target reports 4096 x 4096, under the cap. The same + /// builder at 1 x 1 decodes, so the `None` at 65536 x 65536 (2^32 pixels) is the cap and not + /// a parse error. + #[test] + fn a_codestream_over_the_pixel_cap_is_refused() { + let params = ImageDecodeParams { width: 1, height: 1, ..ImageDecodeParams::default() }; + assert!(decode(&jp2_with_size(1, 1, 0), ¶ms, usize::MAX).is_some()); + assert!(decode(&jp2_with_size(65536, 65536, 0), ¶ms, usize::MAX).is_none()); + let small_target = ImageDecodeParams { target_dimension: Some((1, 1)), ..params }; + assert!(decode(&jp2_with_size(65536, 65536, 4), &small_target, usize::MAX).is_none()); + } + + /// The size check uses the full-resolution size, not the target's. With four decomposition + /// levels a 1x1 target decodes a 64x64 image at a reduced resolution under 1024 pixels; with + /// a 1024-pixel limit the same image at the same target is still refused, because its + /// full-resolution 4096 pixels are over it. (An image a target can't shrink, with no + /// decomposition levels or a JP2 palette like `PALETTE_JP2`, can't tell the two measurements + /// apart.) The small limit lets the unfixed check be seen failing without an attacker-sized + /// allocation. + #[test] + fn jpx_size_guard_uses_full_resolution_before_target_resolution() { + let image = jp2_with_size(64, 64, 4); + let small_target = ImageDecodeParams { + width: 1, + height: 1, + target_dimension: Some((1, 1)), + ..ImageDecodeParams::default() + }; + let reduced = decode(&image, &small_target, usize::MAX).expect("a 64x64 image decodes at a 1x1 target"); + let size = reduced.image_data.as_ref().map(|d| (d.width, d.height)); + assert!( + size.is_some_and(|(w, h)| u64::from(w) * u64::from(h) <= 1024), + "the target shrinks the image under the limit: {size:?}" + ); + assert!(decode_with_pixel_limit(&image, &small_target, usize::MAX, 1024).is_none()); } } diff --git a/vendor/hayro-syntax/src/filter/lzw_flate.rs b/vendor/hayro-syntax/src/filter/lzw_flate.rs index 237057a8d0..81f82722a5 100644 --- a/vendor/hayro-syntax/src/filter/lzw_flate.rs +++ b/vendor/hayro-syntax/src/filter/lzw_flate.rs @@ -6,7 +6,7 @@ use alloc::vec::Vec; pub(crate) mod flate { use super::*; - use crate::filter::lzw_flate::{PredictorParams, apply_predictor}; + use crate::filter::lzw_flate::{PredictorParams, apply_predictor, untagged_png_rows}; pub(crate) use fallback::FlateState; @@ -17,14 +17,26 @@ pub(crate) mod flate { } use crate::object::Dict; - /// PdfCraft patch: `limit` is the most bytes inflated (see `filter::decode_limit`). + /// PdfCraft patch: `limit` is the most bytes inflated (see `filter::decode_limit`), and `rows` + /// the `/Height` of the image the data is the samples of, if it is (see [`untagged_png_rows`]). #[cfg(feature = "unsafe")] - pub(crate) fn decode(data: &[u8], params: &Dict<'_>, limit: usize) -> Option> { - decode_controlled(data, params, limit, None) + pub(crate) fn decode( + data: &[u8], + params: &Dict<'_>, + limit: usize, + rows: Option, + ) -> Option> { + decode_controlled(data, params, limit, None, rows) } #[cfg(feature = "unsafe")] - pub(crate) fn decode_controlled(data: &[u8], params: &Dict<'_>, limit: usize, control: Option<&crate::cancel::Control>) -> Option> { + pub(crate) fn decode_controlled( + data: &[u8], + params: &Dict<'_>, + limit: usize, + control: Option<&crate::cancel::Control>, + rows: Option, + ) -> Option> { use flate2::read::{DeflateDecoder, ZlibDecoder}; use std::io::Read; @@ -59,16 +71,27 @@ pub(crate) mod flate { } let mut params = PredictorParams::from_params(params); params.control = control.cloned(); - apply_predictor(decoded, ¶ms) + undo_predictor(decoded, ¶ms, rows) } #[cfg(not(feature = "unsafe"))] - pub(crate) fn decode(data: &[u8], params: &Dict<'_>, limit: usize) -> Option> { - decode_controlled(data, params, limit, None) + pub(crate) fn decode( + data: &[u8], + params: &Dict<'_>, + limit: usize, + rows: Option, + ) -> Option> { + decode_controlled(data, params, limit, None, rows) } #[cfg(not(feature = "unsafe"))] - pub(crate) fn decode_controlled(data: &[u8], params: &Dict<'_>, limit: usize, control: Option<&crate::cancel::Control>) -> Option> { + pub(crate) fn decode_controlled( + data: &[u8], + params: &Dict<'_>, + limit: usize, + control: Option<&crate::cancel::Control>, + rows: Option, + ) -> Option> { let decoded = fallback::decode(data, limit, control)?; // PdfCraft patch: output cut at the limit is reported, never dropped silently. if decoded.len() >= limit { @@ -76,7 +99,24 @@ pub(crate) mod flate { } let mut params = PredictorParams::from_params(params); params.control = control.cloned(); - apply_predictor(decoded, ¶ms) + undo_predictor(decoded, ¶ms, rows) + } + + /// PdfCraft patch: the predictor undone, unless the image's rows carry none + /// ([`untagged_png_rows`]): the data is then its samples as they are, which is reported. + fn undo_predictor( + decoded: Vec, + params: &PredictorParams, + rows: Option, + ) -> Option> { + if untagged_png_rows(params, decoded.len(), rows) { + warn!( + "flate image rows carry no PNG predictor tags, read as stored ({} rows)", + rows.unwrap_or(0) + ); + return Some(decoded); + } + apply_predictor(decoded, params) } /// Ported from @@ -1117,6 +1157,21 @@ impl PredictorParams { } } +/// PdfCraft patch: whether `len` bytes of an image `rows` high (`None` for data that isn't an +/// image's samples) are its rows without the filter-type byte each row starts with under a PNG +/// predictor (ISO 32000-2 §7.4.4.4): exactly `rows` × the row's bytes, where the predicted data +/// would be `rows` × (the row's bytes + 1). Some writers declare `/Predictor 15` without applying +/// it; read with the predictor, every row's first byte was taken for a filter type, the image +/// shifted a byte a row and came out short, drawn in fragments. PDFium, MuPDF and Poppler read +/// such data as the samples it is. Any other length is decoded with the predictor, as before. +fn untagged_png_rows(params: &PredictorParams, len: usize, rows: Option) -> bool { + let row_len = params.row_length_in_bytes(); + params.predictor >= 10 + && matches!(params.bits_per_component, 1 | 2 | 4 | 8 | 16) + && row_len > 0 + && rows.filter(|&r| r > 0).and_then(|r| r.checked_mul(row_len)) == Some(len) +} + fn apply_predictor(data: Vec, params: &PredictorParams) -> Option> { crate::cancel::check(params.control.as_ref())?; match params.predictor { @@ -1151,15 +1206,31 @@ fn apply_predictor(data: Vec, params: &PredictorParams) -> Option> { return None; } - let (bit_size, chunk_len) = if is_png_predictor { - ( - 8, - // PdfCraft patch: in usize (the u8 product overflowed). - (usize::from(params.colors) * usize::from(params.bits_per_component)).div_ceil(8), - ) - } else { - (params.bits_per_component, params.colors as usize) - }; + if is_png_predictor { + // PdfCraft patch: PNG predictors work on bytes whatever the bit depth, so they are + // undone a row at a time on byte slices instead of through the bit-level readers. + // In usize (the u8 product overflowed). + let bpp = (usize::from(params.colors) * usize::from(params.bits_per_component)) + .div_ceil(8); + return unfilter_png(&data, row_len, bpp, params.control.as_ref()); + } + + if i == 2 + && matches!(params.bits_per_component, 8 | 16) + && params.control.is_none() + && !bit_level_only() + { + // PdfCraft patch: whole-byte samples are undone a row at a time on byte slices + // instead of through the bit-level readers, which packed samples need. + let sample_len = usize::from(params.bits_per_component / 8); + let pixel_len = usize::from(params.colors).saturating_mul(sample_len); + return Some(undo_tiff_bytes(data, row_len, pixel_len, sample_len)); + } + + #[cfg(all(test, feature = "std"))] + BIT_LEVEL_TIFF_ROWS.with(|rows| rows.set(rows.get().saturating_add(num_rows))); + + let (bit_size, chunk_len) = (params.bits_per_component, params.colors as usize); let zero_row = vec![0; row_len]; let mut prev_row = BitChunks::new(&zero_row, bit_size, chunk_len)?; let zero_col = BitChunk::new(0, chunk_len); @@ -1169,56 +1240,7 @@ fn apply_predictor(data: Vec, params: &PredictorParams) -> Option> { for in_row in data.chunks_exact(total_row_len) { crate::cancel::check(params.control.as_ref())?; - if is_png_predictor { - let predictor = in_row[0]; - let in_data = &in_row[1..]; - let in_data_chunks = BitChunks::new(in_data, bit_size, chunk_len)?; - - match predictor { - 1 => apply::( - prev_row, - zero_col.clone(), - zero_col.clone(), - in_data_chunks, - &mut writer, - run, - )?, - 2 => apply::( - prev_row, - zero_col.clone(), - zero_col.clone(), - in_data_chunks, - &mut writer, - run, - )?, - 3 => apply::( - prev_row, - zero_col.clone(), - zero_col.clone(), - in_data_chunks, - &mut writer, - run, - )?, - 4 => apply::( - prev_row, - zero_col.clone(), - zero_col.clone(), - in_data_chunks, - &mut writer, - run, - )?, - _ => { - // Just copy the data. - let mut reader = BitReader::new(in_data); - let mut checks = crate::cancel::Checkpoints::new(params.control.as_ref()); - - while let Some(data) = reader.read(bit_size) { - checks.at(writer.cur_pos())?; - writer.write(data); - } - } - } - } else if i == 2 { + if i == 2 { apply::( prev_row, zero_col.clone(), @@ -1253,6 +1275,179 @@ struct PredictorRun<'a> { control: Option<&'a crate::cancel::Control>, } + +/// PdfCraft patch: undoes TIFF predictor 2 (ISO 32000-2 §7.4.4.4, Table 10; TIFF 6.0 §14) +/// for 8- and 16-bit samples, in rows of `row_len` bytes holding pixels of `pixel_len` bytes, +/// each sample `sample_len` bytes (1 or 2, big-endian): every sample is added to the same +/// component of the pixel to its left, wrapping at the sample's width. Bytes after the last +/// complete row are dropped, as the bit-level path drops them. +fn undo_tiff_bytes( + mut data: Vec, + row_len: usize, + pixel_len: usize, + sample_len: usize, +) -> Vec { + let num_rows = data.len() / row_len.max(1); + data.truncate(num_rows.saturating_mul(row_len)); + if pixel_len == 0 { + return data; + } + + for row in data.chunks_exact_mut(row_len) { + let mut pixels = row.chunks_exact_mut(pixel_len); + let Some(mut left) = pixels.next() else { + continue; + }; + for px in pixels { + if sample_len == 2 { + for (c, l) in px.chunks_exact_mut(2).zip(left.chunks_exact(2)) { + if let ([c0, c1], [l0, l1]) = (c, l) { + let sum = u16::from_be_bytes([*c0, *c1]) + .wrapping_add(u16::from_be_bytes([*l0, *l1])); + [*c0, *c1] = sum.to_be_bytes(); + } + } + } else { + for (c, l) in px.iter_mut().zip(left.iter()) { + *c = c.wrapping_add(*l); + } + } + left = px; + } + } + + data +} + +#[cfg(all(test, feature = "std"))] +std::thread_local! { + /// PdfCraft patch tests: rows the bit-level TIFF predictor path has undone on this thread. + static BIT_LEVEL_TIFF_ROWS: core::cell::Cell = const { core::cell::Cell::new(0) }; + /// PdfCraft patch tests: send whole-byte TIFF samples through the bit-level path too. + static BIT_LEVEL_ONLY: core::cell::Cell = const { core::cell::Cell::new(false) }; +} + +/// PdfCraft patch: whether whole-byte TIFF samples must take the bit-level path (only when a +/// test compares the two paths). +#[cfg(all(test, feature = "std"))] +fn bit_level_only() -> bool { + BIT_LEVEL_ONLY.with(core::cell::Cell::get) +} + +#[cfg(not(all(test, feature = "std")))] +fn bit_level_only() -> bool { + false +} + +/// PdfCraft patch: undoes PNG row filters (ISO 32000-2 §7.4.4.4, PNG specification §9) in +/// rows of `row_len` bytes, each after its filter-type byte, with `bpp` bytes per complete pixel +/// (at least 1). An unknown filter type copies the row as it is. Bytes after the last complete +/// row are dropped. +fn unfilter_png( + data: &[u8], + row_len: usize, + bpp: usize, + control: Option<&crate::cancel::Control>, +) -> Option> { + let bpp = bpp.max(1); + let in_row_len = row_len.saturating_add(1); + let num_rows = data.len() / in_row_len; + let mut out = vec![0; num_rows.saturating_mul(row_len)]; + let zero_row = vec![0; row_len]; + let mut prev: &[u8] = &zero_row; + let mut checks = crate::cancel::Checkpoints::new(control); + let mut work = 0usize; + + for (cur, in_row) in out + .chunks_exact_mut(row_len) + .zip(data.chunks_exact(in_row_len)) + { + let Some((&filter, src)) = in_row.split_first() else { + break; + }; + + match filter { + 1 => { + let mut left: &[u8] = &zero_row; + for (px, src) in cur.chunks_mut(bpp).zip(src.chunks(bpp)) { + for ((c, s), l) in px.iter_mut().zip(src).zip(left) { + checks.at(work)?; + work = work.saturating_add(1); + *c = s.wrapping_add(*l); + } + left = px; + } + } + 2 => { + for ((c, s), u) in cur.iter_mut().zip(src).zip(prev) { + checks.at(work)?; + work = work.saturating_add(1); + *c = s.wrapping_add(*u); + } + } + 3 => { + let mut left: &[u8] = &zero_row; + for ((px, src), up) in cur + .chunks_mut(bpp) + .zip(src.chunks(bpp)) + .zip(prev.chunks(bpp)) + { + for (((c, s), l), u) in px.iter_mut().zip(src).zip(left).zip(up) { + checks.at(work)?; + work = work.saturating_add(1); + // The sum is taken before halving, without wrapping. + let avg = (u16::from(*l) + u16::from(*u)) / 2; + *c = s.wrapping_add(avg as u8); + } + left = px; + } + } + 4 => { + let mut left: &[u8] = &zero_row; + let mut up_left: &[u8] = &zero_row; + for ((px, src), up) in cur + .chunks_mut(bpp) + .zip(src.chunks(bpp)) + .zip(prev.chunks(bpp)) + { + for ((((c, s), l), u), ul) in + px.iter_mut().zip(src).zip(left).zip(up).zip(up_left) + { + checks.at(work)?; + work = work.saturating_add(1); + *c = s.wrapping_add(paeth_byte(*l, *u, *ul)); + } + left = px; + up_left = up; + } + } + _ => { + for (c, s) in cur.iter_mut().zip(src) { + checks.at(work)?; + work = work.saturating_add(1); + *c = *s; + } + } + } + + prev = cur; + } + + Some(out) +} + +/// The Paeth predictor on bytes: the neighbour nearest `left + up - up_left`, preferring left, +/// then up. +fn paeth_byte(left: u8, up: u8, up_left: u8) -> u8 { + let (a, b, c) = (i16::from(left), i16::from(up), i16::from(up_left)); + let pa = (b - c).abs(); + let pb = (a - c).abs(); + let pc = (a + b - c - c).abs(); + + let not_left = if pb <= pc { up } else { up_left }; + if pa <= pb && pa <= pc { left } else { not_left } +} + fn apply<'a, T: Predictor>( prev_row: BitChunks<'a>, mut prev_col: BitChunk, @@ -1304,46 +1499,6 @@ impl Predictor for Sub { } } -struct Up; -impl Predictor for Up { - fn predict(cur_row: u16, prev_row: u16, _: u16, _: u16) -> u16 { - cur_row.wrapping_add(prev_row) - } -} - -struct Avg; -impl Predictor for Avg { - fn predict(cur_row: u16, prev_row: u16, prev_col: u16, _: u16) -> u16 { - cur_row.wrapping_add(((prev_col as u32 + prev_row as u32) / 2) as u16) - } -} - -struct Paeth; -impl Predictor for Paeth { - fn predict(cur_row: u16, prev_row: u16, prev_col: u16, top_left: u16) -> u16 { - fn paeth(a: u16, b: u16, c: u16) -> u16 { - let a = a as i32; - let b = b as i32; - let c = c as i32; - - let p = a + b - c; - let pa = (p - a).abs(); - let pb = (p - b).abs(); - let pc = (p - c).abs(); - - if pa <= pb && pa <= pc { - a as u16 - } else if pb <= pc { - b as u16 - } else { - c as u16 - } - } - - cur_row.wrapping_add(paeth(prev_col, prev_row, top_left)) - } -} - #[cfg(test)] #[rustfmt::skip] mod tests { @@ -1364,7 +1519,7 @@ mod tests { 0x78, 0x9c, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x7, 0x0, 0x5, 0x8c, 0x1, 0xf5, ]; - let decoded = flate::decode(&input, &Dict::default(), usize::MAX).unwrap(); + let decoded = flate::decode(&input, &Dict::default(), usize::MAX, None).unwrap(); assert_eq!(decoded, b"Hello"); } @@ -1372,7 +1527,7 @@ mod tests { fn decode_flate() { let input = [0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x7, 0x0]; - let decoded = flate::decode(&input, &Dict::default(), usize::MAX).unwrap(); + let decoded = flate::decode(&input, &Dict::default(), usize::MAX, None).unwrap(); assert_eq!(decoded, b"Hello"); } @@ -1524,3 +1679,385 @@ mod tests { ); } } + +/// PdfCraft patch tests: PNG predictors are undone byte by byte (`unfilter_png`). +#[cfg(test)] +mod pdfcraft_png_predictor_tests { + use crate::filter::lzw_flate::{PredictorParams, apply_predictor, flate, untagged_png_rows}; + use crate::object::{Dict, FromBytes}; + + /// `data` as one stored (uncompressed) deflate block, at most 65,535 bytes. + fn stored(data: &[u8]) -> Vec { + let len = u16::try_from(data.len()).unwrap(); + let mut out = vec![1]; + out.extend(len.to_le_bytes()); + out.extend((!len).to_le_bytes()); + out.extend(data); + out + } + + /// `data` inflated and its PNG predictor undone, as the last filter of an image `rows` high. + fn inflate(parms: &[u8], data: &[u8], rows: Option) -> Option> { + let parms = Dict::from_bytes(parms).unwrap(); + flate::decode(&stored(data), &parms, usize::MAX, rows) + } + + const RGB3: &[u8] = b"<< /Predictor 15 /Colors 3 /BitsPerComponent 8 /Columns 3 >>"; + + #[test] + fn an_image_whose_rows_carry_no_png_tags_is_read_as_its_samples() { + // Three RGB pixels a row, four rows: 36 bytes, where the predictor would need 40. Every + // row starts with a byte above 4, which the predictor took for a filter type, so the + // image came out three rows of shifted samples. + let samples: Vec = (0..36).map(|i| 200 - i as u8).collect(); + assert_eq!(inflate(RGB3, &samples, Some(4)).unwrap(), samples); + let params = PredictorParams { + predictor: 15, + colors: 3, + bits_per_component: 8, + columns: 3, + early_change: false, + control: None, + }; + assert!( + untagged_png_rows(¶ms, 36, Some(4)), + "the repair is reported" + ); + // Not an image's samples (no height known): the predictor is undone, as before. + assert_eq!( + inflate(RGB3, &samples, None).unwrap(), + apply_predictor(samples.clone(), ¶ms).unwrap() + ); + assert!(!untagged_png_rows(¶ms, 36, None)); + } + + #[test] + fn an_image_whose_rows_carry_png_tags_still_has_its_predictor_undone() { + // The same four rows, each filtered None, then Sub: 40 bytes. + let samples: Vec = (0..36).map(|i| 200 - i as u8).collect(); + let mut tagged = Vec::new(); + for row in samples.chunks(9) { + tagged.push(1); + let mut left = [0u8; 3]; + for px in row.chunks(3) { + tagged.extend(px.iter().zip(left).map(|(s, l)| s.wrapping_sub(l))); + left.copy_from_slice(px); + } + } + assert_eq!(tagged.len(), 40); + assert_eq!(inflate(RGB3, &tagged, Some(4)).unwrap(), samples); + } + + #[test] + fn data_of_neither_length_decodes_as_it_did() { + let params = PredictorParams { + predictor: 15, + colors: 3, + bits_per_component: 8, + columns: 3, + early_change: false, + control: None, + }; + // Short of the untagged length, past it, or between it and the tagged one. + for len in [0, 1, 9, 27, 35, 37, 39, 41, 72] { + let data: Vec = (0..len).map(|i| (i * 7) as u8 % 5).collect(); + assert!(!untagged_png_rows(¶ms, len, Some(4)), "{len} bytes"); + assert_eq!( + inflate(RGB3, &data, Some(4)), + apply_predictor(data.clone(), ¶ms), + "{len} bytes" + ); + } + // Rows of the untagged length for another height. + assert!(!untagged_png_rows(¶ms, 36, Some(3))); + assert!(!untagged_png_rows(¶ms, 36, Some(0))); + // No PNG predictor, or one with an invalid depth. + for (predictor, bits_per_component) in [(1, 8), (2, 8), (15, 3), (15, 0)] { + let params = PredictorParams { + predictor, + bits_per_component, + colors: params.colors, + columns: params.columns, + early_change: params.early_change, + control: None, + }; + assert!(!untagged_png_rows(¶ms, 36, Some(4))); + } + } + + #[test] + fn rows_of_no_bytes_or_of_more_than_memory_holds_do_not_panic() { + for (colors, bits_per_component, columns) in [ + (0, 8, 3), + (3, 8, 0), + (255, 16, usize::MAX), + (1, 1, usize::MAX), + (3, 8, usize::MAX / 24 + 1), + ] { + let params = PredictorParams { + predictor: 15, + colors, + bits_per_component, + columns, + early_change: false, + control: None, + }; + for rows in [None, Some(0), Some(1), Some(4), Some(usize::MAX)] { + for len in [0, 1, 36, usize::MAX] { + let _ = untagged_png_rows(¶ms, len, rows); + } + } + } + let zero = b"<< /Predictor 15 /Colors 3 /BitsPerComponent 8 /Columns 0 >>"; + let huge = + b"<< /Predictor 15 /Colors 255 /BitsPerComponent 16 /Columns 9223372036854775807 >>"; + for parms in [&zero[..], &huge[..]] { + for rows in [None, Some(0), Some(4), Some(usize::MAX)] { + let _ = inflate(parms, &[7; 36], rows); + } + } + } + + /// PNG unfiltering written out from the PNG specification (§9.2–9.4), one byte at a time. + fn reference(data: &[u8], row_len: usize, bpp: usize) -> Vec { + let mut out: Vec = Vec::new(); + for (r, row) in data.chunks_exact(row_len + 1).enumerate() { + let start = r * row_len; + for x in 0..row_len { + let left = if x >= bpp { out[start + x - bpp] } else { 0 }; + let up = if r > 0 { out[start + x - row_len] } else { 0 }; + let up_left = if r > 0 && x >= bpp { + out[start + x - row_len - bpp] + } else { + 0 + }; + let predicted = match row[0] { + 1 => left, + 2 => up, + 3 => ((u16::from(left) + u16::from(up)) / 2) as u8, + 4 => { + let p = i16::from(left) + i16::from(up) - i16::from(up_left); + let (pa, pb, pc) = ( + (p - i16::from(left)).abs(), + (p - i16::from(up)).abs(), + (p - i16::from(up_left)).abs(), + ); + if pa <= pb && pa <= pc { + left + } else if pb <= pc { + up + } else { + up_left + } + } + _ => 0, + }; + out.push(row[1 + x].wrapping_add(predicted)); + } + } + out + } + + #[test] + fn png_predictors_match_the_specification_at_every_depth_and_pixel_size() { + let mut seed: u32 = 0x2545_f491; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed + }; + for case in 0..400 { + let colors = 1 + (next() % 4) as u8; + let bits_per_component = [1u8, 2, 4, 8, 16][(next() % 5) as usize]; + let columns = 1 + (next() % 40) as usize; + let bpp = (usize::from(colors) * usize::from(bits_per_component)).div_ceil(8); + let row_len = + (columns * usize::from(colors) * usize::from(bits_per_component)).div_ceil(8); + let rows = 1 + (next() % 6) as usize; + let mut data = Vec::new(); + for _ in 0..rows { + // Filter types 0–4, and 5–7, which are not PNG filters and copy the row. + data.push((next() % 8) as u8); + data.extend((0..row_len).map(|_| next() as u8)); + } + // A partial row at the end is not decoded. + let tail = (next() % 3) as usize; + data.extend((0..tail.min(row_len)).map(|_| next() as u8)); + + let params = PredictorParams { + predictor: 10 + (next() % 6) as u8, + colors, + bits_per_component, + columns, + early_change: false, + control: None, + }; + let got = apply_predictor(data.clone(), ¶ms).unwrap(); + assert_eq!( + got, + reference(&data, row_len, bpp), + "case {case}: {colors} colours at {bits_per_component} bits, {columns} columns" + ); + } + } + + #[test] + fn a_row_ending_part_way_through_a_pixel_keeps_its_last_byte() { + // Three 4-bit samples are a byte and a half, so a three-column row is five bytes and ends + // half-way through a two-byte pixel. Each row is filtered Up. + let data = [ + 2, 10, 11, 12, 13, 14, // + 2, 20, 21, 22, 23, 24, // + 2, 30, 31, 32, 33, 34, + ]; + let params = PredictorParams { + predictor: 15, + colors: 3, + bits_per_component: 4, + columns: 3, + early_change: false, + control: None, + }; + assert_eq!( + apply_predictor(data.to_vec(), ¶ms).unwrap(), + [10, 11, 12, 13, 14, 30, 32, 34, 36, 38, 60, 63, 66, 69, 72] + ); + } + + #[test] + fn png_average_and_paeth_carry_the_left_pixel_across_a_wide_row() { + // Three 16-bit samples (6 bytes) per pixel: the left neighbour is six bytes back. + let row_len = 6 * 3; + let mut data = vec![3u8]; + data.extend((0..row_len).map(|i| (i * 37 + 200) as u8)); + data.push(4); + data.extend((0..row_len).map(|i| (255 - i * 11) as u8)); + let params = PredictorParams { + predictor: 15, + colors: 3, + bits_per_component: 16, + columns: 3, + early_change: false, + control: None, + }; + assert_eq!( + apply_predictor(data.clone(), ¶ms).unwrap(), + reference(&data, row_len, 6) + ); + } +} + +/// PdfCraft patch tests: TIFF predictor 2 on 8- and 16-bit samples is undone on byte rows +/// (`undo_tiff_bytes`), with the same output as the bit-level path. +#[cfg(all(test, feature = "std"))] +mod pdfcraft_tiff_predictor_tests { + use super::{BIT_LEVEL_ONLY, BIT_LEVEL_TIFF_ROWS}; + use crate::filter::lzw_flate::{PredictorParams, apply_predictor}; + + fn tiff(colors: u8, bits_per_component: u8, columns: usize) -> PredictorParams { + PredictorParams { + predictor: 2, + colors, + bits_per_component, + columns, + early_change: false, + control: None, + } + } + + /// Both paths' output, the byte path's first; `None` from either is kept. + fn both(data: &[u8], params: &PredictorParams) -> (Option>, Option>) { + let fast = apply_predictor(data.to_vec(), params); + BIT_LEVEL_ONLY.with(|only| only.set(true)); + let bits = apply_predictor(data.to_vec(), params); + BIT_LEVEL_ONLY.with(|only| only.set(false)); + (fast, bits) + } + + #[test] + fn whole_byte_samples_match_the_bit_level_path_on_random_rows() { + let mut seed: u32 = 0x9e37_79b9; + let mut next = move || { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed + }; + for case in 0..600 { + let colors = [1u8, 2, 3, 4, 5, 7][(next() % 6) as usize]; + let bits_per_component = [8u8, 16][(next() % 2) as usize]; + let columns = 1 + (next() % 50) as usize; + let row_len = columns * usize::from(colors) * usize::from(bits_per_component) / 8; + let rows = (next() % 7) as usize; + // A partial row at the end, or none. + let tail = (next() % 4) as usize % row_len; + let data: Vec = (0..rows * row_len + tail).map(|_| next() as u8).collect(); + let params = tiff(colors, bits_per_component, columns); + let (fast, bits) = both(&data, ¶ms); + assert_eq!( + fast, bits, + "case {case}: {colors} colours at {bits_per_component} bits, {columns} columns, {rows} rows and {tail} bytes" + ); + } + } + + #[test] + fn whole_byte_samples_add_to_the_same_component_of_the_pixel_to_their_left() { + // Two 8-bit colours, three columns, two rows; sums wrap at 256. + let data = [10, 20, 1, 2, 3, 4, /* row 2 */ 5, 5, 250, 10, 1, 1]; + assert_eq!( + apply_predictor(data.to_vec(), &tiff(2, 8, 3)).unwrap(), + [10, 20, 11, 22, 14, 26, 5, 5, 255, 15, 0, 16] + ); + // One 16-bit colour: a carry crosses the byte boundary and the sum wraps at 65,536. + let data = [ + 0x01, 0x00, 0xff, 0xff, 0x00, 0x02, /* row 2 */ 0x00, 0xff, 0x00, 0x01, 0, 0, + ]; + assert_eq!( + apply_predictor(data.to_vec(), &tiff(1, 16, 3)).unwrap(), + [ + 0x01, 0x00, 0x00, 0xff, 0x01, 0x01, 0x00, 0xff, 0x01, 0x00, 0x01, 0x00 + ] + ); + } + + #[test] + fn whole_byte_samples_do_not_take_the_bit_level_path() { + let start = BIT_LEVEL_TIFF_ROWS.with(core::cell::Cell::get); + for bits_per_component in [8, 16] { + let data = vec![7; 3 * 4 * usize::from(bits_per_component) / 8 * 5]; + apply_predictor(data, &tiff(3, bits_per_component, 4)).unwrap(); + } + assert_eq!(BIT_LEVEL_TIFF_ROWS.with(core::cell::Cell::get), start); + + // Packed samples still do. + apply_predictor(vec![0x5f; 4], &tiff(1, 4, 2)).unwrap(); + assert_eq!(BIT_LEVEL_TIFF_ROWS.with(core::cell::Cell::get), start + 4); + } + + #[test] + fn rows_without_a_complete_row_of_data_are_dropped_on_both_paths() { + for (data, params, want) in [ + // Shorter than one row: nothing. + (vec![1, 2, 3], tiff(1, 8, 4), Some(vec![])), + (vec![1, 2, 3], tiff(1, 16, 2), Some(vec![])), + // A zero-width row is refused. + (vec![1, 2, 3], tiff(1, 8, 0), None), + (vec![], tiff(1, 16, 0), None), + // No data at all. + (vec![], tiff(3, 8, 2), Some(vec![])), + // The trailing partial row is dropped. + ( + vec![1, 1, 1, 1, 2, 2], + tiff(1, 8, 4), + Some(vec![1, 2, 3, 4]), + ), + (vec![0, 1, 0, 1, 9], tiff(1, 16, 2), Some(vec![0, 1, 0, 2])), + ] { + let (fast, bits) = both(&data, ¶ms); + assert_eq!(fast, want, "{data:?}"); + assert_eq!(bits, want, "{data:?}"); + } + } +} diff --git a/vendor/hayro-syntax/src/filter/mod.rs b/vendor/hayro-syntax/src/filter/mod.rs index c52f5d2ab4..833268506d 100644 --- a/vendor/hayro-syntax/src/filter/mod.rs +++ b/vendor/hayro-syntax/src/filter/mod.rs @@ -9,6 +9,13 @@ mod dct; #[cfg(feature = "images")] mod jbig2; #[cfg(feature = "images")] +pub use jbig2::{ + MAX_PAGE_JBIG2_WORK, clear_jbig2_limited, jbig2_limited, jbig2_limited_by_stream, + page_jbig2_work_spent, +}; +#[cfg(all(feature = "images", feature = "std"))] +pub use jbig2::set_page_jbig2_work; +#[cfg(feature = "images")] mod jpx; mod lzw_flate; mod run_length; @@ -86,7 +93,9 @@ impl Filter { } } - /// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`). + /// PdfCraft patch: `limit` is the most bytes the filter may produce (see `decode_limit`), and + /// `rows` the `/Height` of the image whose samples it produces, when it is an image's last + /// filter. pub(crate) fn apply( &self, data: &[u8], @@ -94,6 +103,7 @@ impl Filter { #[cfg_attr(not(feature = "images"), allow(unused))] image_params: &ImageDecodeParams, limit: usize, control: Option<&crate::cancel::Control>, + rows: Option, ) -> Result, DecodeFailure> { crate::cancel::check(control).ok_or(DecodeFailure::StreamDecode)?; let res = match self { @@ -109,7 +119,11 @@ impl Filter { Self::LzwDecode => (if control.is_some() { lzw_flate::lzw::decode_controlled(data, params, limit, control) } else { lzw_flate::lzw::decode(data, params, limit) }) .map(FilterResult::from_data) .ok_or(DecodeFailure::StreamDecode), - Self::FlateDecode => (if control.is_some() { lzw_flate::flate::decode_controlled(data, params, limit, control) } else { lzw_flate::flate::decode(data, params, limit) }) + Self::FlateDecode => (if control.is_some() { + lzw_flate::flate::decode_controlled(data, params, limit, control, rows) + } else { + lzw_flate::flate::decode(data, params, limit, rows) + }) .map(FilterResult::from_data) .ok_or(DecodeFailure::StreamDecode), #[cfg(feature = "images")] @@ -125,7 +139,8 @@ impl Filter { warn!("image decoding is not supported (enable the `images` feature)"); Err(DecodeFailure::ImageDecode) } - _ => Err(DecodeFailure::StreamDecode), + // PdfCraft patch (30): `Stream::raw_data` decrypted the data with the filter this names. + Self::Crypt => Ok(FilterResult::from_data(data.to_vec())), }; crate::cancel::check(control).ok_or(DecodeFailure::StreamDecode)?; diff --git a/vendor/hayro-syntax/src/object/array.rs b/vendor/hayro-syntax/src/object/array.rs index 23b8057c2d..76cee02659 100644 --- a/vendor/hayro-syntax/src/object/array.rs +++ b/vendor/hayro-syntax/src/object/array.rs @@ -2,7 +2,7 @@ use crate::object::macros::object; use crate::object::r#ref::MaybeRef; -use crate::object::{FromBytes, Object, ObjectLike}; +use crate::object::{FromBytes, Null, Object, ObjectLike}; use crate::reader::Reader; use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable}; use alloc::vec::Vec; @@ -142,6 +142,19 @@ impl<'a> Iterator for ArrayIter<'a> { } } +/// PdfCraft patch (46): step over an array item at `start` that the first pass skipped but no +/// object is read from. `None` (end the iteration) if it can't be skipped or the skip makes no +/// progress, so a caller never loops. +fn skip_unreadable_item<'a>(mut start: Reader<'a>, ctx: &ReaderContext<'a>) -> Option> { + let from = start.offset(); + if ctx.in_content_stream() { + start.skip::>(true)?; + } else { + start.skip::>>(false)?; + } + (start.offset() > from).then_some(start) +} + /// An iterator over the array that resolves objects of a specific type. pub struct ResolvedArrayIter<'a, T> { flex_iter: FlexArrayIter<'a>, @@ -192,9 +205,34 @@ impl<'a> FlexArrayIter<'a> { self.reader.skip_white_spaces_and_comments(); if !self.reader.at_end() { - return match self.reader.read_with_context::>(&self.ctx)? { - MaybeRef::Ref(r) => self.ctx.xref().get_with::(r.into(), &self.ctx), - MaybeRef::NotRef(i) => Some(i), + // PdfCraft patch (32): its items each follow a reference. Read as one that might be, a + // reference at the start was taken for the whole group, which it can't be, and lost. + if T::GROUP { + return self.reader.read_with_context::(&self.ctx); + } + + let start = self.reader.clone(); + return match self.reader.read_with_context::>(&self.ctx) { + Some(MaybeRef::Ref(r)) => self.ctx.xref().get_with::(r.into(), &self.ctx), + Some(MaybeRef::NotRef(i)) => Some(i), + // PdfCraft patch (46): an item no object is read from (a lone sign such as `+`) + // reads as null in its slot, as in `raw_iter`, instead of ending the iteration + // and losing the items after it. An object of another type still ends it. The + // slot is passed only when null is a `T`: a typed read that fails leaves it in + // place, as a value of another type is, so the caller can read it as another type. + None => { + let mut probe = start.clone(); + if probe + .read_with_context::>>(&self.ctx) + .is_some() + { + return None; + } + let after = skip_unreadable_item(start, &self.ctx)?; + let item = Object::Null(Null).cast::()?; + self.reader = after; + Some(item) + } }; } diff --git a/vendor/hayro-syntax/src/object/dict.rs b/vendor/hayro-syntax/src/object/dict.rs index a5d84ae209..69025c8a8b 100644 --- a/vendor/hayro-syntax/src/object/dict.rs +++ b/vendor/hayro-syntax/src/object/dict.rs @@ -100,9 +100,13 @@ impl<'a> Dict<'a> { pub fn entries(&self) -> impl Iterator, MaybeRef>)> + '_ { let mut sorted_keys = self.keys().collect::>(); sorted_keys.sort_by(|n1, n2| n1.as_ref().cmp(n2.as_ref())); - sorted_keys - .into_iter() - .filter_map(|k| self.get_raw(k.deref()).map(|obj| (k, obj))) + // PdfCraft patch (46): an entry whose value the first pass skipped but no object is read + // from (a lone sign such as `+` or `++`) is left out, as `get` leaves it unread, rather + // than unwrapping the failed read. + sorted_keys.into_iter().filter_map(|k| { + let obj = self.get_raw(k.deref())?; + Some((k, obj)) + }) } /// Return the object identifier of the dict, if it's an indirect object. @@ -157,8 +161,19 @@ impl Debug for Dict<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { let mut debug_struct = f.debug_struct("Dict"); - for (key, value) in self.entries() { - debug_struct.field(&format!("{:?}", key.as_str()), &value); + if let Some(offsets) = self.offsets() { + let mut r = Reader::new(self.data()); + + for (key, val) in offsets { + r.jump(*val); + // PdfCraft patch (46): an entry no object is read from is left out, as in + // `entries`, instead of unwrapping the failed read. + if let Some(value) = + r.read_with_context::>>(&ReaderContext::dummy()) + { + debug_struct.field(&format!("{:?}", key.as_str()), &value); + } + } } debug_struct.finish() } diff --git a/vendor/hayro-syntax/src/object/mod.rs b/vendor/hayro-syntax/src/object/mod.rs index d692db8b38..6ad97b64e4 100644 --- a/vendor/hayro-syntax/src/object/mod.rs +++ b/vendor/hayro-syntax/src/object/mod.rs @@ -32,7 +32,11 @@ pub mod dict; pub mod stream; /// A trait for PDF objects. -pub(crate) trait ObjectLike<'a>: TryFrom> + Readable<'a> + Debug + Clone {} +pub(crate) trait ObjectLike<'a>: TryFrom> + Readable<'a> + Debug + Clone { + /// PdfCraft patch (32): whether this is several items of an array, read one by one (a tuple). + /// Such a thing can't itself be given by reference, so one at its start is its first item's. + const GROUP: bool = false; +} /// A trait for PDF objects that can be borrowed directly from an [`Object`]. pub(crate) trait ObjectRefLike<'a>: Sized { diff --git a/vendor/hayro-syntax/src/object/ref.rs b/vendor/hayro-syntax/src/object/ref.rs index 71951f4d82..3d3cbffbe1 100644 --- a/vendor/hayro-syntax/src/object/ref.rs +++ b/vendor/hayro-syntax/src/object/ref.rs @@ -39,10 +39,11 @@ impl From for ObjRef { impl Skippable for ObjRef { fn skip(r: &mut Reader<'_>, _: bool) -> Option<()> { + // PdfCraft patch: (hayro-syntax (33)) a comment counts as white space, here too. r.skip::(false)?; - r.skip_white_spaces(); + r.skip_white_spaces_and_comments(); r.skip::(false)?; - r.skip_white_spaces(); + r.skip_white_spaces_and_comments(); r.forward_tag(b"R")?; Some(()) @@ -52,9 +53,9 @@ impl Skippable for ObjRef { impl Readable<'_> for ObjRef { fn read(r: &mut Reader<'_>, _: &ReaderContext<'_>) -> Option { let obj_ref = r.read_without_context::()?; - r.skip_white_spaces(); + r.skip_white_spaces_and_comments(); let gen_num = r.read_without_context::()?; - r.skip_white_spaces(); + r.skip_white_spaces_and_comments(); r.forward_tag(b"R")?; Some(Self::new(obj_ref, gen_num)) diff --git a/vendor/hayro-syntax/src/object/stream.rs b/vendor/hayro-syntax/src/object/stream.rs index 339cf779e3..f464110bec 100644 --- a/vendor/hayro-syntax/src/object/stream.rs +++ b/vendor/hayro-syntax/src/object/stream.rs @@ -5,7 +5,7 @@ use crate::filter::Filter; use crate::object; use crate::object::Dict; use crate::object::Name; -use crate::object::dict::keys::{DECODE_PARMS, DP, F, FILTER, LENGTH, TYPE}; +use crate::object::dict::keys::{DECODE_PARMS, DP, F, FILTER, LENGTH, NAME, TYPE}; use crate::object::{Array, ObjectIdentifier}; use crate::object::{Object, ObjectLike, ObjectRefLike}; use crate::reader::Reader; @@ -13,6 +13,7 @@ use crate::reader::{Readable, ReaderContext, ReaderExt, Skippable}; use crate::trivia::{is_eol_character, is_regular_character, is_white_space_character}; use crate::util::{OptionLog, find_needle}; use alloc::borrow::Cow; +use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::fmt::{Debug, Formatter}; use smallvec::SmallVec; @@ -73,38 +74,44 @@ impl<'a> Stream<'a> { let mut collected_filters = SmallVec::new(); let mut collected_params = SmallVec::new(); + // PdfCraft patch (30): `/DecodeParms` in either form, whichever form `/Filter` has: one filter + // in an array with a lone dictionary is an everyday spelling, and a lone dictionary is the + // first filter's. Read as the chain asks, so a long array costs no more than a short one. + let parms = self + .dict + .get::>(DP) + .or_else(|| self.dict.get::>(DECODE_PARMS)); + let mut in_array = match &parms { + Some(Object::Array(a)) => Some(a.iter::>()), + _ => None, + }; + let mut lone = match parms { + Some(Object::Dict(d)) => Some(d), + _ => None, + }; + let mut next_params = || { + lone.take() + .or_else(|| in_array.as_mut()?.next()?.into_dict()) + .unwrap_or_default() + }; + if let Some(filter) = self .dict .get::>(F) .or_else(|| self.dict.get::>(FILTER)) .and_then(Filter::from_name) { - let params = self - .dict - .get::>(DP) - .or_else(|| self.dict.get::>(DECODE_PARMS)) - .unwrap_or_default(); - collected_filters.push(filter); - collected_params.push(params); + collected_params.push(next_params()); } else if let Some(filters) = self .dict .get::>(F) .or_else(|| self.dict.get::>(FILTER)) { let filters = filters.iter::>().map(Filter::from_name); - let mut params = self - .dict - .get::>(DP) - .or_else(|| self.dict.get::>(DECODE_PARMS)) - .map(|a| a.iter::>()); for filter in filters { - let params = params - .as_mut() - .and_then(|p| p.next()) - .and_then(|p| p.into_dict()) - .unwrap_or_default(); + let params = next_params(); if let Some(filter) = filter { collected_filters.push(filter); @@ -119,6 +126,20 @@ impl<'a> Stream<'a> { } } + /// PdfCraft patch (30): the crypt filter the stream names for itself: `/Crypt` in its chain, its + /// name in that filter's parameters, or `/Identity` without one (ISO 32000-2 §7.4.10). + fn crypt_filter(&self) -> Option { + let FiltersAndParams { filters, params } = self.filters_and_params(); + // A chain longer than cos decodes names none there, so it names none here either: + // `pdfcraft_filters::MAX_CHAIN`, and `/Crypt`. + if filters.len() > 9 { + return None; + } + let i = filters.iter().position(|f| matches!(f, Filter::Crypt))?; + let name = params.get(i).and_then(|p| p.get::>(NAME)); + Some(name.map_or_else(|| "Identity".to_string(), |n| n.as_str().to_string())) + } + /// Return the raw, decrypted data of the stream. /// /// Stream filters will not be applied. @@ -132,9 +153,13 @@ impl<'a> Stream<'a> { .map(|t| t.as_ref() != b"XRef") .unwrap_or(true) { + let own = self.crypt_filter(); + let target = own + .as_deref() + .map_or(DecryptionTarget::Stream, DecryptionTarget::NamedStream); Cow::Owned( ctx.xref() - .decrypt(self.obj_id(), self.data, DecryptionTarget::Stream) + .decrypt(self.obj_id(), self.data, target) // TODO: MAybe an error would be better? .unwrap_or_default(), ) @@ -248,9 +273,25 @@ impl<'a> Stream<'a> { .zip(filters_and_params.params.iter()) .enumerate() { + // PdfCraft patch (30): `raw_data` decrypted the data, so there's nothing to undo, and a + // chain can name this thousands of times. + if matches!(filter, Filter::Crypt) { + continue; + } // PdfCraft patch: see `filter::decode_limit`. let limit = crate::filter::decode_limit(image_params, i + 1 == count, self.dict.ctx().decode_limits()).min(max); - let new = filter.apply(current.as_ref().map(|c| c.data.as_ref()).unwrap_or(&data), params, image_params, limit, self.dict.ctx().control())?; + // PdfCraft patch: the last filter of an image produces its rows. + let rows = (i + 1 == count && image_params.height > 0) + .then(|| usize::try_from(image_params.height).ok()) + .flatten(); + let new = filter.apply( + current.as_ref().map(|c| c.data.as_ref()).unwrap_or(&data), + params, + image_params, + limit, + self.dict.ctx().control(), + rows, + )?; current = Some(new); } @@ -411,7 +452,7 @@ fn parse_fallback<'a>(r: &mut Reader<'a>, dict: &Dict<'a>) -> Option> let control = dict.ctx().control(); let endstream_offset = find_endstream(tail, control)?; let data_end = trim_trailing_ascii_whitespace(&tail[..endstream_offset], control)?; - let data = tail.get(..data_end)?; + let data = tail.get(..data_end)?; r.read_bytes(endstream_offset)?; r.skip_white_spaces(); diff --git a/vendor/hayro-syntax/src/object/tuple.rs b/vendor/hayro-syntax/src/object/tuple.rs index 4a7190e916..c76c1b408c 100644 --- a/vendor/hayro-syntax/src/object/tuple.rs +++ b/vendor/hayro-syntax/src/object/tuple.rs @@ -39,6 +39,7 @@ where T: ObjectLike<'a> + Debug + Clone, U: ObjectLike<'a> + Debug + Clone, { + const GROUP: bool = true; } impl<'a, T, U, V> Readable<'a> for (T, U, V) @@ -78,6 +79,7 @@ where U: ObjectLike<'a> + Debug + Clone, V: ObjectLike<'a> + Debug + Clone, { + const GROUP: bool = true; } impl<'a, T, U, V, W> Readable<'a> for (T, U, V, W) @@ -122,6 +124,7 @@ where V: ObjectLike<'a> + Debug + Clone, W: ObjectLike<'a> + Debug + Clone, { + const GROUP: bool = true; } impl<'a, T, U, V, W, X> Readable<'a> for (T, U, V, W, X) @@ -171,4 +174,5 @@ where W: ObjectLike<'a> + Debug + Clone, X: ObjectLike<'a> + Debug + Clone, { + const GROUP: bool = true; } diff --git a/vendor/hayro-syntax/src/page.rs b/vendor/hayro-syntax/src/page.rs index 58ccbbbe2c..25536c3d41 100644 --- a/vendor/hayro-syntax/src/page.rs +++ b/vendor/hayro-syntax/src/page.rs @@ -453,12 +453,36 @@ impl<'a> Page<'a> { return None; } - let media_box = dict.get::(MEDIA_BOX).or(ctx.media_box).unwrap_or(A4); + // PdfCraft patch (38): a box that encloses no area is no box. A `/MediaBox` without + // area (`[0 0 0 0]`) is read as a missing one, and a `/CropBox` that has none, or + // none in common with the media box, as a missing one (the media box, ISO 32000-2 + // §14.11.2, Table 33). Kept, the page's visible region had no area: nothing was drawn + // and no text was extracted, where other readers show the page. + // A page's own box without area gives way to one it inherits that has some. Each box + // set aside is logged, as other repairs of this reader are. + // PdfCraft patch (44): a page with no `/MediaBox`, its own or inherited, or only ones + // without area, is US Letter, not A4. The box is required (ISO 32000-2 §7.7.3.3, + // Table 31) and has no default; other readers use Letter, as do PdfCraft's page model + // and inspector. The page is then sized, placed and clipped by the same Letter region + // and its content shows. + let own_media = dict.get::(MEDIA_BOX); + let media_box = own_media + .filter(has_area) + .or(ctx.media_box.filter(has_area)) + .unwrap_or(LETTER); + if own_media.or(ctx.media_box).is_some_and(|m| !has_area(&m)) { + warn!("a /MediaBox without area was read as missing"); + } - let crop_box = dict - .get::(CROP_BOX) - .or(ctx.crop_box) + let shows = |c: &Rect| has_area(&c.intersect(media_box)); + let own_crop = dict.get::(CROP_BOX); + let crop_box = own_crop + .filter(shows) + .or(ctx.crop_box.filter(shows)) .unwrap_or(media_box); + if own_crop.or(ctx.crop_box).is_some_and(|c| !shows(&c)) { + warn!("a /CropBox with no area in the media box was read as missing"); + } let rotation = match dict .get::(ROTATE) @@ -609,7 +633,8 @@ impl<'a> Page<'a> { if (crop_box.width() as f32).is_nearly_zero() || (crop_box.height() as f32).is_nearly_zero() { - (A4.width() as f32, A4.height() as f32) + // PdfCraft patch (44): the same US Letter default as a missing `/MediaBox`. + (LETTER.width() as f32, LETTER.height() as f32) } else { // PdfCraft patch: retain a one-point floor after UserUnit, not one raw unit. // The stored unit is finite and within 1..=75000. Round upward only if the @@ -727,11 +752,13 @@ impl<'a> Page<'a> { pub struct Resources<'a> { parent: Option>, ctx: ReaderContext<'a>, + // PdfCraft patch: legacy forms without Resources use the page, not their caller. + page_properties: Dict<'a>, /// The raw dictionary of external graphics states. pub ext_g_states: Dict<'a>, /// The raw dictionary of fonts. pub fonts: Dict<'a>, - /// The raw dictionary of properties. + /// The effective property dictionary selected at page or form entry. pub properties: Dict<'a>, /// The raw dictionary of color spaces. pub color_spaces: Dict<'a>, @@ -763,6 +790,26 @@ impl<'a> Resources<'a> { Self::new(resources, Some(parent), &ctx) } + // PdfCraft patch: page-tree inheritance stops at any present Resources dictionary. + fn for_page(resources: Option>, parent: Self) -> Self { + let properties = resources.as_ref().map_or_else(|| parent.properties.clone(), |dict| dict.get::>(PROPERTIES).unwrap_or_default()); + let mut result = Self::from_parent(resources.unwrap_or_default(), parent); + result.properties = properties.clone(); + result.page_properties = properties; + result + } + + /// Create form resources, using page Properties only when Resources is absent. + /// Other resource categories retain their existing parent-chain lookup. + // PdfCraft patch: ISO 32000-2, 7.8.3 and Table 93 require the page origin. + pub fn for_form(resources: Option>, parent: Self) -> Self { + let properties = + resources.as_ref().map_or_else(|| parent.page_properties.clone(), |dict| dict.get::>(PROPERTIES).unwrap_or_default()); + let mut result = Self::from_parent(resources.unwrap_or_default(), parent); + result.properties = properties; + result + } + /// Create a new `Resources` object. pub(crate) fn new(resources: Dict<'a>, parent: Option, ctx: &ReaderContext<'a>) -> Self { let ext_g_states = resources.get::>(EXT_G_STATE).unwrap_or_default(); @@ -773,6 +820,8 @@ impl<'a> Resources<'a> { let shadings = resources.get::>(SHADING).unwrap_or_default(); let properties = resources.get::>(PROPERTIES).unwrap_or_default(); + // PdfCraft patch: generic child resources retain the page origin. + let page_properties = parent.as_ref().map_or_else(|| properties.clone(), |parent| parent.page_properties.clone()); let parent = parent.map(Box::new); Self { @@ -781,6 +830,7 @@ impl<'a> Resources<'a> { fonts, color_spaces, properties, + page_properties, x_objects, patterns, shadings, @@ -838,6 +888,18 @@ impl<'a> Resources<'a> { const POINTS_PER_INCH: f64 = 72.0; const POINTS_PER_MM: f64 = 1.0 / (10.0 * 2.54) * POINTS_PER_INCH; +/// PdfCraft patch (38): whether `r` encloses some area: finite, and wider and taller than +/// nothing. +fn has_area(r: &Rect) -> bool { + let (w, h) = (r.width() as f32, r.height() as f32); + w.is_finite() + && h.is_finite() + && w > 0.0 + && h > 0.0 + && !w.is_nearly_zero() + && !h.is_nearly_zero() +} + /// The dimension of an A4 page. pub const A4: Rect = Rect { x0: 0.0, @@ -846,6 +908,15 @@ pub const A4: Rect = Rect { y1: 297.0 * POINTS_PER_MM, }; +/// PdfCraft patch (44): the dimension of a US Letter page (8.5 × 11 in), the size of a page +/// that has no `/MediaBox`. +pub const LETTER: Rect = Rect { + x0: 0.0, + y0: 0.0, + x1: 8.5 * POINTS_PER_INCH, + y1: 11.0 * POINTS_PER_INCH, +}; + pub(crate) mod cached { use crate::page::{MAX_PAGE_TREE_WORK, PageTreeError, Pages}; use crate::reader::ReaderContext; @@ -928,7 +999,7 @@ mod page_tree_tests { } fn cached_with_limit(objects: &[String], limit: usize) -> Option { - let xref = crate::xref::root_xref(pdf_bytes(objects).into(), b"", DecodeLimits::default()).unwrap(); + let (xref, _) = crate::xref::root_xref(pdf_bytes(objects).into(), b"", DecodeLimits::default()).unwrap(); cached::CachedPages::new_with_limit(cached::Arc::new(xref), limit) } @@ -949,7 +1020,7 @@ mod page_tree_tests { format!("<< /Type /Pages /Kids [{kids}] /Count 1000 >>"), ]; objects.extend((0..1000).map(|_| String::from("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>"))); - let xref = crate::xref::root_xref_controlled(pdf_bytes(&objects).into(), b"", DecodeLimits::default(), Some(control)).unwrap(); + let (xref, _) = crate::xref::root_xref_controlled(pdf_bytes(&objects).into(), b"", DecodeLimits::default(), Some(control)).unwrap(); armed.store(true, Ordering::Relaxed); assert!(cached::CachedPages::new(cached::Arc::new(xref)).is_none()); assert_eq!(polls.load(Ordering::Relaxed), 100); @@ -1072,12 +1143,12 @@ mod page_tree_tests { let (width, height) = page.render_dimensions(); assert!((1.0..=1.000001).contains(&width) && (1.0..=1.000001).contains(&height), "unit={unit}: {width} by {height}"); } - // A nearly-zero crop box still falls back to A4. + // A nearly-zero crop box still falls back to US Letter (PdfCraft patch 44). for unit in [1.0, 4096.0, 75000.0] { for side in [0.0, 0.0001] { let pdf = Pdf::new(raw_crop_unit_page(unit, [0.0, 0.0, side, side])).unwrap(); let page = &pdf.pages()[0]; - let expected = (595.2755905511812_f64 as f32, 841.8897637795277_f64 as f32); + let expected = (super::LETTER.width() as f32, super::LETTER.height() as f32); assert_eq!(page.base_dimensions(), expected, "unit={unit}, side={side}"); assert_eq!(page.render_dimensions(), (expected.0 * unit as f32, expected.1 * unit as f32)); } diff --git a/vendor/hayro-syntax/src/pdf.rs b/vendor/hayro-syntax/src/pdf.rs index a67a775a92..408dfeb23b 100644 --- a/vendor/hayro-syntax/src/pdf.rs +++ b/vendor/hayro-syntax/src/pdf.rs @@ -6,7 +6,7 @@ use crate::page::Pages; use crate::page::cached::CachedPages; use crate::reader::Reader; use crate::sync::Arc; -use crate::xref::{XRef, XRefError}; +use crate::xref::{XRef, XRefError, cut_off_update_follows, fallback_controlled, root_xref_controlled}; pub use crate::crypto::DecryptionError; use crate::metadata::Metadata; @@ -101,6 +101,8 @@ pub struct Pdf { header_version: PdfVersion, pages: CachedPages, data: PdfData, + /// PdfCraft patch: (hayro-syntax (45)) see [`Pdf::rebuilt_unlinked_update`]. + rebuilt_unlinked_update: bool, } /// An error that occurred while loading a PDF file. @@ -173,8 +175,42 @@ impl Pdf { fn load(data: PdfData, password: &str, limits: DecodeLimits, control: Option) -> Result { let password = password.as_bytes(); let version = find_version(data.as_ref()).unwrap_or(PdfVersion::Pdf10); - let xref = match crate::xref::root_xref_controlled(data.clone(), password, limits, control.clone()) { - Ok(x) => x, + // PdfCraft patch: (hayro-syntax (43)) a last update cut off before its trailer is read by + // rebuilding the table from object headers, the latest definition of each object + // winning, as the document model reads such a file. Only when that finds no page is the + // older table the last `startxref` names read instead (a file cut short in the middle of + // the update, whose new page tree names pages that are not there). + // The table the last `startxref` names is read first either way: a wrong password is + // refused through it, and the rebuilt table must be encrypted exactly when it is, so a + // rebuild that missed the encryption dictionary is not taken. + let root = root_xref_controlled(data.clone(), password, limits, control.clone()); + if let Err(XRefError::Encryption(e)) = root { + return Err(LoadPdfError::Decryption(e)); + } + let root_encrypted = root.as_ref().ok().map(|(x, _)| x.has_decryptor()); + // PdfCraft patch: (hayro-syntax (45)) said of the file whichever table is kept, as + // `pdfcraft-cos` says it under the same conditions. + let rebuilt_unlinked_update = root.as_ref().is_ok_and(|(_, rebuilt)| *rebuilt); + if cut_off_update_follows(data.as_ref()) + && let Some(xref) = fallback_controlled(data.clone(), password, limits, control.clone()) + .filter(|x| root_encrypted.is_none_or(|e| e == x.has_decryptor())) + { + let xref = Arc::new(xref); + crate::cancel::check(control.as_ref()).ok_or(LoadPdfError::Invalid)?; + if let Some(pages) = CachedPages::new(xref.clone()) + && !pages.get().is_empty() + { + return Ok(Self { + xref, + header_version: version, + pages, + data, + rebuilt_unlinked_update, + }); + } + } + let xref = match root { + Ok((x, _)) => x, Err(e) => match e { XRefError::Unknown => { crate::cancel::check(control.as_ref()).ok_or(LoadPdfError::Invalid)?; @@ -188,7 +224,7 @@ impl Pdf { crate::cancel::check(control.as_ref()).ok_or(LoadPdfError::Invalid)?; let pages = CachedPages::new(xref.clone()).ok_or(LoadPdfError::Invalid)?; - Ok(Self { xref, header_version: version, pages, data }) + Ok(Self { xref, header_version: version, pages, data, rebuilt_unlinked_update }) } /// Return this document's immutable stream expansion limits. @@ -196,6 +232,13 @@ impl Pdf { self.xref.decode_limits() } + /// PdfCraft patch: (hayro-syntax (45)) whether the newest cross-reference section has no + /// `/Prev`, so the page tree in the revisions before it could only be found by rebuilding the + /// table from the file's objects. + pub fn rebuilt_unlinked_update(&self) -> bool { + self.rebuilt_unlinked_update + } + /// Return the number of objects present in the PDF file. pub fn len(&self) -> usize { self.xref.len() diff --git a/vendor/hayro-syntax/src/xref.rs b/vendor/hayro-syntax/src/xref.rs index 0d2dadb642..ad632ec592 100644 --- a/vendor/hayro-syntax/src/xref.rs +++ b/vendor/hayro-syntax/src/xref.rs @@ -13,7 +13,7 @@ use crate::object::dict::keys::{ }; use crate::object::dict::{DictCache, probe_dict}; use crate::object::indirect::IndirectObject; -use crate::object::{Array, MaybeRef}; +use crate::object::{Array, MaybeRef, ObjRef}; use crate::object::{DateTime, Dict}; use crate::object::{Object, ObjectLike}; use crate::pdf::PdfVersion; @@ -32,6 +32,17 @@ use core::ops::Deref; pub(crate) const XREF_ENTRY_LEN: usize = 20; +/// PdfCraft patch: (hayro-syntax (33)) how many references a read follows through objects that hold +/// nothing else. Past it, as any cycle goes, the object reads as a missing one. +const MAX_REFERENCE_HOPS: usize = 32; + +/// PdfCraft patch: (hayro-syntax (33)) what [`XRef::fetch`] found at an object's place. +enum Fetched { + Object(T), + /// All the object holds is a reference to this one. + Reference(ObjectIdentifier), +} + #[derive(Debug, Copy, Clone)] pub(crate) enum XRefError { Unknown, @@ -40,16 +51,47 @@ pub(crate) enum XRefError { /// Parse the "root" xref from the PDF. #[cfg(test)] -pub(crate) fn root_xref(data: PdfData, password: &[u8], limits: DecodeLimits) -> Result { +pub(crate) fn root_xref(data: PdfData, password: &[u8], limits: DecodeLimits) -> Result<(XRef, bool), XRefError> { root_xref_controlled(data, password, limits, None) } -pub(crate) fn root_xref_controlled(data: PdfData, password: &[u8], limits: DecodeLimits, control: Option) -> Result { +/// PdfCraft patch: (hayro-syntax (45)) also whether the table was rebuilt because the newest +/// section cuts off the page tree (see below). +pub(crate) fn root_xref_controlled(data: PdfData, password: &[u8], limits: DecodeLimits, control: Option) -> Result<(XRef, bool), XRefError> { let mut xref_map = FxHashMap::default(); let xref_pos = find_last_xref_pos_controlled(data.as_ref(), control.as_ref()).ok_or(XRefError::Unknown)?; let trailer = populate_xref_controlled(data.as_ref(), xref_pos, &mut xref_map, limits, control.clone()).ok_or(XRefError::Unknown)?; + // PdfCraft patch: (hayro-syntax (45)) whether the newest section names an earlier one. Its + // `/XRefStm` (a hybrid file's stream, §7.5.8.4) belongs to the same update and doesn't count, + // as `pdfcraft-cos` doesn't count it. + let linked = Reader::new(trailer) + .read_with_context::>(&ReaderContext::dummy()) + .is_some_and(|newest| prev_offset(data.as_ref(), &newest, &XrefMap::default()).is_some()); - XRef::new(data.clone(), xref_map, XRefInput::TrailerDictData(trailer), false, password, limits, control) + let xref = XRef::new(data.clone(), xref_map, XRefInput::TrailerDictData(trailer), false, password, limits, control)?; + // PdfCraft patch: (hayro-syntax (45)) an update whose section has no `/Prev` (ISO 32000-2 + // §7.5.6, §7.5.8.2) cuts off the revisions before it, and with them the page tree its catalog + // names (the signed files of PDFBOX-2720 and PDFBOX-2942). The table is rebuilt by scanning + // the file, as for a broken one, so the page tree is found rather than whatever page + // dictionaries `Pages::new_brute_force` turns up. Only when that section names no earlier + // one, the file holds another `startxref`, and the page tree can't be read: the conditions + // `pdfcraft-cos` rebuilds under, so the two agree on the pages. + let cut_off = !linked + && xref.get::>(xref.trailer_data().pages_ref).is_none() + && more_than_one_startxref(data.as_ref()); + if cut_off { + warn!("the newest xref section has no Prev and the page tree is unreachable; rebuilding the xref table"); + xref.repair(); + } + Ok((xref, cut_off)) +} + +/// PdfCraft patch: (hayro-syntax (45)) whether `data` holds an earlier `startxref` than its last. +fn more_than_one_startxref(data: &[u8]) -> bool { + let needle = b"startxref"; + findr_needle(data, needle) + .and_then(|last| data.get(..last)) + .is_some_and(|before| crate::util::find_needle(before, needle).is_some()) } /// Try to manually parse the PDF to build an xref table and trailer dictionary. @@ -395,6 +437,7 @@ impl XRef { limits, control, dict_cache: Arc::new(Mutex::new(DictCache::default())), + object_stream_indexes: Arc::new(Mutex::new(ObjectStreamIndexes::default())), }))); // We read the trailer twice, once to determine the encryption used and then a second @@ -603,7 +646,11 @@ impl XRef { iter::from_fn(move || { for next in iter.by_ref() { crate::cancel::check(control)?; - if let Some(obj) = self.get_with(next.0, &ReaderContext::new(self, false)) { + // PdfCraft patch: (hayro-syntax (33)) an object that only refers to another + // isn't one of its own: followed, that one came out once more for each. + if let Some(Fetched::Object(obj)) = + self.fetch(next.0, &ReaderContext::new(self, false)) + { return Some(obj); } else { // Skip invalid objects. @@ -639,6 +686,15 @@ impl XRef { locked.xref_map = xref_map; } + /// PdfCraft patch: (hayro-syntax (43)) whether objects read through this table are + /// decrypted. + pub(crate) fn has_decryptor(&self) -> bool { + match &self.0 { + Inner::Dummy => false, + Inner::Some(r) => !matches!(r.decryptor.as_ref(), Decryptor::None), + } + } + #[inline] pub(crate) fn needs_decryption(&self, ctx: &ReaderContext<'_>) -> bool { match &self.0 { @@ -658,7 +714,7 @@ impl XRef { &self, id: ObjectIdentifier, data: &[u8], - target: DecryptionTarget, + target: DecryptionTarget<'_>, ) -> Option> { match &self.0 { Inner::Dummy => Some(data.to_vec()), @@ -677,6 +733,10 @@ impl XRef { } /// Return the object with the given identifier. + /// + /// PdfCraft patch: (hayro-syntax (33)) an object that holds only a reference stands for what + /// that names. Read as a number it was the reference's own object number, and as anything else + /// it was lost. This is a loop, so a long chain takes no stack. #[allow(private_bounds)] pub(crate) fn get_with<'a, T>( &'a self, @@ -687,6 +747,38 @@ impl XRef { T: ObjectLike<'a>, { crate::cancel::check(ctx.control())?; + let mut id = id; + for _ in 0..=MAX_REFERENCE_HOPS { + match self.fetch::(id, ctx)? { + Fetched::Object(object) => return Some(object), + Fetched::Reference(next) => id = next, + } + } + warn!("references lead on past the limit, or in a cycle: {id:?}"); + + None + } + + /// PdfCraft patch: (hayro-syntax (33)) the object stream `id`. It has to be a stream stored as + /// that object (ISO 32000-2 7.5.7), so this follows no reference: the check of where it is stored + /// is of that object, and one reached through a reference could be a stream stored inside + /// another. + pub(crate) fn object_stream<'a>( + &'a self, + id: ObjectIdentifier, + ctx: &ReaderContext<'a>, + ) -> Option> { + match self.fetch::>(id, ctx)? { + Fetched::Object(stream) => Some(stream), + Fetched::Reference(_) => None, + } + } + + /// What is stored at the object with the given identifier. + fn fetch<'a, T>(&'a self, id: ObjectIdentifier, ctx: &ReaderContext<'a>) -> Option> + where + T: ObjectLike<'a>, + { let Inner::Some(repr) = &self.0 else { return None; }; @@ -712,6 +804,10 @@ impl XRef { ctx.set_in_object_stream(false); r.jump(offset); + if let Some(next) = held_reference(r.clone(), id) { + return Some(Fetched::Reference(next)); + } + if let Some(object) = r.read_with_context::>(&ctx) { // PdfCraft patch: in a table rebuilt by scanning the file, the object number // is what identifies an object. There is no revision history to tell two @@ -720,7 +816,7 @@ impl XRef { // make the object unreadable through the reference that names it (#5580). A // table read from the file's own xref keeps the exact match. if object.id() == &id || (repaired && object.id().obj_number == id.obj_number) { - return Some(object.get()); + return Some(Fetched::Object(object.get())); } } else { // PdfCraft patch: the strict read of the header failed. In a table rebuilt by @@ -732,7 +828,7 @@ impl XRef { && let Some(object) = read_repaired_body::(repr.data.get().as_ref(), offset, id, &ctx) { - return Some(object); + return Some(Fetched::Object(object)); } // There is a valid object at the offset, it's just not of the type the caller // expected, which is fine. @@ -754,7 +850,7 @@ impl XRef { self.repair(); // Now try reading again. - self.get_with::(id, &ctx) + self.fetch::(id, &ctx) } } EntryType::ObjStream(obj_stram_gen_num, index) => { @@ -780,11 +876,19 @@ impl XRef { let data = repr.data.get_with(obj_stream_id, &ctx)?; // PdfCraft patch: the offset table is parsed once per stream (see Data). let offsets = repr.data.object_offsets(obj_stream_id, || { - let stream = self.get_with::>(obj_stream_id, &ctx)?; - ObjectStream::offsets(stream, data) + let _loading = repr.data.enter_loading(obj_stream_id)?; + let Fetched::Object(dict) = self.fetch::>(obj_stream_id, &ctx)? else { + return None; + }; + let num_objects = dict.get::(N)?; + let first_offset = dict.get::(FIRST)?; + read_object_stream_index(num_objects, first_offset, data) })?; let object_stream = ObjectStream::with_offsets(offsets, data, &ctx); - object_stream.get(index) + if let Some(next) = object_stream.reference(index) { + return Some(Fetched::Reference(next)); + } + object_stream.get(index).map(Fetched::Object) } } } @@ -837,6 +941,85 @@ fn find_last_xref_pos_controlled(data: &[u8], control: Option<&crate::cancel::Co finder.read_without_context::()?.try_into().ok() } +const STARTXREF_TAIL: usize = 4096; + +/// PdfCraft patch: (hayro-syntax (43)) whether the last update of the file was cut off before its +/// own cross-reference section and trailer: the last `startxref` is not near the end of the file +/// and objects follow it. That section would supersede the older ones (ISO 32000-2 §7.5.6), so +/// the update's objects are the document; reading the older table the last `startxref` names +/// shows a revision the document model (`pdfcraft-cos`, which rebuilds such a file from its +/// object headers) does not have. A `startxref` near the end, or one followed only by other data +/// (trailing junk), is no cut-off update. +pub(crate) fn cut_off_update_follows(data: &[u8]) -> bool { + let needle = b"startxref"; + findr_needle(data, needle).is_some_and(|pos| { + pos < data.len().saturating_sub(STARTXREF_TAIL) + && data + .get(pos.saturating_add(needle.len())..) + .is_some_and(has_object_header) + }) +} + +/// PdfCraft patch: (hayro-syntax (43)) whether `data` holds an `N G obj` header: two runs of +/// digits and the keyword, separated by white space, at the start of the data or after white +/// space or `>`, the keyword ended by white space, a delimiter or the end of the data (ISO +/// 32000-2 §7.2.3, Table 2), as the document model's repair scan reads it: `1 0 obj_name` is +/// no header, and neither is one whose object number doesn't fit 32 bits (`4294967296 0 obj`), +/// which that scan skips too. One linear pass, no allocation. +fn has_object_header(data: &[u8]) -> bool { + let digits = |from: usize| { + data.get(from..).map_or(0, |rest| { + rest.iter().take_while(|b| b.is_ascii_digit()).count() + }) + }; + let spaces = |from: usize| { + data.get(from..).map_or(0, |rest| { + rest.iter() + .take_while(|&&b| is_white_space_character(b)) + .count() + }) + }; + let mut i = 0; + while i < data.len() { + let at_start = i + .checked_sub(1) + .and_then(|prev| data.get(prev)) + .is_none_or(|&b| is_white_space_character(b) || b == b'>'); + let n = if at_start { digits(i) } else { 0 }; + if n == 0 { + i += 1; + continue; + } + let mut at = i + n; + let s1 = spaces(at); + at += s1; + let g = digits(at); + at += g; + let s2 = spaces(at); + at += s2; + // The object number as the model reads it, a 32-bit unsigned integer. + let number_fits = data + .get(i..i + n) + .and_then(|d| core::str::from_utf8(d).ok()) + .is_some_and(|d| d.parse::().is_ok()); + if number_fits + && s1 > 0 + && g > 0 + && s2 > 0 + && data.get(at..).is_some_and(|rest| rest.starts_with(b"obj")) + && data.get(at + 3).is_none_or(|&b| { + is_white_space_character(b) + || matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') + }) + { + return true; + } + // Past the digits read: none of them starts a header. + i += n; + } + false +} + /// A type of xref entry. #[derive(Debug, PartialEq, Eq, Clone, Copy)] enum EntryType { @@ -919,6 +1102,7 @@ impl TrailerData { #[derive(Debug, Clone)] struct SomeRepr { dict_cache: Arc>, + object_stream_indexes: Arc>, data: Arc, map: Arc>, metadata: Arc, @@ -1344,6 +1528,37 @@ fn get_decryptor(trailer_dict: &Dict<'_>, password: &[u8]) -> Result>>>; + +/// The `(object number, offset)` pairs at the start of an object stream's decoded `data`, the +/// offsets measured from the start of `data`. `None` when the pairs don't parse. Reads no +/// further than the data holds, whatever `/N` claims. +fn read_object_stream_index( + num_objects: usize, + first_offset: usize, + data: &[u8], +) -> Option> { + let mut r = Reader::new(data); + + let mut offsets = vec![]; + + for _ in 0..num_objects { + r.skip_white_spaces_and_comments(); + // Skip object number + let obj_num = r.read_without_context::()?; + r.skip_white_spaces_and_comments(); + let relative_offset = r.read_without_context::()?; + // PdfCraft patch: (hayro-syntax (22)) an offset past `usize` is malformed (it wrapped). + offsets.push((obj_num, first_offset.checked_add(relative_offset)?)); + } + + Some(offsets) +} + struct ObjectStream<'a> { data: &'a [u8], ctx: ReaderContext<'a>, @@ -1366,6 +1581,7 @@ impl<'a> ObjectStream<'a> { fn offsets(inner: Stream<'_>, data: &[u8]) -> Option> { let num_objects = inner.dict().get::(N)?; let first_offset = inner.dict().get::(FIRST)?; + let offsets = read_object_stream_index(num_objects, first_offset, data)?; let mut r = Reader::new(data); r.set_control(inner.dict().ctx().control().cloned()); @@ -1397,6 +1613,28 @@ impl<'a> ObjectStream<'a> { r.read_with_context::(&self.ctx) } + + /// PdfCraft patch: (hayro-syntax (33)) what the object at `index` refers to, when a reference is + /// all it holds. + fn reference(&self, index: u32) -> Option { + let offset = self.offsets.get(index as usize)?.1; + let mut r = Reader::new(self.data); + r.jump(offset); + r.skip_white_spaces_and_comments(); + + Some(r.read_without_context::()?.into()) + } +} + +/// PdfCraft patch: (hayro-syntax (33)) what the indirect object `id` at `r` refers to, when a +/// reference is all it holds. +fn held_reference(mut r: Reader<'_>, id: ObjectIdentifier) -> Option { + if r.read_without_context::()? != id { + return None; + } + r.skip_white_spaces_and_comments(); + + Some(r.read_without_context::()?.into()) } fn parse_metadata(info_dict: &Dict<'_>) -> Metadata { @@ -1431,7 +1669,206 @@ fn parse_metadata(info_dict: &Dict<'_>) -> Metadata { #[cfg(test)] mod tests { use super::*; + use crate::Pdf; + /// A file with an xref stream: `stored` are objects on their own, as they would follow + /// `n 0 obj`, and `packed` says of each object in an object stream which stream and place. + fn with_xref_stream(stored: &[(u32, Vec)], packed: &[(u32, u32, u16)]) -> Vec { + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = alloc::collections::BTreeMap::new(); + for (num, body) in stored { + offsets.insert(*num, out.len()); + out.extend_from_slice(alloc::format!("{num} 0 obj ").as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let last = stored.iter().map(|o| o.0).chain(packed.iter().map(|o| o.0)).max().unwrap_or(0); + let (xref, size) = (last + 1, last + 2); + let at = out.len(); + offsets.insert(xref, at); + let packed: alloc::collections::BTreeMap = packed.iter().map(|o| (o.0, (o.1, o.2))).collect(); + let mut rows = Vec::new(); + for num in 0..size { + if let Some(offset) = offsets.get(&num) { + rows.push(1); + rows.extend_from_slice(&(*offset as u32).to_be_bytes()); + rows.extend_from_slice(&[0, 0]); + } else if let Some((stream, index)) = packed.get(&num) { + rows.push(2); + rows.extend_from_slice(&stream.to_be_bytes()); + rows.extend_from_slice(&index.to_be_bytes()); + } else { + rows.extend_from_slice(&[0; 7]); + } + } + out.extend_from_slice( + alloc::format!( + "{xref} 0 obj << /Type /XRef /Size {size} /W [1 4 2] /Root 1 0 R /Length {} >> stream\n", + rows.len() + ) + .as_bytes(), + ); + out.extend_from_slice(&rows); + out.extend_from_slice(alloc::format!("\nendstream endobj\nstartxref\n{at}\n%%EOF\n").as_bytes()); + out + } + + /// `/Type /ObjStm` around `members`, each stored at its offset, and `entries` of its own. + fn object_stream_of(members: &[(u32, &[u8])], entries: &str) -> Vec { + let (mut head, mut body) = (alloc::string::String::new(), Vec::new()); + for (num, member) in members { + head.push_str(&alloc::format!("{num} {} ", body.len())); + body.extend_from_slice(member); + body.push(b'\n'); + } + head.push('\n'); + let dict = alloc::format!( + "<< /Type /ObjStm /N {} /First {} /Length {} {entries} >> stream\n", + members.len(), + head.len(), + head.len() + body.len() + ); + let mut out = dict.into_bytes(); + out.extend_from_slice(head.as_bytes()); + out.extend_from_slice(&body); + out.extend_from_slice(b"\nendstream"); + out + } + + fn page_objects() -> Vec<(u32, Vec)> { + vec![ + (1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()), + (2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()), + (3, b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_vec()), + ] + } + + /// An object stream is a stream stored as that object, however many references lead to one. + /// Object 10 holds a reference to 11, a stream stored inside object stream 12, and 31 claims to + /// be in 10, with 11's `/N`, `/First` or `/Length` being 31: reading it recursed until the + /// stack ran out. It reads as missing, and so does a member of such a stream. + #[test] + fn an_object_stream_isnt_reached_through_a_reference() { + for key in ["N", "First", "Length"] { + let inner = alloc::format!("<< /Type /ObjStm /{key} 31 0 R >> stream\n31 0 1\n\nendstream"); + let mut stored = page_objects(); + stored.push((10, b"11 0 R".to_vec())); + stored.push((12, object_stream_of(&[(11, inner.as_bytes())], ""))); + let pdf = Pdf::new(with_xref_stream(&stored, &[(11, 12, 0), (31, 10, 0)])).unwrap(); + assert_eq!(pdf.xref().get::(ObjectIdentifier::new(31, 0)), None, "{key}"); + } + let inner = b"<< /Type /ObjStm /N 1 /First 5 /Length 8 >> stream\n20 0 7\n\nendstream"; + let mut stored = page_objects(); + stored.push((10, b"11 0 R".to_vec())); + stored.push((12, object_stream_of(&[(11, inner)], ""))); + let pdf = Pdf::new(with_xref_stream(&stored, &[(11, 12, 0), (20, 10, 0)])).unwrap(); + assert_eq!(pdf.xref().get::(ObjectIdentifier::new(20, 0)), None); + } + + /// `count` object streams stored as themselves, the `keys` of each a member of the next, or + /// with `ring` of the first after the last. Reading the first member reads them all, and it is + /// `count + 100` to tell. + #[cfg(feature = "std")] + fn chain_of_object_streams(count: u32, keys: &[&str], ring: bool) -> Vec { + let mut stored = page_objects(); + let mut packed = Vec::new(); + for i in 0..count { + let (stream, member) = (100 + 2 * i, 101 + 2 * i); + let value = if i == 0 { count + 100 } else { 1 }; + let data = alloc::format!("{member} 0 \n{value}\n"); + let (first, length) = (alloc::format!("{}", alloc::format!("{member} 0 \n").len()), alloc::format!("{}", data.len())); + let next = match (i + 1 == count, ring) { + (true, true) => "101 0 R".into(), + (true, false) => "1".into(), + _ => alloc::format!("{} 0 R", member + 2), + }; + let entry = |key, own: &'_ str| if keys.contains(&key) { next.clone() } else { own.into() }; + let (n, first, length): (alloc::string::String, alloc::string::String, alloc::string::String) = + (entry("N", "1"), entry("First", &first), entry("Length", &length)); + let body = alloc::format!("<< /Type /ObjStm /N {n} /First {first} /Length {length} >> stream\n{data}\nendstream"); + stored.push((stream, body.into_bytes())); + packed.push((member, stream, 0)); + } + with_xref_stream(&stored, &packed) + } + + /// A chain of object streams, each with a member of the next for its `/N`, `/First` or + /// `/Length`, had no limit: one read recursed through all of them, holding a copy of the chain + /// at each, and 50,000 ran out of an 8 MiB stack. It stops at the gate's limit, on half the stack + /// of a render worker. Past that `/N` and `/First` can't be read, so the member reads as missing, + /// and a `/Length` that can't be read falls back on `endstream`, so it reads. A short chain reads. + #[cfg(feature = "std")] + #[test] + fn a_chain_of_object_streams_ends_at_the_limit_of_nested_loads() { + for key in ["N", "First", "Length"] { + let pdf = chain_of_object_streams(50_000, &[key], false); + std::thread::Builder::new() + .stack_size(1 << 20) + .spawn(move || { + let pdf = Pdf::new(pdf).unwrap(); + let read = pdf.xref().get::(ObjectIdentifier::new(101, 0)); + assert_eq!(read, (key == "Length").then_some(50_100), "{key}"); + }) + .unwrap() + .join() + .unwrap(); + } + let pdf = Pdf::new(chain_of_object_streams(10, &["N"], false)).unwrap(); + assert_eq!(pdf.xref().get::(ObjectIdentifier::new(101, 0)), Some(110)); + } + + /// `/Length` and `/N` or `/First` both by reference were two ways to the next stream's index, + /// and an index that fails isn't remembered, so the work doubled at each stream: 65 streams, one + /// past the limit, in 8 KB, didn't finish, and other threads waited at the gate. The index reads + /// the dictionary alone now. Without that this doesn't end, so the time allowed can't fail it. + #[cfg(feature = "std")] + #[test] + fn a_chain_of_object_streams_takes_no_more_work_for_two_ways_on() { + for (count, ring) in [(65, false), (20, true), (5_000, false)] { + for keys in [&["Length", "N"][..], &["Length", "First"]] { + let pdf = chain_of_object_streams(count, keys, ring); + let (done, finished) = std::sync::mpsc::channel(); + std::thread::Builder::new() + .stack_size(1 << 20) + .spawn(move || { + let pdf = Pdf::new(pdf).unwrap(); + let _ = pdf.xref().get::(ObjectIdentifier::new(101, 0)); + let _ = done.send(()); + }) + .unwrap(); + assert!(finished.recv_timeout(std::time::Duration::from_secs(120)).is_ok(), "{keys:?} of {count}"); + } + } + } + + /// Object 5, a member of a real object stream, holds a reference to object 6 stored on its own, + /// and 7, stored on its own, to 8, a member: each reads as what it names. + #[test] + fn a_reference_held_in_either_storage_is_followed() { + let mut stored = page_objects(); + stored.push((6, b"42".to_vec())); + stored.push((7, b"8 0 R".to_vec())); + stored.push((9, object_stream_of(&[(5, b"6 0 R"), (8, b"43")], ""))); + let pdf = Pdf::new(with_xref_stream(&stored, &[(5, 9, 0), (8, 9, 1)])).unwrap(); + assert_eq!(pdf.xref().get::(ObjectIdentifier::new(5, 0)), Some(42)); + assert_eq!(pdf.xref().get::(ObjectIdentifier::new(7, 0)), Some(43)); + } + + /// With no page tree, every page object is a page, and one that another object only refers to + /// is one page, not two. + #[test] + fn a_page_a_reference_is_held_to_is_found_once() { + let mut stored = page_objects(); + stored[0].1 = b"<< /Type /Catalog /Pages 99 0 R >>".to_vec(); + stored[2].1 = b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] /Contents 4 0 R >>".to_vec(); + stored.push((4, b"<< /Length 0 >> stream\n\nendstream".to_vec())); + stored.push((12, b"3 0 R".to_vec())); + let pdf = Pdf::new(with_xref_stream(&stored, &[])).unwrap(); + assert_eq!(pdf.pages().len(), 1); + } + + // PdfCraft patch tests (ported from craft-libs): xref stream entries are bounded by the + // decoded data, and the type field is read at its full width. #[test] fn cancellation_stops_before_a_whole_xref_subsection_is_read() { let data = vec![1; 512 * 1024]; @@ -1917,6 +2354,15 @@ mod tests { let pdf = crate::Pdf::new(twice.as_bytes().to_vec()).unwrap(); assert_eq!(pdf.pages()[0].render_dimensions(), (300.0, 150.0), "`3 0 R` reads the later body, as `3 1` does"); } + + + /// PdfCraft patch: (hayro-syntax (22)) an object's offset past `usize` is malformed: a plain + /// `+` there panics in a debug build and wraps in a release one. + #[test] + fn an_object_stream_offset_past_usize_is_malformed_not_a_panic() { + assert_eq!(read_object_stream_index(1, usize::MAX, b"5 1"), None); + assert_eq!(read_object_stream_index(1, 10, b"5 1"), Some(vec![(5, 11)])); + } } #[cfg(test)] diff --git a/vendor/hayro/src/lib.rs b/vendor/hayro/src/lib.rs index bd6468c808..64eda4bf89 100644 --- a/vendor/hayro/src/lib.rs +++ b/vendor/hayro/src/lib.rs @@ -61,10 +61,16 @@ use vello_cpu::{Level, Pixmap, RenderMode}; mod renderer; /// PdfCraft patch: exported for its regression test. -pub use renderer::{image_resampling_size, tiling_cell_scale, usable_cell_scale}; +pub use renderer::{image_resampling_size, tiling_cell_pixels, tiling_cell_scale, usable_cell_scale}; /// PdfCraft patch: exported for its regression test. #[doc(hidden)] pub use renderer::set_skip_offscreen_paths; +/// PdfCraft patch (27): exported for its regression test. +#[doc(hidden)] +pub use renderer::set_cmyk_band_pixels; +/// PdfCraft patch (30): exported for its regression tests. +#[doc(hidden)] +pub use renderer::{OffscreenDraws, offscreen_draws}; /// A cache used by the renderer. /// @@ -157,6 +163,10 @@ pub struct RenderSettings { /// PdfCraft patch: when set, solid text and line-art paint colours are remapped while /// rendering; `None` renders exactly as without the patch. pub color_replacement: Option, + /// PdfCraft patch (31): the most coverage values the rasterizer keeps for the page; paths + /// past it are left out, with `InterpreterWarning::ContentTruncated`. `None` keeps as many + /// as a strip's index reaches (2^31). + pub max_coverage: Option, } impl Default for RenderSettings { @@ -170,6 +180,7 @@ impl Default for RenderSettings { x_offset: 0.0, y_offset: 0.0, color_replacement: None, + max_coverage: None, } } } @@ -254,6 +265,11 @@ pub fn render_into<'a>( interpreter_settings.preview, ); + // NOTE: vello_cpu in craft-libs is unvendored (0.0.8) and does not yet expose + // `set_max_coverage` / `coverage_full`; `render_settings.max_coverage` is preserved + // on `RenderSettings` for API parity with pdfcraft. + let _ = render_settings.max_coverage; + // PdfCraft patch (18): the page renders as one transparency group (the page group). Its // objects composite with an initially transparent backdrop, and the group is then put on // the paper (ISO 32000-2, page group), so a blend mode only blends where something was diff --git a/vendor/hayro/src/renderer.rs b/vendor/hayro/src/renderer.rs index a9329dae2c..2fff246bfb 100644 --- a/vendor/hayro/src/renderer.rs +++ b/vendor/hayro/src/renderer.rs @@ -193,6 +193,67 @@ fn image_buffer(len: usize) -> Option> { Some(out) } +/// PdfCraft patch: `mask` sampled onto the grid of a `width` × `height` image (no side smaller +/// than the mask's). Each image sample takes the mask sample under its centre or, for a mask that +/// asks for `/Interpolate`, the bilinear blend of the four around it, so the mask's edges stay as +/// smooth as when it was enlarged on its own. `None` for an empty side, an image side smaller than +/// the mask's, or a buffer over the limits. +fn mask_on_image_grid(mask: &LumaData, width: u32, height: u32) -> Option> { + if width == 0 || height == 0 || mask.width == 0 || mask.height == 0 { + return None; + } + let mut out = image_buffer(source_byte_len(width, height, 1, MAX_IMAGE_PIXELS)?)?; + let columns = grid_axis(mask.width, width, mask.interpolate)?; + let rows = grid_axis(mask.height, height, mask.interpolate)?; + let mask_width = mask.width as usize; + let row = |y: usize| { + let start = y.checked_mul(mask_width)?; + mask.data.get(start..start.checked_add(mask_width)?) + }; + let one = u64::from(GRID_ONE); + for &(y0, y1, fy) in &rows { + let (top, bottom, fy) = (row(y0)?, row(y1)?, u64::from(fy)); + for &(x0, x1, fx) in &columns { + let fx = u64::from(fx); + let blend = |r: &[u8]| Some(u64::from(*r.get(x0)?) * (one - fx) + u64::from(*r.get(x1)?) * fx); + // At most 255 × GRID_ONE², so the sum fits in a u64 and the result in a u8. + let v = (blend(top)? * (one - fy) + blend(bottom)? * fy + one * one / 2) / (one * one); + out.push(v.min(255) as u8); + } + } + Some(out) +} + +/// PdfCraft patch: fixed-point unit of [`grid_axis`]'s blend weights. +const GRID_ONE: u32 = 1 << 16; + +/// PdfCraft patch: for each of `dst` samples (`dst >= src`) taken from `src` along one axis, the +/// two source samples it lies between and the weight of the second, in [`GRID_ONE`] units. +/// Centres line up: target `t` lies at `(t + ½)·src/dst − ½` source samples, held to the ends. +/// Without `smooth` both are the nearest sample, so the weight does not matter. +fn grid_axis(src: u32, dst: u32, smooth: bool) -> Option> { + if src == 0 || dst < src { + return None; + } + let mut out = Vec::new(); + out.try_reserve_exact(dst as usize).ok()?; + let last = u64::from(src - 1) << 16; + for t in 0..dst { + if !smooth { + let s = nearest_source_index(src, dst, t); + out.push((s, s, 0)); + continue; + } + // In u128, as `(2t + 1)·src·2^16` can pass 2^64 for a long side; the quotient is at + // most `src·2^16`, so it fits back in a u64. + let centre = ((2 * u128::from(t) + 1) * u128::from(src) << 16) / (2 * u128::from(dst)); + let at = u64::try_from(centre).ok()?.saturating_sub(u64::from(GRID_ONE / 2)).min(last); + let s = (at >> 16) as usize; + out.push((s, (s + 1).min(src as usize - 1), (at & 0xFFFF) as u32)); + } + Some(out) +} + /// PdfCraft patch (#624): the source index that PicScale's nearest-neighbour plan copies for /// destination `index` of `dst` samples taken from `src`. It is the same fixed-point centre /// sampling as `ResampleNearestPlan`, so these are the samples a nearest resize would copy. @@ -236,6 +297,255 @@ fn nearest_premultiplied_rgba( Some(out) } +/// PdfCraft patch: the shorter side, in samples, from which an image that did not ask for +/// `/Interpolate` is still smoothed when enlarged. A page scanned at 72 dpi is 612 samples wide; +/// icons, QR codes and pixel art are usually far smaller and keep their hard pixels. +const SMOOTHED_IMAGE_SIDE: u32 = 512; + +/// PdfCraft patch: the scale above which such an image counts as enlarged. A scan drawn at its own +/// resolution can come out a few ulps above 1 (the scale is an `f32`: a 192 dpi scan on a 2× +/// display at 100%), and sampled bilinearly at a half-pixel offset it blurred by half a pixel. +/// Below 1% nearest-neighbour repeats at most one sample in a hundred. +const SMOOTHED_IMAGE_SCALE: f32 = 1.01; + +/// PdfCraft patch: fixed-point unit of [`area_shrink`]'s weights. +const AREA_ONE: u64 = 1 << 16; + +/// PdfCraft patch: the source samples target sample `t` covers when `src` samples shrink to `dst` +/// (`dst <= src`), with their weights in [`AREA_ONE`] units. Target `t` spans `[t·src, (t+1)·src)` +/// and source `s` spans `[s·dst, (s+1)·dst)`, both in units of 1/(src·dst) of the axis, so every +/// overlap is exact. The weights are differences of one rounded running sum, so they add up to +/// exactly [`AREA_ONE`] and a flat area keeps its exact value. +fn area_taps(src: u32, dst: u32, t: u32) -> impl Iterator { + let (src, dst, t) = (u64::from(src), u64::from(dst), u64::from(t)); + // `t < dst <= src <= 2^28` (MAX_IMAGE_PIXELS), so every product below fits in a u64. + let (lo, hi) = (t * src, (t + 1) * src); + let fixed = move |x: u64| (x * AREA_ONE + src / 2) / src; + (lo / dst..hi.div_ceil(dst)).map(move |s| { + let from = (s * dst).max(lo) - lo; + let to = ((s + 1) * dst).min(hi) - lo; + (s as usize, fixed(to) - fixed(from)) + }) +} + +/// PdfCraft patch: [`area_taps`] of every target sample of one axis, worked out once: for each +/// target, the first source sample it covers and the weights of the samples from there on (the +/// samples a target covers are consecutive). There are at most `src + dst` taps in all. +struct AreaAxis { + first: Vec, + /// Where each target's weights start in `weights`, and where the last one's end. + offsets: Vec, + weights: Vec, +} + +impl AreaAxis { + fn new(src: u32, dst: u32) -> Option { + let n = dst as usize; + let (mut first, mut offsets, mut weights) = (Vec::new(), Vec::new(), Vec::new()); + first.try_reserve_exact(n).ok()?; + offsets.try_reserve_exact(n.checked_add(1)?).ok()?; + weights.try_reserve_exact((src as usize).checked_add(n.checked_mul(2)?)?).ok()?; + offsets.push(0); + for t in 0..dst { + let mut start = None; + for (s, w) in area_taps(src, dst, t) { + start.get_or_insert(s); + // A weight is at most AREA_ONE, so it fits in a u32. + weights.push(w as u32); + } + first.push(start?); + offsets.push(weights.len()); + } + Some(Self { first, offsets, weights }) + } + + /// Target `t`'s first source sample and its weights. + fn get(&self, t: usize) -> Option<(usize, &[u32])> { + let (lo, hi) = (*self.offsets.get(t)?, *self.offsets.get(t.checked_add(1)?)?); + Some((*self.first.get(t)?, self.weights.get(lo..hi)?)) + } +} + +/// PdfCraft patch: shrinks `N`-channel samples from `source` to `target` (no side larger than its +/// source side) by area averaging: each target sample is the mean of the source it covers, +/// weighted by how much of it it covers. Nothing is invented between samples, which is what +/// `/Interpolate` governs (ISO 32000-2 §8.9.5.3, for images drawn above their resolution), and +/// nothing is dropped: nearest-neighbour keeps one sample in N per axis, so a scan shown at screen +/// size lost the strokes of its text. Premultiplied input stays premultiplied. `None` if nothing +/// shrinks, the sizes don't fit or a buffer cannot be allocated. +fn area_shrink(data: &[u8], source: (u32, u32), target: (u32, u32)) -> Option> { + if data.len() != source_byte_len(source.0, source.1, N, MAX_IMAGE_PIXELS)? { + return None; + } + let row_len = (source.0 as usize).checked_mul(N)?; + area_shrink_rows::(source, target, |s, row| { + let start = s.checked_mul(row_len)?; + row.copy_from_slice(data.get(start..start.checked_add(row_len)?)?); + Some(()) + }) +} + +/// PdfCraft patch: [`area_shrink`] of a colour image under its same-size soft mask (a stencil's +/// ink under the stencil, or an image under a mask sampled onto its grid), premultiplied a source +/// row at a time as it is averaged. The result equals premultiplying the expanded RGBA and +/// shrinking that, without building it: a 10718 × 13701 stencil shown at page size peaked at +/// 1.16 GB with the full-resolution RGBA, which is 587 MB. +fn area_shrink_premultiplied( + color: &ImageData, + alpha: &[u8], + source: (u32, u32), + target: (u32, u32), +) -> Option> { + let (samples, channels) = match color { + ImageData::Luma(luma) => (luma.data.as_slice(), 1), + ImageData::Rgb(rgb) => (rgb.data.as_slice(), 3), + }; + if samples.len() != source_byte_len(source.0, source.1, channels, MAX_IMAGE_PIXELS)? + || alpha.len() != source_byte_len(source.0, source.1, 1, MAX_IMAGE_PIXELS)? + { + return None; + } + let width = source.0 as usize; + area_shrink_rows::<4>(source, target, |s, row| { + let start = s.checked_mul(width)?; + let end = start.checked_add(width)?; + let colors = samples.get(start.checked_mul(channels)?..end.checked_mul(channels)?)?; + let alphas = alpha.get(start..end)?; + for ((out, px), a) in row.chunks_exact_mut(4).zip(colors.chunks_exact(channels)).zip(alphas) { + let [r, g, b] = match px { + [v] => [*v; 3], + [r, g, b] => [*r, *g, *b], + _ => return None, + }; + out.copy_from_slice(&AlphaColor::from_rgba8(r, g, b, *a).premultiply().to_rgba8().to_u8_array()); + } + Some(()) + }) +} + +/// PdfCraft patch: the area shrink behind [`area_shrink`], reading source row `s` through +/// `read_row(s, row)` into a buffer of one row. Each target row averages the source rows it +/// covers, and that row is shrunk across at once with taps worked out once per image, so work +/// memory is one source row of samples, one of `u32` accumulators, one shrunk row and the +/// horizontal taps (at most `sw + 2 × tw`): never the image. A side over +/// `MAX_RESAMPLING_SOURCE_SIDE` is refused, so none of it exceeds a few times one source row. +fn area_shrink_rows( + source: (u32, u32), + target: (u32, u32), + mut read_row: impl FnMut(usize, &mut [u8]) -> Option<()>, +) -> Option> { + let ((sw, sh), (tw, th)) = (source, target); + // A side over MAX_RESAMPLING_SOURCE_SIDE would make the accumulator row and the tap table + // several times larger than the samples (a 2^27 × 2 image of zeros is a tiny file). + if tw == 0 + || th == 0 + || tw > sw + || th > sh + || (tw, th) == (sw, sh) + || sw > MAX_RESAMPLING_SOURCE_SIDE + || sh > MAX_RESAMPLING_SOURCE_SIDE + { + return None; + } + let row_len = (sw as usize).checked_mul(N)?; + let zeroed = |len: usize| { + let mut v = image_buffer(len)?; + v.resize(len, 0); + Some(v) + }; + let (mut source_row, mut shrunk_row) = (zeroed(row_len)?, image_buffer(row_len)?); + let mut acc: Vec = Vec::new(); + acc.try_reserve_exact(row_len).ok()?; + acc.resize(row_len, 0); + // The taps depend only on the widths, so they are worked out once, not again for each row. + let taps = if tw == sw { None } else { Some(AreaAxis::new(sw, tw)?) }; + let out_len = match taps { + None => source_byte_len(tw, th, N, MAX_IMAGE_PIXELS)?, + Some(_) => image_byte_len(tw, th, N, MAX_IMAGE_PIXELS)?, + }; + let mut out = image_buffer(out_len)?; + // Weights sum to AREA_ONE (2^16) and samples are at most 255, so every sum fits in a u32. + let round = |acc: u32| ((acc + (AREA_ONE as u32) / 2) >> 16).min(255) as u8; + // The last source row read: neighbouring target rows share the row on their boundary. + let mut loaded = None; + for t in 0..th { + // Vertical: the whole source rows target row `t` covers, averaged. + let row: &[u8] = if th == sh { + read_row(t as usize, &mut source_row)?; + &source_row + } else { + acc.fill(0); + for (s, w) in area_taps(sh, th, t) { + if loaded != Some(s) { + read_row(s, &mut source_row)?; + loaded = Some(s); + } + // A weight is at most AREA_ONE, so it fits in a u32. + let w = w as u32; + for (a, v) in acc.iter_mut().zip(&source_row) { + *a += w * u32::from(*v); + } + } + shrunk_row.clear(); + shrunk_row.extend(acc.iter().map(|a| round(*a))); + &shrunk_row + }; + // Horizontal: that row shrunk to `tw` samples. + let Some(taps) = &taps else { + out.extend_from_slice(row); + continue; + }; + for x in 0..tw as usize { + let (first, weights) = taps.get(x)?; + let samples = row.get(first * N..(first + weights.len()) * N)?; + let mut acc = [0_u32; N]; + for (w, px) in weights.iter().zip(samples.chunks_exact(N)) { + for (a, v) in acc.iter_mut().zip(px) { + *a += w * u32::from(*v); + } + } + out.extend(acc.map(round)); + } + } + Some(out) +} + +/// PdfCraft patch: [`area_shrink`] for an image's pixel format. If it cannot run, the image keeps +/// its source resolution, as when [`Renderer::resize_image_data`] fails. +fn area_resize( + data: Vec, + source: (u32, u32), + target: (u32, u32), + format: ImagePixelFormat, +) -> (Vec, u32, u32) { + let shrunk = match format { + ImagePixelFormat::Luma => area_shrink::<1>(&data, source, target), + ImagePixelFormat::Rgb => area_shrink::<3>(&data, source, target), + ImagePixelFormat::Rgba => area_shrink::<4>(&data, source, target), + }; + match shrunk { + Some(out) => (out, target.0, target.1), + None => { + log::warn!( + "Image area shrink failed or exceeded its buffer limit; falling back to source data" + ); + (data, source.0, source.1) + } + } +} + +/// PdfCraft patch: premultiplies straight RGBA samples in place. +fn premultiply_rgba(rgba: &mut [u8]) { + let (chunks, _) = rgba.as_chunks_mut::<4>(); + for chunk in chunks { + let [r, g, b, a] = *chunk; + *chunk = AlphaColor::from_rgba8(r, g, b, a) + .premultiply() + .to_rgba8() + .to_u8_array(); + } +} + /// PdfCraft patch: most pieces one dashed stroke may be cut into. Stroke expansion keeps every /// dash, so a pattern that is tiny next to its path asks for billions: a fuzzed `/D [[11] 0]` on /// a line from x = 92234775807 allocated over 5 GB, and `[0.000001] 0 d` on a 20 pt line over @@ -327,6 +637,47 @@ pub fn set_skip_offscreen_paths(skip: bool) { SKIP_OFFSCREEN_PATHS.with(|s| s.set(skip)); } +/// PdfCraft patch (30): what the renders on this thread have drawn offscreen, for tests that check +/// a page's cost by counting rather than by timing it (see [`offscreen_draws`]). +#[doc(hidden)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct OffscreenDraws { + /// Tiling pattern cells drawn; a cell taken from `tiling_cells` isn't drawn again. + pub tiling_cells: u64, + /// The pixels of every pixmap drawn offscreen: tiling cells, masks, groups and the like. + pub pixels: u64, +} + +thread_local! { + /// PdfCraft patch (30): see [`OffscreenDraws`]. + static OFFSCREEN_DRAWS: std::cell::Cell = + const { std::cell::Cell::new(OffscreenDraws { tiling_cells: 0, pixels: 0 }) }; +} + +/// PdfCraft patch (30): exported for its regression tests (see [`OffscreenDraws`]). The counts +/// only grow; a test takes the difference across a render. +#[doc(hidden)] +pub fn offscreen_draws() -> OffscreenDraws { + OFFSCREEN_DRAWS + .try_with(std::cell::Cell::get) + .unwrap_or_default() +} + +/// PdfCraft patch (30): a `width` × `height` pixmap to draw offscreen, counted in +/// [`OffscreenDraws`]. Every pixmap the renderer renders into, besides the page, is made here. +fn offscreen_pixmap(width: u16, height: u16, tiling_cell: bool) -> Pixmap { + // Gone only while the thread exits, when there is nothing left to count for. + let _ = OFFSCREEN_DRAWS.try_with(|draws| { + let mut counts = draws.get(); + counts.pixels = counts + .pixels + .saturating_add(u64::from(width) * u64::from(height)); + counts.tiling_cells = counts.tiling_cells.saturating_add(u64::from(tiling_cell)); + draws.set(counts); + }); + Pixmap::new(width, height) +} + /// PdfCraft patch: whether a device-space box can paint a pixel of a `width` × `height` /// canvas. A box whose bounds miss the canvas is skipped without changing a pixel. /// Bounds that aren't finite are drawn as before. @@ -401,33 +752,61 @@ fn may_paint_rect(rect: Rect, transform: Affine, width: u16, height: u16) -> boo paints_canvas(device, width, height) } -/// PdfCraft patch: the whole-pixel device rectangle of a shrunk, axis-aligned image, as -/// `(width, height, x0, y0)`. `transform` maps source pixels to device pixels and `planned` is the -/// size [`image_resampling_size`] chose; `None` (draw as before) for rotated, skewed or flipped -/// images, non-finite geometry, or a snapped size that strays more than a pixel from `planned` -/// (so the memory budget that size passed still holds). +/// PdfCraft patch: how far, in device pixels, the terms [`snap_minified_image`] drops may move an +/// image's far edges: a hundredth of a pixel, which no edge shows. Rounding noise in a turned or +/// scaled matrix stays far below it. +const SNAP_SKEW: f64 = 0.01; + +/// PdfCraft patch: the whole-pixel device rectangle of a shrunk image whose axes lie along the +/// device's, as `(width, height, transform)`: the size to shrink it to (along its own axes) and +/// the transform that draws that raster 1:1, one source-axis step a whole device pixel. Upright, +/// mirrored and quarter-turned images all qualify, so a page under `/Rotate` (or an image placed +/// turned) is drawn as sharply as upright (#5530). `transform` maps source pixels to device +/// pixels and `planned` is the size [`image_resampling_size`] chose; `None` (draw as before) for +/// skewed or freely rotated images, non-finite geometry, or a snapped size that strays more than +/// a pixel from `planned` (so the memory budget that size passed still holds). An image counts +/// as axis-aligned when the terms the snap drops move its far edges by at most [`SNAP_SKEW`]: a +/// tolerance on the coefficients alone let a slight skew of a very wide image through, though it +/// moved the far edge by more than a pixel. fn snap_minified_image( transform: &Affine, source: (u32, u32), planned: (u32, u32), -) -> Option<(u32, u32, f64, f64)> { +) -> Option<(u32, u32, Affine)> { let [a, b, c, d, e, f] = transform.as_coeffs(); - let tiny = 1e-4 * a.abs().max(d.abs()); - if !(a > 0.0 && d > 0.0 && b.abs() <= tiny && c.abs() <= tiny) { - return None; - } + // Halves round up, not away from zero: a tile's origin moves edges by whole pixels, and only + // then do they snap where the whole page snaps them (-2.5 must go to -2 as 2.5 goes to 3). + let snap = |v: f64| (v + 0.5).floor(); + // The device span of a source edge from `origin` across `side` samples of `scale`, rounded. let edge = |origin: f64, scale: f64, side: u32| { - let (lo, hi) = (origin.round(), (origin + scale * f64::from(side)).round()); + let (p, q) = (snap(origin), snap(origin + scale * f64::from(side))); + let (lo, hi) = (p.min(q), p.max(q)); (hi - lo >= 1.0 && lo.abs() < 1e6 && hi.abs() < 1e6).then_some((lo, hi)) }; - let (x0, x1) = edge(e, a, source.0)?; - let (y0, y1) = edge(f, d, source.1)?; - // Bounded by the 1e6 check above, so the casts cannot saturate. - let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32); - (w.abs_diff(planned.0) <= 1 && h.abs_diff(planned.1) <= 1).then_some((w, h, x0, y0)) + // Along an axis drawn backwards (negative scale), the raster starts at the span's far end. + let start = |scale: f64, (lo, hi): (f64, f64)| if scale > 0.0 { lo } else { hi }; + let step = |scale: f64| if scale > 0.0 { 1.0 } else { -1.0 }; + // How far a dropped term moves the image's far edge: `scale` across `side` source samples. + let negligible = |scale: f64, side: u32| (scale * f64::from(side)).abs() <= SNAP_SKEW; + let (width, height) = source; + // Source x along device x, source y along device y (upright or mirrored), or a quarter turn: + // source x along device y, source y along device x. + let (w, h, draw) = if negligible(b, width) && negligible(c, height) { + let (x, y) = (edge(e, a, source.0)?, edge(f, d, source.1)?); + // Bounded by the 1e6 check above, so the casts cannot saturate. + let (w, h) = ((x.1 - x.0) as u32, (y.1 - y.0) as u32); + (w, h, Affine::new([step(a), 0.0, 0.0, step(d), start(a, x), start(d, y)])) + } else if negligible(a, width) && negligible(d, height) { + let (x, y) = (edge(e, c, source.1)?, edge(f, b, source.0)?); + let (w, h) = ((y.1 - y.0) as u32, (x.1 - x.0) as u32); + (w, h, Affine::new([0.0, step(b), step(c), 0.0, start(c, x), start(b, y)])) + } else { + return None; + }; + (w.abs_diff(planned.0) <= 1 && h.abs_diff(planned.1) <= 1).then_some((w, h, draw)) } -/// PdfCraft patch (#3296): what `Renderer::set_paint` found out: the clip path to apply while +/// PdfCraft patch (19): what `Renderer::set_paint` found out: the clip path to apply while /// painting (if any), or that the paint touches no pixel of the canvas, so the caller skips /// the fill or stroke (a mesh shading whose triangles all lie outside the path or canvas). #[must_use] @@ -436,6 +815,27 @@ enum PaintSetup { Nothing, } +/// PdfCraft patch (27): the most device pixels of a group blended in CMYK at once (2^24, a 4096 × +/// 4096 square). Each costs about 16 bytes while its band is blended (two pass canvases, its +/// tints and their RGB); a larger group is blended in bands of whole rows under it, and only +/// the finished group, 4 bytes a pixel, is kept whole. Before, a larger group was blended in RGB +/// instead: a page enlarged to 11 x 17 in for Print as image at 600 dpi drew the X's of a print +/// test file's CMYK blend patches when one group covered most of it. +const MAX_CMYK_GROUP_PIXELS: u64 = 1 << 24; + +thread_local! { + /// PdfCraft patch (27): the band size [`MAX_CMYK_GROUP_PIXELS`] sets, on this thread. Only + /// PdfCraft's regression test lowers it, to blend a small page's groups in many bands. + static CMYK_BAND_PIXELS: std::cell::Cell = const { std::cell::Cell::new(MAX_CMYK_GROUP_PIXELS) }; +} + +/// PdfCraft patch (27): exported for its regression test (see [`CMYK_BAND_PIXELS`]); `None` +/// restores [`MAX_CMYK_GROUP_PIXELS`]. +#[doc(hidden)] +pub fn set_cmyk_band_pixels(pixels: Option) { + CMYK_BAND_PIXELS.with(|p| p.set(pixels.unwrap_or(MAX_CMYK_GROUP_PIXELS).max(1))); +} + pub(crate) struct Renderer { pub(crate) ctx: RenderContext, /// PdfCraft patch: when set, solid text and line-art paint colours are remapped @@ -444,15 +844,14 @@ pub(crate) struct Renderer { /// PdfCraft patch (17): while the page's annotations are being drawn, paints keep their /// colours — reading colours replace document colours, never annotation colours. in_annotations: bool, - /// Knockout patch (pdfcraft #2974): one entry per transparency group pushed, whether it is a - /// knockout group (`Device::set_knockout`). + /// PdfCraft patch (22): one entry per transparency group pushed, whether it is a knockout + /// group (`Device::set_knockout`). knockout: Vec, - /// Knockout patch (pdfcraft #2974): inside a knockout erase pass - /// (`Device::begin_knockout_erase`), and how many transparency groups were skipped in it - /// (nothing is layered while erasing). + /// PdfCraft patch (22): inside a knockout erase pass (`Device::begin_knockout_erase`), and + /// how many transparency groups were skipped in it (nothing is layered while erasing). erasing: bool, erase_groups: usize, - /// Knockout patch (pdfcraft #4898): the knockout groups drawn in blend-mode passes + /// PdfCraft patch (26): the knockout groups drawn in blend-mode passes /// (`Device::begin_knockout_pass`), innermost last. knockout_passes: Vec, pub(crate) inside_pattern: bool, @@ -460,6 +859,9 @@ pub(crate) struct Renderer { /// render, every nested renderer starting empty) and so to one `preview` setting: a mask /// drawn for a preview, which may leave out tiny images, never reaches a final render. pub(crate) soft_mask_cache: HashMap, + /// PdfCraft patch (30): coloured tiling cells drawn during this render (see [`TilingCells`]). + /// Like `soft_mask_cache` it belongs to one renderer, so to one `preview` setting. + tiling_cells: TilingCells, pub(crate) outline_cache: Rc>>>, pub(crate) cur_mask: Option, pub(crate) in_type3_glyph: bool, @@ -468,6 +870,84 @@ pub(crate) struct Renderer { pub(crate) preview: bool, // TODO: Remove this once vello_cpu bug with non-transparent images is fixed image_transparency_stack: Vec, + /// PdfCraft patch (27): set while this renderer draws one ink pass of a group blending + /// in `DeviceCMYK` (see [`Renderer::draw_isolated_cmyk_group`]). + ink: InkState, +} + +/// PdfCraft patch (30): the cell pixmaps of coloured tiling patterns, keyed by the setting of the +/// pattern (`TilingPattern::instance`) and the cell's size and scale. A page that fills many +/// shapes with one pattern (pdf.js issue 8078 paints 73,047 stencil masks with a pattern whose +/// cell is 3.5 MB) drew and kept a cell per fill, which ran out of memory; the fills now share +/// one. A handful of entries covers a run of fills with one pattern, and bounds what the cache +/// keeps besides what the scene holds anyway. +#[derive(Default)] +struct TilingCells(Vec<(TilingCellKey, Arc)>); + +#[derive(Clone, Copy, PartialEq, Eq)] +struct TilingCellKey { + instance: u64, + /// Whether this is the bordered cell of a pattern whose step shows one cell (patch (20)). + one_cell: bool, + is_stroke: bool, + pixels: (u16, u16), + scale: (u64, u64), +} + +impl TilingCells { + const MAX_ENTRIES: usize = 8; + + fn get(&self, key: &TilingCellKey) -> Option> { + self.0.iter().find(|(k, _)| k == key).map(|(_, cell)| cell.clone()) + } + + fn insert(&mut self, key: TilingCellKey, cell: Arc) { + if self.0.len() >= Self::MAX_ENTRIES { + self.0.remove(0); + } + self.0.push((key, cell)); + } +} + +/// PdfCraft patch (27): which inks a pass of a `DeviceCMYK` group draws, and whether the +/// group asked for something a pass can't draw. +/// +/// A pass paints the complement of ink tints as colour — no ink is white — so the RGB blend +/// functions compute ISO 32000-2 §11.3.4's subtractive blend, `1 − B(1 − cb, 1 − cs)`, and +/// complementing the pixels back gives the tints. The cyan, magenta and yellow pass paints +/// them as red, green and blue, which is also how §11.3.5.3 has the nonseparable modes treat +/// them. The black pass paints black ink as a grey, so a separable mode blends it like any +/// tint, and of the nonseparable modes Hue, Saturation and Color keep the backdrop's grey +/// while Luminosity takes the source's: §11.3.5.3's rule for the K component. +#[derive(Clone, Copy, Default)] +struct InkState { + pass: Option, + /// Something in the group has no ink tints (a pattern, an image, an ICCBased CMYK colour): + /// the group is drawn as before instead. + unsupported: bool, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum InkPass { + /// Cyan, magenta and yellow as red, green and blue. + Cmy, + /// Black as grey. + K, +} + +impl InkState { + /// The colour a pass paints for `color`; transparent, with the group marked unsupported, + /// when the colour has no ink tints. + fn paint(&mut self, pass: InkPass, color: &Color) -> AlphaColor { + let Some(([c, m, y, k], alpha)) = color.ink_tints() else { + self.unsupported = true; + return AlphaColor::TRANSPARENT; + }; + match pass { + InkPass::Cmy => AlphaColor::new([1.0 - c, 1.0 - m, 1.0 - y, alpha]), + InkPass::K => AlphaColor::new([1.0 - k, 1.0 - k, 1.0 - k, alpha]), + } + } } #[derive(Clone, Copy)] @@ -478,15 +958,13 @@ enum ImagePixelFormat { } impl Renderer { - /// Knockout patch (pdfcraft #2974): whether the innermost transparency group is a knockout - /// group. + /// PdfCraft patch (22): whether the innermost transparency group is a knockout group. fn in_knockout(&self) -> bool { self.knockout.last().copied().unwrap_or(false) } - /// Knockout patch (pdfcraft #4898): the blend-mode pass of the innermost group, when that - /// group is a knockout group drawn in passes, so the element now drawn is one of its own - /// elements. + /// PdfCraft patch (26): the blend-mode pass of the innermost group, when that group is a + /// knockout group drawn in passes, so the element now drawn is one of its own elements. fn knockout_pass(&mut self) -> Option<&mut KnockoutPass> { let depth = self.knockout.len(); if !self.in_knockout() { @@ -495,9 +973,9 @@ impl Renderer { self.knockout_passes.last_mut().filter(|pass| pass.depth == depth) } - /// Knockout patch (pdfcraft #4898): whether an element of blend mode `mode` belongs to - /// another pass than the current one, so here it clears what is under its shape instead of - /// painting. Records the mode for its own pass. + /// PdfCraft patch (26): whether an element of blend mode `mode` belongs to another pass than + /// the current one, so here it clears what is under its shape instead of painting. Records + /// the mode for its own pass. fn knockout_pass_skips(&mut self, mode: BlendMode) -> bool { let Some(pass) = self.knockout_pass() else { return false; @@ -529,12 +1007,14 @@ impl Renderer { erase_groups: 0, inside_pattern: false, soft_mask_cache: HashMap::default(), + tiling_cells: TilingCells::default(), outline_cache: cache.outline_cache.clone(), cur_mask: None, in_type3_glyph: false, scaler: Scaler::new(ResamplingFunction::CatmullRom), preview, image_transparency_stack: Vec::new(), + ink: InkState::default(), } } @@ -634,14 +1114,16 @@ impl Renderer { erase_groups: 0, inside_pattern: false, soft_mask_cache: HashMap::default(), + tiling_cells: TilingCells::default(), outline_cache: self.outline_cache.clone(), cur_mask: None, in_type3_glyph: false, scaler: self.scaler, preview: self.preview, image_transparency_stack: Vec::new(), + ink: InkState::default(), }; - let mut mask_pix = Pixmap::new(self.ctx.width(), self.ctx.height()); + let mut mask_pix = offscreen_pixmap(self.ctx.width(), self.ctx.height(), false); let rgb_data = ImageData::Rgb(RgbData { data: dummy_rgb, width: alpha_data.width, @@ -800,8 +1282,10 @@ impl Renderer { /// `transform`, or `None` if `draw_image` skips it: off the canvas (PdfCraft patch: see /// `may_paint_rect`; checked before decoding, so a tile no longer decodes every image on its /// page), or, in a preview, covering only a few device pixels (PdfCraft patch; final renders - /// always draw them). The tiny-image test measures axis lengths: the size returned maps a - /// point, so it includes the translation and only suits the decode hint. + /// always draw them). Both sides are the lengths of the image's axes on the device, from the + /// transform's linear part (PdfCraft patch, #3884: mapping the corners as points took in the + /// translation, so on a `/Rotate 90` page a corner on the device origin gave a side of 0, + /// which `hayro-jpeg2000` divides the image size by); as the decode hint each is at least 1. fn image_draw_size(&self, width: u32, height: u32, transform: Affine) -> Option<(u32, u32)> { if !may_paint_rect( Rect::new(0.0, 0.0, f64::from(width), f64::from(height)), @@ -811,23 +1295,14 @@ impl Renderer { ) { return None; } - let target_width = (transform * Point::new(width as f64, 0.0)) - .to_vec2() - .length() - .ceil() as u32; - let target_height = (transform * Point::new(0.0, height as f64)) - .to_vec2() - .length() - .ceil() as u32; - if self.preview { - let c = transform.as_coeffs(); - let tiny_w = (f64::from(width) * (c[0] * c[0] + c[1] * c[1]).sqrt()).ceil() as u32; - let tiny_h = (f64::from(height) * (c[2] * c[2] + c[3] * c[3]).sqrt()).ceil() as u32; - if tiny_w.saturating_mul(tiny_h) < PREVIEW_MIN_IMAGE_AREA { - return None; - } + let (x_axis, y_axis) = x_y_advances(&transform); + // `as` saturates, and turns NaN into 0. + let drawn_width = (f64::from(width) * x_axis.length()).ceil() as u32; + let drawn_height = (f64::from(height) * y_axis.length()).ceil() as u32; + if self.preview && drawn_width.saturating_mul(drawn_height) < PREVIEW_MIN_IMAGE_AREA { + return None; } - Some((target_width, target_height)) + Some((drawn_width.max(1), drawn_height.max(1))) } fn draw_image(&mut self, image_data: ImageData, alpha_data: Option) { @@ -862,17 +1337,51 @@ impl Renderer { return; } let interpolate = image_data.interpolate(); - if let Some(a) = &alpha_data { + let requested_resize = x_scale < 1.0 || y_scale < 1.0; + // PdfCraft patch: an image that did not ask for interpolation and is drawn below its + // resolution is shrunk by area averaging (`area_shrink`), not nearest-neighbour, which + // broke up the text of scans shown at screen size. Type 3 glyph images keep the nearest + // shrink of #624: they are drawn with a frame of their own and never snapped. + let area = !interpolate + && requested_resize + && !self.in_type3_glyph + // Wider sources keep #624's bounded nearest-neighbour shrink (`area_shrink` refuses + // them): skipping them, as a refused shrink at source size would, loses the image. + && source_width.max(source_height) <= MAX_RESAMPLING_SOURCE_SIDE; + let mut alpha_data = alpha_data; + if let Some(a) = alpha_data.take() { if source_byte_len(a.width, a.height, 1, MAX_IMAGE_PIXELS) != Some(a.data.len()) { log::warn!("Image has invalid or over-limit alpha dimensions/data and was skipped"); return; } if a.width != source_width || a.height != source_height || a.interpolate != interpolate { - if let Some(alpha) = alpha_data { - self.draw_image_with_alpha_mask(image_data, alpha); + // PdfCraft patch: a soft mask no larger than its area-shrunk image is sampled onto + // the image's grid, so colour and mask are averaged together, premultiplied. Drawn + // as a mask layer over the image instead, the averaged colour (transparent samples + // included) was multiplied by the averaged mask, and the colour of transparent + // samples showed at the mask's edges. A larger mask carries detail the image does + // not (#1649) and keeps the layer. + let on_grid = (area && a.width <= source_width && a.height <= source_height) + .then(|| mask_on_image_grid(&a, source_width, source_height)) + .flatten(); + match on_grid { + Some(data) => { + alpha_data = Some(LumaData { + data, + width: source_width, + height: source_height, + interpolate, + ..a + }); + } + None => { + self.draw_image_with_alpha_mask(image_data, a); + return; + } } - return; + } else { + alpha_data = Some(a); } } let mut quality = if interpolate { @@ -882,7 +1391,6 @@ impl Renderer { }; let has_alpha = alpha_data.is_some(); let mut may_have_transparency = has_alpha || self.force_images_may_have_transparency(); - let requested_resize = x_scale < 1.0 || y_scale < 1.0; let (new_width, new_height) = match image_resampling_size( source_width, source_height, @@ -912,11 +1420,28 @@ impl Renderer { if requested_resize && self.in_type3_glyph && interpolate { quality = ImageQuality::High; } - // PdfCraft patch: an axis-aligned, interpolated image that is shrunk lands on whole device - // pixels. It is shrunk once to exactly its snapped device rectangle and drawn 1:1 at the - // snapped corner. Otherwise the shrunk raster (rounded up to a whole size) is sampled a - // second time at a fractional scale and offset, which blurs scans and photos. - let snapped = if interpolate + // PdfCraft patch: an image the size of a page scan is smoothed when drawn above its + // resolution, even without `/Interpolate`: bilinearly, as images that ask for it are. + // Scans rarely ask, and drawn nearest-neighbour each sample of a zoomed scan became a + // block, so the edges of its text were staircases. Bicubic looked the same on a zoomed + // 300 dpi scan and drew its tiles five times slower. Smaller images (icons, QR codes, + // pixel art) keep their hard pixels. A scan shrunk on one side and stretched on the other + // is smoothed too: the area shrink leaves the shrunk side at 1:1, where bilinear adds + // nothing, and the stretched side would otherwise be drawn nearest-neighbour. + if !interpolate + && !self.in_type3_glyph + && (x_scale > SMOOTHED_IMAGE_SCALE || y_scale > SMOOTHED_IMAGE_SCALE) + && source_width.min(source_height) >= SMOOTHED_IMAGE_SIDE + { + quality = ImageQuality::Medium; + } + // PdfCraft patch: an image that is shrunk (filtered or area-averaged), with its axes along + // the device's (upright, mirrored or a quarter turn), lands on whole device pixels. It is + // shrunk once to exactly its snapped device rectangle and drawn 1:1 from the snapped + // corner. Otherwise the shrunk raster (rounded up to a whole size) is sampled a second time + // at a fractional scale and offset, which blurs scans and photos (or, by the nearest + // sampler of a non-interpolated image, drops samples again). + let snapped = if (interpolate || area) && requested_resize && !self.in_type3_glyph && (new_width, new_height) != (source_width, source_height) @@ -926,13 +1451,31 @@ impl Renderer { None }; let (new_width, new_height) = snapped.map_or((new_width, new_height), |s| (s.0, s.1)); + // PdfCraft patch: an area shrink never enlarges. A side drawn at or above its resolution + // (an image shrunk across and stretched down, as a 204 × 98 dpi fax is, or a snapped side + // rounded past its source) keeps its samples and is enlarged by the sampler; the snap + // then no longer matches, so the full transform places the image. + let (new_width, new_height) = if area { + (new_width.min(source_width), new_height.min(source_height)) + } else { + (new_width, new_height) + }; let needs_resize = (new_width, new_height) != (source_width, source_height); - // PdfCraft patch (#624): a minified image with a soft mask that is not interpolated is - // nearest-sampled straight into premultiplied target RGBA. That skips the full-resolution - // RGBA copy below and the premultiply pass after it. + // PdfCraft patch (#624): a minified image with a soft mask that is neither interpolated nor + // area-averaged (a Type 3 glyph image, or a source wider than MAX_RESAMPLING_SOURCE_SIDE) + // is nearest-sampled straight into premultiplied target RGBA. That skips the + // full-resolution RGBA copy below and the premultiply pass after it. PdfCraft patch: an + // area-averaged one (a stencil's ink, or an image under its mask) skips them too, and is + // premultiplied a source row at a time as it is averaged (`area_shrink_premultiplied`). let direct = match &alpha_data { - Some(alpha) if needs_resize && !interpolate => nearest_premultiplied_rgba( + Some(alpha) if needs_resize && !interpolate && !area => nearest_premultiplied_rgba( + &image_data, + &alpha.data, + (source_width, source_height), + (new_width, new_height), + ), + Some(alpha) if needs_resize && area => area_shrink_premultiplied( &image_data, &alpha.data, (source_width, source_height), @@ -940,7 +1483,7 @@ impl Renderer { ), _ => None, }; - let premultiplied = direct.is_some(); + let mut premultiplied = direct.is_some(); // Preserve the single-channel/RGB fast paths. With alpha, expand directly to RGBA; // every source and alpha length was validated before zipping or allocating. let (data, format) = match (direct, image_data, alpha_data) { @@ -983,6 +1526,15 @@ impl Renderer { }; let (data, mut img_width, mut img_height) = if premultiplied { (data, new_width, new_height) + } else if needs_resize && area { + let mut data = data; + if matches!(format, ImagePixelFormat::Rgba) { + // Averaging straight colours would bleed the colour of transparent samples into + // their neighbours; premultiplied colours count each by its coverage. + premultiply_rgba(&mut data); + premultiplied = true; + } + area_resize(data, (source_width, source_height), (new_width, new_height), format) } else if needs_resize { self.resize_image_data( data, @@ -1029,14 +1581,7 @@ impl Renderer { rgba }; if has_alpha && !premultiplied { - let (chunks, _) = rgba_data.as_chunks_mut::<4>(); - for chunk in chunks { - let [r, g, b, a] = *chunk; - *chunk = AlphaColor::from_rgba8(r, g, b, a) - .premultiply() - .to_rgba8() - .to_u8_array(); - } + premultiply_rgba(&mut rgba_data); } // Type 3 glyphs get a transparent two-pixel frame for interpolation. Check the padded // RGBA allocation and u16 dimensions too, before narrowing or growing either side. @@ -1074,13 +1619,62 @@ impl Renderer { img_height as u16, may_have_transparency, ); + // The snapped transform draws the raster 1:1, so it holds only if the shrink produced the + // snapped size. A failed resize hands back the source raster: drawn 1:1 it would come out + // at its source size, so it keeps the full transform instead. let draw_transform = match snapped { - Some((_, _, x0, y0)) => Affine::translate((x0, y0)), - None => cur_transform * additional_transform, + Some((w, h, draw)) if (img_width, img_height) == (w, h) => draw, + _ => cur_transform * additional_transform, }; self.draw_pixmap(Arc::new(pixmap), quality, draw_transform); } + /// PdfCraft patch (30): the cell pixmap of tiling pattern `t`, `size` pixels drawn at + /// `initial_transform`; a cell with a `key` is drawn once and then taken from `tiling_cells`. + fn tiling_cell( + &mut self, + t: &hayro_interpret::pattern::TilingPattern<'_>, + key: Option, + size: (u16, u16), + initial_transform: Affine, + is_stroke: bool, + ) -> Arc { + if let Some(cell) = key.and_then(|key| self.tiling_cells.get(&key)) { + return cell; + } + let mut renderer = Self { + ctx: RenderContext::new_with(size.0, size.1, derive_settings(self.ctx.render_settings())), + // PdfCraft patch: a pattern cell is painted as one artwork, so its content is never + // remapped by the reading-colours setting. + color_replacement: None, + in_annotations: false, + knockout: Vec::new(), + erasing: false, + knockout_passes: Vec::new(), + erase_groups: 0, + cur_mask: None, + inside_pattern: true, + soft_mask_cache: HashMap::default(), + tiling_cells: TilingCells::default(), + outline_cache: self.outline_cache.clone(), + in_type3_glyph: false, + scaler: self.scaler, + preview: self.preview, + image_transparency_stack: Vec::new(), + ink: InkState::default(), + }; + t.interpret(&mut renderer, initial_transform, is_stroke); + let mut pix = offscreen_pixmap(size.0, size.1, true); + renderer.ctx.flush(); + let mut resources = vello_cpu::Resources::default(); + renderer.ctx.render_to_pixmap(&mut resources, &mut pix); + let pix = Arc::new(pix); + if let Some(key) = key { + self.tiling_cells.insert(key, pix.clone()); + } + pix + } + fn push_clip_path_inner(&mut self, clip_path: &BezPath, fill: FillRule) { let old_transform = *self.ctx.transform(); @@ -1109,6 +1703,95 @@ impl Renderer { .fill_rect(&Rect::new(0.0, 0.0, width as f64, height as f64)); } + /// PdfCraft patch (27): one ink pass of `group` (see [`InkState`]) on a `width` × `height` + /// canvas whose corner is device point `offset`; `None` when the group holds something the + /// pass has no tints for. + fn ink_pass( + &self, + group: &hayro_interpret::CmykGroup<'_, '_>, + pass: InkPass, + offset: (f64, f64), + width: u16, + height: u16, + ) -> Option { + let mut renderer = Self { + ctx: RenderContext::new_with(width, height, derive_settings(self.ctx.render_settings())), + color_replacement: None, + in_annotations: self.in_annotations, + inside_pattern: self.inside_pattern, + soft_mask_cache: HashMap::default(), + tiling_cells: TilingCells::default(), + outline_cache: self.outline_cache.clone(), + cur_mask: None, + in_type3_glyph: false, + scaler: Scaler::new(ResamplingFunction::CatmullRom), + preview: self.preview, + image_transparency_stack: Vec::new(), + ink: InkState { + pass: Some(pass), + unsupported: false, + }, + knockout: Vec::new(), + erasing: false, + erase_groups: 0, + knockout_passes: Vec::new(), + }; + // The pass draws inside a layer of its own. On the bare canvas, vello_cpu fills a tile + // that a paint covers completely without the blend mode, so the middle of a group wider + // than about two tiles lost its blend (#3777). + renderer.ctx.push_layer(None, None, None, None, None); + group.interpret(&mut renderer, offset); + renderer.ctx.pop_layer(); + if renderer.ink.unsupported { + return None; + } + let mut pix = offscreen_pixmap(width, height, false); + renderer.ctx.flush(); + let mut resources = vello_cpu::Resources::default(); + renderer.ctx.render_to_pixmap(&mut resources, &mut pix); + Some(pix) + } + + /// PdfCraft patch (27): rows `offset.1` .. `offset.1 + height` of `group` blended in CMYK, as + /// a `width` × `height` premultiplied pixmap whose corner is device point `offset`; `None` + /// when the group holds something a pass has no tints for, or its tints can't be converted. + fn cmyk_group_band( + &self, + group: &hayro_interpret::CmykGroup<'_, '_>, + offset: (f64, f64), + width: u16, + height: u16, + ) -> Option { + let cmy = self.ink_pass(group, InkPass::Cmy, offset, width, height)?; + let k = self.ink_pass(group, InkPass::K, offset, width, height)?; + + // A tint is a pass's premultiplied colour un-premultiplied and complemented. + let ink = |premul: u8, alpha: u8| { + if alpha == 0 { + return 0; + } + let straight = (u32::from(premul) * 255 + u32::from(alpha) / 2) / u32::from(alpha); + 255 - straight.min(255) as u8 + }; + let pixels = usize::from(width) * usize::from(height); + let mut tints = Vec::with_capacity(pixels * 4); + for (p, q) in cmy.data().iter().zip(k.data()) { + // Both passes draw the same shapes at the same opacities, so they cover the same + // pixels by the same amounts; each pass's own alpha un-premultiplies its colour. + tints.extend_from_slice(&[ink(p.r, p.a), ink(p.g, p.a), ink(p.b, p.a), ink(q.r, q.a)]); + } + let mut rgb = vec![0u8; pixels * 3]; + hayro_interpret::color::cmyk_to_srgb8(&tints, &mut rgb)?; + + let mut result = offscreen_pixmap(width, height, false); + for ((px, rgb), coverage) in result.data_mut().iter_mut().zip(rgb.chunks_exact(3)).zip(cmy.data()) { + let a = u32::from(coverage.a); + let premul = |v: u8| ((u32::from(v) * a + 127) / 255) as u8; + *px = PremulRgba8 { r: premul(rgb[0]), g: premul(rgb[1]), b: premul(rgb[2]), a: coverage.a }; + } + Some(result) + } + /// PdfCraft patch: remaps a solid paint colour through `color_replacement`, if one is /// set. `Paint::Pattern` (images, shadings, tiling patterns) always passes through /// untouched. @@ -1133,72 +1816,6 @@ impl Renderer { } } - #[must_use] - fn set_paint(&mut self, paint: &Paint<'_>, path: &BezPath, is_stroke: bool) -> PaintSetup { - // Knockout patch (pdfcraft #2974): in a knockout erase pass every paint clears what is - // under its shape (a transparent fill with `Compose::Copy`, weighted by coverage). - // Knockout patch (pdfcraft #4898): so does an element of another pass than the current - // one (`Device::begin_knockout_pass`). - let element_mode = self.knockout_pass().map(|pass| pass.element_mode); - let other_pass = - !self.erasing && element_mode.is_some_and(|mode| self.knockout_pass_skips(mode)); - if self.erasing || other_pass { - if is_shading(paint) { - self.knockout_shading(paint, path, is_stroke, false); - return PaintSetup::Nothing; - } - self.ctx.set_blend_mode(knockout_blend_mode()); - self.ctx.set_paint(AlphaColor::::new([0.0, 0.0, 0.0, 0.0])); - return PaintSetup::Clip(None); - } - if self.in_knockout() && is_shading(paint) { - self.knockout_shading(paint, path, is_stroke, true); - return PaintSetup::Nothing; - } - self.paint_setup(paint, path, is_stroke) - } - - /// Knockout patch (pdfcraft #4898): a shading in a knockout group replaces what is under it - /// where it paints, which a mesh's triangles or the shading's `/BBox` may make less than the - /// path, so it can't be copied over the path like other paints. The shading at full opacity, - /// composited with `Compose::DestOut`, clears its shape; then, when `paint_it`, the shading - /// is painted over the cleared area. A shading that paints nothing clears nothing. The - /// caller paints nothing more. - fn knockout_shading( - &mut self, - paint: &Paint<'_>, - path: &BezPath, - is_stroke: bool, - paint_it: bool, - ) { - let PaintSetup::Clip(clip) = self.paint_setup(&shape_of(paint), path, is_stroke) else { - return; - }; - if let Some(clip) = clip.as_ref() { - self.push_clip_path_inner(clip, FillRule::NonZero); - } - self.ctx - .set_blend_mode(peniko::BlendMode::new(Mix::Normal, Compose::DestOut)); - self.draw_shape(path, is_stroke); - if paint_it && let PaintSetup::Clip(_) = self.paint_setup(paint, path, is_stroke) { - self.ctx - .set_blend_mode(peniko::BlendMode::new(Mix::Normal, Compose::SrcOver)); - self.draw_shape(path, is_stroke); - } - if clip.is_some() { - self.ctx.pop_clip_path(); - } - self.ctx.set_blend_mode(knockout_blend_mode()); - } - - fn draw_shape(&mut self, path: &BezPath, is_stroke: bool) { - if is_stroke { - self.ctx.stroke_path(path); - } else { - self.ctx.fill_path(path); - } - } - /// The device-space area a shading painted on `path` covers: the path's bounding box, with /// the stroke width around it for a stroke, on the canvas. fn shading_bbox(&self, path: &BezPath, is_stroke: bool) -> Rect { @@ -1218,21 +1835,91 @@ impl Renderer { )) } + #[must_use] + fn set_paint(&mut self, paint: &Paint<'_>, path: &BezPath, is_stroke: bool) -> PaintSetup { + // PdfCraft patch (22): in a knockout erase pass every paint clears what is under its + // shape (a transparent fill with `Compose::Copy`, weighted by coverage). + let element_mode = self.knockout_pass().map(|pass| pass.element_mode); + let other_pass = + !self.erasing && element_mode.is_some_and(|mode| self.knockout_pass_skips(mode)); + if self.erasing || other_pass { + if is_shading(paint) { + self.knockout_shading(paint, path, is_stroke, false); + return PaintSetup::Nothing; + } + self.ctx.set_blend_mode(knockout_blend_mode()); + self.ctx.set_paint(AlphaColor::::new([0.0, 0.0, 0.0, 0.0])); + return PaintSetup::Clip(None); + } + if self.in_knockout() && is_shading(paint) { + self.knockout_shading(paint, path, is_stroke, true); + return PaintSetup::Nothing; + } + self.paint_setup(paint, path, is_stroke) + } + + /// PdfCraft patch (26): a shading in a knockout group replaces what is under it where it + /// paints, which a mesh's triangles or the shading's `/BBox` may make less than the path, + /// so it can't be copied over the path like other paints. The shading at full opacity, + /// composited with `Compose::DestOut`, clears its shape; then, when `paint_it`, the shading + /// is painted over the cleared area. A shading that paints nothing clears nothing. The + /// caller paints nothing more. + fn knockout_shading(&mut self, paint: &Paint<'_>, path: &BezPath, is_stroke: bool, paint_it: bool) { + let PaintSetup::Clip(clip) = self.paint_setup(&shape_of(paint), path, is_stroke) else { return }; + if let Some(clip) = clip.as_ref() { + self.push_clip_path_inner(clip, FillRule::NonZero); + } + self.ctx.set_blend_mode(peniko::BlendMode::new(Mix::Normal, Compose::DestOut)); + self.draw_shape(path, is_stroke); + if paint_it && let PaintSetup::Clip(_) = self.paint_setup(paint, path, is_stroke) { + self.ctx.set_blend_mode(peniko::BlendMode::new(Mix::Normal, Compose::SrcOver)); + self.draw_shape(path, is_stroke); + } + if clip.is_some() { + self.ctx.pop_clip_path(); + } + self.ctx.set_blend_mode(knockout_blend_mode()); + } + + fn draw_shape(&mut self, path: &BezPath, is_stroke: bool) { + if is_stroke { + self.ctx.stroke_path(path); + } else { + self.ctx.fill_path(path); + } + } + /// The paint `paint` draws on `path` with, set on the context (see [`PaintSetup`]). fn paint_setup(&mut self, paint: &Paint<'_>, path: &BezPath, is_stroke: bool) -> PaintSetup { let mut paint_transform = Affine::IDENTITY; let mut clip_path = None; - // PdfCraft patch (#3296): `Extend::Repeat` tiles the texture over the path; a mesh - // texture covers its triangles alone and must not repeat outside them. + // PdfCraft patch (19): `Extend::Repeat` tiles the texture over the path; a mesh texture + // covers its triangles alone and must not repeat outside them. let mut extend = peniko::Extend::Repeat; + // PdfCraft patch (27): an ink pass paints tints, and has none for a pattern. + if let Some(pass) = self.ink.pass { + let color = match paint { + Paint::Color(c) => self.ink.paint(pass, c), + Paint::Pattern(_) => { + self.ink.unsupported = true; + AlphaColor::TRANSPARENT + } + }; + self.ctx.set_paint_transform(Affine::IDENTITY); + self.ctx.set_paint(color); + return PaintSetup::Clip(None); + } + let paint: PaintType = match paint.clone() { Paint::Color(c) => { let c = c.to_rgba().to_rgba8(); AlphaColor::from_rgba8(c[0], c[1], c[2], c[3]).into() } Paint::Pattern(p) => { - let path_transform = self.ctx.transform(); + // PdfCraft patch (30): a copy, so a tiling cell can be drawn and kept on `self`. + let current_transform = *self.ctx.transform(); + let path_transform = ¤t_transform; match *p { Pattern::Shading(s) => { @@ -1243,13 +1930,13 @@ impl Renderer { // pixel around it: texels at a fractional edge look one pixel further). let encoded = s.encode_within(Some(bbox.inflate(1.0, 1.0))); - // PdfCraft patch (#3296): a mesh paints only where its triangles are. - // The texture covers the triangles alone (and a pixel around them, - // which stays transparent and is what `Extend::Pad` repeats), not the - // whole path (the canvas, for `sh`): sampled pixel by pixel, 310 - // one-triangle meshes on a plan cost 310 full tiles per tile, and the - // watchdog gave the page up. A mesh with no triangle on the canvas - // paints nothing at all. + // PdfCraft patch (19): a mesh paints only where its triangles are. The + // texture below used to cover the whole path (the canvas, for `sh`) + // and was sampled pixel by pixel: 310 one-triangle meshes on a plan + // cost 310 full tiles per tile, and the watchdog gave the page up. It + // now covers the triangles alone (a pixel around them, which stays + // transparent and is what `Extend::Pad` repeats), and a mesh with no + // triangle on the canvas paints nothing at all. if encoded.extent.is_some() { let Some(area) = mesh_area(bbox, &encoded) else { return PaintSetup::Nothing; @@ -1339,38 +2026,20 @@ impl Renderer { const BORDER: f64 = 1.0; let pix_width = ((bbox.width() as f32 * xs).ceil() as u16).saturating_add(2); let pix_height = ((bbox.height() as f32 * ys).ceil() as u16).saturating_add(2); - let mut renderer = Self { - ctx: RenderContext::new_with( - pix_width, - pix_height, - derive_settings(self.ctx.render_settings()), - ), - color_replacement: None, - in_annotations: false, - knockout: Vec::new(), - erasing: false, - knockout_passes: Vec::new(), - erase_groups: 0, - cur_mask: None, - inside_pattern: true, - soft_mask_cache: HashMap::default(), - outline_cache: self.outline_cache.clone(), - in_type3_glyph: false, - scaler: self.scaler, - preview: self.preview, - image_transparency_stack: Vec::new(), - }; let initial_transform = Affine::translate((BORDER, BORDER)) * Affine::scale_non_uniform(xs as f64, ys as f64) * Affine::translate((-bbox.x0, -bbox.y0)); - t.interpret(&mut renderer, initial_transform, is_stroke); - let mut pix = Pixmap::new(pix_width, pix_height); - renderer.ctx.flush(); - let mut resources = vello_cpu::Resources::default(); - renderer.ctx.render_to_pixmap(&mut resources, &mut pix); + let key = t.is_coloured().then(|| TilingCellKey { + instance: t.instance(), + one_cell: true, + is_stroke, + pixels: (pix_width, pix_height), + scale: (u64::from(xs.to_bits()), u64::from(ys.to_bits())), + }); + let pix = self.tiling_cell(&t, key, (pix_width, pix_height), initial_transform, is_stroke); paint_transform = path_transform.inverse() * t.matrix * initial_transform.inverse(); let image = Image { - image: ImageSource::Pixmap(Arc::new(pix)), + image: ImageSource::Pixmap(pix), sampler: ImageSampler { x_extend: peniko::Extend::Pad, y_extend: peniko::Extend::Pad, @@ -1387,61 +2056,47 @@ impl Renderer { xs = tiling_cell_scale(xs, t.x_step, MAX_PIXMAP_SIZE); ys = tiling_cell_scale(ys, t.y_step, MAX_PIXMAP_SIZE); - let x_step = xs * t.x_step; - let y_step = ys * t.y_step; + // PdfCraft patch (25): the cell pixmap repeats every `pix_width` pixels, + // so one step must be exactly that many pixels. The cell is drawn at the + // scale that makes it so, and the paint transform below maps the pixmap + // back onto pattern space: cells sit at whole multiples of the step at + // any device scale. Drawing at the unrounded scale repeated the cell a + // fraction of a pixel too early or late, and the error grew with every + // step away from the pattern's origin. + let (pix_width, xs) = tiling_cell_pixels(xs, t.x_step, MAX_PIXMAP_SIZE); + let (pix_height, ys) = tiling_cell_pixels(ys, t.y_step, MAX_PIXMAP_SIZE); - let scaled_width = bbox.width() as f32 * xs; - let scaled_height = bbox.height() as f32 * ys; - let pix_width = x_step.abs().round() as u16; - let pix_height = y_step.abs().round() as u16; + let scaled_width = bbox.width() * xs; + let scaled_height = bbox.height() * ys; - let mut renderer = Self { - ctx: RenderContext::new_with( - pix_width, - pix_height, - derive_settings(self.ctx.render_settings()), - ), - // PdfCraft patch: a pattern cell is painted as one artwork, so its - // content is never remapped by the reading-colours setting. - color_replacement: None, - in_annotations: false, - knockout: Vec::new(), - erasing: false, - knockout_passes: Vec::new(), - erase_groups: 0, - cur_mask: None, - inside_pattern: true, - soft_mask_cache: HashMap::default(), - outline_cache: self.outline_cache.clone(), - in_type3_glyph: false, - scaler: self.scaler, - preview: self.preview, - image_transparency_stack: Vec::new(), - }; - let mut initial_transform = Affine::scale_non_uniform(xs as f64, ys as f64) + let mut initial_transform = Affine::scale_non_uniform(xs, ys) * Affine::translate((-bbox.x0, -bbox.y0)); - t.interpret(&mut renderer, initial_transform, is_stroke); - let mut pix = Pixmap::new(pix_width, pix_height); - renderer.ctx.flush(); - let mut resources = vello_cpu::Resources::default(); - renderer.ctx.render_to_pixmap(&mut resources, &mut pix); + // PdfCraft patch (30): a coloured cell is drawn once per setting and scale. + let key = t.is_coloured().then(|| TilingCellKey { + instance: t.instance(), + one_cell: false, + is_stroke, + pixels: (pix_width, pix_height), + scale: (xs.to_bits(), ys.to_bits()), + }); + let pix = self.tiling_cell(&t, key, (pix_width, pix_height), initial_transform, is_stroke); // TODO: Fix these - if x_step < 0.0 { + if t.x_step < 0.0 { initial_transform *= - Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width as f64, 0.0]); + Affine::new([-1.0, 0.0, 0.0, 1.0, scaled_width, 0.0]); } - if y_step < 0.0 { + if t.y_step < 0.0 { initial_transform *= - Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height as f64]); + Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, scaled_height]); } paint_transform = path_transform.inverse() * t.matrix * initial_transform.inverse(); let image = Image { - image: ImageSource::Pixmap(Arc::new(pix)), + image: ImageSource::Pixmap(pix), sampler: ImageSampler { x_extend: peniko::Extend::Repeat, y_extend: peniko::Extend::Repeat, @@ -1479,9 +2134,7 @@ impl Renderer { // PdfCraft patch: apply the reading-colours mapping before painting. let paint = self.replaced(paint, is_text); - let PaintSetup::Clip(clip_path) = self.set_paint(&paint, path, true) else { - return; - }; + let PaintSetup::Clip(clip_path) = self.set_paint(&paint, path, true) else { return }; if let Some(clip_path) = clip_path.as_ref() { self.push_clip_path_inner(clip_path, FillRule::NonZero); } @@ -1510,9 +2163,7 @@ impl Renderer { // PdfCraft patch: apply the reading-colours mapping before painting. let paint = self.replaced(paint, is_text); - let PaintSetup::Clip(clip_path) = self.set_paint(&paint, path, false) else { - return; - }; + let PaintSetup::Clip(clip_path) = self.set_paint(&paint, path, false) else { return }; if let Some(clip_path) = clip_path.as_ref() { self.push_clip_path_inner(clip_path, fill_rule); } @@ -1606,8 +2257,14 @@ impl Renderer { impl<'a> Device<'a> for Renderer { fn draw_image(&mut self, image: hayro_interpret::Image<'a, '_>, mut transform: Affine) { - // Knockout patch (pdfcraft #2974): an erase pass paints nothing; an unmasked image's - // rectangle was cleared by `knockout_shape`, and a masked image's shape is left alone. + // PdfCraft patch (27): an image's pixels are converted to RGB before they reach the + // device, so an ink pass has no tints for them; the group is drawn as before. + if self.ink.pass.is_some() { + self.ink.unsupported = true; + return; + } + // PdfCraft patch (22): an erase pass paints nothing; an unmasked image's rectangle was + // cleared by `knockout_shape`, and a masked image's shape is left alone. if self.erasing { return; } @@ -1677,73 +2334,62 @@ impl<'a> Device<'a> for Renderer { self.ctx.set_fill_rule(old_rule); } Paint::Pattern(_) => { - let (width, height) = (self.ctx.width(), self.ctx.height()); let stencil_rect = Rect::new( 0.0, 0.0, stencil.width as f64, stencil.height as f64, ); - let mask_pix = { - let rgb_bytes = ImageData::Rgb(RgbData { - data: vec![ - 255; - stencil.width as usize - * stencil.height as usize - * 3 - ], - width: stencil.width, - height: stencil.height, - interpolate: stencil.interpolate, - scale_factors: stencil.scale_factors, - }); - let mut sub_renderer = Self { - ctx: RenderContext::new_with( - width, - height, - derive_settings(self.ctx.render_settings()), - ), - // PdfCraft patch: a stencil mask must keep its original - // coverage values, so its content is never remapped by - // the reading-colours setting. - color_replacement: None, - in_annotations: false, - knockout: Vec::new(), - erasing: false, - knockout_passes: Vec::new(), - erase_groups: 0, - inside_pattern: false, - soft_mask_cache: HashMap::default(), - outline_cache: self.outline_cache.clone(), - cur_mask: None, - in_type3_glyph: false, - scaler: self.scaler, - preview: self.preview, - image_transparency_stack: Vec::new(), - }; - let mut sub_pix = Pixmap::new(width, height); - sub_renderer.ctx.set_transform(transform); - sub_renderer.draw_image(rgb_bytes, Some(stencil)); - sub_renderer.ctx.flush(); - let mut resources = vello_cpu::Resources::default(); - sub_renderer - .ctx - .render_to_pixmap(&mut resources, &mut sub_pix); - sub_pix + let Some(len) = source_byte_len( + stencil.width, + stencil.height, + 3, + MAX_IMAGE_PIXELS, + ) else { + log::warn!( + "Stencil mask dimensions exceeded the buffer limit; image skipped" + ); + return; }; - - self.ctx.push_layer( - None, - Some(self.ctx.blend_mode()), - None, - Some(Mask::new_luminance(&mask_pix)), - None, - ); + let Some(mut white) = image_buffer(len) else { + log::warn!( + "Stencil mask buffer could not be allocated; image skipped" + ); + return; + }; + white.resize(len, 255); + // PdfCraft patch (30): under a clip of the stencil's device + // rectangle, the pattern is painted into a layer of its own and + // cut to the stencil by a layer holding the stencil, composited + // with `Compose::DestIn`; a layer is only as large as the clip, + // so a draw costs what its rectangle covers. A luminance mask + // (which vello_cpu only takes at canvas size) cost a + // canvas-sized render, mask and composite per draw: a page of + // 73,047 patterned 16 × 16 stencils took minutes. The clip is + // padded past the rectangle so that a stencil snapped to whole + // device pixels lies inside it; the cut clears the padding. + let device_rect = (transform * stencil_rect.to_path(0.1)) + .bounding_box() + .inflate(2.0, 2.0); + if ![device_rect.x0, device_rect.y0, device_rect.x1, device_rect.y1] + .iter() + .all(|v| v.is_finite()) + { + log::warn!("Stencil mask has an invalid transform; image skipped"); + return; + } + let layer_clip = device_rect.to_path(0.1); + let blend_mode = self.ctx.blend_mode(); + self.ctx.set_transform(Affine::IDENTITY); + self.ctx.push_clip_layer(&layer_clip); + // Unclipped, so isolated: a layer with only a clip draws + // straight into what is under it, which the cut would clear. + self.ctx.push_layer(None, Some(blend_mode), None, None, None); self.ctx.set_transform(transform); // PdfCraft patch: a stencil mask is painted with the fill - // (non-stroking) paint; `true` drew an uncolored tiling pattern - // in its stroke color (black by default) (#2975). + // (non-stroking) paint; `true` drew an uncoloured tiling pattern + // in its stroke colour (black by default) (#2975). if let PaintSetup::Clip(clip_path) = self.set_paint(paint, &stencil_rect.to_path(0.1), false) { @@ -1756,6 +2402,37 @@ impl<'a> Device<'a> for Renderer { } } + // The stencil, as white ink under its own coverage, keeps the + // pattern where it paints and clears the rest of the clip. + let paint_blend = self.ctx.blend_mode(); + self.ctx.set_blend_mode(peniko::BlendMode::default()); + // The pattern left its own paint transform, which would place + // the stencil's pixels. + self.ctx.set_paint_transform(Affine::IDENTITY); + self.ctx.push_blend_layer(peniko::BlendMode::new( + Mix::Normal, + Compose::DestIn, + )); + self.ctx.set_transform(transform); + // The coverage is drawn as a stencil outside a Type 3 glyph is: + // a glyph's image rules (nearest shrink, padded frame) are for + // the glyph's own images. + let in_type3_glyph = std::mem::replace(&mut self.in_type3_glyph, false); + self.draw_image( + ImageData::Rgb(RgbData { + data: white, + width: stencil.width, + height: stencil.height, + interpolate: stencil.interpolate, + scale_factors: stencil.scale_factors, + }), + Some(stencil), + ); + self.in_type3_glyph = in_type3_glyph; + self.ctx.pop_layer(); + self.ctx.set_blend_mode(paint_blend); + + self.ctx.pop_layer(); self.ctx.pop_layer(); } }; @@ -1783,21 +2460,86 @@ impl<'a> Device<'a> for Renderer { self.push_clip_path_inner(&clip_path.path, clip_path.fill); } + /// PdfCraft patch (27): a nested group blending in another space can't be drawn in a pass. + fn group_blends_outside_device_cmyk(&mut self) { + if self.ink.pass.is_some() { + self.ink.unsupported = true; + } + } + + /// PdfCraft patch (27), with hayro-interpret patch (70): an isolated group that blends in + /// `DeviceCMYK` (ISO 32000-2 §11.3.4). Its contents are drawn twice on canvases of their own, + /// as cyan-magenta-yellow and as black (see [`InkState`]), and the tints those passes leave + /// are converted to RGB through the CMYK profile solid CMYK colour is drawn with. The + /// result goes into the layer the interpreter pushed for the group, which composites it + /// with the group's opacity, soft mask and blend mode as before. Declined (and so drawn as + /// before) under reading colours, inside a pass (a nested group then blends in the pass's + /// own CMYK), while erasing for a knockout group (the contents must clear, not paint), and + /// for contents a pass has no tints for. + fn draw_isolated_cmyk_group(&mut self, group: &hayro_interpret::CmykGroup<'a, '_>) -> bool { + if self.color_replacement.is_some() || self.ink.pass.is_some() || self.erasing { + return false; + } + let canvas = Rect::new(0.0, 0.0, f64::from(self.ctx.width()), f64::from(self.ctx.height())); + let area = group.device_bbox().intersect(canvas); + if !(area.width() > 0.0 && area.height() > 0.0) { + // Nothing of the group is on the canvas (a NaN box lands here too). + return true; + } + let (x0, y0) = (area.x0.floor(), area.y0.floor()); + // Within the canvas, so the sides fit its u16 ones. + let width = (area.x1.ceil() - x0) as u16; + let height = (area.y1.ceil() - y0) as u16; + if width == 0 || height == 0 { + return true; + } + // Bands of whole rows, each within the band size: a group of any size blends in CMYK. + // Every band is blended before any is drawn, so a group a pass has no tints for in one + // band is drawn as before, whole. + let band = (CMYK_BAND_PIXELS.with(std::cell::Cell::get) / u64::from(width)).clamp(1, u64::from(height)); + // At most `height`, so it fits a u16. + let band = band as u16; + let mut result = offscreen_pixmap(width, height, false); + let row = usize::from(width); + let mut top = 0u16; + while top < height { + let rows = band.min(height - top); + let Some(piece) = self.cmyk_group_band(group, (x0, y0 + f64::from(top)), width, rows) else { + return false; + }; + let start = usize::from(top) * row; + let Some(dest) = result.data_mut().get_mut(start..start + usize::from(rows) * row) else { + return false; + }; + dest.copy_from_slice(piece.data()); + top += rows; + } + + // The group's own soft mask and blend mode are on its layer; what the contents set + // must not apply to the finished pixels a second time. + self.set_soft_mask(None); + self.set_blend_mode(BlendMode::Normal); + // A pattern painted earlier leaves its paint transform on the context. + self.ctx.set_paint_transform(Affine::IDENTITY); + self.draw_pixmap(Arc::new(result), ImageQuality::Low, Affine::translate((x0, y0))); + true + } + fn push_transparency_group( &mut self, opacity: f32, mask: Option>, blend_mode: BlendMode, ) { - // Knockout patch (pdfcraft #2974): nothing is layered in a knockout erase pass. + // PdfCraft patch (22): nothing is layered in a knockout erase pass. if self.erasing { self.erase_groups += 1; return; } - // Knockout patch (pdfcraft #4898): an image or group of another pass than the current - // one clears what is under its shape instead of painting: its layer, drawn at full - // opacity with no soft mask, composites with `Compose::DestOut`. That clears the coverage - // of a masked image's or a stencil's mask too, which `knockout_image` leaves alone. + // PdfCraft patch (26): an image or group of another pass than the current one clears + // what is under its shape instead of painting: its layer, drawn at full opacity with no + // soft mask, composites with `Compose::DestOut`. That clears the coverage of a masked + // image's or a stencil's mask too, which `knockout_image` leaves alone. let (opacity, mask, layer_blend) = if self.knockout_pass_skips(blend_mode) { (1.0, None, peniko::BlendMode::new(Mix::Normal, Compose::DestOut)) } else { @@ -1846,16 +2588,16 @@ impl<'a> Device<'a> for Renderer { self.ctx.pop_layer(); } - /// Knockout patch (pdfcraft #2974): the group just pushed is a knockout group. Its elements are - /// drawn with `Compose::Copy`, which (weighted by coverage) replaces what earlier elements drew - /// where the element's shape is, so each element composites with the group's initial backdrop - /// (transparent: an isolated group, and the non-isolated approximation every group layer here - /// already makes) instead of with the elements before it. Against a transparent backdrop the - /// element's own blend mode has nothing to blend with, so the mix is Normal. This covers paths, - /// strokes, glyph outlines and shadings. Images and nested groups are drawn into a layer of - /// their own, which can't be copied (it covers the whole canvas, transparent where nothing was - /// drawn): what is under their shape is cleared first (`knockout_shape`, the knockout erase - /// pass) and the layer composites over it. + /// PdfCraft patch (22): the group just pushed is a knockout group. Its elements are drawn + /// with `Compose::Copy`, which (weighted by coverage) replaces what earlier elements drew + /// where the element's shape is, so each element composites with the group's initial + /// backdrop (transparent: an isolated group, and the non-isolated approximation every + /// group layer here already makes) instead of with the elements before it. Against a + /// transparent backdrop the element's own blend mode has nothing to blend with, so the + /// mix is Normal. This covers paths, strokes, glyph outlines and shadings. Images and + /// nested groups are drawn into a layer of their own, which can't be copied (it covers the + /// whole canvas, transparent where nothing was drawn): what is under their shape is cleared + /// first (`knockout_shape`, the knockout erase pass) and the layer composites over it. fn set_knockout(&mut self) { if let Some(top) = self.knockout.last_mut() { *top = true; @@ -1863,9 +2605,9 @@ impl<'a> Device<'a> for Renderer { } } - /// Knockout patch (pdfcraft #2974): in a knockout group, clear what the group drew under - /// `shape` (a transparent fill with `Compose::Copy`, weighted by coverage) before an element - /// drawn into a layer of its own composites there, so the element replaces it. + /// PdfCraft patch (22): in a knockout group, clear what the group drew under `shape` (a + /// transparent fill with `Compose::Copy`, weighted by coverage) before an element drawn into + /// a layer of its own composites there, so the element replaces it. fn knockout_erase_wanted(&mut self) -> bool { self.in_knockout() && !self.erasing } @@ -2007,9 +2749,7 @@ impl<'a> Device<'a> for Renderer { // PdfCraft patch: apply the reading-colours mapping before painting. let paint = self.replaced(paint, false); - let PaintSetup::Clip(clip_path) = self.set_paint(&paint, &path, false) else { - return; - }; + let PaintSetup::Clip(clip_path) = self.set_paint(&paint, &path, false) else { return }; if let Some(clip_path) = clip_path.as_ref() { self.push_clip_path_inner(clip_path, *fill_rule); } @@ -2042,21 +2782,20 @@ impl<'a> Device<'a> for Renderer { Self::stroke_glyph(self, glyph, transform, glyph_transform, paint, s); } GlyphDrawMode::Invisible | GlyphDrawMode::Clip => { - // PdfCraft patch (#3116): neither mode paints; the interpreter installs the clip. + // PdfCraft patch: neither mode paints; clipping was installed by the interpreter. } } } fn set_blend_mode(&mut self, blend_mode: BlendMode) { - // Knockout patch (pdfcraft #4898): the blend mode of the element about to paint, for its - // pass (an erase pass paints nothing, and its content's modes are not the element's). + // PdfCraft patch (26): the blend mode of the element about to paint, for its pass (an + // erase pass paints nothing, and its content's modes are not the element's). if !self.erasing && let Some(pass) = self.knockout_pass() { pass.element_mode = blend_mode; } - // Knockout patch (pdfcraft #2974): inside a knockout group every element replaces what it - // covers. + // PdfCraft patch (22): inside a knockout group every element replaces what it covers. let mode = if self.in_knockout() { knockout_blend_mode() } else { @@ -2139,7 +2878,6 @@ fn render_shading_texture( ) } -/// A renderer for a soft mask's contents, `width` × `height` device pixels. fn soft_mask_renderer(settings: &RenderSettings, width: u16, height: u16, preview: bool) -> Renderer { Renderer { ctx: RenderContext::new_with(width, height, derive_settings(settings)), @@ -2154,11 +2892,13 @@ fn soft_mask_renderer(settings: &RenderSettings, width: u16, height: u16, previe inside_pattern: false, cur_mask: None, soft_mask_cache: HashMap::default(), + tiling_cells: TilingCells::default(), outline_cache: Rc::new(std::cell::RefCell::new(HashMap::new())), in_type3_glyph: false, scaler: Scaler::new(ResamplingFunction::CatmullRom), preview, image_transparency_stack: Vec::new(), + ink: InkState::default(), } } @@ -2167,6 +2907,7 @@ fn draw_soft_mask(mask: &SoftMask<'_>, settings: RenderSettings, width: u16, hei cmyk_luminosity(mask, &settings, width, height, preview) } else { let mut renderer = soft_mask_renderer(&settings, width, height, preview); + let bg_color = mask.background_color().to_rgba(); let apply_bg = bg_color.to_rgba8() != BLACK.to_rgba8().to_u8_array(); @@ -2186,7 +2927,7 @@ fn draw_soft_mask(mask: &SoftMask<'_>, settings: RenderSettings, width: u16, hei renderer.ctx.pop_layer(); } - let mut pix = Pixmap::new(width, height); + let mut pix = offscreen_pixmap(width, height, false); renderer.ctx.flush(); let mut resources = vello_cpu::Resources::default(); renderer.ctx.render_to_pixmap(&mut resources, &mut pix); @@ -2236,7 +2977,7 @@ fn cmyk_luminosity(mask: &SoftMask<'_>, settings: &RenderSettings, width: u16, h mask.interpret_plate(&mut renderer, plate); renderer.ctx.pop_layer(); - let mut pix = Pixmap::new(width, height); + let mut pix = offscreen_pixmap(width, height, false); renderer.ctx.flush(); let mut resources = vello_cpu::Resources::default(); renderer.ctx.render_to_pixmap(&mut resources, &mut pix); @@ -2289,8 +3030,7 @@ fn convert_fill_rule(fill_rule: FillRule) -> Fill { } } -/// Knockout patch (pdfcraft #4898): one blend-mode pass over a knockout group -/// (`Device::begin_knockout_pass`). +/// PdfCraft patch (26): one blend-mode pass over a knockout group (`Device::begin_knockout_pass`). struct KnockoutPass { /// `knockout.len()` with the group pushed: its own elements are drawn at this depth. depth: usize, @@ -2302,7 +3042,7 @@ struct KnockoutPass { other_modes: Vec, } -/// Knockout patch (pdfcraft #4898): `paint` at full opacity, for the shape it covers. +/// PdfCraft patch (26): `paint` at full opacity, for the shape it covers. fn shape_of<'a>(paint: &Paint<'a>) -> Paint<'a> { match paint { Paint::Pattern(p) => match p.as_ref() { @@ -2317,18 +3057,17 @@ fn shape_of<'a>(paint: &Paint<'a>) -> Paint<'a> { } } -/// Knockout patch (pdfcraft #4898): whether `paint` is a shading. +/// PdfCraft patch (26): whether `paint` is a shading. fn is_shading(paint: &Paint<'_>) -> bool { matches!(paint, Paint::Pattern(p) if matches!(p.as_ref(), Pattern::Shading(_))) } -/// Knockout patch (pdfcraft #2974): how an element of a knockout group is drawn (see -/// `set_knockout`). +/// PdfCraft patch (22): how an element of a knockout group is drawn (see `set_knockout`). fn knockout_blend_mode() -> peniko::BlendMode { peniko::BlendMode::new(Mix::Normal, Compose::Copy) } -/// PdfCraft patch (#3296): the part of `bbox` a shading encoded within it paints. A mesh paints +/// PdfCraft patch (19): the part of `bbox` a shading encoded within it paints. A mesh paints /// only around its triangles, and nothing (`None`) when none is in `bbox`; its empty extent is /// `Rect::ZERO`, at the canvas origin, so it is tested before intersecting, or a 1 × 1 /// transparent texture would still be painted over the whole path (310 of them cost 230 ms per @@ -2418,3 +3157,249 @@ pub fn tiling_cell_scale(scale: f32, step: f32, max_pixels: f32) -> f32 { scale } } + +/// PdfCraft patch (25): the side of a tiling cell pixmap in pixels, and the scale to draw the +/// cell at so that one `step` spans exactly that many pixels. The pixmap repeats every whole +/// number of pixels; drawing the cell at `scale` itself would repeat it at `round(scale × step)` +/// instead of `scale × step`, a fraction of a pixel off at every step (ISO 32000-2 8.7.3.1: cells +/// are displaced by multiples of `/XStep` and `/YStep`). The side is kept within 1 and +/// `max_pixels` (itself at most `u16::MAX`). When `scale × step` isn't finite and positive, +/// `scale` is kept and the side is `max_pixels` for an infinite product, 1 otherwise. +pub fn tiling_cell_pixels(scale: f32, step: f32, max_pixels: f32) -> (u16, f64) { + // A whole number of pixels; `max` and `min` (not `clamp`, which panics on NaN) make a NaN cap 1. + let max = f64::from(max_pixels).floor().max(1.0).min(f64::from(u16::MAX)); + let (scale, step) = (f64::from(scale), f64::from(step.abs())); + let exact = scale * step; + if !(exact.is_finite() && exact > 0.0) { + let pixels = if exact == f64::INFINITY { max } else { 1.0 }; + // In 1..=u16::MAX, so the cast is exact. + return (pixels as u16, scale); + } + let pixels = exact.round().max(1.0).min(max); + // `pixels` is in 1..=u16::MAX, so the cast is exact; `step` is positive and finite here + // (`exact` is), so the division is too. + (pixels as u16, pixels / step) +} + +#[cfg(test)] +mod snap_tests { + use super::{snap_minified_image, Affine}; + + /// The skew a snap drops is measured as the distance it moves the image's far edge, not as a + /// coefficient against the scale: a 40 000 sample wide image skewed by 4e-5 per sample moves + /// its far edge 1.6 device pixels, and must keep its full transform (#5640 review). + #[test] + fn a_skew_that_moves_a_far_edge_is_not_snapped() { + let source = (40_000, 400); + let planned = (20_000, 200); + // Upright, shrunk to half, sheared so the far end sits 1.6 pixels lower: not snapped. + let skewed = Affine::new([0.5, 4e-5, 0.0, 0.5, 0.3, 0.3]); + assert!(snap_minified_image(&skewed, source, planned).is_none()); + // A quarter turn with the same stray term along device x: not snapped either. + let turned = Affine::new([4e-5, 0.5, -0.5, 0.0, 200.3, 0.3]); + assert!(snap_minified_image(&turned, source, (20_000, 200)).is_none()); + // Rounding noise far below a hundredth of a pixel at the far edge still snaps. + let noisy = Affine::new([0.5, 1e-9, 0.0, 0.5, 0.3, 0.3]); + assert!(snap_minified_image(&noisy, source, planned).is_some()); + let turned_noisy = Affine::new([1e-9, 0.5, -0.5, 0.0, 200.3, 0.3]); + assert!(snap_minified_image(&turned_noisy, source, (20_000, 200)).is_some()); + } +} + +/// PdfCraft patch: the area-averaging shrink of non-interpolated images. +#[cfg(test)] +mod area_shrink_tests { + use super::{ + AREA_ONE, AreaAxis, ImageData, LumaData, MAX_IMAGE_PIXELS, RgbData, area_shrink, + area_shrink_premultiplied, area_taps, mask_on_image_grid, premultiply_rgba, + }; + + /// Deterministic samples that vary from one to the next. + fn noise(len: usize, seed: u32) -> Vec { + let mut x = seed.wrapping_mul(2_654_435_761) | 1; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + (x >> 24) as u8 + }) + .collect() + } + + /// The shrink as two whole passes, every row averaged down and then every row across, each + /// rounded to a byte: what `area_shrink` did before it worked a row at a time. + fn two_pass_shrink(data: &[u8], (sw, sh): (u32, u32), (tw, th): (u32, u32)) -> Vec { + let round = |acc: u64| ((acc + AREA_ONE / 2) >> 16).min(255) as u8; + let row_len = sw as usize * N; + let tall: Vec = (0..th) + .flat_map(|t| { + (0..row_len).map(move |i| { + round(area_taps(sh, th, t).map(|(s, w)| w * u64::from(data[s * row_len + i])).sum()) + }) + }) + .collect(); + tall.chunks_exact(row_len) + .flat_map(|row| { + (0..tw).flat_map(move |t| { + (0..N).map(move |c| round(area_taps(sw, tw, t).map(|(s, w)| w * u64::from(row[s * N + c])).sum())) + }) + }) + .collect() + } + + /// Working a row at a time gives the same bytes as two whole passes, in both directions, one + /// direction alone, and with source rows shared by neighbouring targets. + #[test] + fn a_row_at_a_time_shrink_equals_two_whole_passes() { + let sizes = [((7, 5), (3, 2)), ((10, 3), (6, 3)), ((4, 9), (4, 4)), ((13, 11), (1, 1)), ((31, 17), (12, 7))]; + for (i, (source, target)) in sizes.into_iter().enumerate() { + let gray = noise((source.0 * source.1) as usize, i as u32); + assert_eq!(area_shrink::<1>(&gray, source, target), Some(two_pass_shrink::<1>(&gray, source, target)), "{source:?} → {target:?}"); + let rgba = noise((source.0 * source.1 * 4) as usize, i as u32 + 99); + assert_eq!(area_shrink::<4>(&rgba, source, target), Some(two_pass_shrink::<4>(&rgba, source, target)), "{source:?} → {target:?}"); + } + } + + /// Premultiplying a row at a time as it is averaged gives the same bytes as premultiplying the + /// whole expanded RGBA first and shrinking that, for gray and RGB colour. + #[test] + fn premultiplying_row_by_row_equals_premultiplying_the_whole_image() { + let sizes = [((7, 5), (3, 2)), ((10, 3), (6, 3)), ((4, 9), (4, 4)), ((31, 17), (12, 7))]; + for (i, (source, target)) in sizes.into_iter().enumerate() { + let (w, h) = source; + let pixels = (w * h) as usize; + let alpha = noise(pixels, i as u32 + 7); + let gray = noise(pixels, i as u32 + 11); + let rgb = noise(pixels * 3, i as u32 + 13); + let colors = [ + ImageData::Luma(LumaData { data: gray.clone(), width: w, height: h, interpolate: false, scale_factors: (1.0, 1.0) }), + ImageData::Rgb(RgbData { data: rgb.clone(), width: w, height: h, interpolate: false, scale_factors: (1.0, 1.0) }), + ]; + for color in &colors { + let mut whole: Vec = match color { + ImageData::Luma(_) => gray.iter().zip(&alpha).flat_map(|(g, a)| [*g, *g, *g, *a]).collect(), + ImageData::Rgb(_) => rgb.chunks_exact(3).zip(&alpha).flat_map(|(c, a)| [c[0], c[1], c[2], *a]).collect(), + }; + premultiply_rgba(&mut whole); + assert_eq!( + area_shrink_premultiplied(color, &alpha, source, target), + area_shrink::<4>(&whole, source, target), + "{source:?} → {target:?}" + ); + } + let short = alpha.get(1..).unwrap_or_default(); + assert_eq!(area_shrink_premultiplied(&colors[0], short, source, target), None, "alpha shorter than the image"); + } + } + + fn mask(data: &[u8], width: u32, height: u32) -> LumaData { + LumaData { data: data.to_vec(), width, height, interpolate: false, scale_factors: (1.0, 1.0) } + } + + /// Each image sample takes the mask sample under its centre, at whole and fractional ratios. + #[test] + fn a_mask_is_sampled_onto_the_image_grid() { + assert_eq!(mask_on_image_grid(&mask(&[10, 20], 2, 1), 4, 2), Some(vec![10, 10, 20, 20, 10, 10, 20, 20])); + // Centres of 7 samples over 3: 0.5/7·3 = 0.21 → 0, 1.5/7·3 = 0.64 → 0, 2.5/7·3 = 1.07 → 1, … + assert_eq!(mask_on_image_grid(&mask(&[1, 2, 3], 3, 1), 7, 1), Some(vec![1, 1, 2, 2, 2, 3, 3])); + } + + /// A mask that asks for `/Interpolate` is blended between the samples around each centre, + /// and held at its ends: the centres of 4 samples over 2 lie at -¼, ¼, ¾ and 1¼. + #[test] + fn an_interpolated_mask_is_blended_onto_the_image_grid() { + let smooth = |data: &[u8], width, height| LumaData { interpolate: true, ..mask(data, width, height) }; + assert_eq!(mask_on_image_grid(&smooth(&[0, 255], 2, 1), 4, 2), Some(vec![0, 64, 191, 255, 0, 64, 191, 255])); + // Centres of 7 samples over 3 lie 3/7 apart, from -2/7 to 2 2/7: a ramp, flat at the ends. + assert_eq!(mask_on_image_grid(&smooth(&[0, 70, 140], 3, 1), 7, 1), Some(vec![0, 10, 40, 70, 100, 130, 140])); + assert_eq!(mask_on_image_grid(&smooth(&[0, 255], 1, 2), 1, 4), Some(vec![0, 64, 191, 255])); + assert_eq!(mask_on_image_grid(&smooth(&[7, 9], 2, 1), 2, 1), Some(vec![7, 9]), "same size is unchanged"); + } + + #[test] + fn malformed_masks_are_not_sampled() { + assert_eq!(mask_on_image_grid(&mask(&[], 0, 1), 4, 1), None, "an empty mask"); + assert_eq!(mask_on_image_grid(&mask(&[1, 2], 2, 1), 0, 1), None, "an empty image"); + assert_eq!(mask_on_image_grid(&mask(&[1], 2, 1), 4, 1), None, "mask data shorter than its size"); + assert_eq!(mask_on_image_grid(&mask(&[1, 2, 3, 4], 1, 4), 1, 2), None, "a mask larger than the image"); + } + + /// Every target sample's weights add up to exactly one, and together the targets take every + /// source sample exactly once (each `dst / src` of it, in fixed point within rounding). + #[test] + fn taps_are_exact_partitions_of_unity() { + for src in 1..=40_u32 { + for dst in 1..=src { + let mut taken = vec![0_u64; src as usize]; + for t in 0..dst { + let taps: Vec<_> = area_taps(src, dst, t).collect(); + assert_eq!(taps.iter().map(|(_, w)| w).sum::(), AREA_ONE, "{src} → {dst}, target {t}"); + assert!(taps.iter().all(|(_, w)| *w > 0), "{src} → {dst}, target {t}: an empty tap"); + for (s, w) in taps { + taken[s] += w; + } + } + // Source s is dst/src of one target in all; scaled by src/dst, that is one. + for (s, w) in taken.iter().enumerate() { + let share = (*w * u64::from(src)) as f64 / (AREA_ONE * u64::from(dst)) as f64; + assert!((share - 1.0).abs() < 1e-3, "{src} → {dst}: source {s} weighs {share}"); + } + } + } + } + + /// The table the horizontal pass reads holds exactly the taps of every target, in order. + #[test] + fn the_tap_table_holds_every_targets_taps() { + for src in 1..=40_u32 { + for dst in 1..=src { + let axis = AreaAxis::new(src, dst).expect("table"); + for t in 0..dst { + let (first, weights) = axis.get(t as usize).expect("target"); + let expected: Vec<(usize, u64)> = area_taps(src, dst, t).collect(); + let got: Vec<(usize, u64)> = weights.iter().enumerate().map(|(k, w)| (first + k, u64::from(*w))).collect(); + assert_eq!(got, expected, "{src} → {dst}, target {t}"); + } + assert_eq!(axis.get(dst as usize), None, "{src} → {dst}: no target past the last"); + } + } + } + + /// The largest side an image may have still computes in u64 without overflowing. + #[test] + fn taps_at_the_pixel_limit_do_not_overflow() { + let side = MAX_IMAGE_PIXELS as u32; + for (dst, t) in [(1, 0), (3, 2), (side - 1, side - 2), (side, side - 1)] { + assert_eq!(area_taps(side, dst, t).map(|(_, w)| w).sum::(), AREA_ONE, "{side} → {dst}, target {t}"); + } + } + + #[test] + fn flat_images_keep_their_exact_value() { + for (source, target) in [((7, 5), (3, 2)), ((10, 3), (6, 3)), ((4, 9), (4, 4)), ((13, 11), (1, 1))] { + let data = vec![77_u8; (source.0 * source.1 * 3) as usize]; + let out = area_shrink::<3>(&data, source, target).expect("shrinks"); + assert_eq!(out.len(), (target.0 * target.1 * 3) as usize); + assert!(out.iter().all(|v| *v == 77), "{source:?} → {target:?}: {out:?}"); + } + } + + /// A side over the resampling limit is refused before any work buffer is allocated. + #[test] + fn sides_over_the_resampling_limit_are_refused() { + let wide = (super::MAX_RESAMPLING_SOURCE_SIDE + 1) as usize; + assert_eq!(area_shrink::<1>(&vec![0_u8; wide], (wide as u32, 1), (10, 1)), None, "too wide"); + assert_eq!(area_shrink::<1>(&vec![0_u8; wide], (1, wide as u32), (1, 10)), None, "too tall"); + } + + #[test] + fn malformed_shrinks_are_refused() { + let data = vec![0_u8; 4 * 4]; + assert_eq!(area_shrink::<1>(&data, (4, 4), (4, 4)), None, "nothing shrinks"); + assert_eq!(area_shrink::<1>(&data, (4, 4), (5, 2)), None, "a side grows"); + assert_eq!(area_shrink::<1>(&data, (4, 4), (0, 2)), None, "an empty side"); + assert_eq!(area_shrink::<1>(&data[1..], (4, 4), (2, 2)), None, "data shorter than the source"); + assert_eq!(area_shrink::<3>(&data, (4, 4), (2, 2)), None, "data of another channel count"); + } +}