Merge main into feat/craft-video-mjpeg-decode-into

This commit is contained in:
dotCooCoo committed 2026-11-21 13:53:08 -08:00
commit 557e919187
94 files changed
+16253 -267

No files matched your search

+3
View File
@@ -16,6 +16,7 @@ on:
- "crates/tiff/**"
- "crates/heif/**"
- "crates/cms/**"
- "crates/cdr/**"
- "Cargo.toml"
- "Cargo.lock"
- ".github/workflows/formats.yml"
@@ -33,6 +34,7 @@ on:
- "crates/tiff/**"
- "crates/heif/**"
- "crates/cms/**"
- "crates/cdr/**"
- "Cargo.toml"
- "Cargo.lock"
- ".github/workflows/formats.yml"
@@ -67,6 +69,7 @@ jobs:
- { crate: craft-tiff, features: "" }
- { crate: craft-heif, features: "testdata" }
- { crate: craft-cms, features: "" }
- { crate: craft-cdr, features: "synth" }
# fmt, clippy with default and with all features, and the tests run in the Workspace gate on
# every OS; this lints each feature alone and checks the web build.
name: ${{ matrix.crate }} feature sets, WASM
Generated
+11
View File
@@ -1647,6 +1647,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-cdr"
version = "0.1.0"
dependencies = [
"craft-cdr",
"crc32fast",
"flate2",
"proptest",
]
[[package]]
name = "craft-cfb"
version = "0.1.0"
@@ -2985,6 +2995,7 @@ name = "craft-ppt-binary"
version = "0.1.0"
dependencies = [
"craft-cfb",
"craft-codepage",
"craft-drawingml",
"craft-pptx",
"image",
+1
View File
@@ -39,6 +39,7 @@ craft-wasm = { path = "crates/wasm" }
craft-platform = { path = "crates/platform" }
craft-aep = { path = "crates/aep" }
craft-affinity = { path = "crates/affinity" }
craft-cdr = { path = "crates/cdr" }
craft-ai = { path = "crates/ai" }
craft-ai-core = { path = "crates/ai-core" }
craft-anicraft-format = { path = "crates/anicraft-format" }
+6
View File
@@ -426,3 +426,9 @@ Original src/avx2/fdct.rs opening notice
* Based on the x86 SIMD extension for IJG JPEG library
* Copyright (C) 1999-2006, MIYASAKA Masaru.
*/
The .cdr reader (crates/cdr, moved from VectorCraft crates/cdr) reads the record layouts that the
Kaitai Struct specification coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy,
MIT License) and its fork by Zach Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch
new_stuff, MIT License) describe. No part of either specification is copied into the crate; the
license text is in crates/cdr/LICENSE-kaitai.txt.
+31 -5
View File
@@ -205,6 +205,16 @@ impl<'a> Bits<'a> {
const BLOCK_SIZES: [usize; 16] = [0, 192, 576, 1152, 2304, 4608, 0, 0, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768];
struct FrameHeader {
variable: bool,
number: u64,
block_size: usize,
sample_rate: u32,
bits: u32,
channels: usize,
mode: Stereo,
}
/// A frame decoder. `info` supplies what a frame header leaves to the STREAMINFO.
#[derive(Debug, Clone, Copy, Default)]
pub struct Decoder {
@@ -223,14 +233,12 @@ impl Decoder {
Decoder { info: None }
}
/// Decode the frame at the start of `data`.
pub fn decode_frame(&self, data: &[u8]) -> Result<Frame> {
fn read_frame_header(&self, r: &mut Bits<'_>) -> Result<FrameHeader> {
// StreamInfo has public fields: container callers can construct it without
// parse(), so validate before it can control shifts and sample reads.
if self.info.is_some_and(|i| !(4..=32).contains(&i.bits_per_sample) || !(1..=8).contains(&i.channels) || i.sample_rate == 0) {
return Err(DecodeError::Invalid("invalid decoder STREAMINFO"));
}
let mut r = Bits::new(data);
if r.bits(15)? != 0x7FFC {
return Err(DecodeError::Invalid("missing frame sync code"));
}
@@ -240,7 +248,7 @@ impl Decoder {
if r.bit()? != 0 {
return Err(DecodeError::Invalid("reserved bit set"));
}
let number = coded_number(&mut r)?;
let number = coded_number(r)?;
let block_size = match bs_code {
0 => return Err(DecodeError::Invalid("reserved block size")),
6 => r.bits(8)? as usize + 1,
@@ -267,7 +275,7 @@ impl Decoder {
};
let header_len = r.pos.div_ceil(8);
let stored_crc = r.bits(8)? as u8;
if crc8(&data[..header_len]) != stored_crc {
if crc8(&r.data[..header_len]) != stored_crc {
return Err(DecodeError::Crc("a frame header"));
}
let bits = match bps_code {
@@ -287,6 +295,24 @@ impl Decoder {
10 => (2, Stereo::MidSide),
_ => return Err(DecodeError::Invalid("reserved channel assignment")),
};
Ok(FrameHeader { variable, number, block_size, sample_rate, bits, channels, mode })
}
/// Read a FLAC packet's sample count from an intact header even if the body is damaged.
pub(crate) fn packet_block_size(&self, data: &[u8]) -> Option<usize> {
let info = self.info?;
let header = self.read_frame_header(&mut Bits::new(data)).ok()?;
(header.sample_rate == info.sample_rate
&& header.bits == u32::from(info.bits_per_sample)
&& header.channels == usize::from(info.channels)
&& header.block_size <= usize::from(u16::MAX))
.then_some(header.block_size)
}
/// Decode the frame at the start of `data`.
pub fn decode_frame(&self, data: &[u8]) -> Result<Frame> {
let mut r = Bits::new(data);
let FrameHeader { variable, number, block_size, sample_rate, bits, channels, mode } = self.read_frame_header(&mut r)?;
let mut out: Vec<Vec<i64>> = Vec::with_capacity(channels);
for c in 0..channels {
let extra = match (mode, c) {
+114
View File
@@ -0,0 +1,114 @@
//! FLAC speaker layout from STREAMINFO and Vorbis comments (RFC 9639).
use crate::ChannelLayout;
use crate::pcm::{be_u32, le_u32};
/// The layout of the FLAC stream at `at`, from its STREAMINFO channel count and its channel mask
/// comment, or `None` when it does not start with a STREAMINFO block.
#[cfg(feature = "symphonia")]
pub(crate) fn layout(b: &[u8], at: usize) -> Option<ChannelLayout> {
let head = be_u32(b, at.checked_add(4)?)?;
if (head >> 24) & 0x7f != 0 {
return None;
}
// In STREAMINFO: 3 bits of channels - 1 after the 20 bits of rate.
let channels = u16::from((b.get(at.checked_add(4 + 4 + 10 + 2)?)? >> 1) & 0x7) + 1;
Some(layout_of(b, at, channels))
}
/// `channels` channels described by the channel mask comment of the stream at `at`, or else in
/// the layout decoders assume for the count (RFC 9639 §8.6.2, §9.1.3).
pub(crate) fn layout_of(b: &[u8], at: usize, channels: u16) -> ChannelLayout {
layout_from(channel_mask(b, at), channels)
}
/// `channels` channels described by a channel mask comment's value, or else in the layout decoders
/// assume for the count.
pub(crate) fn layout_from(mask: Option<u32>, channels: u16) -> ChannelLayout {
let mask = mask.unwrap_or_else(|| crate::layout::flac_assumed_mask(usize::from(channels)));
ChannelLayout::from_mask_and_channels(mask, channels)
}
/// The value of the first `WAVEFORMATEXTENSIBLE_CHANNEL_MASK` comment that holds a `0x` hexadecimal
/// number, in the stream at `at`.
fn channel_mask(b: &[u8], at: usize) -> Option<u32> {
let mut pos = at.checked_add(4)?;
loop {
let head = be_u32(b, pos)?;
let (body, len) = (pos.checked_add(4)?, (head & 0x00ff_ffff) as usize);
let end = body.checked_add(len)?.min(b.len());
if (head >> 24) & 0x7f == 4 {
return comments_mask(b.get(body..end)?);
}
if head >> 31 == 1 {
return None;
}
pos = body.checked_add(len)?;
}
}
/// The mask in a comment, when its key is the channel mask's and its value a `0x` hexadecimal number.
fn comment_mask(key: &[u8], value: &[u8]) -> Option<u32> {
if !key.eq_ignore_ascii_case(b"WAVEFORMATEXTENSIBLE_CHANNEL_MASK") {
return None;
}
let hex = value.strip_prefix(b"0x").or_else(|| value.strip_prefix(b"0X"))?;
u32::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()
}
/// The channel mask in a Vorbis comment block's body.
pub(crate) fn comments_mask(block: &[u8]) -> Option<u32> {
let vendor = le_u32(block, 0)? as usize;
let mut at = 4usize.checked_add(vendor)?;
let count = le_u32(block, at)?;
at += 4;
for _ in 0..count {
let len = le_u32(block, at)? as usize;
let comment = block.get(at + 4..(at + 4).checked_add(len)?)?;
at += 4 + len;
let Some(eq) = comment.iter().position(|&c| c == b'=') else { continue };
if let Some(mask) = comment_mask(&comment[..eq], &comment[eq + 1..]) {
return Some(mask);
}
}
None
}
#[cfg(test)]
mod tests {
use super::comments_mask;
fn block(comments: &[&str]) -> Vec<u8> {
let mut b = 3u32.to_le_bytes().to_vec();
b.extend_from_slice(b"abc");
b.extend_from_slice(&(comments.len() as u32).to_le_bytes());
for c in comments {
b.extend_from_slice(&(c.len() as u32).to_le_bytes());
b.extend_from_slice(c.as_bytes());
}
b
}
#[test]
fn the_channel_mask_comment_is_found_in_any_case() {
assert_eq!(comments_mask(&block(&["TITLE=x", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"])), Some(0x107));
assert_eq!(comments_mask(&block(&["waveformatextensible_channel_mask=0X3f"])), Some(0x3F));
assert_eq!(comments_mask(&block(&["TITLE=x"])), None);
}
#[test]
fn a_bad_channel_mask_comment_is_ignored() {
for value in ["63", "0x", "0xZZ", "0x1FFFFFFFF"] {
assert_eq!(comments_mask(&block(&[&format!("WAVEFORMATEXTENSIBLE_CHANNEL_MASK={value}")])), None, "{value}");
}
assert_eq!(comments_mask(&block(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=bad", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x3"])), Some(3));
}
#[test]
fn a_truncated_comment_block_has_no_mask() {
let whole = block(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x3"]);
for cut in 0..whole.len() {
assert_eq!(comments_mask(&whole[..cut]), None, "{cut}");
}
}
}
+2 -1
View File
@@ -151,6 +151,7 @@ impl TryFrom<RawLayout> for ChannelLayout {
feature = "opus-decode",
feature = "ac3-decode",
feature = "mpa-decode",
feature = "flac-decode",
feature = "pcm-encode"
))]
pub(crate) fn count(n: usize) -> u16 {
@@ -273,7 +274,7 @@ impl std::fmt::Display for ChannelLayout {
/// The layout decoders assume for 1–8 FLAC channels with no channel mask comment, as a WAV mask.
/// RFC 9639 §9.1.3 leaves "back/surround" open for 5 and 6 channels; libFLAC and ffmpeg read side
/// surrounds. 7 channels are 6.1 with sides (FL FR FC LFE BC SL SR).
#[cfg(any(feature = "symphonia", feature = "flac-encode"))]
#[cfg(any(feature = "symphonia", feature = "flac-encode", feature = "flac-decode"))]
pub(crate) fn flac_assumed_mask(channels: usize) -> u32 {
match channels {
5 => 0x607,
+26 -3
View File
@@ -49,6 +49,8 @@ pub mod alac;
mod buffer;
#[cfg(feature = "dsd")]
pub mod dsd;
#[cfg(any(feature = "flac-decode", feature = "symphonia"))]
mod flac_layout;
#[cfg(feature = "g722")]
pub mod g722;
#[cfg(feature = "g726")]
@@ -62,7 +64,14 @@ pub mod mp3;
pub mod mpa;
#[cfg(any(feature = "opus-decode", feature = "opus-encode"))]
pub mod opus;
#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))]
#[cfg(any(
feature = "aac-decode",
feature = "alac-decode",
feature = "opus-decode",
feature = "ac3-decode",
feature = "mpa-decode",
feature = "flac-decode"
))]
mod pcm;
#[cfg(feature = "peaks")]
pub mod peaks;
@@ -72,7 +81,14 @@ pub mod qoa;
mod read;
#[cfg(feature = "sbc")]
pub mod sbc;
#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))]
#[cfg(any(
feature = "aac-decode",
feature = "alac-decode",
feature = "opus-decode",
feature = "ac3-decode",
feature = "mpa-decode",
feature = "flac-decode"
))]
mod track;
#[cfg(feature = "vmd-decode")]
pub mod vmd;
@@ -150,7 +166,14 @@ pub use read::{
};
#[cfg(feature = "decode-native")]
pub use read::{RawPcm, aiff_pcm, wav_pcm};
#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))]
#[cfg(any(
feature = "aac-decode",
feature = "alac-decode",
feature = "opus-decode",
feature = "ac3-decode",
feature = "mpa-decode",
feature = "flac-decode"
))]
pub use track::{LOOKAHEAD_PACKETS, TrackDecoder};
#[cfg(any(
feature = "pcm-encode",
+2 -2
View File
@@ -14,7 +14,7 @@ pub(crate) fn le_u16(b: &[u8], pos: usize) -> Option<u16> {
}
/// Little-endian `u32` at `pos`.
#[cfg(feature = "decode-native")]
#[cfg(any(feature = "decode-native", feature = "flac-decode"))]
pub(crate) fn le_u32(b: &[u8], pos: usize) -> Option<u32> {
let s: [u8; 4] = b.get(pos..pos.checked_add(4)?)?.try_into().ok()?;
Some(u32::from_le_bytes(s))
@@ -35,7 +35,7 @@ pub(crate) fn be_u16(b: &[u8], pos: usize) -> Option<u16> {
}
/// Big-endian `u32` at `pos`.
#[cfg(feature = "decode-native")]
#[cfg(any(feature = "decode-native", feature = "flac-decode"))]
pub(crate) fn be_u32(b: &[u8], pos: usize) -> Option<u32> {
let s: [u8; 4] = b.get(pos..pos.checked_add(4)?)?.try_into().ok()?;
Some(u32::from_be_bytes(s))
+3 -110
View File
@@ -2,8 +2,10 @@
use craft_media::ogg;
use crate::flac_layout::{comments_mask, layout_of};
pub(crate) use crate::flac_layout::{layout, layout_from};
use crate::pcm::{be_u32, le_u32};
use crate::{AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result, SampleFormat};
use crate::{AudioError, AudioInfo, CodecId, Container, Result, SampleFormat};
/// Refuse the FLAC stream at `at` if a comment or picture field claims more bytes than its
/// metadata block holds: symphonia allocates each field's length before reading it.
@@ -72,58 +74,6 @@ pub(crate) fn empty_stream_info(b: &[u8], at: usize) -> Option<AudioInfo> {
Some(AudioInfo::new(Container::Flac, CodecId::Flac, sample_format, sample_rate, layout_of(b, at, channels), 0))
}
/// The layout of the FLAC stream at `at`, from its STREAMINFO channel count and its channel mask
/// comment, or `None` when it does not start with a STREAMINFO block.
pub(crate) fn layout(b: &[u8], at: usize) -> Option<ChannelLayout> {
let head = be_u32(b, at.checked_add(4)?)?;
if (head >> 24) & 0x7f != 0 {
return None;
}
// In STREAMINFO: 3 bits of channels - 1 after the 20 bits of rate.
let channels = u16::from((b.get(at.checked_add(4 + 4 + 10 + 2)?)? >> 1) & 0x7) + 1;
Some(layout_of(b, at, channels))
}
/// `channels` channels described by the channel mask comment of the stream at `at`, or else in
/// the layout decoders assume for the count (RFC 9639 §8.6.2, §9.1.3).
fn layout_of(b: &[u8], at: usize, channels: u16) -> ChannelLayout {
layout_from(channel_mask(b, at), channels)
}
/// `channels` channels described by a channel mask comment's value, or else in the layout decoders
/// assume for the count.
pub(crate) fn layout_from(mask: Option<u32>, channels: u16) -> ChannelLayout {
let mask = mask.unwrap_or_else(|| crate::layout::flac_assumed_mask(usize::from(channels)));
ChannelLayout::from_mask_and_channels(mask, channels)
}
/// The value of the first `WAVEFORMATEXTENSIBLE_CHANNEL_MASK` comment that holds a `0x` hexadecimal
/// number, in the stream at `at`.
fn channel_mask(b: &[u8], at: usize) -> Option<u32> {
let mut pos = at.checked_add(4)?;
loop {
let head = be_u32(b, pos)?;
let (body, len) = (pos.checked_add(4)?, (head & 0x00ff_ffff) as usize);
let end = body.checked_add(len)?.min(b.len());
if (head >> 24) & 0x7f == 4 {
return comments_mask(b.get(body..end)?);
}
if head >> 31 == 1 {
return None;
}
pos = body.checked_add(len)?;
}
}
/// The mask in a comment, when its key is the channel mask's and its value a `0x` hexadecimal number.
fn comment_mask(key: &[u8], value: &[u8]) -> Option<u32> {
if !key.eq_ignore_ascii_case(b"WAVEFORMATEXTENSIBLE_CHANNEL_MASK") {
return None;
}
let hex = value.strip_prefix(b"0x").or_else(|| value.strip_prefix(b"0X"))?;
u32::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()
}
/// The audio streams of the Ogg file `b` in file order, as `tracks` lists them: each one's serial
/// and, for FLAC, its channel mask comment. Empty when the demuxer cannot read the file.
pub(crate) fn ogg_audio_streams(b: &[u8]) -> Vec<(u32, Option<u32>)> {
@@ -136,24 +86,6 @@ pub(crate) fn ogg_audio_streams(b: &[u8]) -> Vec<(u32, Option<u32>)> {
file.streams.iter().filter(|s| s.codec.codec_id().is_audio()).map(|s| (s.serial, mask(s).filter(|_| s.codec == ogg::Codec::Flac))).collect()
}
/// The channel mask in a Vorbis comment block's body.
fn comments_mask(block: &[u8]) -> Option<u32> {
let vendor = le_u32(block, 0)? as usize;
let mut at = 4usize.checked_add(vendor)?;
let count = le_u32(block, at)?;
at += 4;
for _ in 0..count {
let len = le_u32(block, at)? as usize;
let comment = block.get(at + 4..(at + 4).checked_add(len)?)?;
at += 4 + len;
let Some(eq) = comment.iter().position(|&c| c == b'=') else { continue };
if let Some(mask) = comment_mask(&comment[..eq], &comment[eq + 1..]) {
return Some(mask);
}
}
None
}
/// Whether a vendor string or comment in a (little-endian) Vorbis comment block claims more than
/// the block holds.
fn comments_overrun(b: &[u8], body: usize, end: usize) -> bool {
@@ -180,42 +112,3 @@ fn overruns(b: &[u8], mut at: usize, end: usize, read: fn(&[u8], usize) -> Optio
}
false
}
#[cfg(test)]
mod tests {
use super::comments_mask;
fn block(comments: &[&str]) -> Vec<u8> {
let mut b = 3u32.to_le_bytes().to_vec();
b.extend_from_slice(b"abc");
b.extend_from_slice(&(comments.len() as u32).to_le_bytes());
for c in comments {
b.extend_from_slice(&(c.len() as u32).to_le_bytes());
b.extend_from_slice(c.as_bytes());
}
b
}
#[test]
fn the_channel_mask_comment_is_found_in_any_case() {
assert_eq!(comments_mask(&block(&["TITLE=x", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"])), Some(0x107));
assert_eq!(comments_mask(&block(&["waveformatextensible_channel_mask=0X3f"])), Some(0x3F));
assert_eq!(comments_mask(&block(&["TITLE=x"])), None);
}
#[test]
fn a_bad_channel_mask_comment_is_ignored() {
for value in ["63", "0x", "0xZZ", "0x1FFFFFFFF"] {
assert_eq!(comments_mask(&block(&[&format!("WAVEFORMATEXTENSIBLE_CHANNEL_MASK={value}")])), None, "{value}");
}
assert_eq!(comments_mask(&block(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=bad", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x3"])), Some(3));
}
#[test]
fn a_truncated_comment_block_has_no_mask() {
let whole = block(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x3"]);
for cut in 0..whole.len() {
assert_eq!(comments_mask(&whole[..cut]), None, "{cut}");
}
}
}
+10
View File
@@ -820,6 +820,11 @@ fn open_mp4<'a>(src: &Src<'a>, container: Container, track: Option<usize>) -> Op
return Some(Err(AudioError::Malformed("MP4 sample is larger than the file".into())));
}
let params = t.codec_params();
// Keep file-level FLAC on its existing path until this reader can index variable packet
// lengths and final duration from the frame headers. The packet API has no such timing role.
if params.codec == CodecId::Flac {
return None;
}
let lookahead: Vec<Vec<u8>> =
(0..t.samples.len().min(crate::track::LOOKAHEAD_PACKETS)).filter_map(|i| file.read_sample(src, track, i).ok()).collect();
let timescale = t.timescale;
@@ -897,6 +902,11 @@ fn open_mkv<'a>(src: &Src<'a>, container: Container, track: Option<usize>) -> Op
return None;
}
let params = t.codec_params();
// The Matroska file API needs FLAC frame counts to undo timestamp rounding on seeks.
// Keep its existing fallback until it can index those counts.
if params.codec == CodecId::Flac {
return None;
}
let lookahead: Vec<Vec<u8>> =
(0..t.samples.len().min(crate::track::LOOKAHEAD_PACKETS)).filter_map(|i| demux.read_sample(track, i).ok()).collect();
let probe = TrackDecoder::new(&params, &lookahead.iter().map(Vec::as_slice).collect::<Vec<_>>()).ok()?;
+55 -7
View File
@@ -1,5 +1,5 @@
//! [`TrackDecoder`]: one track's packets in, planar `f32` in WAV channel order out, whatever the
//! codec. The file-level [`crate::decode`] and [`crate::Decoder`] use it for every native codec;
//! codec. The file-level [`crate::decode`] and [`crate::Decoder`] use it for their native routes;
//! an app with its own demuxer (MXF, MPEG-TS, a network stream) uses it directly.
#[cfg(feature = "aac-decode")]
@@ -17,6 +17,9 @@ use crate::opus;
use crate::pcm::{PcmKind, deinterleave};
use crate::{AudioBuffer, AudioError, ChannelLayout, CodecId, CodecParams, Result, SampleFormat};
#[cfg(feature = "flac-decode")]
mod flac_packet;
/// How many leading packets [`TrackDecoder::new`] looks at.
pub const LOOKAHEAD_PACKETS: usize = 8;
@@ -39,6 +42,8 @@ enum Inner {
/// 2^-(bit depth - 1): full scale to ±1.
scale: f64,
},
#[cfg(feature = "flac-decode")]
Flac(Box<flac_packet::FlacTrack>),
/// The decoder, and what the packets read so far say of the track's packets.
#[cfg(feature = "ac3-decode")]
Ac3(Box<ac3::Decoder>, Ac3Packets),
@@ -76,7 +81,7 @@ pub(crate) type PacketFrames = fn(&[u8], u64) -> Option<u64>;
///
/// It takes the track's [`CodecParams`] (from `isobmff::Track::codec_params`,
/// `matroska::Track::codec_params`, `ogg::Stream::codec_params`, or built by hand for another
/// container) and decodes AAC (LC, and HE-AAC with its SBR high band), ALAC, Opus, AC-3/E-AC-3,
/// container) and decodes AAC (LC, and HE-AAC with its SBR high band), ALAC, FLAC, Opus, AC-3/E-AC-3,
/// MP1/MP2, MP3 and PCM. Container timing (AAC priming, Opus pre-skip, end trimming) is the caller's:
/// every decoded sample is returned.
///
@@ -130,11 +135,10 @@ impl TrackDecoder {
/// Opus with empty `extradata` and 1 or 2 `channels` (RTP, MPEG-TS) needs no `OpusHead`. Other
/// missing configuration is [`AudioError::Malformed`].
///
/// FLAC needs the `fLaC` magic and metadata blocks, starting with STREAMINFO, in `extradata`.
/// ALAC needs its magic cookie in `extradata`.
///
/// Codecs without a native packet decoder yet (FLAC, Vorbis) are
/// [`AudioError::Unsupported`]; `craft_audio::decode` decodes them through symphonia when the
/// `symphonia` feature is on.
/// Unavailable packet codecs return [`AudioError::Unsupported`].
pub fn new(params: &CodecParams, lookahead: &[&[u8]]) -> Result<TrackDecoder> {
#[cfg(not(feature = "aac-decode"))]
let _ = lookahead;
@@ -209,6 +213,18 @@ impl TrackDecoder {
let scale = 2f64.powi(1 - i32::from(cfg.bit_depth));
(Inner::Alac { dec, order, scale }, CodecId::Alac, rate, layout, sample_format)
}
#[cfg(feature = "flac-decode")]
CodecId::Flac => {
let (track, layout) = flac_packet::FlacTrack::new(&params.extradata)?;
let rate = track.info.sample_rate;
let sample_format = match track.info.bits_per_sample {
4..=8 => SampleFormat::Int8,
9..=16 => SampleFormat::Int16,
17..=24 => SampleFormat::Int24,
_ => SampleFormat::Int32,
};
(Inner::Flac(Box::new(track)), CodecId::Flac, rate, layout, sample_format)
}
#[cfg(feature = "ac3-decode")]
CodecId::Ac3 | CodecId::Eac3 => match ac3::parse_header(first) {
Ok(h) => {
@@ -313,6 +329,25 @@ impl TrackDecoder {
self.sample_format
}
/// The exact codec configuration for a FLAC track.
#[cfg(feature = "flac-decode")]
pub fn flac_stream_info(&self) -> Option<crate::flac::StreamInfo> {
match &self.inner {
Inner::Flac(track) => Some(track.info),
_ => None,
}
}
/// The FLAC packet's actual sample count, including a short final frame. This requires an
/// intact header and matching stream format but can read through a damaged frame body.
#[cfg(feature = "flac-decode")]
pub fn flac_packet_frames(&self, packet: &[u8]) -> Option<usize> {
match &self.inner {
Inner::Flac(track) => track.packet_frames(packet),
_ => None,
}
}
/// Decode one packet. An MP4 or Matroska packet may hold several AC-3 or MPEG audio frames;
/// an E-AC-3 dependent substream decodes to no frames. A packet that fails is an error for
/// every codec: call [`TrackDecoder::conceal`] for audio of its length, so what follows keeps
@@ -347,6 +382,8 @@ impl TrackDecoder {
let floats = decoded.into_iter().map(|c| c.into_iter().map(|v| (f64::from(v) * *scale) as f32).collect()).collect();
reorder(floats, *order)
}
#[cfg(feature = "flac-decode")]
Inner::Flac(track) => track.decode(packet)?,
#[cfg(feature = "mpa-decode")]
Inner::Mpa { dec, several } => {
let (out, first, count, cut) = mpa_frames(packet, |f| dec.decode(f))?;
@@ -453,6 +490,8 @@ impl TrackDecoder {
Inner::Alac { dec, .. } => {
Some(dec.packet_frames(data).unwrap_or(if self.last_frames > 0 { self.last_frames } else { dec.config().frame_length as usize }))
}
#[cfg(feature = "flac-decode")]
Inner::Flac(track) => track.packet_frames(data),
#[cfg(feature = "ac3-decode")]
Inner::Ac3(..) => Some(ac3_packet_frames(data)),
#[cfg(feature = "mpa-decode")]
@@ -488,6 +527,8 @@ impl TrackDecoder {
Inner::Aac { sbr, .. } => Some(aac::FRAME_LEN * if *sbr { 2 } else { 1 }),
#[cfg(feature = "alac-decode")]
Inner::Alac { .. } => None,
#[cfg(feature = "flac-decode")]
Inner::Flac(..) => None,
#[cfg(feature = "ac3-decode")]
Inner::Ac3(_, shape) if shape.varies => None,
#[cfg(feature = "ac3-decode")]
@@ -544,6 +585,8 @@ impl TrackDecoder {
Inner::Aac { sbr, .. } => 2 * aac::FRAME_LEN * if *sbr { 2 } else { 1 },
#[cfg(feature = "alac-decode")]
Inner::Alac { .. } => 0,
#[cfg(feature = "flac-decode")]
Inner::Flac(..) => 0,
#[cfg(feature = "ac3-decode")]
Inner::Ac3(_, shape) if shape.short => usize::MAX,
#[cfg(feature = "ac3-decode")]
@@ -570,6 +613,8 @@ impl TrackDecoder {
Inner::Aac { dec, .. } => dec.reset(),
#[cfg(feature = "alac-decode")]
Inner::Alac { .. } => {}
#[cfg(feature = "flac-decode")]
Inner::Flac(..) => {}
#[cfg(feature = "ac3-decode")]
Inner::Ac3(d, _) => d.reset(),
#[cfg(feature = "opus-decode")]
@@ -587,6 +632,7 @@ fn unsupported(codec: CodecId) -> AudioError {
let feature = match codec {
CodecId::Aac | CodecId::HeAac => Some("aac-decode"),
CodecId::Alac => Some("alac-decode"),
CodecId::Flac => Some("flac-decode"),
CodecId::Ac3 | CodecId::Eac3 => Some("ac3-decode"),
CodecId::Opus => Some("opus-decode"),
CodecId::Mp1 | CodecId::Mp2 => Some("mpa-decode"),
@@ -596,7 +642,7 @@ fn unsupported(codec: CodecId) -> AudioError {
match feature {
// A codec this crate decodes, in a build without its feature.
Some(f) => AudioError::Unsupported(format!("decoding {} needs the `{f}` feature", codec.name())),
None if cfg!(feature = "symphonia") && matches!(codec, CodecId::Flac | CodecId::Vorbis) => {
None if cfg!(feature = "symphonia") && codec == CodecId::Vorbis => {
AudioError::Unsupported(format!("no native {} packet decoder yet (craft_audio::decode reads it through symphonia)", codec.name()))
}
None => AudioError::Unsupported(format!("no native {} packet decoder yet", codec.name())),
@@ -1315,7 +1361,7 @@ mod tests {
#[test]
fn codecs_without_a_packet_decoder_are_unsupported() {
for codec in [CodecId::Flac, CodecId::Vorbis, CodecId::H264] {
for codec in [CodecId::Vorbis, CodecId::H264] {
assert!(matches!(TrackDecoder::new(&CodecParams::new(codec), &[]), Err(AudioError::Unsupported(_))), "{codec:?}");
}
// A codec whose feature is off names the feature.
@@ -1323,6 +1369,8 @@ mod tests {
assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Aac), &[]), Err(AudioError::Unsupported(m)) if m.contains("aac-decode")));
#[cfg(not(feature = "alac-decode"))]
assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Alac), &[]), Err(AudioError::Unsupported(m)) if m.contains("alac-decode")));
#[cfg(not(feature = "flac-decode"))]
assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Flac), &[]), Err(AudioError::Unsupported(m)) if m.contains("flac-decode")));
#[cfg(not(feature = "opus-decode"))]
assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Opus), &[]), Err(AudioError::Unsupported(m)) if m.contains("opus-decode")));
#[cfg(not(feature = "mp3-decode"))]
+46
View File
@@ -0,0 +1,46 @@
//! FLAC framing shared by the MP4 and Matroska packet readers.
use crate::flac_decode::{Decoder, StreamInfo};
use crate::{AudioError, ChannelLayout, Result};
pub(super) struct FlacTrack {
pub(super) info: StreamInfo,
decoder: Decoder,
}
impl FlacTrack {
pub(super) fn new(private: &[u8]) -> Result<(Self, ChannelLayout)> {
let [b'f', b'L', b'a', b'C', kind, 0, 0, 34, body @ ..] = private else {
return Err(AudioError::Malformed("FLAC track without a STREAMINFO block".into()));
};
if kind & 0x7f != 0 {
return Err(AudioError::Malformed("FLAC STREAMINFO must be the first metadata block".into()));
}
let info = StreamInfo::parse(body).map_err(|error| AudioError::Malformed(format!("FLAC STREAMINFO: {error}")))?;
if info.sample_rate == 0 {
return Err(AudioError::Malformed("FLAC track sample rate is zero".into()));
}
let layout = crate::flac_layout::layout_of(private, 0, u16::from(info.channels));
Ok((Self { info, decoder: Decoder::new(info) }, layout))
}
pub(super) fn decode(&self, packet: &[u8]) -> Result<Vec<Vec<f32>>> {
let frame = self.decoder.decode_frame(packet).map_err(|error| AudioError::Malformed(format!("FLAC packet: {error}")))?;
if frame.size != packet.len() {
return Err(AudioError::Malformed("FLAC packet must hold exactly one frame".into()));
}
if frame.sample_rate != self.info.sample_rate
|| frame.bits_per_sample != self.info.bits_per_sample
|| frame.channels.len() != usize::from(self.info.channels)
|| frame.block_size > usize::from(u16::MAX)
{
return Err(AudioError::Malformed("FLAC packet format differs from STREAMINFO".into()));
}
let scale = 2f64.powi(1 - i32::from(self.info.bits_per_sample));
Ok(frame.channels.into_iter().map(|plane| plane.into_iter().map(|sample| (f64::from(sample) * scale) as f32).collect()).collect())
}
pub(super) fn packet_frames(&self, data: &[u8]) -> Option<usize> {
self.decoder.packet_block_size(data)
}
}
+51
View File
@@ -4,6 +4,7 @@
//! ffmpeg's encoder writes at every compression level.
use craft_audio::flac::{DecodeError, Decoder, Encoder, EncoderConfig, STREAMINFO_OFFSET, StreamInfo, decode};
use craft_audio::{AudioError, CodecId, CodecParams, SampleFormat, TrackDecoder};
use std::process::Command;
fn signal(channels: usize, frames: usize, bits: u32, seed: u32) -> Vec<Vec<i32>> {
@@ -79,6 +80,56 @@ fn frames_decode_one_at_a_time() {
let _ = Decoder::without_streaminfo().decode_frame(&file[at..]);
}
#[test]
fn track_decoder_uses_streaminfo_layout_and_packet_length() {
let source = signal(4, 80, 24, 17);
let mut config = EncoderConfig::new(96_000, 4, 24);
config.block_size = 32;
let mut encoder = Encoder::new(config).expect("encoder");
let mut private = encoder.header(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x603"]);
let planes: Vec<&[i32]> = source.iter().map(Vec::as_slice).collect();
let mut packets = encoder.encode_frames(&planes).expect("packets");
packets.push(encoder.finish());
let at = STREAMINFO_OFFSET as usize;
private[at..at + 34].copy_from_slice(&encoder.streaminfo());
let params = CodecParams::new(CodecId::Flac).with_extradata(private).with_sample_rate(48_000).with_channels(4);
let mut track = TrackDecoder::new(&params, &[]).expect("native FLAC track");
assert_eq!(track.sample_rate(), 96_000);
assert_eq!(track.flac_stream_info().expect("FLAC stream info").bits_per_sample, 24);
assert_eq!(track.layout().channels(), 4);
assert_eq!(track.layout().mask(), Some(0x603));
assert_eq!(track.sample_format(), SampleFormat::Int24);
assert_eq!(track.frames_per_packet(), None);
assert_eq!(track.preroll(), 0);
let final_packet = packets.last().expect("final packet");
let decoded = track.decode(final_packet).expect("independent final frame");
assert_eq!(decoded.frames(), 16);
for (plane, expected) in decoded.channels.iter().zip(&source) {
for (sample, expected) in plane.iter().zip(&expected[64..]) {
assert_eq!(*sample, (f64::from(*expected) / 8_388_608.0) as f32);
}
}
assert_eq!(track.decode(&packets[0]).expect("backwards seek").frames(), 32);
let truncated = &final_packet[..final_packet.len() - 1];
assert_eq!(track.flac_packet_frames(truncated), Some(16));
assert!(matches!(track.decode(truncated), Err(AudioError::Malformed(_))));
let concealed = track.conceal(Some(truncated)).expect("silence from the intact header");
assert_eq!(concealed.frames(), 16);
assert_eq!(concealed.peak(), 0.0);
track.reset();
assert_eq!(track.decode(final_packet).expect("decode after reset"), decoded);
let mut extra = final_packet.clone();
extra.push(0);
assert!(matches!(track.decode(&extra), Err(AudioError::Malformed(_))));
assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Flac), &[]), Err(AudioError::Malformed(_))));
let mut incomplete = params.clone();
incomplete.extradata.truncate(at + 33);
assert!(matches!(TrackDecoder::new(&incomplete, &[]), Err(AudioError::Malformed(_))));
}
#[test]
fn hostile_input_is_an_error_not_a_panic() {
let src = signal(2, 6000, 16, 11);
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "craft-cdr"
description = "Bounded reader for .cdr drawings of versions 1 to 27 and .cmx files: WL records, RIFF index, compressed lists, ZIP packages, shapes, fills, outlines, pages and layers"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[features]
# Synthetic-file builders for tests and fuzz seeds; not a .cdr writer.
synth = []
[dependencies]
crc32fast = "1.5"
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
[dev-dependencies]
proptest = { workspace = true }
craft-cdr = { path = ".", features = ["synth"] }
+33
View File
@@ -0,0 +1,33 @@
The record layouts this crate reads are described in the Kaitai Struct
specification `coreldraw_cdr.ksy`
(https://github.com/kaitai-io/coreldraw_cdr.ksy, commit
9d8e2704b946961f5114115f1a488750a3c86ed0), which is published under the
license below. No part of that specification is copied into this crate;
`PROVENANCE.md` cites it by line.
Some layouts are also taken from the fork of that specification by Zach Wolfe
(https://github.com/filestar/coreldraw_cdr.ksy, branch new_stuff, commit
2189b68f07e0cafe9afec3dcf699ebc0342144c7), which is published under the same
license and copyright notice.
MIT License
Copyright (c) 2020 Kaitai team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+127
View File
@@ -0,0 +1,127 @@
# Where each layout comes from
The reader relies on the record layouts below. Code cites a row by its id (`R1` ...), and
`tests/it/provenance.rs` fails when a cited id has no row here.
Sources:
- **K**: the Kaitai Struct specification `coreldraw_cdr.ksy` (MIT, notice in `LICENSE-kaitai.txt`),
https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/coreldraw_cdr.ksy
- **KF**: the fork of K by Zach Wolfe, `filestar/coreldraw_cdr.ksy`, branch `new_stuff`, under the same
MIT license and notice as K (`LICENSE-kaitai.txt`),
https://github.com/filestar/coreldraw_cdr.ksy/blob/2189b68f07e0cafe9afec3dcf699ebc0342144c7/coreldraw_cdr.ksy
- **KR**: the README and the `bin/cdr-unpk` script of the Kaitai Struct specification (MIT), at
the same commit as K,
https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/README.md
and https://github.com/kaitai-io/coreldraw_cdr.ksy/blob/9d8e2704b946961f5114115f1a488750a3c86ed0/bin/cdr-unpk
- **Z**: the PKWARE ZIP specification, APPNOTE.TXT version 6.3.10,
https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT, and RFC 1951 (DEFLATE),
https://www.rfc-editor.org/rfc/rfc1951
- **F**: the magic database of the `file` utility (BSD-2-Clause),
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/images and
https://github.com/file/file/blob/b778217dbd35/magic/Magdir/riff
- **PR**: the PRONOM registry's signatures for versions 1.0, 2.0 and 4.0,
https://pronom.nationalarchives.gov.uk/fmt/467.xml,
https://pronom.nationalarchives.gov.uk/fmt/466.xml and
https://pronom.nationalarchives.gov.uk/fmt/465.xml
- **S**: own inspection of the bytes of public sample files, checked against the picture each file
carries of its drawing where it has one (versions 2 and 4 to 25; files of versions 1 and 3 carry
none). The files come from:
- **TP**: https://telparia.com/fileFormatSamples/image/cdr/, by file name
- **LT**: https://git.libreoffice.org/libcdr-test at commit
`dafe4fe53d685d89df20a5c0bb18f318ccefb4a8`, `testset/<version>/<file>`
- **UC**: https://svn.code.sf.net/p/uniconvertor/code/formats/CDR/testing%20base/ at revision
434, by file name
- **TDF**: attachments to The Document Foundation's bug tracker,
https://bugs.documentfoundation.org/attachment.cgi?id=<id>
- **NR**: Natural Resources Canada's tactile maps,
https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/approach-approch/cdr/banff_ap_en.cdr and
https://ftp.maps.canada.ca/pub/nrcan_rncan/raster/tactile/atlas-atlas/cdr/ab_en_br.cdr
- **DM**: the clip art of https://discmaster.textfiles.com/browse/31541, by file name
- **CX**: the `.cmx` files of https://telparia.com/fileFormatSamples/image/cmx/, by file name. The
nine with 32-bit coordinates are `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`,
`gold_bar.cmx`, `goldblue.cmx`, `PC.CMX`, `squares.cmx` and `thatch.cmx`; they carry no picture
of their drawing.
- **CN**: the `.cmx` notes of an MIT OR Apache-2.0 drawing program, which mark each layout
"confirmed" when the program's authors found it in sample files,
https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/docs/cmx-format.md.
The same program's `.cmx` reader at that commit,
https://github.com/tracedraw/tracedraw/blob/2ac6d02e97773e040a51be6cfb27cc424e3deeaa/crates/cdr/src/cmx.rs,
was read for the order of fields that the notes do not spell out (the table entries, the rendering
attributes and the curve body); no code was copied from it
Status: `public-spec` (K, KF, KR, Z, F or PR), `sample` (S), `public-notes` (a layout CN marks
confirmed that no CX file shows), `unconfirmed` (a point no source states and no sample file shows;
listed so it can be checked against a file, with what the reader does when it is wrong).
Public specifications cover only parts of versions 1 to 4: the rows that cite K, F or PR, such as
the version 3 fill (R34) and page settings (R38). The other rows of those versions rest on the
sample files they name.
The test inputs are the synthetic files that `src/synth.rs` builds from the rows below; no sample
file is committed.
| Id | What the code relies on | Source | Status |
|---|---|---|---|
| R1 | `RIFF`, the body length, then the form type `CDR` or `cdr` and a version character: `1` to `9`, `A` (10) to `H` (17), `J` (18) on, `I` unused; `cdr8` is 8.01 from the form type alone, whatever its `vrsn` chunk names, `CDR ` is 3, `CDRX` is another format. Files of versions 23 to 25 carry `O` (23), `P` (24), `Q` (24.3, with a `vrsn` of 2430) and `R` (25), which count differently from the version 24 update on, so their `vrsn` chunk decides (R2) | K L68-L133; S: LT `testset/23` to `testset/25`, such as `circle_redfill_nooutline_cdr25.cdr` | public-spec (letters from version 23: sample; letters of versions 26 and 27: unconfirmed, and the `vrsn` chunk decides when the file has one) |
| R2 | `vrsn`: the version as a u16, in hundreds | K L276-L278 | public-spec |
| R3 | `LIST cmpr`: two (compressed, uncompressed) u32 pairs, then two blocks of `CPng`, `01 00 04 00` and a zlib stream; the first inflates to the chunk stream, the second to a pool of u32 sizes that each chunk's size field indexes | K L193-L220, L2626-L2682 | public-spec |
| R4 | A chunk is an id, a u32 size and the body, padded to an even length; a `LIST` body starts with its form type; from version 7 a `LIST stlt` holds the style tables, not chunks | K L68-L78, L135-L155, L307-L334 | public-spec |
| R5 | Coordinates: i16 in 1/1000 inch before version 6, else i32 in 1/254000 inch; header fields, counts and offsets are u16 before version 6, else u32 | K L58-L66, L2688-L2700 | public-spec |
| R6 | `loda` and `lobj`: length, argument count, offsets table, types table, object type; count + 1 offsets bound the arguments; the types table runs in reverse; object types (1 rectangle, 2 ellipse, 3 curve, 0x14 polygon) and argument types (10 outline, 20 fill, 30 coordinates, 1000 name, 11000 polygon, 19130 page size) | K L335-L450, L846-L893 | public-spec |
| R7 | Angles: i16 tenths of a degree before version 6, else i32 millionths of a degree | K L2835-L2855 | public-spec |
| R8 | `trfd`: length, count, offsets table; each entry has 8 bytes first from version 13, a u16 type, and type 8 is a matrix after 6 bytes (from version 6) of six f64 `a c tx b d ty`, `tx` and `ty` in coordinate units; the matrices of one record apply in file order | K L895-L953, L2808-L2834 | public-spec |
| R9 | Name argument (1000): Windows-1252 up to a NUL before version 12, UTF-16LE from it | K L601-L630 | public-spec |
| R10 | `mcfg`: 12 bytes (13 on), 4 (9 to 12), 28 (6) or none, then the page width and height as coordinates | K L1670-L1765 | public-spec |
| R11 | `fild` (`fill` before 7): id; from 13 a record tagged 1300 with its length, which records tagged 2400 or more may precede; the fill type u16 (0 none, 1 uniform, others not read); uniform: 2 bytes then a color before 13, from 13 a record tagged 1300 holding a property list (u8 type, u32 length, body; 0 ends it; 1 a color, 8 a palette id and a UTF-16 name, 3 a UTF-16 name) | K L1025-L1302; S: LT `testset/15` to `testset/25` `circle_redfill_nooutline_cdr<version>.cdr`, whose fill records hold a record tagged 2400 before the one tagged 1300 | public-spec (2400 records: sample) |
| R12 | `outl`: id; from 13 records (u32 id, u32 length, body) up to id 1, whose body follows; a record of id 2 holds a property list laid out as R11's, and the reader takes the outline's color from it when it names a library color; line type, caps and join u16; 2 bytes (6 to 12); width; stretch u16; 2 bytes (6 on); nib angle; 52 bytes (6 to 12) or 46 (13 on); the color; 16 bytes (10 before 6); the dash count u16 and the dashes, in multiples of the width; the arrowhead ids 22 bytes after the first dash in versions 6 to 12, 20 bytes from 13. Caps 0 butt, 1 round, 2 square; joins 0 miter, 1 round, 2 bevel | K L954-L1024; KF L1225-L1249 (the id 2 record); S: caps and joins in UC `outl_line_caps_cdr7.cdr` and `outl_corner_cdr7.cdr`; arrowhead ids, matched against the drawing's `arrw` records, in TP `web_cd.cdr` (6), UC `rogan_logo_cdr7.cdr`, `rogan_logo_cdr8.cdr` and `rogan_logo_cdr11.cdr`, NR `ab_en_br.cdr` (9) and `banff_ap_en.cdr` (10), TDF 76820 (12) and 140638 (13) | public-spec (caps, joins and arrowhead places: sample; arrowheads before version 6: no sample names one, and the reader does not look for them; the id 2 record: no sample names a library color in it, and a wrong guess changes only the outline's color) |
| R13 | Bit 0 of the outline's line type: no outline | S: LT `square_blackfill_nooutline_cdr<version>.cdr` and the other `nooutline` files of `testset/15` to `testset/25`, whose outline records all have line type 1 and whose pictures show no outline | sample |
| R14 | A color record from version 5: model u16, palette u16, 4 bytes, four value bytes. Models: 2 CMYK in percent, 3 and 17 CMYK 0 to 255, 4 CMY 0 to 255, 5 blue, green, red, 9 gray 0 to 255, 20 registration, 21 blue, green, red and a tint in percent already applied; 1, 14 and 25 a library color's number (u16) and tint in percent (u16) | K L2856-L2965; S: model 25 in LT `testset/12/square_pantoneblackfill_nooutline.cdr` (number 14, tint 100), model 1 in UC `rogan_logo_cdr11.cdr` (number 4, tint 50) | public-spec (library values of models 1 and 25: sample; model 14: unconfirmed, and its color opens as a spot color without a look) |
| R15 | Rectangle coordinates: width, height and one radius, three more radii from version 9, running counterclockwise from the corner at (width, 0) | K L674-L700 | public-spec |
| R16 | Point list: u32 count (before version 6 as R39 gives it), the points, then one type byte each, the count held to what fits; type bits 7 and 6 move, line, curve end, control point; bit 3 closes the subpath | K L782-L787, L840-L845, L2701-L2807 | public-spec |
| R17 | Ellipse coordinates: width, height, start and end angles, pie flag (u16 before 6, else u32); the radii are half the width and height; the angles turn from the ellipse's own axes, which a negative width or height points the other way | K L754-L781; S: the pies of negative height in the ellipse-sector drawings of versions 12 and 13 in UC | public-spec (axis direction of a negative size: sample) |
| R18 | Polygon argument (11000): 4 bytes before 13, the side count u32, the next point u32 (the u32 after it when it is 0 or 1, else 4 bytes), 4 more from 13, rx and ry f64, the centre; the base curve is one side on a circle of 1000 mm from the top vertex to the vertex it runs to clockwise, copied once for each side | K L631-L655; S: the polygons and stars of UC `shapes_cdr10.cdr` | public-spec (base curve: sample) |
| R19 | `flgs`: byte 3 the record type, byte 2 marks the master page. On a layer, group or object, bit 0x01 of byte 1 hides it and bit 0x10 of byte 0 locks it. A layer's own `loda` names what it is by its object type: 11 a grid, 12 guides, 17 the desktop, any other a drawing layer (version 3 one less, R32). Only a layer without a `loda` is taken by the low four bits of its byte 0: 0x0a guides, or a grid when bit 0x10 is also set; in versions 7 to 13 0x02 the same way; 0x08 the desktop when byte 2 is set and a drawing layer when it is clear; any other a drawing layer, except [0, 1, 1] in versions 7 to 13, the desktop | K L1602-L1639 (record types); KF L1831-L1866 (the hidden and lock bits); S: every grid layer of versions 14 to 25 in the sample files (631) carries byte 1 = 1, and 206 of the 927 of versions 7 to 13 do; desktop layers carry byte 1 = 0 except TDF 114901's [0, 1, 1]; the drawing layers with byte 1 = 1 (TDF 114901, NR `banff_ap_en.cdr` and `symbology_en.cdr`) also carry bit 0x08; of the group and object lists in the sample files, only one object of TDF 60491 (version 14) sets either bit, the lock bit; in every sample file of versions 3 to 25 the layer's object type agrees with its name; byte 0 does not: TDF 114901 (version 8) flags its master page's guides [2, 1, 1], desktop [0, 1, 1], grid [0x12, 0, 1] and drawing layer [8, 1, 0], and NR `ab_en_br.cdr` (version 9) flags drawing layers 0x10 and its guides 0x1a; over the sample files of versions 3 to 25, drawing layers carry 0, 0x10, 0x40, or 0x08, 0x18 or 0x58 with byte 2 clear, desktop layers 0x08, 0x18 or 0x48 with byte 2 set, guides 0x0a, 0x4a, 0x02 or (in `ab_en_br.cdr`) 0x1a, and grids 0x1a, 0x5a or 0x12 | public-spec (layer types: sample; byte 0 of a layer without a `loda`: unconfirmed, as no sample has such a layer, and a wrong guess drops or shows that layer's objects; bit 0x10 is also the lock bit, so a locked guides layer without a `loda` reads as a grid) |
| R20 | Fill and outline arguments (20, 10): a u32 record id | K L452-L460, L548-L556 | public-spec |
| R21 | Page size argument (19130): width and height | K L666-L672 | public-spec |
| R22 | `LIST page` holds `LIST layr` lists, directly or in a list it holds (a `LIST gobj` in the samples); a layer holds `LIST obj ` and `LIST grp `; a page, layer or object keeps its own `loda` (and an object its `trfd`, in a `trfl` list) among its chunks or in a `LIST lgob` | K L1602-L1639 (record types); S: the chunk trees of every sample file of versions 3 to 25 | sample |
| R23 | Guideline (object type 0x16), argument 16000: 12 bytes, the angle in millionths of a degree, then points from the page centre; version 7 keeps them in a `guid` chunk: a u32 count, the count again, 40-byte records laid out the same way | S: argument 16000 in NR `ab_en_br.cdr` (9) and TDF 194220 (13); the `guid` chunk of TDF 123971 (7). Pictures do not show guidelines | sample |
| R24 | ZIP: the end of central directory record (signature `PK\5\6`, 22 bytes and a comment of up to 65,535 bytes) gives the member count and where the central directory lies; each central directory entry (46 bytes, then name, extra field and comment) gives the flags, method, CRC-32, sizes and its local header; a local header is 30 bytes, then its name and extra field, then the member's bytes. Flag bit 0 marks an encrypted member; method 0 is stored and 8 deflated; 0xFFFF and 0xFFFFFFFF mark ZIP64 fields, and a ZIP64 locator (`PK\6\7`, 20 bytes) precedes the end record of a ZIP64 archive; disk numbers other than 0 mark an archive split across files | Z 4.3.7, 4.3.12, 4.3.15, 4.3.16, 4.4.1.4, 4.4.4, 4.4.5, 4.4.7, 4.4.8, 4.4.13 | public-spec |
| R25 | Versions 14 and 15 save a ZIP package whose member `content/riffData.cdr` is the RIFF file | KR README L33, `cdr-unpk` L30 | public-spec |
| R26 | From version 16 the package's member `content/root.dat` is the RIFF file; `content/dataFileList.dat` names the data streams, one per line, members of `content/data/`; a redirect's stream number counts lines from 0 | KR README L34, L40, `cdr-unpk` L34-L66; K L173-L180 | public-spec |
| R27 | In a package of version 16 on, a chunk outside a compressed list whose size is 16 (in `root.dat` or in a redirected list's body) is a redirect record: stream u32, length u32, offset u32 and a reserved u32; its body is `length` bytes at `offset` of the stream; stream `0xFFFFFFFF` holds the body (at most 8 bytes) in the record after the length; a redirected list's body starts with its form type | K L144-L193 | public-spec |
| R28 | Templates have the form type `CDT` and a letter of their own; the `vrsn` chunk names the version. The reader takes any letter `A` to `Z` there | none: no sample template | unconfirmed (a template is read as a drawing of the version its `vrsn` chunk names, and one without that chunk is refused) |
| R29 | Rectangle coordinates from version 15: width and height as f64 coordinate units, scale x and y (f64, repeating the transform's scale), the scale-with flag (u8) and 7 bytes, then the four radii as f64, 16 bytes apart (a corner type byte and 15 bytes after the first), in the order of R15. With the flag clear each radius is a share of half the shorter side; with it set the radii are multiplied by 254000 coordinate units, which makes them inches | K L674-L752; S: LT `square_blackfill_nooutline_roundedcorners_cdr<version>.cdr` of `testset/15` to `testset/25` (flag clear, a share of 0.25) | public-spec (radius share with the flag clear: sample; that the scale is not applied: unconfirmed, as every sample has a scale of 1, and a wrong guess changes only the corners' size) |
| R30 | Object type 0x25 (version 10 on) is a path: 4 bytes, two u16 counts that add up to the point count, 16 bytes, then the points and their type bytes as in R16 | K L788-L799, L892; S: TDF 78250 (version 15) and UC `shapes_cdr10.cdr`, `shapes_cdr11.cdr`, `shapes_cdr12.cdr` and `shapes_x3.cdr` (versions 10 to 13), whose type bytes start where the counts put them; no sample before version 10 holds the type | public-spec (from version 10: sample) |
| R31 | Version 3 is a RIFF file with the form type `CDR ` (a space) and a `vrsn` of 300; version 4 has the form type `CDR4` and a `vrsn` chunk. Both use the 16-bit fields of R5 and R7. Their pages, layers, groups and objects are read by the rules of R19 and R22 | K L117-L134; PR fmt/465; F `riff` L786; S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | public-spec (pages and layers as R19 and R22: sample) |
| R32 | Version 3 counts its object types from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4; later versions use these plus one | S: the rectangles, curves and text of TP `ARMYSTF1.CDR`, `DALI.CDR` and `FOX.CDR`, which come out whole | sample (ellipse 1 and bitmap 4: unconfirmed, as no sample holds them; a bitmap is left out with a warning) |
| R33 | Version 3 keeps an object's transforms in argument 100 of its `lobj`: a u16, the entry count (u16), then 10-byte entries of a type (u16) and, at byte 6, where the entry's data starts, counted from the start of the argument. Type 0x8c is a matrix as R37, and the matrices apply in file order. Type 0x14 is an envelope, which this reader does not apply: the shape keeps its outline, placed by the matrices alone, and the drawing's warnings name the envelopes. A group's own `lobj` holds an argument 100 that places all of the group's objects after their own transforms | K L851; S: the matrices of every version 3 file in TP, whose drawings come out whole | sample (envelope type 0x14: unconfirmed, as no sample holds one; it is not applied, with a warning) |
| R34 | Version 3 fill, argument 20: a type byte (0 none, 1 uniform, 2 and 4 fountain, 6 texture, 7 and 10 pattern); a uniform fill's color follows as R36 | K L452-L547 | public-spec |
| R35 | Version 3 outline, argument 10: a flags byte with bit 0 set when the object is outlined, the width (coordinate), the stretch (u16), the nib angle, the color as R36, 7 bytes, the dash count (u8) and 10 bytes that hold the dashes as one byte each, the join (u16 at byte 30) and the caps (u16 at byte 32) numbered as R12, then the two arrowhead ids (u32). Dashes are read in multiples of the width as R12 | K L548-L592; S: the outlines of the version 3 files in TP | public-spec (flag bit: sample; dash unit, and the join, where bytes 32 and 33 of some samples hold 2 and 2: unconfirmed, and a wrong guess changes only how corners, ends and dashes are drawn) |
| R36 | A color before version 5: in versions 1 to 3 a model byte and four value bytes, in version 4 a model u16, four u16 values and 2 bytes. Model 1 is cyan, magenta, yellow and black in percent. Model 0 is an ink number (u16) and a tint in percent (u16): ink 0 is black at the tint, ink 1 is white, and other numbers are inks of a numbered library that the file does not store. Other models are read as R14 | K L2882-L2908; S: model 1 in TP `ARMYSTF1.CDR` (3) and DM `lion1.cdr` (4), model 0 in TP `ARROW5.CDR` (3) and `WI.CDR` (1) | sample (ink 1, and models other than 0 and 1: unconfirmed; an ink of another number opens as a spot color without a look) |
| R37 | A matrix of versions 3 and 4: six i32 `a c tx b d ty`, the four factors in 16.16 fixed point and `tx` and `ty` in coordinate units. A version 4 `trfd` entry of type 8 holds one where R8 has six f64 | S: TP `FOX.CDR` and `DALI.CDR` (3), DM `lion1.cdr` and `tiger.cdr` (4) | sample |
| R38 | `mcfg` of version 3: 2 bytes, then the page's two corners as four coordinates; the page size is the distance between them | K L1676-L1678, L1745-L1756 | public-spec |
| R39 | A point list before version 6 starts with a u16 count and another u16 (1 in some curves of versions 1, 2 and 4, 0 in the others), where K reads the two as one u32 | S: TP `DALI.CDR` (3), DM `headup.cdr` and `lion1.cdr` (4), TP `WI.CDR` (1), `FLAG.CDR` and `MENU.CDR` (2) | sample |
| R40 | Versions 1 and 2 are not RIFF files. A file starts with `WL`, a marker byte, a zero byte and five u32: the start of the settings, the start and the end of the object records, the start of the trailer and that value minus two. Version 1 has the marker `e` and its settings start at byte 28. Version 2 has the marker `m` or `l`, and its settings start after a 1-bit picture of the drawing, whose header starts where the u32 at byte 28 says. The reader takes these three markers | F `images` L4159-L4172; PR fmt/467, fmt/466; S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`), `MENU.CDR` and `DRINKS.CDR` (`l`) | public-spec (markers `e` and `m`: F and PR; the offsets and the marker `l`: sample) |
| R41 | The page's box in a file of version 1 or 2: four i16 two bytes after the start of the settings (left, top, right, bottom) in 1/1000 inch around the page's centre, y pointing up | S: TP `WI.CDR`, `FLAG.CDR` and `MENU.CDR` | sample |
| R42 | The records of a file of version 1 or 2 run from the front of the stacking order to the back. Every record starts with the u32 24. A group or layer record is 28 bytes, and bit 0x40 of its flags byte at 26 is clear. A drawn object has that bit set (0x40 in files with the markers `e` and `m`, 0xc0 with `l`) and a u16 body size at byte 28; it is the body size plus 32 bytes long. A drawn object of another type than those of R43 gives its length otherwise, and the records after it are not read | S: TP `WI.CDR`, `FLAG.CDR`, `MENU.CDR` and `DRINKS.CDR`; the order checked against the picture of `MENU.CDR` | sample |
| R43 | A drawn object of version 1 or 2: a point (two i16) at byte 32; six i32 in 16.16 fixed point at 36, `a b tx c d ty`, with x' = a x + b y + tx + the point's x and y' = c x + d y + ty + the point's y; the object type at 60 (0 rectangle, 1 ellipse, 2 curve, 3 text); a byte at 67 that is not 0 when the object is outlined, the outline's width (u16) at 68 and its color at 74; the fill type (0 none, 1 uniform) and its color after it, at 94 and 95 with the marker `e` and at 105 and 106 with `l` and `m`; the shape from byte 114 with `e` and 136 with `l` and `m`. Colors are as R36 | S: TP `WI.CDR` (`e`), `FLAG.CDR` (`m`) and `MENU.CDR` (`l`), checked against the pictures of `FLAG.CDR` and `MENU.CDR` | sample |
| R44 | Shapes of version 1 or 2: a rectangle's width and height (i16), then a corner radius; an ellipse's width and height, then two angles; a curve's point list as R39 and R16 | S: rectangles in TP `FLAG.CDR`, ellipses and curves in TP `WI.CDR`, curves in TP `MENU.CDR` | sample (the radius of files with the marker `e`, which no sample shows, and how the angles make an arc: unconfirmed; a radius is kept only when it is at most half the shorter side, and an ellipse whose angles differ is left out with a warning) |
| R45 | `LIST stlt` from version 7: a u32 style count, and when it is not 0: the fill table (a u32 count, entries of a table id, 4 bytes and a `fild` id, 12 bytes each, 60 from version 13), the outline table (12-byte entries laid out the same way, naming `outl` ids), the text tables (fonts of 44 bytes, 60 from version 10; alignments of 12; spacings of 52; tables of 152 and 784; bullets whose length a u32 inside them sets; indents of 28; hyphenation of 32, 36 from 13; drop caps of 28; from 8.01 a table of 12), then the styles: kind (u32), id, parent id, 8 bytes, name length and name (bytes before 12, UTF-16 units from it), the fill and outline table ids, then 16 bytes (20 from 8.01) for kinds above 1 and 20 more for kinds above 2. An object names its style in argument 200 (u16 before version 6, u32 from it). An object without argument 20 or 10 takes the fill or outline of its style; a style whose table id is 0 takes its parent's | K L593-L600, L852, L1926-L2198; S: UC `outl_width_cdr7.cdr`, one of whose lines carries argument 200 and neither 10 nor 20 and names the style whose outline is black and 0.003 inch wide and whose fill is none, as the file's picture shows; the table parses exactly to the end of the list in each of the 498 sample files of versions 7 to 15 that has one, and every object with argument 200 in them names a style whose table ids are in the tables; argument 200 is 2 bytes on all 844 objects of versions 4 and 5 in the sample files that carry it, and 4 bytes on all 18 of version 6 | public-spec (what the table ids name, and that an object takes its style's fill and outline: sample; a style taking its parent's entry: unconfirmed, as only text styles in the samples leave theirs to the parent, and a wrong guess draws a shape without that fill or outline) |
| R46 | A clipping container carries argument 8005; its first u32 is the id that the `spnd` chunk (a u32, a u16 before version 6) of one `LIST grp ` in the document's `LIST clpt` holds. That group's objects are the ones the container clips; they keep their own transforms, in page space like the container's | K L252, L860-L862, L1895-L1901 (the argument and the chunk); S: LT `powerclipsquare_blackfill_whiterectangleinside` of `testset/12` to `testset/25` and eight UC files of versions 7 to 13, in each of which the id in argument 8005 matches one group's `spnd`; in the UC file of version 7 the group's box, -1.96 to 1.97 inches across, overlaps the container's, -1.81 to 1.84 inches, and the file's picture shows the group cut to the container | public-spec (what the id names, and the space of the group's objects: sample) |
| R47 | Argument 8000 marks an object seen through: a lens or a transparency. From version 13 it holds records of a u32 version, a u32 length and a body; a body of version 1300 that is 117 bytes long holds an f64 at byte 61 and a merge mode byte at byte 77, which the reader applies as a uniform transparency. VectorCraft reads the f64 as the transparency in percent (0 opaque, 100 clear) and maps the merge modes 0 normal, 9 multiply, 11 lighten, 12 darken, 14 color, 15 hue, 16 saturation, 17 luminosity, 24 difference, 28 screen, 29 overlay, 30 soft light, 31 hard light, 33 color dodge, 34 color burn and 36 exclusion to its blend modes. Other merge modes, other records (a lens record of version 13 is 84 bytes) and the argument before version 13 are not applied, and the reader names them with lenses in the warnings | K L859 (the argument); KF L707-L798 (the records, the 117-byte body and the merge modes); S: the version 1300 record of LT `square_blackfill_nooutline_transparency50percent` of `testset/15` to `testset/25` is 117 bytes long, with 50.0 at byte 61 and 0 at byte 77; the lens records of UC `corel_lens_test_x3.cdr` (13) are 84 bytes long; of the sample files of versions 7 to 25, the argument is on the see-through objects that the pictures of LT `square_blackfill_nooutline_transparency50percent` of `testset/12` to `testset/25`, TDF 80103 and eight UC lens test files of versions 7 to 13 show, and otherwise only on text in UC `fancytext_cdr7.cdr` to `fancytext_x3.cdr` and on two objects of TDF 114901. The value K reads at byte 10 (14 from version 13) is not the transparency in these samples | public-spec (the argument: K; what it marks: sample; the direction of the value: VectorCraft's own reading, as every sample is at 50%, and a wrong reading shows a 25% transparency at 75%; the layout before version 13: unconfirmed, and it is not read) |
| R48 | Bit 2 (0x04) of the outline's line type marks the outline dashed; the dashes of an outline without it are not drawn | S: every outline of versions 6 to 25 in the sample files with that bit set (316 of them, in 29 files) stores dashes; TDF 76771 (version 15) stores dashes 2 and 1 in an outline of line type 0x22, and the file's picture draws that outline solid | sample |
| R49 | Bit 4 (0x10) of the outline's line type puts the outline behind the fill | S: UC `outl_behind_fill_cdr7.cdr` to `outl_behind_fill_x3.cdr`, whose outline of line type 0x12 the file's picture shows behind the fill, and whose other outlines (0x02) it shows over the fill | sample |
| R50 | Bit 5 (0x20) of the outline's line type scales the outline's width and dashes with the shape's matrix. The engine multiplies them by the square root of the matrix's area factor (VectorCraft's own value for a matrix that scales x and y differently) | S: UC `outl_scale_with_cdr7.cdr` to `outl_scale_with_cdr12.cdr`, of whose outlines only one, 3.969 mm wide, has line type 0x22 and the others 0x02 or 0x01; TDF 76771 (version 15), whose outline of line type 0x22 is 10 mm wide on a shape that the matrix stretches and skews, and whose picture draws that outline several times wider and skewed | sample (the bit; the single width for a matrix that scales x and y differently: VectorCraft's own) |
| R51 | A `trfd` offsets table holds one offset more than the entries; each entry runs from its offset to the next, and the last offset is the record's end | KF L1079, L1113-L1121; S: every `trfd` of versions 4 to 25 in the sample files (25,425 records) has the extra offset, equal to the record's length | public-spec |
| R52 | Byte 0 of argument 14001 is the fill's winding flag. VectorCraft reads a byte other than 0 as the nonzero fill rule, and 0 or an object without the argument as even-odd | KF L575-L583, L1047; S: the argument is 4 bytes in the sample files that carry it, with byte 0 = 1 on LT `complexshape_blackfill_nooutline` of `testset/12` and `testset/15` to `testset/25` and on objects of TDF 127576 (13) and 60026 (14), and 0 on 27 objects of TP `example.cdr` (17) | public-spec (the flag: KF; which rule each value means, and the rule without the argument: VectorCraft's own reading, and a wrong reading fills or leaves holes where a curve's subpaths overlap) |
| R53 | A `.cmx` file is a RIFF form of type `CMX1`, little-endian (a `RIFX` form is big-endian and is refused); its chunks are laid out as R4. A chunk can run short of its contents: when the bytes after it don't read as a chunk id (an ASCII letter, then three ASCII letters, digits or spaces), the next id is the first at an even distance of 2 to 64 bytes that names a chunk the reader uses or whose length keeps it inside its list (VectorCraft's own rule) | CN "Container"; S: all 14 CX files are `RIFF` forms of type `CMX1`; in `balloon.cmx`, `bars.cmx`, `bluecros.cmx`, `bluedrop.cmx`, `gold_bar.cmx`, `goldblue.cmx`, `squares.cmx` and `thatch.cmx` 16 bytes follow `ccmm` and 4 follow `rlst` before the next id | sample |
| R54 | `cont`: byte 52 is the coordinate size as an ASCII digit, `4` for 32-bit coordinates and `2` for 16-bit ones (refused); bytes 64 to 72 hold an f64, the size of a coordinate unit in meters. A value that isn't above 0 and at most 1 reads as 0.1 µm (VectorCraft's own fallback) | CN "Container"; S: the nine CX files with `4` all hold 1e-7; `abydos.cmx`, `CM33.CMX`, `LIZARDS.CMX`, `output.000.cmx` and `test.cmx` hold `2` | sample |
| R55 | A table (`rclr`, `rpen`, `rott`, `rdot`, `rotl`) is a u16 entry count, then one field list per entry; an instruction's body is field lists too. A field is a u8 tag, a u16 length counting its 3 header bytes, and the data; 0xff ends the list. Objects name table entries from 1 | CN "Tables"; S: every one of these tables in the nine CX files with 32-bit coordinates reads its count of entries with no bytes left | sample |
| R56 | A color entry: a property list in field 10 (a u32 length, then parts laid out as R11's, the color in part 1 as R14), or in older files the model and palette bytes in field 1 and the values in field 2. Models of the older fields: 2 cyan, magenta, yellow and black in percent; 3 the same in 0 to 255; 4 cyan, magenta and yellow in 0 to 255; 5 red, green and blue in 0 to 255; 9 gray in 0 to 255, 255 white. Other models read as black with a warning | CN "Tables" (`rclr`); S: every color of the nine CX files is model 2 in the older fields | sample (model 2), public-notes (field 10), unconfirmed (models 3 and 5 of the older fields, read as the program of CN reads them, and models 4 and 9, read as R14's; a wrong reading gives a wrong color) |
| R57 | `rpen` field 1: the width as a u32 in coordinate units (then an aspect, an angle and a matrix, not read). `rott` field 1: a flags byte (1 no outline, 2 solid, 4 dashed, 8 behind the fill, 16 scaled with the object), then the caps in the low 4 bits and the join in the high 4 bits, numbered as R12. `rdot` field 1: a u16 count, then the dash and gap lengths in outline widths (u16 each). A pattern whose lengths are all 0 draws a solid line, as R48's | CN "Tables"; S: line types 0x02 and 0x22 with caps and joins 0x00, 0x01 and 0x11 in the CX files | public-notes (the flags 4, 8 and 16 and the cap and join numbering; bit 0x20, set in `balloon.cmx`, is not read) |
| R58 | `rotl` field 1: six u16, the 1-based entries of the outline's line type, screen, color, arrowhead pair, pen and dash pattern | CN "Tables"; S: every `rotl` entry of the CX files names entries that exist | sample |
| R59 | `rota`: a u16 count, then pairs of u16 (start and end arrowheads, 0 for none), not field lists | CN "Tables"; S: `rota` is `01 00 00 00 00 00` in every CX file | sample (pairs of 0), public-notes (other values) |
| R60 | A `page` chunk is a stream of instructions: a u16 size counting the whole instruction and an i16 code, or 0xFFFF, a u32 size and the code (the long form); then field lists. Codes: 9 and 10 begin and end a page, 11 and 12 a layer, 13 and 14 a group, 67 a curve; 20 and 21 a text object, 65 its drawn characters, 66 an ellipse, 68 a rectangle, 69 an image, 88 and 89 add and remove a clipping path, 111 a jump whose field 1 is the u32 file offset to go on from (the bytes jumped over hold images). Objects are drawn in file order, the first at the back | CN "page: instructions"; S: codes 9 to 14 and 67 in the CX files; in `squares.cmx` the large square comes first and the two smaller ones inside it after | sample (9 to 14, 67, the order), public-notes (the long form and the other codes) |
| R61 | Field 4 of instruction 9: the page's width and height, u32 each in coordinate units. Without it, field 1 gives the drawing's bounds: a u16 page number, a u32, then the left, top, right and bottom edges as i32 in coordinate units; the page takes the bounds' size and is centered on them (VectorCraft's own choice). Without either, the page has no size, and the importer gives it 612 × 792 pt as it does a `.cdr` page without one (VectorCraft's own size) | CN "page: instructions"; S: none of the CX files has field 4; in all nine with 32-bit coordinates, the four edges in field 1 match the extent of the file's curves | public-notes (field 4), sample (field 1) |
| R62 | A layer's name: field 4 as a u32 count and UTF-16 units, or field 1 from byte 12 as a u16 count and 8-bit characters (read as Windows-1252, VectorCraft's own choice); a layer without a name is left unnamed, as a `.cdr` layer is. A curve: field 1 its rendering attributes, field 2 a u16 point count, the points as i32 x and y, then a type byte for each as R16; coordinates are from the page's center, y up. A field 2 too short for its count is read as whole points with their type bytes when its length is a multiple of 9, and the curve is left out as damaged otherwise (VectorCraft's own rule) | CN "page: instructions" and "Coordinates"; S: the 8-bit names `Layer 1`, `Desktop`, `Grid` and `Guides` of the CX files (the last three hold nothing in every file); every curve of the CX files has field 2 of exactly 2 + 9 bytes per point | sample (8-bit names, curves), public-notes (field 4) |
| R63 | Rendering attributes: a mask (1 fill, 2 outline, 4 lens, 8 canvas, 16 container; lenses, canvases and containers are not read, with a warning), then a field list for the fill when the mask names it and one for the outline. The fill's field 1 is a u16 type and a field list; type 0 is no fill, type 1 a uniform fill whose field 1 is the color entry (u16) and a screen (u16); other types (2 fountain and more) are not read. The outline's field 1 is its `rotl` entry (u16) | CN "Rendering attributes"; S: masks 1, 2 and 3, fill types 1, 2 and 6, and uniform fills with a 4-byte field 1 in the CX files | sample |
+98
View File
@@ -0,0 +1,98 @@
# craft-cdr
A bounded Rust reader for `.cdr` drawings of versions 1 to 27 (and `.cdt` templates).
It reads the `WL` files of versions 1 and 2, the RIFF chunk tree of versions 3 and later with its
compressed lists, the ZIP packages that versions 14 and later save (with the data streams of
versions 16 and later) and the records listed below, and hands the engine a drawing in points,
with each object's transform. It does not write `.cdr` files.
## What is read
| In the `.cdr` file | Read as |
|---|---|
| ZIP packages: `content/riffData.cdr` (versions 14 and 15), `content/root.dat` with the data streams `content/dataFileList.dat` names (16 on) | the RIFF chunk tree; a data stream is inflated only when a chunk the reader reads, or a list it splits, points into it |
| Pages, the page size in `mcfg` or a page's own size | pages, laid out by the engine as artboards side by side |
| Layers (drawing, desktop, guides and grid layers), the master page's among them | layers by name and kind |
| The hidden and locked flags of layers, groups and objects | flags |
| Guidelines (object type 0x16, and the version 7 `guid` chunk) | guidelines at their point and angle |
| Groups (`LIST grp `) | groups |
| Clipping containers and the groups of `LIST clpt` they clip | the container with the objects it clips |
| Curves (point lists of moves, lines and cubic curves) and paths (object type 0x25, version 10 on) | paths |
| Rectangles (one corner radius, four from version 9) | rectangles with each corner's radius |
| Ellipses, arcs and pies | ellipses, and paths for arcs and pies |
| Polygons and stars (a base side copied for each side) | paths |
| Uniform fills: CMYK, CMY, RGB, gray, registration, library colors | colors, spot colors with their tints |
| The fill's winding flag | the nonzero fill rule, or even-odd |
| Outlines: width, caps, joins, dashes, the no-outline and behind-the-fill flags, and from version 13 a library color named in their property list | outlines |
| Uniform transparency (version 13 on) and its merge mode | the shape's opacity and blend mode |
| Styles (`LIST stlt`, versions 7 to 15) that objects name | the fill and outline of an object that has none of its own |
Text, bitmaps, linked groups (blends, contours, brush strokes), B-spline curves, fountain,
pattern, texture and PostScript fills, outline arrowheads, lenses, transparency other than uniform
transparency of version 13 and later, and merge modes without a VectorCraft blend mode are not
read; the drawing's
`warnings` name each kind it held. Drawings of versions after 27 are refused, and so are packages
that are encrypted, ZIP64 archives or split across files.
VectorCraft reads a uniform transparency's stored value as the transparency in percent (0 opaque,
100 clear), and a winding flag other than 0 as the nonzero fill rule. These are VectorCraft's own
readings: no public source states either direction.
## Versions 1 to 4
Public specifications cover only parts of these versions, such as the version 3 fill and page
settings. For the rest, the reader follows the layouts of public sample files that
`PROVENANCE.md` lists (rows R31 to R44), and its tests read the synthetic files that
`src/synth.rs` builds from those rows.
| Version | Read | Left out or refused |
|---|---|---|
| 1 and 2 (`WL` files) | the page size; rectangles with one corner radius, whole ellipses and curves, each with its matrix; uniform fills and outlines with their width and color, in CMYK percent and the inks black and white. The objects come in on one page and one layer, front to back | text and objects of other types, and ellipses whose two angles differ (arcs and pies), with the unsupported-objects warning; fills of other types, with the unsupported-fills warning; inks of a numbered library, which read as spot colors without a look; groups and layers, whose records are passed over; dashes, caps, joins and arrowheads, which the reader does not look for; the records after a drawn object of another type, with the unsupported-objects warning |
| 3 (RIFF, form type `CDR `) | the page size from the page's corners; pages, layers and groups; rectangles, ellipses, arcs and curves with the matrices of the object and of the groups around it; uniform fills; outlines with their width, color, caps, joins and dashes | text and bitmaps; envelopes, with the envelopes warning (the objects and groups under one keep their outlines and matrices); fountain, pattern and texture fills; arrowheads |
| 4 (RIFF, form type `CDR4`) | as version 5, with the colors and the fixed-point transforms of version 4 | as version 5 |
A file is taken for version 1 or 2 by its content only when, after `WL`, its marker byte is one of
`e`, `l` and `m`, the next byte is zero, and the offsets of its header fit the file. The reader
reports version 1 for the marker `e` and version 2 for the other two. A RIFF file that names
a version before 3 is refused, and so is the version 4 template form type `CDST`, which reads as
not a `.cdr` drawing.
## `.cmx` files
`read_cmx` reads `.cmx` exchange files with 32-bit coordinates (rows R53 to R63) into the same
drawing model, with a version of 0. It reads the color, pen, line type, dash, outline and
arrowhead tables, then each page's instructions in drawing order:
| In the `.cmx` file | Read as |
|---|---|
| Pages, with the size the page gives, or else the size of the drawing's bounds that the page stores | pages; a page sized to the bounds is centered on them |
| Layers, by their UTF-16 or 8-bit name | drawing layers, unnamed when the file gives no name; a layer that holds nothing is left out |
| Groups | groups |
| Curves (moves, lines and cubic curves, as `.cdr` point lists) | paths |
| Uniform fills: CMYK in percent or 0 to 255, CMY, RGB, gray, and library colors with their names | colors, spot colors |
| Outlines: width, color, caps, joins, dashes, the no-outline, behind-the-fill and scaled-with flags | outlines |
Text, images, rectangles, ellipses, clipping paths, fills other than uniform ones, outline
arrowheads and lenses are not read; the drawing's `warnings` name each kind it held. A clipping
path is left out and the objects it clips are read without it. Files in big-endian byte order and
files with 16-bit coordinates are refused.
## Provenance
`PROVENANCE.md` lists every record layout the reader relies on, with its public source and status.
Code cites the rows by id (`R1` ...), and `tests/it/provenance.rs` fails when a cited id has no row.
The test inputs are synthetic drawings built by `src/synth.rs` and `src/synth_cmx.rs` (the
`synth` feature); no third-party file is committed.
## Limits
`Limits` bounds the input size, the bytes inflated from compressed lists and package members, the
size of one package member, the number of members, the nesting depth, the chunk count, the
objects, the coordinates and the outline dashes of one read. Past a limit the reader stops with an
error or leaves the rest out with a warning; it does not recurse and does not panic. Each record
of a version 1 or 2 file counts toward the chunk count, and the transform entries of a version 3
object are held to the arguments one record may have. A package's
data stream is read once however many lines of `content/dataFileList.dat` name it. A redirected
list whose bytes overlap those of an earlier redirected list is left out with the damage warning.
Other records may share bytes, and the bytes read again may add up to the member limit; past it
the records are left out with the limit warning.
+917
View File
@@ -0,0 +1,917 @@
//! The drawing the chunk index holds: pages, layers, objects and the fills and outlines they name
//! (R19 to R23). Records are decoded only when an object refers to them.
use std::collections::HashMap;
use crate::bytes::Rd;
use crate::geometry;
use crate::inline;
use crate::layout::{self, Profile};
use crate::limits::Budget;
use crate::model::{Blend, Color, Drawing, Flags, Geometry, Guideline, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape};
use crate::records::{self, Loda};
use crate::riff::{Chunk, Index, push};
use crate::styles::Styles;
use crate::{Error, Warning};
/// Object types (R6).
const RECTANGLE: u32 = 1;
const ELLIPSE: u32 = 2;
const CURVE: u32 = 3;
const POLYGON: u32 = 0x14;
const GUIDELINE: u32 = 0x16;
const PATH: u32 = 0x25;
/// Argument types (R6, R20, R21, R33, R52).
const ARG_OUTLINE: u32 = 10;
const ARG_FILL: u32 = 20;
const ARG_COORDS: u32 = 30;
const ARG_TRANSFORMS: u32 = 100;
const ARG_STYLE: u32 = 200;
const ARG_NAME: u32 = 1000;
const ARG_LENS: u32 = 8000;
const ARG_CONTAINER: u32 = 8005;
const ARG_POLYGON: u32 = 11000;
const ARG_WINDING: u32 = 14001;
const ARG_GUIDE: u32 = 16000;
const ARG_PAGE_SIZE: u32 = 19130;
/// What a RIFF file that names a version before 3 is refused as.
const BEFORE_3: &str = "RIFF files of versions before 3";
/// What one read keeps while mapping.
struct Ctx<'a, 'b> {
ix: &'b Index<'a>,
p: Profile,
budget: &'b mut Budget,
warn: &'b mut Vec<Warning>,
/// Fill and outline records by id, decoded on first use.
fill_chunks: HashMap<u32, &'b [u8]>,
outline_chunks: HashMap<u32, &'b [u8]>,
fills: HashMap<u32, Option<Color>>,
outlines: HashMap<u32, Option<Outline>>,
/// The styles objects name in argument 200 (R45): `Err` when the file's style table doesn't
/// parse.
styles: Result<Styles, ()>,
/// The groups of `LIST clpt` that containers clip, by the id in their `spnd` chunk (R46).
clips: HashMap<u32, &'b Chunk>,
/// The clipped groups being read, innermost last.
open_clips: Vec<u32>,
/// Whether the walk of a clipped group stopped at the clipped chunk limit.
clip_cut: bool,
/// The chunks the object lists of clipped groups keep for themselves, by list, each found the
/// first time a read needs it.
own: HashMap<(*const Chunk, Own), Option<&'b Chunk>>,
/// The matrices the `trfd` chunks of clipped groups' objects hold, by chunk; `None` for one
/// that can't be read.
trfds: HashMap<*const Chunk, Option<Matrix>>,
}
/// A chunk an object list keeps for itself.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Own {
/// Its `loda` (or `lobj`).
Loda,
/// Its `flgs`, among its own chunks alone.
Flags,
/// Its `trfd`.
Trfd,
}
impl Own {
fn ids(self) -> &'static [&'static [u8; 4]] {
match self {
Own::Loda => &[b"loda", b"lobj"],
Own::Flags => &[b"flgs"],
Own::Trfd => &[b"trfd"],
}
}
}
/// The most clipped groups read one inside another: VectorCraft's own limit.
const MAX_CLIP_DEPTH: usize = 64;
pub(crate) fn drawing(ix: &Index, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Drawing, Error> {
let root = ix.root().ok_or(Error::NotCdr)?;
let version = ix.version();
// A template whose `vrsn` chunk doesn't name a version read (R28).
if version == 0 {
return Err(Error::NotCdr);
}
// Versions 1 and 2 are `WL` files (R40); no source shows a RIFF file that names a version
// before 3.
if version < layout::OLDEST_RIFF {
return Err(Error::Unsupported(BEFORE_3));
}
let p = layout::for_version(version).ok_or(Error::Version(version))?;
let mut found = Found::default();
collect(ix, root, &mut found);
let page_size = found.mcfg.and_then(|c| page_size(ix.data(c), &p));
// Before version 7 a `LIST stlt` holds chunks, not the style table (R4).
let styles = match found.stlt {
Some(c) if version >= 700 => Styles::read(ix.data(c), version, budget)?.ok_or(()),
_ => Ok(Styles::default()),
};
let mut cx = Ctx {
ix,
p,
budget,
warn,
fill_chunks: HashMap::new(),
outline_chunks: HashMap::new(),
fills: HashMap::new(),
outlines: HashMap::new(),
styles,
clips: HashMap::new(),
open_clips: Vec::new(),
clip_cut: false,
own: HashMap::new(),
trfds: HashMap::new(),
};
// The `spnd` id is a u16 in files of 16-bit fields (R46).
let spnd = |b: &[u8]| if p.short { Rd::new(b).u16().map(u32::from) } else { Rd::new(b).u32() };
for g in found.clpt.iter().flat_map(|c| ix.children(c)).filter(|g| g.is_list(b"grp ")) {
if let Some(id) = ix.children(g).iter().find(|c| &c.id == b"spnd").and_then(|c| spnd(ix.data(c))) {
cx.clips.entry(id).or_insert(g);
}
}
for c in &found.fills {
if let Some(id) = Rd::new(ix.data(c)).u32() {
cx.fill_chunks.entry(id).or_insert(ix.data(c));
}
}
for c in &found.outlines {
if let Some(id) = Rd::new(ix.data(c)).u32() {
cx.outline_chunks.entry(id).or_insert(ix.data(c));
}
}
let mut guides = found.guid.map(|c| guid_chunk(ix.data(c), &cx.p, cx.budget, cx.warn)).unwrap_or_default();
let mut pages = Vec::new();
let mut master = Vec::new();
for page in &found.pages {
let (is_master, read) = cx.page(page);
if is_master {
// Guidelines on any of the master page's layers show on every page.
for mut layer in read.layers {
guides.append(&mut layer.guides);
if !layer.objects.is_empty() && layer.kind != LayerKind::Grid {
master.push(layer);
}
}
} else {
pages.push(read);
}
}
// A file of only a master page keeps it as its page.
if pages.is_empty() && !master.is_empty() {
pages.push(Page { size: None, layers: std::mem::take(&mut master) });
}
Ok(Drawing { version, page_size, pages, master, guides, warnings: std::mem::take(cx.warn) })
}
#[derive(Default)]
struct Found<'i> {
fills: Vec<&'i Chunk>,
outlines: Vec<&'i Chunk>,
mcfg: Option<&'i Chunk>,
guid: Option<&'i Chunk>,
stlt: Option<&'i Chunk>,
clpt: Vec<&'i Chunk>,
pages: Vec<&'i Chunk>,
}
/// Every fill, outline, `LIST clpt` and page in file order, and the first `mcfg`, `guid` and
/// `LIST stlt`; pages are not looked into.
fn collect<'i>(ix: &'i Index, root: &'i Chunk, found: &mut Found<'i>) {
let mut stack: Vec<&Chunk> = ix.children(root).iter().rev().collect();
while let Some(c) = stack.pop() {
match &c.id {
b"fild" | b"fill" => found.fills.push(c),
b"outl" => found.outlines.push(c),
b"mcfg" => found.mcfg = found.mcfg.or(Some(c)),
b"guid" => found.guid = found.guid.or(Some(c)),
// Before version 7 the list holds chunks, which are looked through.
_ if c.is_list(b"stlt") => {
found.stlt = found.stlt.or(Some(c));
stack.extend(ix.children(c).iter().rev());
}
_ if c.is_list(b"clpt") => found.clpt.push(c),
_ if c.is_list(b"page") => found.pages.push(c),
_ => stack.extend(ix.children(c).iter().rev()),
}
}
}
/// The page size in `mcfg` (R10); in version 3 the distance between the page's two corners, after
/// 2 bytes (R38).
fn page_size(b: &[u8], p: &Profile) -> Option<(f64, f64)> {
let mut r = Rd::at(b, p.mcfg_skip);
if p.mcfg_corners {
r.skip(2)?;
let (x0, y0, x1, y1) = (records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?, records::coord(&mut r, p)?);
return sane_size(x1 - x0, y1 - y0);
}
sane_size(records::coord(&mut r, p)?, records::coord(&mut r, p)?)
}
fn sane_size(w: f64, h: f64) -> Option<(f64, f64)> {
let (w, h) = (w.abs(), h.abs());
(w > 0.0 && h > 0.0).then_some((w, h))
}
/// The version 7 `guid` chunk (R23): two counts, then 40-byte records laid out as argument 16000.
/// Each guideline counts toward the objects a read maps; past them the rest are left out.
fn guid_chunk(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Vec<Guideline> {
let mut r = Rd::new(b);
let Some(n) = r.u32() else { return Vec::new() };
let _again = r.u32();
let fits = r.left() / 40;
if n as usize > fits {
push(warn, Warning::Damaged);
}
let n = (n as usize).min(fits);
let mut out = Vec::new();
for i in 0..n {
if !budget.take_object() {
push(warn, Warning::TooDeep);
break;
}
out.extend(b.get(8 + i * 40..8 + (i + 1) * 40).and_then(|g| guideline(g, p)));
}
out
}
/// A guideline record (R23): 12 bytes, the angle in millionths of a degree, then a point.
fn guideline(b: &[u8], p: &Profile) -> Option<Guideline> {
if p.short {
return None;
}
let mut r = Rd::at(b, 12);
let angle = f64::from(r.i32()?) / 1_000_000.0;
let at = Pt { x: records::coord(&mut r, p)?, y: records::coord(&mut r, p)? };
Some(Guideline { at, angle, hidden: false })
}
/// Marks the guidelines from `from` on hidden when `flags` hide what holds them.
fn hide_guides(guides: &mut [Guideline], from: usize, flags: Flags) {
if flags.hidden {
for g in guides.iter_mut().skip(from) {
g.hidden = true;
}
}
}
/// A list's flags (R19): four bytes.
fn flags(ix: &Index, list: &Chunk) -> Option<[u8; 4]> {
flgs_bytes(ix, ix.children(list).iter().find(|c| &c.id == b"flgs")?)
}
/// The four bytes of a `flgs` chunk.
fn flgs_bytes(ix: &Index, c: &Chunk) -> Option<[u8; 4]> {
ix.data(c).get(..4)?.try_into().ok()
}
/// Whether a layer, group or object list is hidden (bit 0x01 of byte 1) or locked (bit 0x10 of
/// byte 0) (R19).
fn state(ix: &Index, list: &Chunk) -> Flags {
flags(ix, list).map_or(Flags::default(), flag_bits)
}
/// What a list's four flag bytes say, as [`state`] reads them.
fn flag_bits([b0, b1, _, _]: [u8; 4]) -> Flags {
Flags { hidden: b1 & 0x01 != 0, locked: b0 & 0x10 != 0 }
}
/// `o` with `f` added to its own flags: the objects of a group left ungrouped keep the group's.
fn inherit(o: &mut Object, f: Flags) {
let own = match o {
Object::Shape(s) => &mut s.flags,
Object::Group { flags, .. } => flags,
Object::Clip { container, .. } => &mut container.flags,
};
own.hidden |= f.hidden;
own.locked |= f.locked;
}
/// What a layer's object type makes it (R19): 11 a grid, 12 guides, 17 the desktop, any other a
/// drawing layer. Version 3 counts its types from 0, one less (R32).
fn layer_kind_of_type(kind: u32, types_from_zero: bool) -> LayerKind {
match kind.saturating_add(u32::from(types_from_zero)) {
11 => LayerKind::Grid,
12 => LayerKind::Guides,
17 => LayerKind::Desktop,
_ => LayerKind::Drawing,
}
}
/// What a layer's flags make it, for a layer without an object type of its own (R19). The low
/// four bits of byte 0 hold the kind: 0x0a guides, or a grid with bit 0x10 set (versions 7 to 13
/// also flag them 0x02); 0x08 the desktop when byte 2 is set, a drawing layer when it is clear.
/// Versions 7 to 13 may flag the master page's desktop layer 0 with bytes 1 and 2 set. Bit 0x10
/// alone does not make a grid.
fn layer_kind(f: [u8; 4], version_below_14: bool) -> LayerKind {
let [b0, b1, b2, _] = f;
let grid_bit = b0 & 0x10 != 0;
match b0 & 0x0f {
0x0a if grid_bit => LayerKind::Grid,
0x0a => LayerKind::Guides,
0x02 if version_below_14 && grid_bit => LayerKind::Grid,
0x02 if version_below_14 => LayerKind::Guides,
0x08 if b2 != 0 => LayerKind::Desktop,
0 if version_below_14 && b1 == 1 && b2 == 1 => LayerKind::Desktop,
_ => LayerKind::Drawing,
}
}
/// The first chunk of one of `ids` that a page, layer or object keeps for itself: among its own
/// chunks, or in its `lgob` list and the `trfl` list there (R22).
fn own_chunk<'i>(ix: &'i Index, list: &'i Chunk, ids: &[&[u8; 4]]) -> Option<&'i Chunk> {
find_own(ix, list, ids, true, || true).flatten()
}
/// The first chunk of one of `ids` among `list`'s own chunks, and when `nested` also in its `lgob`
/// list and the `trfl` list there, as [`own_chunk`] finds it. `visit` is asked before each chunk
/// the search looks at, and the search stops with `None` when it answers `false`.
fn find_own<'i>(ix: &'i Index, list: &'i Chunk, ids: &[&[u8; 4]], nested: bool, mut visit: impl FnMut() -> bool) -> Option<Option<&'i Chunk>> {
// The lists being looked through, outermost first, each with the next chunk to look at, and
// the innermost one's place.
let mut stack: [(&'i [Chunk], usize); 3] = [(ix.children(list), 0), (&[], 0), (&[], 0)];
let mut depth = 0;
loop {
let Some(top) = stack.get_mut(depth) else { return Some(None) };
let chunks: &'i [Chunk] = top.0;
let Some(c) = chunks.get(top.1) else {
if depth == 0 {
return Some(None);
}
depth -= 1;
continue;
};
top.1 += 1;
if !visit() {
return None;
}
if ids.contains(&&c.id) {
return Some(Some(c));
}
if nested && depth < 2 && (c.is_list(b"lgob") || c.is_list(b"trfl")) {
depth += 1;
if let Some(next) = stack.get_mut(depth) {
*next = (ix.children(c), 0);
}
}
}
}
/// The `loda` (or `lobj`) a page, layer or object keeps for itself.
fn own_loda<'i>(ix: &'i Index, list: &'i Chunk) -> Option<&'i Chunk> {
own_chunk(ix, list, &[b"loda", b"lobj"])
}
/// A page's layer lists in file order: its own, and those in the lists it holds, such as the
/// `gobj` list of files of versions 7 to 13 (R22).
fn page_layers<'i>(ix: &'i Index, page: &'i Chunk) -> Vec<&'i Chunk> {
let mut out = Vec::new();
let mut stack: Vec<&Chunk> = ix.children(page).iter().rev().collect();
while let Some(c) = stack.pop() {
if c.is_list(b"layr") {
out.push(c);
} else if c.id == crate::riff::LIST && !c.is_list(b"lgob") {
stack.extend(ix.children(c).iter().rev());
}
}
out
}
/// One frame of the object walk: a list's chunks, the next one to look at, and the objects so far.
struct Frame<'i> {
chunks: &'i [Chunk],
next: usize,
objects: Vec<Object>,
/// Whether its objects form a group in the frame below.
group: bool,
/// The group's own flags.
flags: Flags,
/// The first of the guidelines read inside it.
guides_from: usize,
/// What places its objects after their own transforms: the matrices of the version 3 groups
/// around them (R33). The identity in other versions, whose objects hold their whole transform.
outer: Matrix,
}
impl<'a, 'b> Ctx<'a, 'b> {
/// A page: whether it is the master page, and its layers.
fn page(&mut self, page: &Chunk) -> (bool, Page) {
let ix = self.ix;
let is_master = flags(ix, page).is_some_and(|f| f[2] != 0);
let size = own_loda(ix, page)
.and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn))
.and_then(|l| l.arg(ARG_PAGE_SIZE).and_then(|b| self.size_arg(b)));
let mut layers = Vec::new();
for l in page_layers(ix, page) {
let layer = self.layer(l);
let empty = layer.objects.is_empty() && layer.guides.is_empty();
// The entries that stand for the master page's layers hold nothing of the page's own.
if empty && (is_master || layer.kind != LayerKind::Drawing) {
continue;
}
layers.push(layer);
}
(is_master, Page { size, layers })
}
fn size_arg(&self, b: &[u8]) -> Option<(f64, f64)> {
let mut r = Rd::new(b);
sane_size(records::coord(&mut r, &self.p)?, records::coord(&mut r, &self.p)?)
}
fn layer(&mut self, list: &Chunk) -> Layer {
let ix = self.ix;
let loda = own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn));
// The layer's own object type says what it is; its flags, only when it has none (R19).
let kind = match &loda {
Some(l) => layer_kind_of_type(l.kind, self.p.types_from_zero),
None => flags(ix, list).map_or(LayerKind::Drawing, |f| layer_kind(f, self.p.old_master_flags)),
};
let name = loda.and_then(|l| l.arg(ARG_NAME).map(|b| records::name(b, &self.p, self.warn))).unwrap_or_default();
let mut guides = Vec::new();
let objects = self.objects(ix.children(list), &mut guides);
let flags = state(ix, list);
hide_guides(&mut guides, 0, flags);
Layer { name, kind, flags, objects, guides }
}
/// The objects of a layer's chunks, groups nested, front to back; guidelines go to `guides`.
fn objects(&mut self, chunks: &'b [Chunk], guides: &mut Vec<Guideline>) -> Vec<Object> {
let ix = self.ix;
let mut stack = vec![Frame {
chunks,
next: 0,
objects: Vec::new(),
group: false,
flags: Flags::default(),
guides_from: guides.len(),
outer: Matrix::IDENTITY,
}];
loop {
let Some(top) = stack.last_mut() else { return Vec::new() };
let (here, outer) = (top.chunks, top.outer);
let Some(c) = here.get(top.next) else {
let Some(done) = stack.pop() else { return Vec::new() };
// A hidden group hides the guidelines inside it.
hide_guides(guides, done.guides_from, done.flags);
match stack.last_mut() {
// A group counts toward the objects a read maps; past them its objects stay,
// ungrouped, with the group's flags.
Some(parent) if done.group && !done.objects.is_empty() => {
if self.budget.take_object() {
parent.objects.push(Object::Group { objects: done.objects, flags: done.flags });
} else {
push(self.warn, Warning::TooDeep);
let mut objects = done.objects;
for o in &mut objects {
inherit(o, done.flags);
}
parent.objects.extend(objects);
}
}
Some(parent) if !done.group => parent.objects.extend(done.objects),
Some(_) => {}
None => return done.objects,
}
continue;
};
top.next += 1;
// Every chunk of a clipped group counts, empty groups included, each time a container
// names the group; past the limit the group is left out.
if !self.open_clips.is_empty() && !self.budget.take_clipped_chunk() {
push(self.warn, Warning::TooDeep);
self.clip_cut = true;
return Vec::new();
}
if c.is_list(b"obj ") {
if let Some(o) = self.object(c, guides, &outer) {
top.objects.push(o);
}
// Past the limit while looking for what the object keeps for itself.
if self.clip_cut {
return Vec::new();
}
} else if c.is_list(b"grp ") {
let own = self.group_placement(c);
let flags = state(ix, c);
let guides_from = guides.len();
stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: true, flags, guides_from, outer: outer.after(&own) });
} else if c.is_list(b"lnkg") {
// Linked groups (brush strokes, blends, contours) place their objects with a
// matrix of their own, which this reader doesn't apply: they are left out.
push(self.warn, Warning::UnsupportedObjects);
} else if c.id == crate::riff::LIST && !c.is_list(b"lgob") {
// Other lists under a layer are looked through (R22).
let guides_from = guides.len();
stack.push(Frame { chunks: ix.children(c), next: 0, objects: Vec::new(), group: false, flags: Flags::default(), guides_from, outer });
}
}
}
/// The `which` chunk object list `list` keeps for itself. In a clipped group it is looked for
/// once per read, the first time a container's walk needs it, and each chunk the search looks
/// at counts toward the clipped chunk limit then; past that limit the walk stops (`None`).
fn own(&mut self, list: &'b Chunk, which: Own) -> Option<Option<&'b Chunk>> {
let nested = which != Own::Flags;
if self.open_clips.is_empty() {
return find_own(self.ix, list, which.ids(), nested, || true);
}
let key = (std::ptr::from_ref(list), which);
if let Some(c) = self.own.get(&key) {
return Some(*c);
}
let Some(c) = find_own(self.ix, list, which.ids(), nested, || self.budget.take_clipped_chunk()) else {
push(self.warn, Warning::TooDeep);
self.clip_cut = true;
return None;
};
self.own.insert(key, c);
Some(c)
}
/// The matrix `trfd` holds, or `None` when it can't be read. In a clipped group each `trfd` is
/// read once per read, however many containers name the group.
fn trfd(&mut self, c: &'b Chunk) -> Option<Matrix> {
if self.open_clips.is_empty() {
return records::trfd(self.ix.data(c), &self.p);
}
let ix = self.ix;
let p = &self.p;
*self.trfds.entry(std::ptr::from_ref(c)).or_insert_with(|| records::trfd(ix.data(c), p))
}
/// The matrix a group places its objects with. Only a version 3 group has one, in the
/// transforms argument of its own `lobj` (R33); one that can't be read is damage, and the
/// group's objects stay where their own transforms put them.
fn group_placement(&mut self, list: &Chunk) -> Matrix {
if !self.p.inline_styles {
return Matrix::IDENTITY;
}
let ix = self.ix;
let Some(arg) =
own_loda(ix, list).and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)).and_then(|l| l.arg(ARG_TRANSFORMS))
else {
return Matrix::IDENTITY;
};
self.placement(arg)
}
/// The matrices of a transforms argument (R33). An envelope among them is not applied: the
/// shapes keep their outlines, placed by the matrices alone, with the envelopes warning.
fn placement(&mut self, arg: &[u8]) -> Matrix {
match inline::transforms(arg, &self.p, &self.budget.limits, self.warn) {
Some(t) => {
if t.envelope {
push(self.warn, Warning::Envelopes);
}
t.matrix
}
None => {
push(self.warn, Warning::Damaged);
Matrix::IDENTITY
}
}
}
/// One `LIST obj `: a shape placed by its own transform and then by `outer`, or `None` (a
/// guideline goes to `guides`).
fn object(&mut self, list: &'b Chunk, guides: &mut Vec<Guideline>, outer: &Matrix) -> Option<Object> {
let ix = self.ix;
let Some(loda) = self.own(list, Own::Loda)?.and_then(|c| records::loda(ix.data(c), &self.p, &self.budget.limits, self.warn)) else {
push(self.warn, Warning::Damaged);
return None;
};
// Guidelines count toward the objects a read maps.
if !self.budget.take_object() {
push(self.warn, Warning::TooDeep);
return None;
}
let flags = self.own(list, Own::Flags)?.and_then(|c| flgs_bytes(ix, c)).map_or(Flags::default(), flag_bits);
if loda.kind == GUIDELINE {
guides.extend(loda.arg(ARG_GUIDE).and_then(|b| guideline(b, &self.p)).map(|g| Guideline { hidden: flags.hidden, ..g }));
return None;
}
if self.p.inline_styles {
return self.inline_object(&loda, outer, flags);
}
let geometry = self.geometry(&loda)?;
// A uniform transparency from version 13 applies (R47); a lens, and a transparency of
// another kind or version, is not applied: the shape shows opaque.
let (opacity, blend) = match loda.arg(ARG_LENS) {
None => (1.0, Blend::Normal),
Some(b) => match records::transparency(b).filter(|_| self.p.tagged) {
Some(t) => t,
None => {
push(self.warn, Warning::Lenses);
(1.0, Blend::Normal)
}
},
};
let nonzero = self.nonzero(&loda);
// A transform that is there but can't be read is damage; the shape stays where it is.
let matrix = match self.own(list, Own::Trfd)? {
None => Matrix::IDENTITY,
Some(c) => self.trfd(c).unwrap_or_else(|| {
push(self.warn, Warning::Damaged);
Matrix::IDENTITY
}),
};
// Without a fill or outline argument of its own, an object takes its style's (R45). The
// style id is a u16 in files of 16-bit fields.
let style = loda.arg(ARG_STYLE).and_then(|b| if self.p.short { self.short_id(b) } else { self.id(b) });
let fill_id = match loda.arg(ARG_FILL) {
Some(b) => self.id(b),
None => style.and_then(|s| self.style_entry(s, Styles::fill)),
};
let outline_id = match loda.arg(ARG_OUTLINE) {
Some(b) => self.id(b),
None => style.and_then(|s| self.style_entry(s, Styles::outline)),
};
let fill = fill_id.and_then(|id| self.fill(id));
let outline = outline_id.and_then(|id| self.outline(id));
let shape = Box::new(Shape { geometry, matrix, fill, outline, nonzero, opacity, blend, flags });
// A container clips the group its argument 8005 names (R46).
Some(match loda.arg(ARG_CONTAINER).and_then(|b| self.id(b)) {
Some(id) => self.clip(shape, id, guides),
None => Object::Shape(shape),
})
}
/// `container` and the objects of the clipped group `id`, which keep their own transforms.
/// A group that isn't there is damage; one already being read, past the depth limit or past
/// the chunks clipped groups may walk is left out with the limit warning, the guidelines it
/// holds included. Either way the container stays, as a plain shape.
fn clip(&mut self, container: Box<Shape>, id: u32, guides: &mut Vec<Guideline>) -> Object {
let Some(&group) = self.clips.get(&id) else {
push(self.warn, Warning::Damaged);
return Object::Shape(container);
};
if self.open_clips.contains(&id) || self.open_clips.len() >= MAX_CLIP_DEPTH {
push(self.warn, Warning::TooDeep);
return Object::Shape(container);
}
self.open_clips.push(id);
let (ix, mark) = (self.ix, guides.len());
let objects = self.objects(ix.children(group), guides);
self.open_clips.pop();
if std::mem::take(&mut self.clip_cut) {
guides.truncate(mark);
return Object::Shape(container);
}
// The clipped group's own flags hide or lock the objects it holds; it and the container
// hide its guidelines.
let flags = state(ix, group);
hide_guides(guides, mark, flags);
hide_guides(guides, mark, container.flags);
if objects.is_empty() {
return Object::Shape(container);
}
let mut objects = objects;
for o in &mut objects {
inherit(o, flags);
}
Object::Clip { container, objects }
}
/// The record id that argument `b` names; an argument too short for one is damage.
fn id(&mut self, b: &[u8]) -> Option<u32> {
let id = id_of(b);
if id.is_none() {
push(self.warn, Warning::Damaged);
}
id
}
/// A u16 id at the start of argument `b`; an argument too short for one is damage.
fn short_id(&mut self, b: &[u8]) -> Option<u32> {
let id = Rd::new(b).u16().map(u32::from);
if id.is_none() {
push(self.warn, Warning::Damaged);
}
id
}
/// Whether the object's fill rule is nonzero: byte 0 of argument 14001 set (R52). Without the
/// argument the fill is even-odd; an argument without its byte is damage.
fn nonzero(&mut self, loda: &Loda) -> bool {
let Some(b) = loda.arg(ARG_WINDING) else { return false };
match b.first() {
Some(v) => *v != 0,
None => {
push(self.warn, Warning::Damaged);
false
}
}
}
/// The fill or outline record that style `id` names; a style table that doesn't parse is
/// damage, and the object is drawn without it.
fn style_entry(&mut self, id: u32, entry: fn(&Styles, u32) -> Option<u32>) -> Option<u32> {
match &self.styles {
Ok(s) => entry(s, id),
Err(()) => {
push(self.warn, Warning::Damaged);
None
}
}
}
/// A version 3 object, whose transforms, fill and outline are arguments of its own record
/// (R33, R34, R35). A fill or an outline that is there but can't be read is damage.
fn inline_object(&mut self, loda: &Loda, outer: &Matrix, flags: Flags) -> Option<Object> {
let own = match loda.arg(ARG_TRANSFORMS) {
None => Matrix::IDENTITY,
Some(arg) => self.placement(arg),
};
let geometry = self.geometry(loda)?;
let fill = loda.arg(ARG_FILL).and_then(|b| {
let read = inline::fill(b, &self.p, self.warn);
if read.is_none() {
push(self.warn, Warning::Damaged);
}
read.flatten()
});
let outline = loda.arg(ARG_OUTLINE).and_then(|b| {
let read = inline::outline(b, &self.p, self.warn);
if read.is_none() {
push(self.warn, Warning::Damaged);
}
read.flatten()
});
// Past the dashes a read takes, the outline is solid.
let outline = outline.map(|mut o| {
if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) {
o.dashes = Vec::new();
push(self.warn, Warning::TooDeep);
}
o
});
let nonzero = self.nonzero(loda);
let shape = Shape { nonzero, flags, ..Shape::new(geometry, outer.after(&own), fill, outline) };
Some(Object::Shape(Box::new(shape)))
}
fn geometry(&mut self, loda: &Loda) -> Option<Geometry> {
let coords = loda.arg(ARG_COORDS);
// Version 3 counts the first object types from 0, one below the later numbers (R32).
let kind = if self.p.types_from_zero && loda.kind <= 4 { loda.kind + 1 } else { loda.kind };
// A shape without its coordinates, or a polygon without its sides, is damage like a shape
// whose coordinates can't be read; one left out at the coordinate limit is not.
self.budget.coordinates_refused();
let g = match kind {
RECTANGLE => coords.and_then(|c| geometry::rect(c, &self.p)),
ELLIPSE => coords.and_then(|c| geometry::ellipse(c, &self.p)),
CURVE => coords.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn)).map(Geometry::Path),
PATH if self.p.paths => coords.and_then(|c| geometry::path_record(c, &self.p, self.budget, self.warn)).map(Geometry::Path),
POLYGON => match loda.arg(ARG_POLYGON) {
Some(sides) => coords
.and_then(|c| geometry::point_list(c, &self.p, self.budget, self.warn))
.and_then(|base| geometry::polygon(&base, sides, &self.p, self.budget, self.warn)),
None => {
push(self.warn, Warning::Damaged);
return None;
}
},
_ => {
push(self.warn, Warning::UnsupportedObjects);
return None;
}
};
if g.is_none() && !self.budget.coordinates_refused() {
push(self.warn, Warning::Damaged);
}
g
}
fn fill(&mut self, id: u32) -> Option<Color> {
if let Some(f) = self.fills.get(&id) {
return f.clone();
}
// A record that is missing or can't be read is damage, and the shape is drawn without a
// fill; id 0 without a record is no fill.
if id != 0 && !self.fill_chunks.contains_key(&id) {
push(self.warn, Warning::Damaged);
}
let read = self.fill_chunks.get(&id).and_then(|b| {
let read = records::fill(b, &self.p, self.warn);
if read.is_none() {
push(self.warn, Warning::Damaged);
}
read.and_then(|(_, c)| c)
});
self.fills.insert(id, read.clone());
read
}
/// The outline of record `id`. Its dashes count toward the read's dashes for every shape that
/// uses it; past them the shape's outline is solid.
fn outline(&mut self, id: u32) -> Option<Outline> {
if !self.outlines.contains_key(&id) {
// A record that is missing is damage, as one that can't be read is; id 0 without a
// record is no outline.
if id != 0 && !self.outline_chunks.contains_key(&id) {
push(self.warn, Warning::Damaged);
}
let read = self.outline_chunks.get(&id).and_then(|b| {
let read = records::outline(b, &self.p, self.warn);
if read.is_none() {
push(self.warn, Warning::Damaged);
}
read.and_then(|(_, o)| o)
});
// An outline with more dashes than the read may still take is kept solid.
let read = read.map(|mut o| {
if o.dashes.len() > self.budget.dashes_left() {
o.dashes = Vec::new();
push(self.warn, Warning::TooDeep);
}
o
});
self.outlines.insert(id, read);
}
let o = self.outlines.get_mut(&id)?.as_mut()?;
// The dashes left only shrink, so an outline refused once is refused for every later
// shape: its dashes are dropped from the cache, and later shapes take it solid.
if !o.dashes.is_empty() && !self.budget.take_dashes(o.dashes.len()) {
o.dashes = Vec::new();
push(self.warn, Warning::TooDeep);
}
Some(o.clone())
}
}
/// A fill or outline argument: the record id (R20).
fn id_of(b: &[u8]) -> Option<u32> {
Rd::new(b).u32()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn layer_flags_name_the_kinds() {
assert_eq!(layer_kind([0, 0, 0, 0x98], true), LayerKind::Drawing);
assert_eq!(layer_kind([0x0a, 0, 0, 0x98], true), LayerKind::Guides);
assert_eq!(layer_kind([0x02, 1, 1, 0x98], true), LayerKind::Guides);
assert_eq!(layer_kind([0x08, 0, 1, 0x98], true), LayerKind::Desktop);
assert_eq!(layer_kind([0, 1, 1, 0x98], true), LayerKind::Desktop);
assert_eq!(layer_kind([0x1a, 0, 1, 0x98], true), LayerKind::Grid);
assert_eq!(layer_kind([0x12, 0, 1, 0x98], true), LayerKind::Grid);
// From version 14 the master page flags its layers by byte 0 alone.
assert_eq!(layer_kind([0x0a, 0, 1, 0x98], false), LayerKind::Guides);
assert_eq!(layer_kind([0x08, 0, 1, 0x98], false), LayerKind::Desktop);
assert_eq!(layer_kind([0x5a, 1, 1, 0x98], false), LayerKind::Grid);
assert_eq!(layer_kind([0x02, 1, 1, 0x98], false), LayerKind::Drawing);
assert_eq!(layer_kind([0, 1, 1, 0x98], false), LayerKind::Drawing);
// Drawing layers flagged 0x10, 0x08, 0x18, 0x40 and 0x58 with byte 2 clear, as sample
// files flag them, and desktop and guides layers with bit 0x40 or 0x10 set.
for f in [[0x10, 0, 0, 0x98], [0x08, 1, 0, 0x98], [0x18, 1, 0, 0x98], [0x40, 0, 0, 0x98], [0x58, 1, 0, 0x98]] {
assert_eq!(layer_kind(f, true), LayerKind::Drawing, "{f:?}");
assert_eq!(layer_kind(f, false), LayerKind::Drawing, "{f:?}");
}
assert_eq!(layer_kind([0x18, 0, 1, 0x98], true), LayerKind::Desktop);
assert_eq!(layer_kind([0x48, 0, 1, 0x98], false), LayerKind::Desktop);
assert_eq!(layer_kind([0x4a, 1, 1, 0x98], true), LayerKind::Guides);
}
/// An outline record refused at the dash limit keeps no dashes in the cache, so the shapes
/// that use it later copy none.
#[test]
fn an_outline_past_the_dash_limit_keeps_no_dashes() {
let v = crate::synth::V(1100);
let pen = crate::synth::Pen { line_type: 4, width: 1.0, cap: 0, join: 0 };
let record = v.outline(1, pen, &crate::synth::color(5, [0, 0, 0, 255]), &[3, 1, 3]);
let file = crate::synth::riff(1100, &[]);
let mut budget = Budget::new(crate::Limits { dashes: 4, ..crate::Limits::default() });
let mut warn = Vec::new();
let ix = crate::riff::Index::build(&file, None, &mut budget, &mut warn).unwrap();
let mut cx = Ctx {
ix: &ix,
p: layout::for_version(1100).unwrap(),
budget: &mut budget,
warn: &mut warn,
fill_chunks: HashMap::new(),
outline_chunks: HashMap::from([(1, record.as_slice())]),
fills: HashMap::new(),
outlines: HashMap::new(),
styles: Ok(Styles::default()),
clips: HashMap::new(),
open_clips: Vec::new(),
clip_cut: false,
own: HashMap::new(),
trfds: HashMap::new(),
};
assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(3));
for _ in 0..3 {
assert_eq!(cx.outline(1).map(|o| o.dashes.len()), Some(0));
assert_eq!(cx.outlines.get(&1).and_then(|o| o.as_ref()).map(|o| o.dashes.len()), Some(0));
}
assert_eq!(*cx.warn, vec![Warning::TooDeep]);
}
}
+76
View File
@@ -0,0 +1,76 @@
//! Little-endian reads that fail instead of panicking.
/// A cursor over one record's bytes. Every read returns `None` past the end.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Rd<'a> {
b: &'a [u8],
pos: usize,
}
impl<'a> Rd<'a> {
pub(crate) fn new(b: &'a [u8]) -> Self {
Rd { b, pos: 0 }
}
pub(crate) fn at(b: &'a [u8], pos: usize) -> Self {
Rd { b, pos }
}
pub(crate) fn pos(&self) -> usize {
self.pos
}
pub(crate) fn left(&self) -> usize {
self.b.len().saturating_sub(self.pos)
}
pub(crate) fn skip(&mut self, n: usize) -> Option<()> {
let end = self.pos.checked_add(n)?;
(end <= self.b.len()).then(|| self.pos = end)
}
pub(crate) fn bytes(&mut self, n: usize) -> Option<&'a [u8]> {
let end = self.pos.checked_add(n)?;
let s = self.b.get(self.pos..end)?;
self.pos = end;
Some(s)
}
fn array<const N: usize>(&mut self) -> Option<[u8; N]> {
self.bytes(N)?.try_into().ok()
}
pub(crate) fn u8(&mut self) -> Option<u8> {
Some(self.array::<1>()?[0])
}
pub(crate) fn u16(&mut self) -> Option<u16> {
self.array().map(u16::from_le_bytes)
}
pub(crate) fn i16(&mut self) -> Option<i16> {
self.array().map(i16::from_le_bytes)
}
pub(crate) fn u32(&mut self) -> Option<u32> {
self.array().map(u32::from_le_bytes)
}
pub(crate) fn i32(&mut self) -> Option<i32> {
self.array().map(i32::from_le_bytes)
}
/// A finite f64; NaN and the infinities read as `None`.
pub(crate) fn f64(&mut self) -> Option<f64> {
self.array().map(f64::from_le_bytes).filter(|v| v.is_finite())
}
pub(crate) fn fourcc(&mut self) -> Option<[u8; 4]> {
self.array()
}
}
/// The u32 at `pos` of `b`.
pub(crate) fn u32_at(b: &[u8], pos: usize) -> Option<u32> {
Rd::at(b, pos).u32()
}
+655
View File
@@ -0,0 +1,655 @@
//! Reader for `.cmx` exchange files with 32-bit coordinates: the RIFF form `CMX1` (R53), its
//! header (R54), the color, pen, line type, dash, outline and arrowhead tables (R55 to R59) and the
//! instructions of each page (R60): pages, layers, groups and curves (R61, R62) with uniform fills
//! and outlines (R63). Text, images, rectangles, ellipses, clipping paths, other fills and lenses
//! are left out with a warning.
use crate::bytes::{Rd, u32_at};
use crate::geometry::path_of;
use crate::layout::{self, Profile};
use crate::limits::Budget;
use crate::model::{Cap, Color, Drawing, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Pt, Shape};
use crate::records::{name, property_color};
use crate::riff::{LIST, push};
use crate::{Error, Warning};
const FORM: [u8; 4] = *b"CMX1";
/// Meters per coordinate unit when the header gives no usable value: the 0.1 µm of every sample
/// file with 32-bit coordinates (R54).
const DEFAULT_UNIT: f64 = 1e-7;
/// How far past a chunk that runs short the next chunk id is looked for (R53).
const RESYNC: usize = 64;
/// The chunks the reader uses (R53 to R60).
const READ_IDS: [[u8; 4]; 9] = [*b"LIST", *b"cont", *b"page", *b"rclr", *b"rpen", *b"rott", *b"rdot", *b"rotl", *b"rota"];
/// The most UTF-16 units read of a layer's name; [`name`] keeps 256 of them.
const MAX_NAME_UNITS: usize = 4096;
// Instruction codes (R60).
const BEGIN_PAGE: i16 = 9;
const END_PAGE: i16 = 10;
const BEGIN_LAYER: i16 = 11;
const END_LAYER: i16 = 12;
const BEGIN_GROUP: i16 = 13;
const END_GROUP: i16 = 14;
const BEGIN_TEXT: i16 = 20;
const END_TEXT: i16 = 21;
const GLYPH_RUN: i16 = 65;
const ELLIPSE: i16 = 66;
const CURVE: i16 = 67;
const RECTANGLE: i16 = 68;
const IMAGE: i16 = 69;
const ADD_CLIP: i16 = 88;
const REMOVE_CLIP: i16 = 89;
const JUMP: i16 = 111;
/// Does `bytes` start as a CMX file: a RIFF or RIFX form of type `CMX1` (R53)?
pub(crate) fn is_cmx(bytes: &[u8]) -> bool {
matches!(bytes.get(0..4), Some(b"RIFF" | b"RIFX")) && bytes.get(8..12) == Some(FORM.as_slice())
}
/// A chunk outside the `LIST` chunks: its id, its body and where the body starts in the file.
struct Chunk<'a> {
id: [u8; 4],
body: &'a [u8],
start: usize,
}
/// The tables that page instructions refer to by 1-based index (R55 to R59).
#[derive(Default)]
struct Tables {
colors: Vec<Option<Color>>,
/// Outline widths in points.
pens: Vec<Option<f64>>,
/// Flags, and the caps and join.
line_types: Vec<Option<(u8, u8)>>,
dashes: Vec<Vec<u16>>,
/// Line type, screen, color, arrowheads, pen and dashes.
outlines: Vec<Option<[u16; 6]>>,
arrowheads: Vec<(u16, u16)>,
}
pub(crate) fn drawing(bytes: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
if !is_cmx(bytes) {
return Err(Error::NotCmx);
}
if bytes.get(0..4) == Some(b"RIFX") {
return Err(Error::Unsupported("big-endian CMX files"));
}
let mut warn = Vec::new();
let chunks = chunks(bytes, budget, &mut warn)?;
let cont = chunks.iter().find(|c| c.id == *b"cont").map(|c| c.body).ok_or(Error::Damaged("CMX header"))?;
match cont.get(52) {
Some(b'4') => {}
Some(b'2') => return Err(Error::Unsupported("CMX files with 16-bit coordinates")),
_ => return Err(Error::Damaged("CMX header")),
}
let meters = Rd::at(cont, 64).f64().filter(|m| *m > 0.0 && *m <= 1.0).unwrap_or(DEFAULT_UNIT);
let unit = meters / 0.0254 * 72.0;
let tables = Tables::read(&chunks, unit, budget, &mut warn)?;
let mut pages = Vec::new();
for c in chunks.iter().filter(|c| c.id == *b"page") {
pages.push(PageRead::new(&tables, unit, budget, &mut warn).read(c)?);
}
Ok(Drawing { version: 0, page_size: None, pages, master: Vec::new(), guides: Vec::new(), warnings: warn })
}
/// The chunks of the file in order, those inside `LIST` chunks in place (R53).
fn chunks<'a>(b: &'a [u8], budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Vec<Chunk<'a>>, Error> {
let declared = u32_at(b, 4).and_then(|n| (n as usize).checked_add(8)).unwrap_or(b.len());
if declared > b.len() {
// The file was cut short of the size its header gives.
push(warn, Warning::Damaged);
}
let end = declared.min(b.len());
let mut out = Vec::new();
// (position, end, depth) of the lists still to walk; a list's children go before the rest of
// the list that holds it.
let mut stack = vec![(12usize, end, 0usize)];
while let Some((mut pos, end, depth)) = stack.pop() {
while pos.saturating_add(8) <= end {
let Some(id) = Rd::at(b, pos).fourcc() else { break };
if !is_id(&id) {
match resync(b, pos, end) {
Some(next) => {
pos = next;
continue;
}
None => {
push(warn, Warning::Damaged);
break;
}
}
}
budget.take_chunk()?;
let size = u32_at(b, pos + 4).map_or(0, |s| s as usize);
let start = pos + 8;
let stop = start.saturating_add(size);
if stop > end {
// Stray bytes that happen to start with four letters give a length past the list:
// look for the next chunk id after them. A chunk the reader uses is kept, cut at
// the end of the list.
if !READ_IDS.contains(&id)
&& let Some(next) = resync(b, pos, end)
{
pos = next;
continue;
}
push(warn, Warning::Damaged);
}
let stop = stop.min(end);
let next = stop.saturating_add(size & 1);
if id == LIST {
if depth >= budget.limits.depth {
push(warn, Warning::TooDeep);
pos = next;
continue;
}
stack.push((next, end, depth));
stack.push((start + 4, stop, depth + 1));
break;
}
if let Some(body) = b.get(start..stop) {
out.push(Chunk { id, body, start });
}
pos = next;
}
}
Ok(out)
}
/// Is `t` a chunk id: an ASCII letter, then three ASCII letters, digits or spaces (R53)?
fn is_id(t: &[u8]) -> bool {
matches!(t, [first, rest @ ..] if t.len() == 4 && first.is_ascii_alphabetic() && rest.iter().all(|c| c.is_ascii_alphanumeric() || *c == b' '))
}
/// Where the next chunk after `pos` lies: the first chunk id at an even distance of 2 to [`RESYNC`]
/// bytes that names a chunk the reader uses, or another chunk whose length keeps it inside the list
/// that ends at `end` (R53).
fn resync(b: &[u8], pos: usize, end: usize) -> Option<usize> {
let fits = |p: usize| u32_at(b, p + 4).and_then(|s| (p + 8).checked_add(s as usize)).is_some_and(|stop| stop <= end);
let chunk_at = |p: usize| Rd::at(b, p).fourcc().is_some_and(|id| is_id(&id) && (READ_IDS.contains(&id) || fits(p)));
(pos + 2..=pos.saturating_add(RESYNC).min(end.saturating_sub(8))).step_by(2).find(|&p| chunk_at(p))
}
/// The end of the field list at `pos` of `b`: after its 0xff, or the end of `b` when a field runs
/// past it (R55).
fn list_end(b: &[u8], mut pos: usize) -> usize {
while let Some(&tag) = b.get(pos) {
if tag == 0xff {
return pos + 1;
}
match Rd::at(b, pos + 1).u16().map(usize::from).filter(|n| *n >= 3) {
Some(n) if pos + n <= b.len() => pos += n,
_ => break,
}
}
b.len()
}
/// The data of field `tag` in the field list `b` (R55).
fn field(b: &[u8], tag: u8) -> Option<&[u8]> {
let mut pos = 0;
while let Some(&t) = b.get(pos) {
if t == 0xff {
return None;
}
let n = usize::from(Rd::at(b, pos + 1).u16()?);
let data = b.get(pos + 3..pos.checked_add(n)?).filter(|_| n >= 3)?;
if t == tag {
return Some(data);
}
pos += n;
}
None
}
/// The field lists of a table: a u16 count, then that many lists (R55). Each entry counts toward
/// the chunk limit.
fn entries<'a>(d: &'a [u8], budget: &mut Budget) -> Result<Vec<&'a [u8]>, Error> {
let count = Rd::new(d).u16().map_or(0, usize::from);
let mut out = Vec::new();
let mut pos = 2;
for _ in 0..count {
if pos >= d.len() {
break;
}
budget.take_chunk()?;
let end = list_end(d, pos);
out.push(d.get(pos..end).unwrap_or_default());
pos = end;
}
Ok(out)
}
impl Tables {
/// The first chunk of each table; a table that is missing is empty.
fn read(chunks: &[Chunk], unit: f64, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Tables, Error> {
let first = |id: &[u8; 4]| chunks.iter().find(|c| c.id == *id).map_or(&[][..], |c| c.body);
// A color record of field 10 holds a property list as a `.cdr` fill does (R56).
let record = layout::for_version(1300);
let mut t = Tables::default();
for e in entries(first(b"rclr"), budget)? {
t.colors.push(color(e, record.as_ref(), warn));
}
for e in entries(first(b"rpen"), budget)? {
t.pens.push(field(e, 1).and_then(|f| Rd::new(f).u32()).map(|w| f64::from(w) * unit));
}
for e in entries(first(b"rott"), budget)? {
t.line_types.push(field(e, 1).and_then(|f| Some((*f.first()?, f.get(1).copied().unwrap_or(0)))));
}
for e in entries(first(b"rdot"), budget)? {
let mut r = Rd::new(field(e, 1).unwrap_or_default());
let n = r.u16().map_or(0, usize::from);
let mut pattern: Vec<u16> = (0..n).map_while(|_| r.u16()).collect();
// A pattern of zero lengths draws as a solid line, as in a `.cdr` outline (R48).
if pattern.iter().all(|x| *x == 0) {
pattern.clear();
}
t.dashes.push(pattern);
}
for e in entries(first(b"rotl"), budget)? {
t.outlines.push(field(e, 1).and_then(|f| {
let mut r = Rd::new(f);
Some([r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?, r.u16()?])
}));
}
// Arrowhead pairs are plain u16 pairs after the count, not field lists (R59).
let mut r = Rd::new(first(b"rota"));
let n = r.u16().map_or(0, usize::from);
for _ in 0..n {
let Some(pair) = r.u16().zip(r.u16()) else { break };
budget.take_chunk()?;
t.arrowheads.push(pair);
}
Ok(t)
}
/// Entry `index` (1-based) of `list`, or `None` with a warning when there is none.
fn get<T: Clone>(list: &[Option<T>], index: u16, warn: &mut Vec<Warning>) -> Option<T> {
let found = usize::from(index).checked_sub(1).and_then(|i| list.get(i)).cloned().flatten();
if found.is_none() {
push(warn, Warning::Damaged);
}
found
}
fn color(&self, index: u16, warn: &mut Vec<Warning>) -> Color {
Tables::get(&self.colors, index, warn).unwrap_or(Color::Rgb([0.0; 3]))
}
/// The outline of `rotl` entry `index`, or `None` when its line type draws none (R57, R58).
fn outline(&self, index: u16, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Outline> {
let [line, _screen, color, arrows, pen, dash] = Tables::get(&self.outlines, index, warn)?;
let (flags, caps_join) = Tables::get(&self.line_types, line, warn).unwrap_or((2, 0));
if flags & 1 != 0 {
return None;
}
let width = Tables::get(&self.pens, pen, warn).unwrap_or(0.0);
let mut dashes = Vec::new();
if flags & 4 != 0 {
let stored = usize::from(dash).checked_sub(1).and_then(|i| self.dashes.get(i));
match stored {
Some(d) if d.is_empty() => {}
Some(d) if budget.take_dashes(d.len()) => dashes = d.iter().map(|x| f64::from(*x)).collect(),
Some(_) => push(warn, Warning::TooDeep),
None => push(warn, Warning::Damaged),
}
}
if usize::from(arrows).checked_sub(1).and_then(|i| self.arrowheads.get(i)).is_some_and(|(s, e)| *s != 0 || *e != 0) {
push(warn, Warning::Arrowheads);
}
Some(Outline {
width,
color: self.color(color, warn),
cap: match caps_join & 0x0f {
1 => Cap::Round,
2 => Cap::Square,
_ => Cap::Butt,
},
join: match caps_join >> 4 {
1 => Join::Round,
2 => Join::Bevel,
_ => Join::Miter,
},
dashes,
behind_fill: flags & 8 != 0,
scale_with: flags & 16 != 0,
})
}
}
/// A color entry (R56): the property list of field 10 when there is one, else the model and
/// palette bytes of field 1 and the values of field 2. Colors in other models read as black with a
/// warning.
fn color(e: &[u8], record: Option<&Profile>, warn: &mut Vec<Warning>) -> Option<Color> {
if let (Some(f), Some(p)) = (field(e, 10), record) {
let mut r = Rd::new(f);
let len = r.u32()? as usize;
return property_color(r.bytes(len.min(r.left()))?, p, warn);
}
let model = *field(e, 1)?.first()?;
let v = field(e, 2)?;
let byte = |i: usize| v.get(i).map(|b| f32::from(*b));
let pct = |i: usize| byte(i).map(|x| (x / 100.0).clamp(0.0, 1.0));
let full = |i: usize| byte(i).map(|x| x / 255.0);
Some(match model {
2 => Color::Cmyk([pct(0)?, pct(1)?, pct(2)?, pct(3)?]),
3 => Color::Cmyk([full(0)?, full(1)?, full(2)?, full(3)?]),
4 => Color::Cmyk([full(0)?, full(1)?, full(2)?, 0.0]),
5 => Color::Rgb([full(0)?, full(1)?, full(2)?]),
9 => Color::Gray(1.0 - full(0)?),
_ => {
push(warn, Warning::UnknownColors);
Color::Rgb([0.0; 3])
}
})
}
/// The objects of one layer while it is read: the layer's own list, then one list for each group
/// left open.
struct LayerRead {
name: String,
lists: Vec<Vec<Object>>,
}
impl LayerRead {
/// The layer, its open groups closed. Lists are drawn back to front (R60), and the model holds
/// them front to back.
fn finish(mut self) -> Layer {
while self.lists.len() > 1 {
close_group(&mut self.lists);
}
let mut objects = self.lists.pop().unwrap_or_default();
objects.reverse();
Layer { name: self.name, kind: LayerKind::Drawing, flags: Default::default(), objects, guides: Vec::new() }
}
}
/// Close the innermost open group of `lists` into the one that holds it.
fn close_group(lists: &mut Vec<Vec<Object>>) {
if lists.len() < 2 {
return;
}
let mut objects = lists.pop().unwrap_or_default();
objects.reverse();
if let Some(top) = lists.last_mut() {
top.push(Object::Group { objects, flags: Default::default() });
}
}
/// The reading of one page chunk.
struct PageRead<'t, 'b> {
tables: &'t Tables,
unit: f64,
budget: &'b mut Budget,
warn: &'b mut Vec<Warning>,
size: Option<(f64, f64)>,
/// The page's center in the file's coordinates when the page takes its size from the
/// drawing's bounds; points are moved by it so the art lies on the page.
center: (f64, f64),
layers: Vec<Layer>,
open: Option<LayerRead>,
/// Groups nested past the depth limit that are still open; their content is left out.
skipped: usize,
}
impl<'t, 'b> PageRead<'t, 'b> {
fn new(tables: &'t Tables, unit: f64, budget: &'b mut Budget, warn: &'b mut Vec<Warning>) -> Self {
PageRead { tables, unit, budget, warn, size: None, center: (0.0, 0.0), layers: Vec::new(), open: None, skipped: 0 }
}
/// The instructions of a page chunk: a u16 size counting the whole instruction and an i16 code,
/// or 0xFFFF, a u32 size and the code; then the code's field lists (R60).
fn read(mut self, c: &Chunk) -> Result<Page, Error> {
let d = c.body;
let mut pos = 0usize;
while pos.saturating_add(4) <= d.len() {
self.budget.take_chunk()?;
let mut r = Rd::at(d, pos);
let (size, code, head) = match r.u16() {
Some(0xFFFF) => match (r.u32(), r.i16()) {
(Some(size), Some(code)) => (size as usize, code, 8),
_ => break,
},
Some(size) => match r.i16() {
Some(code) => (usize::from(size), code, 4),
None => break,
},
None => break,
};
if size < head {
push(self.warn, Warning::Damaged);
break;
}
let end = pos.saturating_add(size);
if end > d.len() {
push(self.warn, Warning::Damaged);
}
let body = d.get(pos + head..end.min(d.len())).unwrap_or_default();
if code == JUMP {
// Field 1 is the file offset the instructions go on from; the bytes passed over
// hold the page's images (R60).
let target = field(body, 1).and_then(|f| Rd::new(f).u32()).and_then(|t| (t as usize).checked_sub(c.start));
pos = target.filter(|t| *t >= end && *t <= d.len()).unwrap_or(end);
if pos > end {
push(self.warn, Warning::UnsupportedObjects);
}
continue;
}
self.instruction(code, body);
pos = end;
}
if pos < d.len() {
// An instruction whose head runs past the page was not read.
push(self.warn, Warning::Damaged);
}
self.close_layer();
// A layer that holds nothing (the special layers every sample file lists empty) is left
// out. The file lists layers back to front.
let mut layers = self.layers;
layers.retain(|l| !l.objects.is_empty());
layers.reverse();
Ok(Page { size: self.size, layers })
}
fn instruction(&mut self, code: i16, body: &[u8]) {
match code {
BEGIN_PAGE => {
// Field 4: the page's width and height (R61).
let mut r = Rd::new(field(body, 4).unwrap_or_default());
if let (Some(w), Some(h)) = (r.u32(), r.u32()) {
let (w, h) = (f64::from(w) * self.unit, f64::from(h) * self.unit);
self.size = (w > 0.0 && h > 0.0).then_some((w, h));
}
if self.size.is_none() {
self.size_from_bounds(field(body, 1).unwrap_or_default());
}
}
BEGIN_LAYER => {
self.close_layer();
// A layer without a name is left unnamed, as in a `.cdr` drawing.
let name = self.layer_name(body).unwrap_or_default();
self.open = Some(LayerRead { name, lists: vec![Vec::new()] });
}
END_LAYER => self.close_layer(),
BEGIN_GROUP => {
let open = self.layer().lists.len();
if self.skipped > 0 || open > self.budget.limits.depth {
self.skipped += 1;
push(self.warn, Warning::TooDeep);
} else if self.budget.take_object() {
self.layer().lists.push(Vec::new());
} else {
// Past the object limit the group's content joins the group that holds it.
self.skipped += 1;
push(self.warn, Warning::TooDeep);
}
}
END_GROUP => {
if self.skipped > 0 {
self.skipped -= 1;
} else {
close_group(&mut self.layer().lists);
}
}
CURVE if self.skipped == 0 => {
if let Some(shape) = self.curve(body) {
if self.budget.take_object() {
if let Some(list) = self.layer().lists.last_mut() {
list.push(Object::Shape(Box::new(shape)));
}
} else {
push(self.warn, Warning::TooDeep);
}
}
}
BEGIN_TEXT | GLYPH_RUN | ELLIPSE | RECTANGLE | IMAGE | ADD_CLIP => push(self.warn, Warning::UnsupportedObjects),
// These and the other codes (text styles and characters, color contexts) draw nothing
// on their own.
END_PAGE | END_TEXT | REMOVE_CLIP => {}
_ => {}
}
}
/// A page without a size of its own is sized to the drawing's bounds in field 1 (R61): a u16
/// page number, a u32 of flags, then the left, top, right and bottom edges as i32 in
/// coordinate units. The page is centered on those bounds.
fn size_from_bounds(&mut self, f: &[u8]) {
let mut r = Rd::new(f);
if r.u16().is_none() || r.u32().is_none() {
return;
}
let (Some(l), Some(t), Some(rt), Some(b)) = (r.i32(), r.i32(), r.i32(), r.i32()) else {
return;
};
let (l, t, rt, b) = (f64::from(l) * self.unit, f64::from(t) * self.unit, f64::from(rt) * self.unit, f64::from(b) * self.unit);
let (w, h) = ((rt - l).abs(), (t - b).abs());
if w > 0.0 && h > 0.0 {
self.size = Some((w, h));
self.center = ((l + rt) / 2.0, (t + b) / 2.0);
}
}
/// The open layer, or a new unnamed one when objects come before any layer begins.
fn layer(&mut self) -> &mut LayerRead {
self.open.get_or_insert_with(|| LayerRead { name: String::new(), lists: vec![Vec::new()] })
}
fn close_layer(&mut self) {
self.skipped = 0;
if let Some(l) = self.open.take() {
self.layers.push(l.finish());
}
}
/// A layer's name: field 4 as a u32 count and UTF-16 units, else field 1 from byte 12 as a
/// u16 count and 8-bit characters (R62).
fn layer_name(&mut self, body: &[u8]) -> Option<String> {
// A field 4 that can't be read leaves the name to field 1.
let wide = field(body, 4).and_then(|f| {
let mut r = Rd::new(f);
let n = (r.u32()? as usize).min(MAX_NAME_UNITS).min(r.left() / 2);
Some((r.bytes(n * 2)?, layout::for_version(1200)?))
});
if let Some((units, l)) = wide {
let s = name(units, &l, self.warn);
if !s.trim().is_empty() {
return Some(s);
}
}
let mut r = Rd::at(field(body, 1)?, 12);
let n = usize::from(r.u16()?).min(r.left());
let s = name(r.bytes(n)?, &layout::for_version(1100)?, self.warn);
(!s.trim().is_empty()).then_some(s)
}
/// A curve (R62): field 1 its rendering attributes, field 2 a u16 point count, the points (i32
/// x and y) and one type byte for each. Points are from the page's center, y up.
fn curve(&mut self, body: &[u8]) -> Option<Shape> {
let mut r = Rd::new(field(body, 2).unwrap_or_default());
let Some(count) = r.u16().map(usize::from) else {
// A curve without its points is lost.
push(self.warn, Warning::Damaged);
return None;
};
// `stored` points are read, so the type bytes are found after all of them, and the first
// `n`, those that have a type byte, are kept. When the field holds every point, a short
// field has lost type bytes. When it holds whole points and their types for fewer points,
// the count is too large. Otherwise the field lost points, and its type bytes can't be
// found: the curve is lost.
let left = r.left();
let (stored, n) = match count.checked_mul(8).filter(|c| *c <= left) {
Some(c) => (count, count.min(left - c)),
None if left.is_multiple_of(9) => (left / 9, left / 9),
None => {
push(self.warn, Warning::Damaged);
return None;
}
};
if n < count {
push(self.warn, Warning::Damaged);
}
if !self.budget.take_coordinates(stored) {
push(self.warn, Warning::TooDeep);
return None;
}
let mut points = Vec::with_capacity(stored);
for _ in 0..stored {
let (x, y) = (f64::from(r.i32()?) * self.unit, f64::from(r.i32()?) * self.unit);
points.push(Pt { x: x - self.center.0, y: y - self.center.1 });
}
points.truncate(n);
let path = path_of(&points, r.bytes(n)?);
if path.subpaths.is_empty() {
return None;
}
let (fill, outline) = self.attributes(field(body, 1).unwrap_or_default());
Some(Shape::new(Geometry::Path(path), Matrix::IDENTITY, fill, outline))
}
/// Rendering attributes (R63): a mask (1 fill, 2 outline, 4 lens), then a field list for the
/// fill and one for the outline when the mask names them.
fn attributes(&mut self, a: &[u8]) -> (Option<Color>, Option<Outline>) {
let Some(&mask) = a.first() else { return (None, None) };
let mut pos = 1;
let mut fill = None;
if mask & 1 != 0 {
let end = list_end(a, pos);
let list = a.get(pos..end).unwrap_or_default();
pos = end;
// Field 1: the fill type (u16), then its own field list; type 1, uniform, names its
// color in field 1.
let v = field(list, 1).unwrap_or_default();
match Rd::new(v).u16() {
Some(0) | None => {}
Some(1) => {
let index = field(v.get(2..).unwrap_or_default(), 1).and_then(|c| Rd::new(c).u16());
fill = Some(match index {
Some(i) => self.tables.color(i, self.warn),
None => {
push(self.warn, Warning::Damaged);
Color::Rgb([0.0; 3])
}
});
}
Some(_) => push(self.warn, Warning::UnsupportedFills),
}
}
let mut outline = None;
if mask & 2 != 0 {
let list = a.get(pos..list_end(a, pos)).unwrap_or_default();
match field(list, 1).and_then(|f| Rd::new(f).u16()) {
Some(i) => outline = self.tables.outline(i, self.budget, self.warn),
None => push(self.warn, Warning::Damaged),
}
}
if mask & 4 != 0 {
push(self.warn, Warning::Lenses);
}
// A canvas (8) or a container (16) is not read.
if mask & (8 | 16) != 0 {
push(self.warn, Warning::UnsupportedObjects);
}
(fill, outline)
}
}
+455
View File
@@ -0,0 +1,455 @@
//! The coordinates argument (30) of each object type read as geometry: curves (R16), rectangles
//! (R15), ellipses and arcs (R17) and polygons (R18).
use std::f64::consts::PI;
use crate::Warning;
use crate::bytes::Rd;
use crate::layout::Profile;
use crate::limits::Budget;
use crate::model::{Geometry, Path, Pt, Segment, SubPath};
use crate::records::{angle, coord};
use crate::riff::push;
/// The most sides a polygon record may give (VectorCraft's own bound).
const MAX_POLYGON_SIDES: u32 = 1000;
/// The base curve of a polygon lies on a circle of 1000 mm (R18), in points.
const POLYGON_UNIT_RADIUS: f64 = 1000.0 / 25.4 * 72.0;
/// What a point type byte asks for (R16): bits 7 and 6.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Op {
Move,
Line,
Curve,
Control,
}
fn op(t: u8) -> Op {
match t >> 6 {
0 => Op::Move,
1 => Op::Line,
2 => Op::Curve,
_ => Op::Control,
}
}
/// Bit 3 closes the subpath (R16).
const CLOSES: u8 = 0x08;
/// A point list (R16): the count, the points, then one type byte each. The count is a u32 from
/// version 6 and a u16 followed by another u16 before it (R39). It is held to what the bytes hold;
/// `None` when the points are past the budget.
pub(crate) fn point_list(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Path> {
let mut r = Rd::new(b);
let count = if p.short {
let count = usize::from(r.u16()?);
r.skip(2)?;
count
} else {
r.u32()? as usize
};
points(b, r, count, p, budget, warn)
}
/// A path record (object type 0x25, R30): 4 bytes, two u16 counts whose sum is the point count, 16
/// bytes, then the points and their type bytes as in a point list.
pub(crate) fn path_record(b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Path> {
let mut r = Rd::new(b);
r.skip(4)?;
let count = usize::from(r.u16()?) + usize::from(r.u16()?);
r.skip(16)?;
points(b, r, count, p, budget, warn)
}
/// `count` points from `r` over `b`, then their type bytes. A list cut short is read two ways: as
/// all `count` points with the type bytes after them, and as the points and type bytes the bytes
/// hold split evenly. The reading that keeps more points with a type byte wins, the first on a tie.
fn points(b: &[u8], mut r: Rd, count: usize, p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Path> {
let each = 2 * p.word();
let left = r.left();
let split = (left / (each + 1)).min(count);
let whole = count.checked_mul(each).filter(|len| *len <= left).map(|len| (left - len).min(count));
let stored = match whole {
Some(typed) if typed >= split => count,
_ => split,
};
let types = b.get(r.pos() + stored * each..)?;
let n = stored.min(types.len());
if count > n {
push(warn, Warning::Damaged);
}
if !budget.take_coordinates(n) {
push(warn, Warning::TooDeep);
return None;
}
let mut points = Vec::with_capacity(n);
for _ in 0..n {
points.push(Pt { x: coord(&mut r, p)?, y: coord(&mut r, p)? });
}
Some(path_of(&points, types))
}
/// The subpaths that points and their type bytes draw.
pub(crate) fn path_of(points: &[Pt], types: &[u8]) -> Path {
let mut subpaths = Vec::new();
let mut cur: Option<SubPath> = None;
// The last two control points: a curve end uses only those.
let mut controls: Vec<Pt> = Vec::with_capacity(2);
for (&pt, &t) in points.iter().zip(types) {
let o = op(t);
if o == Op::Control {
if controls.len() == 2 {
controls.remove(0);
}
controls.push(pt);
continue;
}
if o == Op::Move || cur.is_none() {
subpaths.extend(cur.take());
cur = Some(SubPath { start: pt, segments: Vec::new(), closed: t & CLOSES != 0 && o == Op::Move });
controls.clear();
if o == Op::Move {
continue;
}
}
let Some(sp) = cur.as_mut() else { continue };
let seg = match (o, controls.as_slice()) {
(Op::Curve, [c1, c2]) => Segment::Cubic(*c1, *c2, pt),
_ => Segment::Line(pt),
};
controls.clear();
sp.segments.push(seg);
if t & CLOSES != 0 {
sp.closed = true;
}
}
subpaths.extend(cur);
// A closed subpath with no segments, or an open one with none, draws nothing.
subpaths.retain(|s| !s.segments.is_empty());
Path { subpaths }
}
/// A rectangle record (R15): width, height, then one corner radius for every corner, four from
/// version 9.
pub(crate) fn rect(b: &[u8], p: &Profile) -> Option<Geometry> {
if p.f64_rect {
return rect_f64(b, p);
}
let mut r = Rd::new(b);
let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?);
let first = coord(&mut r, p)?.abs();
let mut radii = [first; 4];
if p.four_radii {
for slot in radii.iter_mut().skip(1) {
*slot = coord(&mut r, p)?.abs();
}
}
Some(Geometry::Rect { w, h, radii })
}
/// A rectangle record from version 15 (R29): width and height as f64 coordinate units, two scale
/// factors that repeat the transform's (not applied), the scale-with flag and 7 bytes, then the
/// four radii as f64 16 bytes apart. With the flag clear each radius is a share of half the shorter
/// side; with it set the radius is in inches. A corner is held to half the shorter side, and
/// sizes to the range of the 32-bit coordinates of earlier versions.
fn rect_f64(b: &[u8], p: &Profile) -> Option<Geometry> {
let mut r = Rd::new(b);
let size = |v: f64| (v.abs() <= f64::from(i32::MAX)).then(|| v * p.unit());
let (w, h) = (size(r.f64()?)?, size(r.f64()?)?);
r.skip(8 + 8)?;
let inches = r.u8()? != 0;
r.skip(7)?;
let short = w.abs().min(h.abs());
let mut radii = [0.0; 4];
for (k, slot) in radii.iter_mut().enumerate() {
if k > 0 {
r.skip(16)?;
}
let v = r.f64()?.abs();
let radius = if inches { v * 72.0 } else { v * short / 2.0 };
*slot = radius.min(short / 2.0);
}
Some(Geometry::Rect { w, h, radii })
}
/// An ellipse record (R17): the box's width and height, the start and end angles and whether
/// the arc closes through the centre. Equal angles make a whole ellipse.
pub(crate) fn ellipse(b: &[u8], p: &Profile) -> Option<Geometry> {
let mut r = Rd::new(b);
let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?);
let (a1, a2) = (angle(&mut r, p)?, angle(&mut r, p)?);
let pie = if p.short { r.u16()? != 0 } else { r.u32()? != 0 };
let sweep = (a2 - a1).rem_euclid(360.0);
if sweep.abs() < 1e-9 {
return Some(Geometry::Ellipse { w, h });
}
Some(Geometry::Path(arc(w, h, a1, sweep, pie)))
}
/// The arc of the ellipse in the box from the origin to (`w`, `h`), from `start` degrees through
/// `sweep` degrees, in the ellipse's own axes; a pie runs from the centre and closes there. The
/// radii are half the size, and a negative width or height points its axis the other way (R17), so
/// with a negative height 0 to 180 degrees is the half below the centre.
fn arc(w: f64, h: f64, start: f64, sweep: f64, pie: bool) -> Path {
let (cx, cy, rx, ry) = (w / 2.0, h / 2.0, w / 2.0, h / 2.0);
let at = |t: f64| Pt { x: cx + rx * t.cos(), y: cy + ry * t.sin() };
let tangent = |t: f64| Pt { x: -rx * t.sin(), y: ry * t.cos() };
let pieces = (sweep / 90.0).ceil().max(1.0) as usize;
let step = sweep.to_radians() / pieces as f64;
let k = 4.0 / 3.0 * (step / 4.0).tan();
let t0 = start.to_radians();
let mut segments = Vec::with_capacity(pieces + 2);
if pie {
segments.push(Segment::Line(at(t0)));
}
for i in 0..pieces {
let (a, b) = (t0 + step * i as f64, t0 + step * (i + 1) as f64);
let (p0, p1, d0, d1) = (at(a), at(b), tangent(a), tangent(b));
segments.push(Segment::Cubic(Pt { x: p0.x + k * d0.x, y: p0.y + k * d0.y }, Pt { x: p1.x - k * d1.x, y: p1.y - k * d1.y }, p1));
}
let start = if pie { Pt { x: cx, y: cy } } else { at(t0) };
Path { subpaths: vec![SubPath { start, segments, closed: pie }] }
}
/// A polygon (R18): its base curve, one side of the outline on a circle of 1000 mm with its top
/// vertex first, copied once per side and turned clockwise each time by the vertices the side
/// spans, then scaled by (`rx`, `ry`) and moved to the centre the polygon argument (11000) gives.
/// A star whose sides skip vertices draws as one outline, or as several when the side count and
/// the step share a factor.
pub(crate) fn polygon(base: &Path, b: &[u8], p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Geometry> {
let mut r = Rd::new(b);
if !p.tagged {
r.skip(4)?;
}
let sides = r.u32()?;
// The next point: the first field, or the second when the first is 0 or 1.
let (first, second) = (r.u32()?, r.u32()?);
let next = if first > 1 { first } else { second };
if p.tagged {
r.skip(4)?;
}
let (rx, ry) = (r.f64()?, r.f64()?);
let (cx, cy) = (coord(&mut r, p)?, coord(&mut r, p)?);
let side = base.subpaths.first()?;
if !(1..=MAX_POLYGON_SIDES).contains(&sides) {
push(warn, Warning::Damaged);
return None;
}
if !budget.take_coordinates(side.segments.len().saturating_mul(3).saturating_mul(sides as usize)) {
push(warn, Warning::TooDeep);
return None;
}
// The base curve's own unit radius, measured from its first point, keeps the scale right
// whatever unit the file's coordinates are in.
let unit = side.start.x.hypot(side.start.y);
let unit = if unit > 0.0 { unit } else { POLYGON_UNIT_RADIUS };
let place = |q: Pt, turn: f64| {
let (s, c) = turn.sin_cos();
let (x, y) = (q.x * c - q.y * s, q.x * s + q.y * c);
Pt { x: x / unit * POLYGON_UNIT_RADIUS * rx + cx, y: y / unit * POLYGON_UNIT_RADIUS * ry + cy }
};
let step = side_step(side, sides, next);
let outlines = gcd(sides, step);
let each = sides / outlines;
let angle = |k: u32| -2.0 * PI * f64::from(k % sides) / f64::from(sides);
let mut subpaths = Vec::with_capacity(outlines as usize);
for o in 0..outlines {
let mut segments = Vec::with_capacity(side.segments.len() * each as usize);
for j in 0..each {
let turn = angle(o + j * step);
segments.extend(side.segments.iter().map(|s| match *s {
Segment::Line(a) => Segment::Line(place(a, turn)),
Segment::Cubic(a, b, c) => Segment::Cubic(place(a, turn), place(b, turn), place(c, turn)),
}));
}
subpaths.push(SubPath { start: place(side.start, angle(o)), segments, closed: true });
}
Some(Geometry::Path(Path { subpaths }))
}
/// How many vertices the base side moves on from its first point (R18): the vertex its last
/// point lies at, clockwise; else the next-point field when it names one; else 1.
fn side_step(side: &SubPath, sides: u32, next: u32) -> u32 {
let field = if (1..sides).contains(&next) { next } else { 1 };
let Some(end) = side.segments.last().map(|s| match *s {
Segment::Line(e) | Segment::Cubic(_, _, e) => e,
}) else {
return field;
};
let (r0, r1) = (side.start.x.hypot(side.start.y), end.x.hypot(end.y));
if !(r0 > 0.0 && (r1 - r0).abs() <= r0 * 1e-3) {
return field;
}
let turned = (side.start.y.atan2(side.start.x) - end.y.atan2(end.x)) / (2.0 * PI / f64::from(sides));
let k = turned.round();
if !k.is_finite() || (turned - k).abs() > 1e-3 {
return field;
}
match k.rem_euclid(f64::from(sides)) as u32 {
0 => field,
k => k,
}
}
fn gcd(a: u32, b: u32) -> u32 {
let (mut a, mut b) = (a, b);
while b != 0 {
(a, b) = (b, a % b);
}
a.max(1)
}
#[cfg(test)]
mod tests {
use super::*;
fn pt(x: f64, y: f64) -> Pt {
Pt { x, y }
}
#[test]
fn type_bytes_make_moves_lines_curves_and_closes() {
let points = [pt(0.0, 0.0), pt(10.0, 0.0), pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0), pt(20.0, 20.0), pt(30.0, 20.0)];
// move (closed), line, control, control, curve end closing; move, line.
let types = [0x08, 0x40, 0xC0, 0xC0, 0x88, 0x00, 0x40];
let path = path_of(&points, &types);
assert_eq!(path.subpaths.len(), 2);
let first = &path.subpaths[0];
assert!(first.closed);
assert_eq!(first.segments, vec![Segment::Line(pt(10.0, 0.0)), Segment::Cubic(pt(10.0, 5.0), pt(5.0, 10.0), pt(0.0, 10.0))]);
assert!(!path.subpaths[1].closed);
}
#[test]
fn a_point_list_short_of_type_bytes_reads_them_after_all_its_points() {
let p = crate::layout::for_version(1300).unwrap_or_else(|| panic!("profile"));
// Three points, (0, 0), (1 inch, 0) and (0, 0), and type bytes for the first two only.
let mut b = 3u32.to_le_bytes().to_vec();
for v in [0i32, 0, 254_000, 0, 0, 0] {
b.extend(v.to_le_bytes());
}
b.extend([0x00, 0x40]);
let mut warn = vec![];
let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path"));
assert_eq!(path.subpaths.len(), 1);
assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(72.0, 0.0))]);
assert_eq!(warn, vec![Warning::Damaged]);
// A count past the points the bytes hold keeps the points that have a type byte.
// Eight points and their eight type bytes take the bytes of nine points.
let mut b = 9u32.to_le_bytes().to_vec();
for i in 0..8 {
b.extend((i * 254_000i32).to_le_bytes());
b.extend(0i32.to_le_bytes());
}
b.extend([0x00, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40]);
let mut warn = vec![];
let path = point_list(&b, &p, &mut Budget::new(crate::Limits::default()), &mut warn).unwrap_or_else(|| panic!("path"));
assert_eq!(path.subpaths[0].segments.len(), 7);
assert!(matches!(path.subpaths[0].segments[6], Segment::Line(end) if (end.x - 504.0).abs() < 1e-9 && end.y == 0.0));
assert_eq!(warn, vec![Warning::Damaged]);
}
#[test]
fn a_run_of_control_points_keeps_the_last_two() {
let points: Vec<Pt> = (0..7).map(|i| pt(f64::from(i), 0.0)).collect();
let path = path_of(&points, &[0x00, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0x80]);
assert_eq!(path.subpaths[0].segments, vec![Segment::Cubic(pt(4.0, 0.0), pt(5.0, 0.0), pt(6.0, 0.0))]);
}
#[test]
fn a_curve_end_without_two_controls_is_a_line() {
let path = path_of(&[pt(0.0, 0.0), pt(1.0, 1.0)], &[0x00, 0x80]);
assert_eq!(path.subpaths[0].segments, vec![Segment::Line(pt(1.0, 1.0))]);
}
#[test]
fn a_quarter_arc_ends_on_the_ellipse() {
let p = arc(20.0, 10.0, 0.0, 90.0, false);
let sp = &p.subpaths[0];
assert_eq!(sp.start, pt(20.0, 5.0));
let Some(Segment::Cubic(_, _, end)) = sp.segments.last() else { panic!("no curve") };
assert!((end.x - 10.0).abs() < 1e-9 && (end.y - 10.0).abs() < 1e-9);
let pie = arc(20.0, 10.0, 0.0, 180.0, true);
assert!(pie.subpaths[0].closed && pie.subpaths[0].start == pt(10.0, 5.0));
}
#[test]
fn a_negative_height_turns_the_arc_below_the_centre() {
let p = arc(20.0, -10.0, 0.0, 180.0, false);
let sp = &p.subpaths[0];
assert_eq!(sp.start, pt(20.0, -5.0));
let Some(Segment::Cubic(_, _, mid)) = sp.segments.first() else { panic!("no curve") };
assert!((mid.x - 10.0).abs() < 1e-9 && (mid.y + 10.0).abs() < 1e-9, "{mid:?}");
}
/// A version 13 polygon argument: `sides`, the two next-point fields, then rx = ry = 1 at the
/// origin.
fn polygon_arg(sides: u32, first: u32, second: u32) -> Vec<u8> {
let mut b = Vec::new();
for v in [sides, first, second, 0] {
b.extend(v.to_le_bytes());
}
b.extend(1.0f64.to_le_bytes());
b.extend(1.0f64.to_le_bytes());
b.extend([0; 8]);
b
}
/// Vertex `k` of `sides`, counted clockwise from the top, on the base circle.
fn vertex(k: u32, sides: u32) -> Pt {
let a = PI / 2.0 - 2.0 * PI * f64::from(k) / f64::from(sides);
pt(POLYGON_UNIT_RADIUS * a.cos(), POLYGON_UNIT_RADIUS * a.sin())
}
fn ends(sp: &SubPath) -> Vec<Pt> {
sp.segments
.iter()
.map(|s| match *s {
Segment::Line(e) | Segment::Cubic(_, _, e) => e,
})
.collect()
}
fn close(a: &[Pt], b: &[Pt]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.x - q.x).abs() < 1e-6 && (p.y - q.y).abs() < 1e-6)
}
fn star(sides: u32, step: u32, first: u32, second: u32) -> Path {
let p = crate::layout::for_version(1300).unwrap();
let base = Path { subpaths: vec![SubPath { start: vertex(0, sides), segments: vec![Segment::Line(vertex(step, sides))], closed: false }] };
let mut budget = Budget::new(crate::Limits::default());
let Some(Geometry::Path(path)) = polygon(&base, &polygon_arg(sides, first, second), &p, &mut budget, &mut vec![]) else {
panic!("no polygon")
};
path
}
#[test]
fn a_star_whose_sides_skip_a_vertex_chains_its_points() {
// {5/2}: each side runs two vertices on, so the outline visits 2, 4, 1, 3 and 0.
let path = star(5, 2, 2, 0);
assert_eq!(path.subpaths.len(), 1);
let want: Vec<Pt> = [2, 4, 1, 3, 0].iter().map(|&k| vertex(k, 5)).collect();
assert!(close(&ends(&path.subpaths[0]), &want), "{:?}", ends(&path.subpaths[0]));
// The base side alone tells the step when the field doesn't.
assert!(close(&ends(&star(5, 2, 0, 0).subpaths[0]), &want));
}
#[test]
fn a_star_sharing_a_factor_with_its_sides_draws_one_outline_for_each() {
// {6/2}: two triangles, 0-2-4 and 1-3-5.
let path = star(6, 2, 0, 2);
assert_eq!(path.subpaths.len(), 2);
assert!(close(&ends(&path.subpaths[0]), &[vertex(2, 6), vertex(4, 6), vertex(0, 6)]));
assert!(close(&[path.subpaths[1].start], &[vertex(1, 6)]));
assert!(close(&ends(&path.subpaths[1]), &[vertex(3, 6), vertex(5, 6), vertex(1, 6)]));
}
#[test]
fn a_plain_polygon_turns_one_vertex_for_each_side() {
let path = star(4, 1, 0, 1);
assert_eq!(path.subpaths.len(), 1);
assert!(close(&ends(&path.subpaths[0]), &[1, 2, 3, 0].map(|k| vertex(k, 4))));
}
}
+230
View File
@@ -0,0 +1,230 @@
//! What a version 3 object holds as arguments where later versions name records: its transforms
//! (argument 100, R33), its fill (argument 20, R34) and its outline (argument 10, R35).
use crate::bytes::Rd;
use crate::layout::Profile;
use crate::model::{Cap, Color, Join, Matrix, Outline};
use crate::records::{self, angle, coord};
use crate::riff::push;
use crate::{Limits, Warning};
/// Transform entry types (R33): a matrix, and an envelope.
const MATRIX: u16 = 0x8c;
const ENVELOPE: u16 = 0x14;
/// The bytes of one transform entry (R33).
const ENTRY: usize = 10;
/// The bytes an outline keeps for its dashes, one byte each (R35).
const DASH_AREA: usize = 10;
/// The transforms of one object or group.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Placement {
/// The matrices composed in file order, in points.
pub(crate) matrix: Matrix,
/// An envelope bends the shape. The reader doesn't apply envelopes.
pub(crate) envelope: bool,
}
/// The transforms argument (R33): a u16, the entry count, then 10-byte entries of a type and, at
/// byte 6, where the entry's data starts in the argument. The count is held to the entries the
/// argument holds and to the arguments a record may have. Entries of other types are passed over.
pub(crate) fn transforms(b: &[u8], p: &Profile, limits: &Limits, warn: &mut Vec<Warning>) -> Option<Placement> {
let mut r = Rd::new(b);
r.skip(2)?;
let stored = usize::from(r.u16()?);
let count = stored.min(r.left() / ENTRY).min(limits.arguments);
if count < stored {
push(warn, Warning::Damaged);
}
let mut out = Placement { matrix: Matrix::IDENTITY, envelope: false };
for _ in 0..count {
let mut e = Rd::new(r.bytes(ENTRY)?);
let kind = e.u16()?;
e.skip(4)?;
let at = usize::from(e.u16()?);
match kind {
MATRIX => out.matrix = records::fixed_matrix(&mut Rd::at(b, at), p.unit())?.after(&out.matrix),
ENVELOPE => out.envelope = true,
_ => {}
}
}
Some(out)
}
/// The fill argument (R34): a type byte, 0 for none and 1 for a uniform fill with its color. Fills
/// of other types read as none with a warning. The outer `None` is an argument that can't be read.
pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<Option<Color>> {
let mut r = Rd::new(b);
match r.u8()? {
0 => Some(None),
1 => Some(Some(records::color(&mut r, p, warn)?)),
_ => {
push(warn, Warning::UnsupportedFills);
Some(None)
}
}
}
/// The outline argument (R35): a flags byte whose bit 0 is set when the object is outlined, the
/// width, the stretch, the nib angle, the color, 7 bytes, the dash count and 10 bytes that hold the
/// dashes, the join and the caps (u16 each), then the two arrowhead ids. An argument that ends
/// after its color gives a solid line with butt caps and miter joins. The outer `None` is an
/// argument that can't be read.
pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<Option<Outline>> {
let mut r = Rd::new(b);
if r.u8()? & 1 == 0 {
return Some(None);
}
let width = coord(&mut r, p)?.abs();
let _stretch = r.u16()?;
let _nib = angle(&mut r, p)?;
let color = records::color(&mut r, p, warn)?;
let mut out = Outline { width, color, cap: Cap::Butt, join: Join::Miter, dashes: Vec::new(), behind_fill: false, scale_with: false };
let Some(stored) = r.skip(7).and_then(|()| r.u8()).map(usize::from) else { return Some(Some(out)) };
let Some(area) = r.bytes(DASH_AREA) else { return Some(Some(out)) };
if stored > DASH_AREA {
push(warn, Warning::Damaged);
}
let dashes: Vec<f64> = area.iter().take(stored).map(|d| f64::from(*d)).collect();
if dashes.iter().any(|d| *d > 0.0) {
out.dashes = dashes;
}
out.join = match r.u16() {
Some(1) => Join::Round,
Some(2) => Join::Bevel,
_ => Join::Miter,
};
out.cap = match r.u16() {
Some(1) => Cap::Round,
Some(2) => Cap::Square,
_ => Cap::Butt,
};
if matches!((r.u32(), r.u32()), (Some(s), Some(e)) if s != 0 || e != 0) {
push(warn, Warning::Arrowheads);
}
Some(Some(out))
}
#[cfg(test)]
mod tests {
use super::*;
fn p3() -> Profile {
crate::layout::for_version(300).unwrap()
}
/// A transforms argument of `entries` (type, data offset), then `data` from byte 4 + 10 for
/// each entry.
fn arg(count: u16, entries: &[(u16, u16)], data: &[i32]) -> Vec<u8> {
let mut b = vec![0, 0];
b.extend(count.to_le_bytes());
for (kind, at) in entries {
b.extend(kind.to_le_bytes());
b.extend([0; 4]);
b.extend(at.to_le_bytes());
b.extend([0; 2]);
}
b.extend(data.iter().flat_map(|v| v.to_le_bytes()));
b
}
#[test]
fn matrices_compose_in_file_order_and_other_entries_are_passed_over() {
// Scale by 2, then move 1 inch right: entry types 0x8c, an unknown one and 0x8c.
let scale = [131072, 0, 0, 0, 131072, 0];
let shift = [65536, 0, 1000, 0, 65536, 0];
let b = arg(3, &[(MATRIX, 34), (0x99, 0), (MATRIX, 58)], &[scale, shift].concat());
let mut w = vec![];
let t = transforms(&b, &p3(), &Limits::default(), &mut w).unwrap();
assert_eq!((t.matrix, t.envelope), (Matrix([2.0, 0.0, 0.0, 2.0, 72.0, 0.0]), false));
assert!(w.is_empty());
let b = arg(2, &[(MATRIX, 24), (ENVELOPE, 0)], &scale);
assert!(transforms(&b, &p3(), &Limits::default(), &mut vec![]).unwrap().envelope);
}
#[test]
fn hostile_transform_arguments_do_not_read_past_their_bytes() {
let scale = [131072, 0, 0, 0, 131072, 0];
// A count of 65,535 over one entry reads that entry, with the damage warning.
let b = arg(u16::MAX, &[(MATRIX, 14)], &scale);
let mut w = vec![];
assert_eq!(transforms(&b, &p3(), &Limits::default(), &mut w).unwrap().matrix.0[0], 2.0);
assert_eq!(w, vec![Warning::Damaged]);
// A data offset past the argument, and one that leaves less than a matrix.
for at in [5000, 14 + 4] {
assert!(transforms(&arg(1, &[(MATRIX, at)], &scale), &p3(), &Limits::default(), &mut vec![]).is_none(), "{at}");
}
// More entries than a record may have arguments.
let many: Vec<(u16, u16)> = vec![(0x99, 0); 100];
let limits = Limits { arguments: 8, ..Limits::default() };
let mut w = vec![];
assert!(transforms(&arg(100, &many, &[]), &p3(), &limits, &mut w).is_some());
assert_eq!(w, vec![Warning::Damaged]);
for len in 0..4 {
assert!(transforms(&b[..len], &p3(), &Limits::default(), &mut vec![]).is_none());
}
}
/// An outline argument: flags, width in 1/1000 inch, black, `dashes`, join, caps, arrowheads.
fn outline_arg(flags: u8, count: u8, dashes: &[u8], join: u16, cap: u16, heads: [u32; 2]) -> Vec<u8> {
let mut b = vec![flags];
b.extend(28i16.to_le_bytes());
b.extend([100, 0, 0, 0]);
b.extend([1, 0, 0, 0, 100]);
b.extend([0; 7]);
b.push(count);
let mut area = dashes.to_vec();
area.resize(DASH_AREA, 0);
b.extend(area);
b.extend(join.to_le_bytes());
b.extend(cap.to_le_bytes());
b.extend(heads.iter().flat_map(|h| h.to_le_bytes()));
b
}
#[test]
fn an_outline_reads_its_width_color_dashes_join_and_caps() {
let mut w = vec![];
let o = outline(&outline_arg(1, 2, &[3, 1], 1, 2, [0, 0]), &p3(), &mut w).unwrap().unwrap();
assert!((o.width - 2.016).abs() < 1e-9, "{}", o.width);
assert_eq!((o.color, o.join, o.cap, o.dashes), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Join::Round, Cap::Square, vec![3.0, 1.0]));
assert!(w.is_empty());
// Bit 0 clear: no outline, whatever follows.
assert_eq!(outline(&outline_arg(0, 2, &[3, 1], 1, 2, [7, 0]), &p3(), &mut w), Some(None));
assert_eq!(outline(&[0], &p3(), &mut w), Some(None));
assert!(w.is_empty());
outline(&outline_arg(1, 0, &[], 0, 0, [0, 9]), &p3(), &mut w).unwrap().unwrap();
assert_eq!(w, vec![Warning::Arrowheads]);
}
#[test]
fn a_dash_count_past_the_dash_bytes_is_held_to_them() {
let mut w = vec![];
let o = outline(&outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]), &p3(), &mut w).unwrap().unwrap();
assert_eq!(o.dashes.len(), DASH_AREA);
assert_eq!(w, vec![Warning::Damaged]);
// An argument that ends inside the dashes keeps a solid line; one cut before the color is
// unreadable.
let full = outline_arg(1, 255, &[2; 10], 0, 0, [0, 0]);
assert_eq!(outline(&full[..25], &p3(), &mut vec![]).unwrap().unwrap().dashes, Vec::<f64>::new());
assert_eq!(outline(&full[..12], &p3(), &mut vec![]).unwrap().unwrap().cap, Cap::Butt);
for len in 0..12 {
assert!(outline(&full[..len], &p3(), &mut vec![]).is_none(), "{len}");
}
}
#[test]
fn fills_read_none_uniform_and_other_types() {
let mut w = vec![];
assert_eq!(fill(&[0], &p3(), &mut w), Some(None));
assert_eq!(fill(&[1, 1, 100, 0, 0, 0], &p3(), &mut w), Some(Some(Color::Cmyk([1.0, 0.0, 0.0, 0.0]))));
assert!(w.is_empty());
for kind in [2, 4, 6, 7, 10] {
let mut w = vec![];
assert_eq!(fill(&[kind, 0, 0], &p3(), &mut w), Some(None));
assert_eq!(w, vec![Warning::UnsupportedFills], "{kind}");
}
assert_eq!(fill(&[], &p3(), &mut w), None);
assert_eq!(fill(&[1, 1, 100], &p3(), &mut w), None);
}
}
+181
View File
@@ -0,0 +1,181 @@
//! Where the fields of each record lie, by version: one table, resolved once per file. Each field
//! names the `PROVENANCE.md` row it rests on.
/// The layouts of one range of versions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Profile {
/// Coordinates are i16 in 1/1000 inch, record headers, counts and angles 16-bit (R5, R6, R7).
pub(crate) short: bool,
/// Bytes before the page size in `mcfg` (R10).
pub(crate) mcfg_skip: usize,
/// Bytes before a `trfd` entry's type (R8).
pub(crate) trfd_head: usize,
/// Bytes between a matrix entry's type and its six numbers (R8).
pub(crate) matrix_skip: usize,
/// Fill and outline records start with tagged records (R11, R12).
pub(crate) tagged: bool,
/// Outline: bytes after the join, after the stretch, after the nib angle and after the color
/// (R12).
pub(crate) outl_after_join: usize,
pub(crate) outl_after_stretch: usize,
pub(crate) outl_after_angle: usize,
pub(crate) outl_after_color: usize,
/// Where the start marker id lies after the first dash (R13); `None` where no source says.
pub(crate) marker_after_dash: Option<usize>,
/// Rectangles carry four corner radii, not one (R15).
pub(crate) four_radii: bool,
/// Rectangles are f64 sizes with radii as shares of half the shorter side (R29).
pub(crate) f64_rect: bool,
/// The master page flags its guides and desktop layers the way of versions 7 to 13 (R19).
pub(crate) old_master_flags: bool,
/// Object type 0x25 is a path (R30).
pub(crate) paths: bool,
/// Names are UTF-16LE, not Windows-1252 (R9).
pub(crate) utf16_names: bool,
/// An object holds its transform, fill and outline as arguments; there are no `trfd`, `fill`
/// or `outl` records (R33, R34, R35).
pub(crate) inline_styles: bool,
/// Object types count from 0: rectangle 0, ellipse 1, curve 2, text 3, bitmap 4 (R32).
pub(crate) types_from_zero: bool,
/// How a color is laid out (R14, R36).
pub(crate) color: ColorLayout,
/// A matrix is six i32 with its factors in 16.16 fixed point, not six f64 (R37).
pub(crate) fixed_matrix: bool,
/// `mcfg` holds 2 bytes and the page's two corners, not its width and height (R38).
pub(crate) mcfg_corners: bool,
}
/// The layouts of a color.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ColorLayout {
/// A model byte and four value bytes (R36).
Bytes5,
/// A model u16, four u16 values and 2 bytes (R36).
Words12,
/// A model u16, a palette u16, 4 bytes and four value bytes (R14).
Record12,
}
const fn profile(from: u16) -> Profile {
let short = from < 600;
Profile {
short,
inline_styles: from < 400,
types_from_zero: from < 400,
color: if from < 400 {
ColorLayout::Bytes5
} else if from < 500 {
ColorLayout::Words12
} else {
ColorLayout::Record12
},
fixed_matrix: from < 500,
mcfg_corners: from < 400,
mcfg_skip: if from >= 1300 {
12
} else if from >= 900 {
4
} else if from >= 600 && from < 700 {
28
} else {
0
},
trfd_head: if from >= 1300 { 8 } else { 0 },
matrix_skip: if short { 0 } else { 6 },
tagged: from >= 1300,
outl_after_join: if from >= 600 && from < 1300 { 2 } else { 0 },
outl_after_stretch: if short { 0 } else { 2 },
outl_after_angle: if from >= 1300 {
46
} else if !short {
52
} else {
0
},
outl_after_color: if short { 10 } else { 16 },
marker_after_dash: if from >= 1300 {
Some(20)
} else if from >= 600 {
Some(22)
} else {
None
},
four_radii: from >= 900,
f64_rect: from >= 1500,
old_master_flags: from < 1400,
paths: from >= 1000,
utf16_names: from >= 1200,
}
}
/// The newest version read: 27, as the `vrsn` chunk names it (R1, R2).
pub(crate) const NEWEST: u16 = 2799;
/// The first version of each range, with its layouts. Ranges start where a field moves.
const PROFILES: &[(u16, Profile)] = &[
(300, profile(300)),
(400, profile(400)),
(500, profile(500)),
(600, profile(600)),
(700, profile(700)),
(800, profile(800)),
(900, profile(900)),
(1000, profile(1000)),
(1100, profile(1100)),
(1200, profile(1200)),
(1300, profile(1300)),
(1400, profile(1400)),
(1500, profile(1500)),
(1600, profile(1600)),
];
/// The oldest version of a RIFF file read: 3 (R31). Versions 1 and 2 are not RIFF files (`wl.rs`).
pub(crate) const OLDEST_RIFF: u16 = 300;
/// The layouts of the RIFF file of `version` (hundreds; 801 is the 8.01 variant, 2430 is 24.3), or
/// `None` outside 3 to 27.
pub(crate) fn for_version(version: u16) -> Option<Profile> {
if !(OLDEST_RIFF..=NEWEST).contains(&version) {
return None;
}
PROFILES.iter().rev().find(|(from, _)| *from <= version).map(|(_, p)| *p)
}
impl Profile {
/// Points per coordinate unit.
pub(crate) fn unit(&self) -> f64 {
if self.short { 72.0 / 1000.0 } else { 72.0 / 254_000.0 }
}
/// Bytes of a coordinate, and of header fields and counts.
pub(crate) fn word(&self) -> usize {
if self.short { 2 } else { 4 }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_version_from_3_to_27_has_one_profile() {
assert!(for_version(299).is_none() && for_version(2800).is_none());
assert!(for_version(300).is_some_and(|p| p.short && p.inline_styles && p.types_from_zero && p.mcfg_corners && p.fixed_matrix));
assert!(for_version(399).is_some_and(|p| p.color == ColorLayout::Bytes5));
assert!(for_version(400).is_some_and(|p| p.short && !p.inline_styles && !p.mcfg_corners && p.fixed_matrix));
assert!(for_version(499).is_some_and(|p| p.color == ColorLayout::Words12));
assert!(for_version(500).is_some_and(|p| !p.fixed_matrix && !p.types_from_zero && p.color == ColorLayout::Record12));
assert!(for_version(1300).is_some_and(|p| p.old_master_flags));
assert!(for_version(1400).is_some_and(|p| p.tagged && !p.f64_rect && !p.old_master_flags));
assert!(for_version(1500).is_some_and(|p| p.tagged && p.f64_rect && p.mcfg_skip == 12 && p.paths));
assert!(for_version(2430).is_some_and(|p| p.f64_rect && p.paths && p.utf16_names));
assert!(for_version(500).is_some_and(|p| p.short && p.mcfg_skip == 0 && p.marker_after_dash.is_none()));
assert!(for_version(600).is_some_and(|p| !p.short && p.mcfg_skip == 28 && p.marker_after_dash == Some(22)));
assert!(for_version(801).is_some_and(|p| p.mcfg_skip == 0 && p.marker_after_dash == Some(22)));
assert!(for_version(999).is_some_and(|p| !p.paths && p.marker_after_dash == Some(22)));
assert!(for_version(1000).is_some_and(|p| p.mcfg_skip == 4 && p.four_radii && !p.utf16_names && p.paths));
assert!(for_version(1300).is_some_and(|p| p.tagged && p.trfd_head == 8 && p.outl_after_angle == 46));
// The table is in order, so the search finds each range's own row.
assert!(PROFILES.windows(2).all(|w| w[0].0 < w[1].0));
}
}
+110
View File
@@ -0,0 +1,110 @@
//! Reader for `.cdr` drawings of versions 1 to 27 (`.cdr`, and `.cdt` templates): the `WL` files
//! of versions 1 and 2, the RIFF chunk tree of versions 3 on with its compressed lists, the ZIP
//! packages of versions 14 on with their data streams, then pages, layers, guidelines, groups,
//! curves, rectangles, ellipses, arcs and polygons with uniform fills and outlines. It also reads
//! `.cmx` exchange files with 32-bit coordinates ([`read_cmx`]): their pages, layers, groups and
//! curves with uniform fills and outlines.
//!
//! Every record layout the reader relies on is listed in `PROVENANCE.md` with its public source
//! and status; code cites the row ids (R1 ...). Reading is bounded by [`Limits`], never recurses and does not
//! panic. Nothing here writes `.cdr` or `.cmx` files.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::fmt;
mod build;
mod bytes;
mod cmx;
mod geometry;
mod inline;
mod layout;
mod limits;
pub mod model;
mod package;
mod records;
mod riff;
mod styles;
#[cfg(any(test, feature = "synth"))]
pub mod synth;
#[cfg(any(test, feature = "synth"))]
pub mod synth_cmx;
mod wl;
mod zip;
pub use limits::Limits;
pub use model::{Drawing, Warning};
/// Does `bytes` look like a `.cdr` drawing: a RIFF file, a ZIP package holding one, or a `WL` file
/// of version 1 or 2 whose header offsets fit the file?
pub fn is_cdr(bytes: &[u8]) -> bool {
riff::is_cdr_riff(bytes) || package::is_package(bytes) || wl::is_wl(bytes)
}
/// Does `bytes` start as a `.cmx` exchange file: a RIFF form (or its big-endian RIFX form) of type
/// `CMX1`?
pub fn is_cmx(bytes: &[u8]) -> bool {
cmx::is_cmx(bytes)
}
/// Why a file can't be read.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
/// Not a `.cdr` drawing.
NotCdr,
/// Not a `.cmx` file.
NotCmx,
/// A drawing of a version this reader doesn't read (hundreds: 2800 is version 28).
Version(u16),
/// A container structure that doesn't parse.
Damaged(&'static str),
/// Past one of the [`Limits`].
Limit(&'static str),
/// A file this reader doesn't open: an encrypted, ZIP64 or split package, or a RIFF file that
/// names a version before 3; a big-endian `.cmx` file or one with 16-bit coordinates.
Unsupported(&'static str),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::NotCdr => write!(f, "not a CDR drawing"),
Error::NotCmx => write!(f, "not a CMX file"),
Error::Version(v) => write!(f, "version {} drawings are not read", v / 100),
Error::Damaged(what) => write!(f, "damaged {what}"),
Error::Limit(what) => write!(f, "past the {what} limit"),
Error::Unsupported(what) => write!(f, "{what} are not read"),
}
}
}
impl std::error::Error for Error {}
/// Read a drawing within `limits`.
pub fn read(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
if bytes.len() > limits.input {
return Err(Error::Limit("input size"));
}
let mut budget = limits::Budget::new(limits);
// Versions 1 and 2 are not RIFF files (R40).
if wl::is_wl(bytes) {
return wl::drawing(bytes, &mut budget);
}
let mut warnings = Vec::new();
// Versions 14 on save a ZIP package around the RIFF stream (R24, R25, R26).
let (stream, streams) = if zip::is_zip(bytes) { package::open(bytes, &mut budget)? } else { (std::borrow::Cow::Borrowed(bytes), None) };
let ix = riff::Index::build(&stream, streams, &mut budget, &mut warnings)?;
let mut drawing = build::drawing(&ix, &mut budget, &mut warnings)?;
ix.stream_warnings(&mut drawing.warnings);
Ok(drawing)
}
/// Read a `.cmx` exchange file within `limits`. Files in big-endian byte order and files with
/// 16-bit coordinates are refused with [`Error::Unsupported`]. Its [`Drawing::version`] is 0.
pub fn read_cmx(bytes: &[u8], limits: Limits) -> Result<Drawing, Error> {
if bytes.len() > limits.input {
return Err(Error::Limit("input size"));
}
let mut budget = limits::Budget::new(limits);
cmx::drawing(bytes, &mut budget)
}
+168
View File
@@ -0,0 +1,168 @@
//! What one read may take. The values are VectorCraft's own; wasm32 gets half the memory limits.
use crate::Error;
/// The most a read may take, checked before every allocation and descent.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
/// Bytes of input.
pub input: usize,
/// Bytes inflated from compressed lists and package members, all of one file together.
pub inflated: usize,
/// Bytes of one package member.
pub member: usize,
/// Members of a package.
pub members: usize,
/// Nested lists below the file's own. Deeper content is left out with a warning.
pub depth: usize,
/// Chunks in the index, nested ones included, and the entries and styles of the style table;
/// in a `.cmx` file, its chunks, table entries and page instructions.
pub chunks: usize,
/// Objects mapped (shapes, groups and guidelines).
pub objects: usize,
/// Points of all curves together.
pub coordinates: usize,
/// Arguments of one `loda` record.
pub arguments: usize,
/// Dashes of all outlines together, an outline's counted again for every shape that uses it.
/// Past them a shape's outline is solid, with a warning.
pub dashes: usize,
/// Chunks walked inside clipped groups, all containers together, a group's counted again for
/// every container that names it. Each search of an object's list for its `loda`, `flgs` and
/// `trfd` runs once per read and counts every chunk it looks at. Past them a container's group
/// is left out, with a warning.
pub clipped_chunks: usize,
}
#[cfg(not(target_arch = "wasm32"))]
const MIB: usize = 1 << 20;
impl Default for Limits {
#[cfg(not(target_arch = "wasm32"))]
fn default() -> Self {
Limits {
input: 512 * MIB,
inflated: 1024 * MIB,
member: 512 * MIB,
members: 4096,
depth: 256,
chunks: 2_000_000,
objects: 1_000_000,
coordinates: 16_000_000,
arguments: 64,
dashes: 16_000_000,
clipped_chunks: 2_000_000,
}
}
#[cfg(target_arch = "wasm32")]
fn default() -> Self {
Limits {
input: 256 << 20,
inflated: 512 << 20,
member: 256 << 20,
members: 4096,
depth: 256,
chunks: 2_000_000,
objects: 1_000_000,
coordinates: 16_000_000,
arguments: 64,
dashes: 8_000_000,
clipped_chunks: 2_000_000,
}
}
}
/// The running counters of one read against its [`Limits`].
#[derive(Debug)]
pub(crate) struct Budget {
pub(crate) limits: Limits,
inflated: usize,
chunks: usize,
objects: usize,
coordinates: usize,
dashes: usize,
clipped_chunks: usize,
/// A request for coordinates was refused since [`Budget::coordinates_refused`] last asked.
refused: bool,
}
impl Budget {
pub(crate) fn new(limits: Limits) -> Self {
Budget { limits, inflated: 0, chunks: 0, objects: 0, coordinates: 0, dashes: 0, clipped_chunks: 0, refused: false }
}
/// Whether a request for coordinates was refused since the last call, which tells a shape
/// left out at the limit from one whose bytes don't parse.
pub(crate) fn coordinates_refused(&mut self) -> bool {
std::mem::take(&mut self.refused)
}
/// Bytes an inflate may still produce.
pub(crate) fn inflate_left(&self) -> usize {
self.limits.inflated.saturating_sub(self.inflated)
}
pub(crate) fn take_inflated(&mut self, n: usize) -> Result<(), Error> {
self.inflated = self.inflated.checked_add(n).filter(|&t| t <= self.limits.inflated).ok_or(Error::Limit("inflated size"))?;
Ok(())
}
pub(crate) fn take_chunk(&mut self) -> Result<(), Error> {
self.take_chunks(1)
}
/// `n` more chunks or style table entries.
pub(crate) fn take_chunks(&mut self, n: usize) -> Result<(), Error> {
self.chunks = self.chunks.saturating_add(n);
if self.chunks > self.limits.chunks { Err(Error::Limit("chunk count")) } else { Ok(()) }
}
/// One more object, or `false` when the drawing already holds as many as a read maps.
pub(crate) fn take_object(&mut self) -> bool {
if self.objects >= self.limits.objects {
return false;
}
self.objects += 1;
true
}
/// `n` more curve points, or `false` past the limit (nothing is taken then).
pub(crate) fn take_coordinates(&mut self, n: usize) -> bool {
match self.coordinates.checked_add(n).filter(|&t| t <= self.limits.coordinates) {
Some(t) => {
self.coordinates = t;
true
}
None => {
self.refused = true;
false
}
}
}
/// Dashes the read may still take.
pub(crate) fn dashes_left(&self) -> usize {
self.limits.dashes.saturating_sub(self.dashes)
}
/// `n` more dashes, or `false` past the limit (nothing is taken then).
pub(crate) fn take_dashes(&mut self, n: usize) -> bool {
match self.dashes.checked_add(n).filter(|&t| t <= self.limits.dashes) {
Some(t) => {
self.dashes = t;
true
}
None => false,
}
}
/// One more chunk walked inside a clipped group, or `false` past the limit.
pub(crate) fn take_clipped_chunk(&mut self) -> bool {
if self.clipped_chunks >= self.limits.clipped_chunks {
return false;
}
self.clipped_chunks += 1;
true
}
}
+255
View File
@@ -0,0 +1,255 @@
//! What a drawing reads as. Lengths are in points (1/72 inch), from the centre of the page, with y
//! pointing up, as the file stores them.
/// A point in points.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pt {
pub x: f64,
pub y: f64,
}
/// An affine map `[a, b, c, d, e, f]`: x' = a x + c y + e, y' = b x + d y + f.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Matrix(pub [f64; 6]);
impl Matrix {
pub const IDENTITY: Matrix = Matrix([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
/// `self` after `first`: the map that applies `first`, then `self`.
pub fn after(&self, first: &Matrix) -> Matrix {
let [a, b, c, d, e, f] = self.0;
let [p, q, r, s, t, u] = first.0;
Matrix([a * p + c * q, b * p + d * q, a * r + c * s, b * r + d * s, a * t + c * u + e, b * t + d * u + f])
}
pub fn apply(&self, p: Pt) -> Pt {
let [a, b, c, d, e, f] = self.0;
Pt { x: a * p.x + c * p.y + e, y: b * p.x + d * p.y + f }
}
}
/// One segment after the previous point.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Segment {
Line(Pt),
/// Two control points, then the end point.
Cubic(Pt, Pt, Pt),
}
#[derive(Clone, Debug, PartialEq)]
pub struct SubPath {
pub start: Pt,
pub segments: Vec<Segment>,
pub closed: bool,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Path {
pub subpaths: Vec<SubPath>,
}
/// The shape of an object, in its own space ([`Shape::matrix`] places it).
#[derive(Clone, Debug, PartialEq)]
pub enum Geometry {
Path(Path),
/// A rectangle from the origin to (`w`, `h`) (either may be negative). `radii` round its
/// corners counterclockwise from the one at (`w`, 0): (`w`, 0), (`w`, `h`), (0, `h`), (0, 0).
Rect {
w: f64,
h: f64,
radii: [f64; 4],
},
/// A whole ellipse in the box from the origin to (`w`, `h`).
Ellipse {
w: f64,
h: f64,
},
}
#[derive(Clone, Debug, PartialEq)]
pub enum Color {
Rgb([f32; 3]),
Cmyk([f32; 4]),
/// Ink: 0 is white, 1 black.
Gray(f32),
/// Every ink at full strength.
Registration,
/// A color of a named library, printed on its own plate. `look` is its full-strength color
/// when the file stores one (an approximation in sRGB); `tint` is 0 to 1.
Spot {
name: String,
tint: f32,
look: Option<[f32; 3]>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cap {
Butt,
Round,
Square,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Join {
Miter,
Round,
Bevel,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Outline {
pub width: f64,
pub color: Color,
pub cap: Cap,
pub join: Join,
/// Dash and gap lengths, in outline widths; empty for a solid line.
pub dashes: Vec<f64>,
/// Drawn behind the fill, so that a filled shape shows only the outer half of it.
pub behind_fill: bool,
/// Scaled with the shape: the shape's matrix scales the width and dashes as it scales the
/// geometry.
pub scale_with: bool,
}
/// Whether a layer, group or shape is hidden or locked.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Flags {
pub hidden: bool,
pub locked: bool,
}
/// How a shape's colors combine with the art below it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Blend {
#[default]
Normal,
Multiply,
Screen,
Overlay,
SoftLight,
HardLight,
ColorDodge,
ColorBurn,
Darken,
Lighten,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Shape {
pub geometry: Geometry,
pub matrix: Matrix,
pub fill: Option<Color>,
pub outline: Option<Outline>,
/// The fill covers every area its subpaths wind around (nonzero); otherwise subpaths that
/// overlap leave holes (even-odd).
pub nonzero: bool,
/// 1 opaque, 0 clear.
pub opacity: f32,
pub blend: Blend,
pub flags: Flags,
}
impl Shape {
/// An opaque, shown shape filled even-odd.
pub fn new(geometry: Geometry, matrix: Matrix, fill: Option<Color>, outline: Option<Outline>) -> Shape {
Shape { geometry, matrix, fill, outline, nonzero: false, opacity: 1.0, blend: Blend::Normal, flags: Flags::default() }
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Object {
Shape(Box<Shape>),
Group {
objects: Vec<Object>,
flags: Flags,
},
/// A clipping container and the objects it clips: `objects` (front to back) show only
/// inside the container's shape, with its fill behind them and its outline over them.
Clip {
container: Box<Shape>,
objects: Vec<Object>,
},
}
/// A guideline through `at`, at `angle` degrees counterclockwise from horizontal.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Guideline {
pub at: Pt,
pub angle: f64,
/// The guideline, a group around it or its layer is hidden.
pub hidden: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LayerKind {
Drawing,
/// The objects left beside the pages.
Desktop,
Guides,
Grid,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Layer {
pub name: String,
pub kind: LayerKind,
pub flags: Flags,
/// Front to back, as the file lists them.
pub objects: Vec<Object>,
pub guides: Vec<Guideline>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Page {
/// Width and height in points, when the page gives its own.
pub size: Option<(f64, f64)>,
/// Front to back, as the file lists them.
pub layers: Vec<Layer>,
}
/// What was left out or changed while reading. Each kind is listed once.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Warning {
/// Text, bitmaps, splines and other objects not read yet.
UnsupportedObjects,
/// Fountain, pattern, texture and PostScript fills.
UnsupportedFills,
/// Colors in models not read; shown black.
UnknownColors,
/// Library spot colors whose look the file doesn't store; shown black.
SpotLooks,
/// Outline arrowheads.
Arrowheads,
/// Envelopes, which are not applied: the shapes under them keep their outlines.
Envelopes,
/// Lenses, and object transparency that isn't read, which are not applied: the objects show
/// opaque.
Lenses,
/// Content nested deeper, or past the counts, that a read takes.
TooDeep,
/// Chunks or records that end early or don't parse.
Damaged,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Drawing {
/// In hundreds, as a RIFF file stores it: 300 to 2799. A file of version 1 or 2 stores no
/// number: it gives 200 when its marker byte is the one of version 2, and 100 otherwise. A
/// `.cmx` file gives 0.
pub version: u16,
/// Page size from the document settings, in points.
pub page_size: Option<(f64, f64)>,
pub pages: Vec<Page>,
/// Layers every page shows, from the master page.
pub master: Vec<Layer>,
/// Guidelines every page shows, kept outside any layer.
pub guides: Vec<Guideline>,
pub warnings: Vec<Warning>,
}
+147
View File
@@ -0,0 +1,147 @@
//! The packages of versions 14 on (R25, R26): a ZIP archive holding the RIFF stream as
//! `content/riffData.cdr` (14 and 15), or as `content/root.dat` with its chunk bodies in the data
//! streams that `content/dataFileList.dat` names (16 on). A data stream is inflated only when a
//! chunk the reader reads, or a list it splits, points into it.
use std::borrow::Cow;
use std::cell::{Cell, OnceCell};
use crate::limits::{Budget, Limits};
use crate::riff::push;
use crate::zip::{self, Archive};
use crate::{Error, Warning};
const RIFF_DATA: &[u8] = b"content/riffData.cdr";
const ROOT: &[u8] = b"content/root.dat";
const DATA_FILE_LIST: &[u8] = b"content/dataFileList.dat";
const DATA_DIR: &[u8] = b"content/data/";
/// Is `bytes` a ZIP archive with a `.cdr` drawing's root stream?
pub(crate) fn is_package(bytes: &[u8]) -> bool {
zip::is_zip(bytes) && Archive::open(bytes, Limits::default().members).is_ok_and(|a| a.find(RIFF_DATA).or_else(|| a.find(ROOT)).is_some())
}
/// The RIFF stream of the package `bytes`, and its data streams when it has them (16 on).
pub(crate) fn open<'a>(bytes: &'a [u8], budget: &mut Budget) -> Result<(Cow<'a, [u8]>, Option<Streams<'a>>), Error> {
let zip = Archive::open(bytes, budget.limits.members)?;
if let Some(i) = zip.find(RIFF_DATA) {
return Ok((member(&zip, i, budget)?, None));
}
let root = zip.find(ROOT).ok_or(Error::NotCdr)?;
let root = member(&zip, root, budget)?;
let list = match zip.find(DATA_FILE_LIST) {
Some(i) => member(&zip, i, budget)?,
None => Cow::Borrowed(&[][..]),
};
// One name for each line; a line feed after the last name ends it.
let list = list.strip_suffix(b"\n").unwrap_or(&list);
let mut members = Vec::new();
if !list.is_empty() {
for line in list.split(|&b| b == b'\n') {
if members.len() == budget.limits.members {
return Err(Error::Limit("package member count"));
}
let name = line.strip_suffix(b"\r").unwrap_or(line);
let found = zip.find(&[DATA_DIR, name].concat());
// A data stream that is encrypted or packed some other way refuses the file, as the
// root stream does.
if let Some(i) = found {
zip.check(i)?;
}
members.push(found);
}
}
let loaded = (0..zip.count()).map(|_| OnceCell::new()).collect();
let streams = Streams { zip, members, loaded, member_limit: budget.limits.member, damaged: Cell::new(false) };
Ok((root, Some(streams)))
}
/// Member `i` within the member limit and, when deflated, what is left to inflate.
fn member<'a>(zip: &Archive<'a>, i: usize, budget: &mut Budget) -> Result<Cow<'a, [u8]>, Error> {
let m = zip.read(i, budget.limits.member, budget.inflate_left())?;
if let Cow::Owned(v) = &m {
budget.take_inflated(v.len())?;
}
Ok(m)
}
/// What reading one package member gave.
#[derive(Debug)]
enum Slot<'a> {
Read(Cow<'a, [u8]>),
Damaged,
PastLimit,
}
/// The data streams of a version 16+ package, in `dataFileList.dat` order (R26).
#[derive(Debug)]
pub(crate) struct Streams<'a> {
zip: Archive<'a>,
/// The member holding each stream; `None` when the archive lacks it.
members: Vec<Option<usize>>,
/// Each member's bytes once read, so that streams naming one member read it once.
loaded: Vec<OnceCell<Slot<'a>>>,
member_limit: usize,
/// A stream, or a chunk's bytes in one, could not be found.
damaged: Cell<bool>,
}
impl<'a> Streams<'a> {
/// The member holding stream `s`; `None` when there is no such stream.
pub(crate) fn member_of(&self, s: usize) -> Option<usize> {
*self.members.get(s)?
}
/// The size the archive gives stream `s`; `None` when there is no such stream.
pub(crate) fn size(&self, s: usize) -> Option<usize> {
Some(self.zip.size(self.member_of(s)?))
}
/// Stream `s`, its member read on first use within the member limit and, when deflated,
/// within `left` more inflated bytes (which it takes from).
pub(crate) fn get(&self, s: usize, left: &Cell<usize>) -> Option<&[u8]> {
let Some(i) = self.member_of(s) else {
self.damaged.set(true);
return None;
};
let slot = self.loaded.get(i)?.get_or_init(|| {
let read = self.zip.read(i, self.member_limit, left.get());
if !matches!(read, Err(Error::Limit(_))) {
left.set(left.get().saturating_sub(self.zip.inflate_cost(i)));
}
match read {
Ok(b) => Slot::Read(b),
Err(Error::Limit(_)) => Slot::PastLimit,
Err(_) => {
self.damaged.set(true);
Slot::Damaged
}
}
});
match slot {
Slot::Read(b) => Some(b.as_ref()),
Slot::Damaged | Slot::PastLimit => None,
}
}
/// Was stream `s` left out because it is past a limit? Chunks in it are then not damage.
pub(crate) fn past_limit(&self, s: usize) -> bool {
let slot = self.member_of(s).and_then(|i| self.loaded.get(i)).and_then(OnceCell::get);
matches!(slot, Some(Slot::PastLimit))
}
/// Mark a chunk whose stream bytes could not be found.
pub(crate) fn note_damage(&self) {
self.damaged.set(true);
}
/// The warnings for streams that were left out.
pub(crate) fn warnings(&self, warn: &mut Vec<Warning>) {
if self.damaged.get() {
push(warn, Warning::Damaged);
}
if self.loaded.iter().any(|s| matches!(s.get(), Some(Slot::PastLimit))) {
push(warn, Warning::TooDeep);
}
}
}
+659
View File
@@ -0,0 +1,659 @@
//! Hand-written decoders of the records a drawing's objects refer to: the `loda` argument table
//! (R6), transforms (R8), colors (R14), fills (R11) and outlines (R12, R13).
use crate::bytes::Rd;
use crate::layout::{ColorLayout, Profile};
use crate::model::{Blend, Cap, Color, Join, Matrix, Outline};
use crate::riff::push;
use crate::{Limits, Warning};
/// The tag of a record's current layout in tagged files (R11, R12).
const TAG_1300: u32 = 1300;
/// The most tagged records skipped before a fill's own (R11).
const MAX_SKIPPED: usize = 4;
/// The most records skipped before an outline's own (R12).
const MAX_OUTLINE_RECORDS: usize = 16;
/// The most UTF-16 units of a library color's name kept, and the most bytes or UTF-16 units of
/// a layer's.
const MAX_NAME: usize = 256;
/// A header field: u16 in short files, u32 otherwise.
fn word(r: &mut Rd, p: &Profile) -> Option<usize> {
if p.short { r.u16().map(usize::from) } else { r.u32().map(|v| v as usize) }
}
/// A coordinate in points.
pub(crate) fn coord(r: &mut Rd, p: &Profile) -> Option<f64> {
let raw = if p.short { f64::from(r.i16()?) } else { f64::from(r.i32()?) };
Some(raw * p.unit())
}
/// An angle in degrees: tenths in short files, millionths otherwise (R7).
pub(crate) fn angle(r: &mut Rd, p: &Profile) -> Option<f64> {
if p.short { Some(f64::from(r.i16()?) / 10.0) } else { Some(f64::from(r.i32()?) / 1_000_000.0) }
}
/// A `loda` record (R6): its object type and arguments as (type, bytes).
pub(crate) struct Loda<'a> {
pub(crate) kind: u32,
pub(crate) args: Vec<(u32, &'a [u8])>,
}
impl<'a> Loda<'a> {
pub(crate) fn arg(&self, kind: u32) -> Option<&'a [u8]> {
self.args.iter().find(|(k, _)| *k == kind).map(|(_, b)| *b)
}
}
pub(crate) fn loda<'a>(b: &'a [u8], p: &Profile, limits: &Limits, warn: &mut Vec<Warning>) -> Option<Loda<'a>> {
let mut r = Rd::new(b);
let (_len, count, offsets_at, types_at, kind) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?);
// The types table is indexed from the stored count, however many arguments are read.
let stored = count;
let count = if count > limits.arguments {
push(warn, Warning::Damaged);
limits.arguments
} else {
count
};
let table_bytes = count.checked_add(1)?.checked_mul(p.word())?;
if offsets_at.checked_add(table_bytes)? > b.len() {
return None;
}
let mut offsets = Vec::with_capacity(count + 1);
let mut ro = Rd::at(b, offsets_at);
for _ in 0..=count {
offsets.push(word(&mut ro, p)?);
}
let mut args = Vec::with_capacity(count);
for i in 0..count {
// The types table runs the other way: offset i pairs with type stored - 1 - i.
let kind = word(&mut Rd::at(b, types_at.checked_add((stored - 1 - i).checked_mul(p.word())?)?), p)? as u32;
let (start, end) = (*offsets.get(i)?, *offsets.get(i + 1)?);
match b.get(start..end) {
Some(body) => args.push((kind, body)),
None => push(warn, Warning::Damaged),
}
}
Some(Loda { kind: kind as u32, args })
}
/// The matrices of a `trfd` record composed in file order, in points (R8). Each entry ends where
/// the next offset points, and the last at the offset after it (R51); an entry too short for its
/// matrix makes the record unreadable.
pub(crate) fn trfd(b: &[u8], p: &Profile) -> Option<Matrix> {
let mut r = Rd::new(b);
let (_len, count, offsets_at) = (word(&mut r, p)?, word(&mut r, p)?, word(&mut r, p)?);
let mut m = Matrix::IDENTITY;
let k = p.unit();
// Each entry takes at least its offset's bytes, which bounds the count by the record's size.
for i in 0..count.min(b.len() / p.word()) {
let slot = offsets_at.checked_add(i.checked_mul(p.word())?)?;
let start = word(&mut Rd::at(b, slot), p)?;
// A table that stops before the last entry's end offset leaves that entry the rest of the
// record.
let end = word(&mut Rd::at(b, slot.checked_add(p.word())?), p).unwrap_or(b.len());
let mut e = Rd::at(b.get(start..end)?, p.trfd_head);
if e.u16()? != 8 {
continue;
}
e.skip(p.matrix_skip)?;
let next = if p.fixed_matrix {
fixed_matrix(&mut e, k)?
} else {
let (a, c, tx, bb, d, ty) = (e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?, e.f64()?);
Matrix([a, bb, c, d, tx * k, ty * k])
};
m = next.after(&m);
}
Some(m)
}
/// A number in 16.16 fixed point.
pub(crate) fn fixed(r: &mut Rd) -> Option<f64> {
Some(f64::from(r.i32()?) / 65536.0)
}
/// A matrix of versions 3 and 4 (R37): six i32 `a c tx b d ty`, the factors in 16.16 fixed point
/// and `tx` and `ty` in coordinate units of `k` points.
pub(crate) fn fixed_matrix(r: &mut Rd, k: f64) -> Option<Matrix> {
let (a, c, tx) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?));
let (b, d, ty) = (fixed(r)?, fixed(r)?, f64::from(r.i32()?));
Some(Matrix([a, b, c, d, tx * k, ty * k]))
}
/// A color in the layout of the file's version (R14, R36). Unknown models read as black with a
/// warning.
pub(crate) fn color(r: &mut Rd, p: &Profile, warn: &mut Vec<Warning>) -> Option<Color> {
match p.color {
ColorLayout::Record12 => {
let model = r.u16()?;
let palette = r.u16()?;
r.skip(4)?;
let v: [u8; 4] = r.bytes(4)?.try_into().ok()?;
Some(model_color(model, palette, v, warn))
}
ColorLayout::Words12 => {
let model = r.u16()?;
let w = [r.u16()?, r.u16()?, r.u16()?, r.u16()?];
r.skip(2)?;
// The models take 8-bit values, as in the other layouts; a larger value reads as 255.
Some(early_color(model, w.map(|x| u8::try_from(x).unwrap_or(u8::MAX)), w[0], w[1], warn))
}
ColorLayout::Bytes5 => Some(color5(r.bytes(5)?.try_into().ok()?, warn)),
}
}
/// A 5-byte color (R36): a model byte and four value bytes.
pub(crate) fn color5(b: [u8; 5], warn: &mut Vec<Warning>) -> Color {
let [model, v @ ..] = b;
early_color(u16::from(model), v, u16::from_le_bytes([v[0], v[1]]), u16::from_le_bytes([v[2], v[3]]), warn)
}
/// A color of versions 1 to 4 (R36). Model 1 is CMYK in percent. Model 0 is a numbered ink and
/// its tint in percent: 0 is black, 1 is white, and other numbers are inks of a library the file
/// doesn't store. Other models read as in later versions.
fn early_color(model: u16, v: [u8; 4], index: u16, tint: u16, warn: &mut Vec<Warning>) -> Color {
let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0);
match (model, index) {
(1, _) => Color::Cmyk(v.map(|x| pct(f32::from(x)))),
(0, 0) => Color::Gray(pct(f32::from(tint))),
(0, 1) => Color::Gray(0.0),
(0, number) => {
push(warn, Warning::SpotLooks);
Color::Spot { name: format!("Spot 0:{number}"), tint: pct(f32::from(tint)), look: None }
}
_ => model_color(model, 0, v, warn),
}
}
/// The color of `model` with the four value bytes `v`, from version 5 (R14).
fn model_color(model: u16, palette: u16, v: [u8; 4], warn: &mut Vec<Warning>) -> Color {
let (v0, v1, v2, v3) = (f32::from(v[0]), f32::from(v[1]), f32::from(v[2]), f32::from(v[3]));
let pct = |x: f32| (x / 100.0).clamp(0.0, 1.0);
let byte = |x: f32| x / 255.0;
match model {
2 => Color::Cmyk([pct(v0), pct(v1), pct(v2), pct(v3)]),
3 | 17 => Color::Cmyk([byte(v0), byte(v1), byte(v2), byte(v3)]),
4 => Color::Cmyk([byte(v0), byte(v1), byte(v2), 0.0]),
5 | 21 => Color::Rgb([byte(v2), byte(v1), byte(v0)]),
9 => Color::Gray(1.0 - byte(v0)),
20 => Color::Registration,
1 | 14 | 25 => {
let number = u16::from_le_bytes([v[0], v[1]]);
let tint = pct(f32::from(u16::from_le_bytes([v[2], v[3]])));
push(warn, Warning::SpotLooks);
// Each library numbers its own colors: the name holds the palette and the number.
Color::Spot { name: format!("Spot {palette}:{number}"), tint, look: None }
}
_ => {
push(warn, Warning::UnknownColors);
Color::Rgb([0.0; 3])
}
}
}
/// A UTF-16 name stored as a character count and its code units. Every shape that uses the color
/// gets its own copy of the name: a name longer than [`MAX_NAME`] units keeps its first ones and a
/// hash of the whole name, with a warning, so two long names that start alike stay apart.
fn counted_utf16(r: &mut Rd, warn: &mut Vec<Warning>) -> Option<String> {
let n = r.u32()? as usize;
let b = r.bytes(n.checked_mul(2)?)?;
// Trailing NULs are padding.
let all = b.as_chunks::<2>().0;
let all = all.get(..all.iter().rposition(|c| *c != [0, 0]).map_or(0, |i| i + 1)).unwrap_or_default();
let units = all.iter().map(|c| u16::from_le_bytes(*c));
if all.len() <= MAX_NAME {
let units: Vec<u16> = units.collect();
return Some(String::from_utf16_lossy(&units));
}
push(warn, Warning::TooDeep);
// FNV-1a over the code units.
let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u64::from(u)).wrapping_mul(0x0100_0000_01b3));
let kept: Vec<u16> = units.take(MAX_NAME).collect();
Some(format!("{} {hash:016x}", String::from_utf16_lossy(&kept)))
}
/// The color of the property list of a tagged uniform fill (R11) or outline (R12): its color
/// record, named by the library name it carries.
pub(crate) fn property_color(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<Color> {
let mut r = Rd::new(b);
let (mut found, mut name) = (None, None);
while r.left() >= 5 {
let kind = r.u8()?;
let len = r.u32()? as usize;
if kind == 0 {
break;
}
let body = r.bytes(len)?;
let mut br = Rd::new(body);
match kind {
1 => found = color(&mut br, p, warn),
8 => name = br.skip(16).and_then(|_| counted_utf16(&mut br, warn)),
3 => name = name.or_else(|| counted_utf16(&mut br, warn)),
_ => {}
}
}
match (found?, name.filter(|n| !n.is_empty())) {
// A library color with its name: the record's sRGB has the tint applied already.
(Color::Rgb(rgb), Some(name)) => {
let tint = b_tint(b).unwrap_or(1.0);
Some(Color::Spot { name, tint, look: Some(untinted(rgb, tint)) })
}
(c, _) => Some(c),
}
}
/// The tint byte of the first color property of a property list (model 21 keeps it last).
fn b_tint(b: &[u8]) -> Option<f32> {
let mut r = Rd::new(b);
while r.left() >= 5 {
let kind = r.u8()?;
let len = r.u32()? as usize;
let body = r.bytes(len)?;
if kind == 1 {
let mut c = Rd::new(body);
return (c.u16()? == 21).then(|| f32::from(*body.get(11).unwrap_or(&100)) / 100.0).map(|t| t.clamp(0.0, 1.0));
}
}
None
}
/// The full-strength color behind sRGB `rgb` shown at `tint` (a tint mixes toward white).
fn untinted(rgb: [f32; 3], tint: f32) -> [f32; 3] {
if tint <= 0.0 {
return rgb;
}
rgb.map(|v| (1.0 - (1.0 - v) / tint).clamp(0.0, 1.0))
}
/// A fill record: its id, and its color (`None`: no fill). Fills of other kinds read as none with
/// a warning (R11).
pub(crate) fn fill(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<(u32, Option<Color>)> {
let mut r = Rd::new(b);
let id = r.u32()?;
let body = if p.tagged { tagged_body(&mut r)? } else { r.bytes(r.left())? };
let mut r = Rd::new(body);
let kind = r.u16()?;
let color = match kind {
0 => None,
1 if p.tagged => {
if r.u32()? != TAG_1300 {
push(warn, Warning::Damaged);
return Some((id, None));
}
// A uniform fill whose color can't be read is damage, not a fill of none.
let len = r.u32()? as usize;
Some(property_color(r.bytes(len.min(r.left()))?, p, warn)?)
}
1 => {
r.skip(2)?;
Some(color(&mut r, p, warn)?)
}
_ => {
push(warn, Warning::UnsupportedFills);
None
}
};
Some((id, color))
}
/// The body of the record tagged 1300 that follows tagged records of later layouts (R11).
fn tagged_body<'a>(r: &mut Rd<'a>) -> Option<&'a [u8]> {
for _ in 0..=MAX_SKIPPED {
let (tag, len) = (r.u32()?, r.u32()? as usize);
let body = r.bytes(len.min(r.left()))?;
if tag == TAG_1300 {
return Some(body);
}
}
None
}
/// An outline record: its id and the outline (`None`: no outline) (R12, R13).
pub(crate) fn outline(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> Option<(u32, Option<Outline>)> {
let mut r = Rd::new(b);
let id = r.u32()?;
// A library color named in a record of type 2, with the warnings its read gave.
let mut named = None;
if p.tagged {
let mut found = false;
for _ in 0..MAX_OUTLINE_RECORDS {
let (rec, len) = (r.u32()?, r.u32()? as usize);
if rec == 1 {
found = true;
break;
}
let body = r.bytes(len)?;
// Type 2 holds the outline's color as a property list, as a uniform fill does (R12).
// Only a library color with its name is taken from it; any other color comes from
// the fixed field below.
if rec == 2 {
let mut w = Vec::new();
if let Some(c @ Color::Spot { look: Some(_), .. }) = property_color(body, p, &mut w) {
named = Some((c, w));
}
}
}
if !found {
return None;
}
}
let (line_type, cap, join) = (r.u16()?, r.u16()?, r.u16()?);
r.skip(p.outl_after_join)?;
let width = coord(&mut r, p)?.abs();
let _stretch = r.u16()?;
r.skip(p.outl_after_stretch)?;
let _nib = angle(&mut r, p)?;
r.skip(p.outl_after_angle)?;
let color = match named {
Some((named, w)) => {
color(&mut r, p, &mut Vec::new())?;
for x in w {
push(warn, x);
}
named
}
None => color(&mut r, p, warn)?,
};
r.skip(p.outl_after_color)?;
let count = usize::from(r.u16()?);
let first_dash = r.pos();
let fits = r.left() / 2;
if count > fits {
push(warn, Warning::Damaged);
}
// At most 65,535; the read's dash limit is applied where shapes use them.
let dashes: Vec<f64> = (0..count.min(fits)).filter_map(|_| r.u16().map(f64::from)).collect();
if let Some(after) = p.marker_after_dash {
let mut m = Rd::at(b, first_dash + after);
if matches!((m.u32(), m.u32()), (Some(s), Some(e)) if s != 0 || e != 0) {
push(warn, Warning::Arrowheads);
}
}
// Bit 0 of the line type: no outline (R13).
if line_type & 1 != 0 {
return Some((id, None));
}
let cap = match cap {
1 => Cap::Round,
2 => Cap::Square,
_ => Cap::Butt,
};
let join = match join {
1 => Join::Round,
2 => Join::Bevel,
_ => Join::Miter,
};
// Bit 2 of the line type marks the outline dashed; without it the dashes stored are not drawn
// (R48).
let dashes = if line_type & 4 != 0 && dashes.iter().any(|d| *d > 0.0) { dashes } else { Vec::new() };
// Bit 4 of the line type: behind the fill (R49).
let behind_fill = line_type & 0x10 != 0;
// Bit 5 of the line type: scaled with the shape (R50).
let scale_with = line_type & 0x20 != 0;
Some((id, Some(Outline { width, color, cap, join, dashes, behind_fill, scale_with })))
}
/// The opacity and blend of argument 8000 from version 13 (R47): records of a u32 version, a u32
/// length and a body. A body of version 1300 that is [`UNIFORM_LEN`] bytes long is a uniform
/// transparency: an f64 at byte 61 and the merge mode at byte 77. VectorCraft reads the f64 as the
/// transparency in percent, 0 opaque and 100 clear. `None` for any other argument, such as a lens,
/// and for a value out of range or a merge mode without a VectorCraft blend mode.
pub(crate) fn transparency(b: &[u8]) -> Option<(f32, Blend)> {
let mut r = Rd::new(b);
while r.left() >= 8 {
let (since, len) = (r.u32()?, r.u32()? as usize);
let body = r.bytes(len)?;
if since != TAG_1300 {
continue;
}
if body.len() != UNIFORM_LEN {
return None;
}
let value = Rd::at(body, 61).f64()?;
if !(0.0..=100.0).contains(&value) {
return None;
}
return Some(((1.0 - value / 100.0) as f32, blend(*body.get(77)?)?));
}
None
}
/// The length of a uniform transparency's record body (R47).
const UNIFORM_LEN: usize = 117;
/// The blend mode of a transparency's merge mode byte (R47); `None` for the modes VectorCraft has
/// no blend mode for.
fn blend(mode: u8) -> Option<Blend> {
Some(match mode {
0 => Blend::Normal,
9 => Blend::Multiply,
11 => Blend::Lighten,
12 => Blend::Darken,
14 => Blend::Color,
15 => Blend::Hue,
16 => Blend::Saturation,
17 => Blend::Luminosity,
24 => Blend::Difference,
28 => Blend::Screen,
29 => Blend::Overlay,
30 => Blend::SoftLight,
31 => Blend::HardLight,
33 => Blend::ColorDodge,
34 => Blend::ColorBurn,
36 => Blend::Exclusion,
_ => return None,
})
}
/// A name argument (R9): Windows-1252 up to a NUL before version 12, UTF-16LE from it. A name
/// longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones (without half of a
/// surrogate pair) and a hash of the whole name, with a warning, as a library color's name does.
pub(crate) fn name(b: &[u8], p: &Profile, warn: &mut Vec<Warning>) -> String {
if p.utf16_names {
let units = b.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0);
let (mut kept, hash) = capped(units, warn);
if hash.is_some() && kept.last().is_some_and(|u| (0xD800..0xDC00).contains(u)) {
kept.pop();
}
with_hash(String::from_utf16_lossy(&kept), hash)
} else {
let bytes = b.iter().copied().take_while(|c| *c != 0);
let (kept, hash) = capped(bytes, warn);
with_hash(kept.into_iter().map(windows_1252).collect(), hash)
}
}
/// The first [`MAX_NAME`] of `units`, and when there are more, an FNV-1a hash of them all, with a
/// warning.
fn capped<T: Copy + Into<u64>>(units: impl Iterator<Item = T> + Clone, warn: &mut Vec<Warning>) -> (Vec<T>, Option<u64>) {
if units.clone().nth(MAX_NAME).is_none() {
return (units.collect(), None);
}
push(warn, Warning::TooDeep);
let hash = units.clone().fold(0xcbf2_9ce4_8422_2325_u64, |h, u| (h ^ u.into()).wrapping_mul(0x0100_0000_01b3));
(units.take(MAX_NAME).collect(), Some(hash))
}
/// `name`, followed by `hash` in hexadecimal when there is one.
fn with_hash(name: String, hash: Option<u64>) -> String {
match hash {
Some(h) => format!("{name} {h:016x}"),
None => name,
}
}
/// The characters Windows-1252 puts at 0x80 to 0x9F (U+FFFD where it has none); the other bytes
/// are Latin-1.
const CP1252_HIGH: [char; 32] = [
'€', '\u{FFFD}', '‚', 'ƒ', '„', '…', '†', '‡', 'ˆ', '‰', 'Š', '‹', 'Œ', '\u{FFFD}', 'Ž', '\u{FFFD}', '\u{FFFD}', '‘', '’', '“', '”', '•', '–',
'—', '˜', '™', 'š', '›', 'œ', '\u{FFFD}', 'ž', 'Ÿ',
];
fn windows_1252(c: u8) -> char {
match c {
0x80..=0x9F => CP1252_HIGH.get(usize::from(c - 0x80)).copied().unwrap_or('\u{FFFD}'),
_ => char::from(c),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// An outline that names an arrowhead says so with a warning, in each version whose arrowhead
/// ids have a known place: 22 bytes after the first dash in versions 6 to 12, 20 from 13.
#[test]
fn arrowheads_are_named_from_version_6() {
let pen = crate::synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 };
let color = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100];
for (version, place) in [
(500, None),
(600, Some(22)),
(700, Some(22)),
(800, Some(22)),
(900, Some(22)),
(1000, Some(22)),
(1100, Some(22)),
(1200, Some(22)),
(1300, Some(20)),
(1700, Some(20)),
] {
let p = crate::layout::for_version(version).unwrap();
let plain = crate::synth::V(version).outline(7, pen, &color, &[]);
// The record ends with 32 bytes after its dashes, and this one has none.
let first_dash = plain.len() - 32;
let mut w = vec![];
assert!(outline(&plain, &p, &mut w).is_some_and(|(id, o)| id == 7 && o.is_some()), "{version}");
assert!(w.is_empty(), "{version}: {w:?}");
let Some(place) = place else { continue };
let mut arrow = plain.clone();
arrow[first_dash + place..first_dash + place + 4].copy_from_slice(&9u32.to_le_bytes());
let mut w = vec![];
assert!(outline(&arrow, &p, &mut w).is_some(), "{version}");
assert_eq!(w, vec![Warning::Arrowheads], "{version}");
}
}
#[test]
fn single_byte_names_read_as_windows_1252() {
let p = crate::layout::for_version(1100).unwrap();
assert_eq!(name(b"Caf\xe9 \x80\x96\0junk", &p, &mut vec![]), "Café €–");
let p = crate::layout::for_version(1200).unwrap();
assert_eq!(name(&[0x41, 0, 0x42, 0, 0, 0, 0x43, 0], &p, &mut vec![]), "AB");
}
/// A layer name longer than [`MAX_NAME`] bytes or UTF-16 units keeps its first ones and a hash
/// of the whole name, with a warning, in both encodings. A cut never keeps half of a surrogate
/// pair.
#[test]
fn long_layer_names_are_cut_with_a_hash() {
for version in [1100, 1200] {
let p = crate::layout::for_version(version).unwrap();
let bytes =
|s: &str| if p.utf16_names { s.encode_utf16().flat_map(u16::to_le_bytes).collect::<Vec<u8>>() } else { s.as_bytes().to_vec() };
let mut w = vec![];
let a = name(&bytes(&"N".repeat(100_000)), &p, &mut w);
let b = name(&bytes(&format!("{}M", "N".repeat(99_999))), &p, &mut vec![]);
assert_ne!(a, b, "{version}");
assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{version}: {}", a.len());
assert_eq!(w, vec![Warning::TooDeep], "{version}");
let mut w = vec![];
assert_eq!(name(&bytes(&"N".repeat(MAX_NAME)), &p, &mut w), "N".repeat(MAX_NAME), "{version}");
assert!(w.is_empty(), "{version}");
}
let p = crate::layout::for_version(1200).unwrap();
let emoji: Vec<u8> = format!("N{}", "\u{1F600}".repeat(200)).encode_utf16().flat_map(u16::to_le_bytes).collect();
let cut = name(&emoji, &p, &mut vec![]);
assert!(!cut.contains('\u{FFFD}'), "{cut}");
assert_eq!(cut.chars().filter(|c| *c == '\u{1F600}').count(), (MAX_NAME - 1) / 2);
}
#[test]
fn colors_read_in_their_models() {
let p = crate::layout::for_version(500).unwrap();
let rec = |model: u16, v: [u8; 4]| {
let mut b = model.to_le_bytes().to_vec();
b.extend([0; 6]);
b.extend(v);
let mut w = vec![];
(color(&mut Rd::new(&b), &p, &mut w), w)
};
assert_eq!(rec(2, [100, 50, 0, 10]).0, Some(Color::Cmyk([1.0, 0.5, 0.0, 0.1])));
assert_eq!(rec(5, [255, 0, 0, 0]).0, Some(Color::Rgb([0.0, 0.0, 1.0])));
assert_eq!(rec(9, [255, 0, 0, 0]).0, Some(Color::Gray(0.0)));
assert_eq!(rec(25, [7, 0, 40, 0]).0, Some(Color::Spot { name: "Spot 0:7".into(), tint: 0.4, look: None }));
// The same number in another library is another color.
let mut other = 25u16.to_le_bytes().to_vec();
other.extend(3u16.to_le_bytes());
other.extend([0; 4]);
other.extend([7, 0, 40, 0]);
assert_eq!(color(&mut Rd::new(&other), &p, &mut vec![]), Some(Color::Spot { name: "Spot 3:7".into(), tint: 0.4, look: None }));
let (c, w) = rec(6, [1, 2, 3, 4]);
assert_eq!((c, w), (Some(Color::Rgb([0.0; 3])), vec![Warning::UnknownColors]));
}
#[test]
fn colors_of_versions_3_and_4_read_models_0_and_1() {
let read = |version: u16, model: u8, v: [u16; 4]| {
let p = crate::layout::for_version(version).unwrap();
let b: Vec<u8> = if version < 400 {
std::iter::once(model).chain(v.map(|x| x as u8)).collect()
} else {
u16::from(model).to_le_bytes().into_iter().chain(v.iter().flat_map(|x| x.to_le_bytes())).chain([0, 0]).collect()
};
let mut r = Rd::new(&b);
let mut w = vec![];
let c = color(&mut r, &p, &mut w);
assert_eq!(r.left(), 0, "{version}");
(c, w)
};
for version in [300, 400] {
// Model 1 is CMYK in percent, not a library color as from version 5.
assert_eq!(read(version, 1, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}");
assert_eq!(read(version, 2, [0, 100, 50, 10]).0, Some(Color::Cmyk([0.0, 1.0, 0.5, 0.1])), "{version}");
}
// Model 0: an ink number and a tint. Version 3 stores each as a u16 in its four bytes.
assert_eq!(read(300, 0, [0, 0, 60, 0]).0, Some(Color::Gray(0.6)));
assert_eq!(read(300, 0, [1, 0, 60, 0]).0, Some(Color::Gray(0.0)));
assert_eq!(read(300, 0, [44, 1, 60, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks]));
assert_eq!(read(400, 0, [0, 60, 0, 0]).0, Some(Color::Gray(0.6)));
assert_eq!(read(400, 0, [1, 60, 0, 0]).0, Some(Color::Gray(0.0)));
assert_eq!(read(400, 0, [300, 60, 0, 0]), (Some(Color::Spot { name: "Spot 0:300".into(), tint: 0.6, look: None }), vec![Warning::SpotLooks]));
}
#[test]
fn a_fixed_point_matrix_reads_its_factors_and_offsets() {
let raw: Vec<u8> = [65536i32, -32768, 1000, 131072, 16384, -500].iter().flat_map(|v| v.to_le_bytes()).collect();
let m = fixed_matrix(&mut Rd::new(&raw), 0.5).unwrap();
assert_eq!(m, Matrix([1.0, 2.0, -0.5, 0.25, 500.0, -250.0]));
assert!(fixed_matrix(&mut Rd::new(&raw[..23]), 0.5).is_none());
}
#[test]
fn long_names_that_start_alike_stay_apart() {
let read = |name: &str| {
let mut b = (name.encode_utf16().count() as u32).to_le_bytes().to_vec();
b.extend(name.encode_utf16().flat_map(u16::to_le_bytes));
let mut w = vec![];
(counted_utf16(&mut Rd::new(&b), &mut w).unwrap(), w)
};
let (a, w) = read(&"N".repeat(300));
let (b, _) = read(&format!("{}M", "N".repeat(299)));
assert_ne!(a, b);
assert!(a.starts_with(&"N".repeat(MAX_NAME)) && a.chars().count() == MAX_NAME + 17, "{a}");
assert_eq!(w, vec![Warning::TooDeep]);
assert_eq!(read("Sky Blue"), ("Sky Blue".to_string(), vec![]));
// Padding doesn't count toward the length or the name.
let (padded, w) = read(&format!("{}\0\0", "N".repeat(MAX_NAME - 1)));
assert_eq!((padded, w), ("N".repeat(MAX_NAME - 1), vec![]));
}
#[test]
fn a_tint_mixes_toward_white_and_comes_off_again() {
let shown = [0.6, 0.8, 1.0];
let base = untinted(shown, 0.5);
assert!((base[0] - 0.2).abs() < 1e-6 && (base[1] - 0.6).abs() < 1e-6 && base[2] == 1.0);
}
}
+465
View File
@@ -0,0 +1,465 @@
//! The chunk index: one flat table of every chunk, a list's children contiguous, built without
//! recursion. Payloads are not copied: an entry names a range of the RIFF stream, of the bytes
//! inflated from `LIST cmpr`, or of a package's data stream (layouts R1 to R4, R27).
use std::cell::Cell;
use std::collections::BTreeMap;
use std::io::Read as _;
use crate::bytes::{Rd, u32_at};
use crate::layout;
use crate::limits::Budget;
use crate::package::Streams;
use crate::{Error, Warning};
pub(crate) const LIST: [u8; 4] = *b"LIST";
const CMPR: [u8; 4] = *b"cmpr";
const CPNG: [u8; 4] = *b"CPng";
/// What follows `CPng` before the zlib stream (R3).
const CPNG_HEAD: [u8; 4] = [1, 0, 4, 0];
/// The size of a redirect record, and the stream number of one that holds its body (R27).
const REDIRECT: usize = 16;
const INLINE: u32 = u32::MAX;
/// One chunk: 28 bytes. `start` and `len` give the payload (after a list's form type) in its
/// source: 0 is the RIFF stream followed by the inflated bytes, `s + 1` is data stream `s`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Chunk {
pub(crate) id: [u8; 4],
/// A list's form type; zeros for other chunks.
pub(crate) form: [u8; 4],
src: u32,
start: u32,
len: u32,
first: u32,
count: u32,
}
impl Chunk {
pub(crate) fn is_list(&self, form: &[u8; 4]) -> bool {
self.id == LIST && &self.form == form
}
}
/// Every chunk of a file, and the bytes they point into.
pub(crate) struct Index<'a> {
input: &'a [u8],
inflated: Vec<u8>,
chunks: Vec<Chunk>,
/// The version the form type names: hundreds, as `vrsn` stores it (0 when the `vrsn` chunk
/// decides).
pub(crate) form_version: u16,
/// A version 16+ package's data streams; chunks of 16 bytes are redirect records then.
streams: Option<Streams<'a>>,
/// Bytes that inflating may still produce.
left: Cell<usize>,
/// The bytes redirected lists have taken: (package member, start) to end.
lists: Cell<BTreeMap<(usize, usize), usize>>,
/// The bytes other redirected chunks have taken, the same way.
leaves: Cell<BTreeMap<(usize, usize), usize>>,
/// Bytes that redirects to bytes another chunk already took may still read.
shared_left: Cell<usize>,
/// The first `vrsn` chunk among the file's own chunks, once seen, and the version it names
/// (`None` when it can't be read) (R2).
vrsn: Option<Option<u16>>,
}
/// A list still to be split into its children.
struct Pending {
entry: usize,
src: u32,
/// Its children's bytes.
start: usize,
end: usize,
/// The size pool of a compressed list's stream (`start..end` in source 0).
pool: Option<(usize, usize)>,
depth: usize,
}
/// What reading one chunk header gives.
enum Read {
Chunk(Chunk),
/// A redirect record whose body can't be found: the chunk is left out, its list read on.
Lost,
/// A redirect record into a data stream past a limit: the chunk is left out without the
/// damage warning.
PastLimit,
/// A redirect record to bytes another chunk took, past the shared-bytes limit: the chunk is
/// left out with the limit warning.
SharedPastLimit,
}
/// The version the RIFF form type names (R1): `CDR5`..`CDR9`, `CDRA` (10) to `CDRH` (17) with `I`
/// unused, then `J` (18) on; `CDR ` is version 3. Some files use a lower-case `cdr`, which names
/// the same versions except that `cdr8` is the 8.01 variant. Templates of version 21 have the form
/// type `CDTQ`; for `CDT` the `vrsn` chunk names the version, so this gives 0 (R28).
pub(crate) fn form_version(form: [u8; 4]) -> Option<u16> {
let [a, b, c, v] = form;
match (&[a, b, c], v) {
(b"cdr", b'8') => Some(801),
(b"CDR" | b"cdr", b' ') => Some(300),
(b"CDR" | b"cdr", b'1'..=b'9') => Some(100 * u16::from(v - b'0')),
(b"CDR" | b"cdr", b'A'..=b'H') => Some(100 * u16::from(v - b'A' + 10)),
(b"CDR" | b"cdr", b'J'..=b'W') => Some(100 * u16::from(v - b'J' + 18)),
(b"CDT", b'A'..=b'Z') => Some(0),
_ => None,
}
}
/// Does `bytes` start like a RIFF `.cdr` drawing (not the `CDRX` exchange variant)?
pub(crate) fn is_cdr_riff(bytes: &[u8]) -> bool {
bytes.get(..4) == Some(b"RIFF") && bytes.get(8..12).and_then(|f| f.try_into().ok()).and_then(form_version).is_some()
}
impl<'a> Index<'a> {
pub(crate) fn build(input: &'a [u8], streams: Option<Streams<'a>>, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<Self, Error> {
if input.len() > budget.limits.input {
return Err(Error::Limit("input size"));
}
let mut r = Rd::new(input);
if r.fourcc() != Some(*b"RIFF") {
return Err(Error::NotCdr);
}
let declared = r.u32().ok_or(Error::NotCdr)? as usize;
let form = r.fourcc().ok_or(Error::NotCdr)?;
let version = form_version(form).ok_or(Error::NotCdr)?;
// A file cut short keeps what it holds: its last chunk is truncated with a warning. A
// length that ends inside the form type is damage too, and the chunks after it are read.
let end = match declared.checked_add(8) {
Some(e) if (12..=input.len()).contains(&e) => e,
_ => {
push(warn, Warning::Damaged);
input.len()
}
};
let left = Cell::new(budget.inflate_left());
let mut ix = Index {
input,
inflated: Vec::new(),
chunks: Vec::new(),
form_version: version,
streams,
left,
lists: Cell::default(),
leaves: Cell::default(),
shared_left: Cell::new(budget.limits.member),
vrsn: None,
};
ix.chunks.push(Chunk { id: *b"RIFF", form, src: 0, start: 12, len: 0, first: 0, count: 0 });
let mut queue = vec![Pending { entry: 0, src: 0, start: 12, end, pool: None, depth: 0 }];
while let Some(p) = queue.pop() {
ix.split(p, &mut queue, budget, warn)?;
}
Ok(ix)
}
/// The bytes `start..end` of source `src`, or `None` when the range crosses its end. A data
/// stream is read on first use.
fn span(&self, src: u32, start: usize, end: usize) -> Option<&[u8]> {
if src > 0 {
let s = self.streams.as_ref()?;
return s.get(src as usize - 1, &self.left)?.get(start..end);
}
let n = self.input.len();
if end <= n {
self.input.get(start..end)
} else if start >= n {
self.inflated.get(start - n..end - n)
} else {
None
}
}
pub(crate) fn data(&self, c: &Chunk) -> &[u8] {
let start = c.start as usize;
match self.span(c.src, start, start + c.len as usize) {
Some(b) => b,
None => {
if let Some(s) = &self.streams
&& !self.past_limit(c.src)
{
s.note_damage();
}
&[]
}
}
}
/// Was source `src` a data stream left out because it is past a limit? Its chunks are then
/// left out with that warning alone.
fn past_limit(&self, src: u32) -> bool {
src > 0 && self.streams.as_ref().is_some_and(|s| s.past_limit(src as usize - 1))
}
pub(crate) fn children(&self, c: &Chunk) -> &[Chunk] {
let first = c.first as usize;
self.chunks.get(first..first + c.count as usize).unwrap_or_default()
}
pub(crate) fn root(&self) -> Option<&Chunk> {
self.chunks.first()
}
/// The version: the `vrsn` chunk's when it names one from 3 to 27, else the form type's (R1,
/// R2). A template's form type names no version, so its `vrsn` chunk decides whatever it names
/// (R28). Letters count differently from the version 24 update on (R1), so when both name a
/// version after 27 the `vrsn` chunk's is the one refused. The `cdr8` form type alone makes a
/// file the 8.01 variant, whatever its `vrsn` chunk names (R1).
pub(crate) fn version(&self) -> u16 {
match self.vrsn.flatten() {
_ if self.form_version == 801 => 801,
Some(v) if (layout::OLDEST_RIFF..=layout::NEWEST).contains(&v) => v,
Some(v) if self.form_version == 0 => v,
Some(v) if v > layout::NEWEST && self.form_version > layout::NEWEST => v,
_ => self.form_version,
}
}
/// The warnings for data streams that were left out.
pub(crate) fn stream_warnings(&self, warn: &mut Vec<Warning>) {
if let Some(s) = &self.streams {
s.warnings(warn);
}
}
/// Split list `p` into its children, appended to the table together; their lists are queued.
fn split(&mut self, p: Pending, queue: &mut Vec<Pending>, budget: &mut Budget, warn: &mut Vec<Warning>) -> Result<(), Error> {
let first = self.chunks.len();
let mut at = p.start;
let mut lists = Vec::new();
while at < p.end {
let Some((read, next, cut)) = self.read_chunk(p.src, at, p.end, p.pool) else {
push(warn, Warning::Damaged);
break;
};
if cut {
push(warn, Warning::Damaged);
}
at = next;
// A redirect record whose body can't be found counts as well, so that lists redirected
// to again and again can't repeat such records past the limit.
budget.take_chunk()?;
let chunk = match read {
Read::Chunk(chunk) => chunk,
Read::Lost => {
push(warn, Warning::Damaged);
continue;
}
Read::PastLimit => continue,
Read::SharedPastLimit => {
push(warn, Warning::TooDeep);
continue;
}
};
if p.entry == 0 && chunk.id == *b"vrsn" && self.vrsn.is_none() {
let at = chunk.start as usize;
self.vrsn = Some(self.span(chunk.src, at, at + chunk.len as usize).and_then(|b| Rd::new(b).u16()));
}
if chunk.id == LIST {
lists.push(self.chunks.len());
}
self.chunks.push(chunk);
}
let count = (self.chunks.len() - first) as u32;
if let Some(parent) = self.chunks.get_mut(p.entry) {
parent.first = first as u32;
parent.count = count;
}
for i in lists {
let Some(c) = self.chunks.get(i).copied() else { continue };
// From version 7 a `LIST stlt` holds the style tables, not chunks (R4); its body is read
// whole (R45). Before version 7 it holds chunks. The file's own chunks, its `vrsn`
// among them, are all read before this.
if c.form == *b"stlt" && self.version() >= 700 {
continue;
}
if p.depth + 1 > budget.limits.depth {
push(warn, Warning::TooDeep);
continue;
}
let (start, end) = (c.start as usize, c.start as usize + c.len as usize);
if c.form == CMPR && p.pool.is_none() {
match self.inflate_cmpr(c.src, start, end) {
Ok((s, e, pool)) => queue.push(Pending { entry: i, src: 0, start: s, end: e, pool: Some(pool), depth: p.depth + 1 }),
Err(Error::Limit(what)) => return Err(Error::Limit(what)),
Err(_) => push(warn, Warning::Damaged),
}
} else {
queue.push(Pending { entry: i, src: c.src, start, end, pool: p.pool, depth: p.depth + 1 });
}
}
Ok(())
}
/// The chunk at `at` (before `end`) of source `src`, and where the next one starts. In a
/// compressed stream the size field is an index into the size pool (R3); in a version 16+
/// package a chunk of 16 bytes outside one is a redirect record (R27). The flag is set for a
/// list cut short at `end`.
fn read_chunk(&self, src: u32, at: usize, end: usize, pool: Option<(usize, usize)>) -> Option<(Read, usize, bool)> {
let head = self.span(src, at, at.checked_add(8)?.min(end))?;
let id: [u8; 4] = head.get(..4)?.try_into().ok()?;
let raw = u32_at(head, 4)? as usize;
let size = match pool {
None => raw,
Some((ps, pe)) => {
let off = raw.checked_mul(4)?.checked_add(ps)?;
(off.checked_add(4)? <= pe).then_some(())?;
u32_at(self.span(0, off, off + 4)?, 0)? as usize
}
};
let body = at + 8;
// A list cut short by the end of its parent keeps the bytes it has, so the children
// before the cut are read; the caller warns that it is damaged. Other chunks are lost.
let (size, cut) = match body.checked_add(size) {
Some(e) if e <= end => (size, false),
_ if id == LIST => (end.checked_sub(body)?, true),
_ => return None,
};
let next = (body + size + (size & 1)).min(end);
if cut {
return Some((self.chunk(id, src, body, size).map_or(Read::Lost, Read::Chunk), next, true));
}
if self.streams.is_some() && pool.is_none() && size == REDIRECT {
let read = match self.redirect(id, src, body) {
Some(read) => read,
None if self.redirect_past_limit(src, body) => Read::PastLimit,
None => Read::Lost,
};
return Some((read, next, false));
}
Some((Read::Chunk(self.chunk(id, src, body, size)?), next, false))
}
/// Chunk `id` whose body is `len` bytes at `body` of source `src`; a list's body starts with
/// its form type.
fn chunk(&self, id: [u8; 4], src: u32, body: usize, len: usize) -> Option<Chunk> {
let (form, start) = if id == LIST {
let f: [u8; 4] = self.span(src, body, body.checked_add(4).filter(|_| len >= 4)?)?.try_into().ok()?;
(f, body + 4)
} else {
([0; 4], body)
};
let len = len - (start - body);
Some(Chunk { id, form, src, start: u32::try_from(start).ok()?, len: u32::try_from(len).ok()?, first: 0, count: 0 })
}
/// The chunk the redirect record at `body` of `src` stands for (R27): stream, length, offset
/// and a reserved u32. Stream `0xFFFFFFFF` holds at most 8 bytes in the record itself, after
/// the length. The body is not read again as a redirect record. `None` when the body can't
/// be found.
///
/// A redirected list whose bytes overlap those of an earlier redirected list, in any stream of
/// the same package member, is left out, so that no list is split twice. Other chunks may
/// share bytes: each one after the first to read them takes their length from the
/// shared-bytes limit (the member limit), so that many redirects to one body can't decode it
/// without end.
fn redirect(&self, id: [u8; 4], src: u32, body: usize) -> Option<Read> {
let mut r = Rd::new(self.span(src, body, body + REDIRECT)?);
let stream = r.u32()?;
let len = r.u32()? as usize;
if stream == INLINE {
return (len <= 8).then(|| self.chunk(id, src, body + 8, len).map(Read::Chunk))?;
}
let off = r.u32()? as usize;
let streams = self.streams.as_ref()?;
let size = streams.size(stream as usize)?;
let end = off.checked_add(len).filter(|&e| e <= size)?;
let member = streams.member_of(stream as usize)?;
if id == LIST {
if !claim(&self.lists, member, off, end) {
return None;
}
} else if !claim(&self.leaves, member, off, end) {
let left = self.shared_left.get();
if len > left {
return Some(Read::SharedPastLimit);
}
self.shared_left.set(left - len);
}
// Only a list's form type is read now; other bodies are read when the mapping asks.
self.chunk(id, stream.checked_add(1)?, off, len).map(Read::Chunk)
}
/// Does the redirect record at `body` of `src` point into a data stream past a limit?
fn redirect_past_limit(&self, src: u32, body: usize) -> bool {
let stream = self.span(src, body, body + 4).and_then(|b| u32_at(b, 0));
stream.is_some_and(|s| s != INLINE && self.past_limit(s.saturating_add(1)))
}
/// Inflate the two blocks of a `LIST cmpr` body at `start..end` of `src` (R3) → the chunk
/// stream and the size pool, as ranges of source 0.
fn inflate_cmpr(&mut self, src: u32, start: usize, end: usize) -> Result<(usize, usize, (usize, usize)), Error> {
let body = self.span(src, start, end).ok_or(Error::Damaged("compressed list"))?;
let mut r = Rd::new(body);
let c1 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize;
r.skip(4).ok_or(Error::Damaged("compressed list"))?;
let c2 = r.u32().ok_or(Error::Damaged("compressed list"))? as usize;
let block = |at: usize, len: usize| -> Result<&[u8], Error> {
let b = body.get(at..at.checked_add(len).ok_or(Error::Damaged("compressed list"))?).ok_or(Error::Damaged("compressed list"))?;
let mut h = Rd::new(b);
if h.fourcc() != Some(CPNG) || h.fourcc() != Some(CPNG_HEAD) {
return Err(Error::Damaged("compressed block"));
}
Ok(b.get(8..).unwrap_or_default())
};
let second_at = c1.checked_add(16).ok_or(Error::Damaged("compressed list"))?;
let (first, second) = (block(16, c1)?.to_vec(), block(second_at, c2)?.to_vec());
let base = self.input.len();
let stream = self.inflate(&first)?;
let pool = self.inflate(&second)?;
Ok((base + stream.0, base + stream.1, (base + pool.0, base + pool.1)))
}
/// Inflate zlib `data` onto the end of the inflated bytes, within what is left → its range
/// there.
fn inflate(&mut self, data: &[u8]) -> Result<(usize, usize), Error> {
let at = self.inflated.len();
let left = self.left.get();
let reader = flate2::read::ZlibDecoder::new(data);
// One byte past what is left tells a stream that is too long from one that just fits.
let got = match reader.take((left as u64).saturating_add(1)).read_to_end(&mut self.inflated) {
Ok(n) => n,
Err(_) => {
// What a stream inflated before it failed counts toward the limit too, so that
// streams that fail late can't inflate past it again and again.
let produced = self.inflated.len().saturating_sub(at);
self.left.set(left.saturating_sub(produced));
self.inflated.truncate(at);
return Err(Error::Damaged("compressed block"));
}
};
if got > left {
self.inflated.truncate(at);
return Err(Error::Limit("inflated size"));
}
self.left.set(left - got);
if self.input.len().saturating_add(self.inflated.len()) > u32::MAX as usize {
return Err(Error::Limit("inflated size"));
}
Ok((at, at + got))
}
}
/// Take bytes `start..end` of package member `member` in `claimed`, or `false` when an earlier
/// redirect there took any of them. Empty ranges take nothing.
fn claim(claimed: &Cell<BTreeMap<(usize, usize), usize>>, member: usize, start: usize, end: usize) -> bool {
if start == end {
return true;
}
let mut taken = claimed.take();
let before = taken.range(..=(member, start)).next_back().is_some_and(|(&(m, _), &e)| m == member && e > start);
let after = taken.range((member, start)..).next().is_some_and(|(&(m, s), _)| m == member && s < end);
let free = !before && !after;
if free {
taken.insert((member, start), end);
}
claimed.set(taken);
free
}
/// Add `w` to the warnings once.
pub(crate) fn push(warn: &mut Vec<Warning>, w: Warning) {
if !warn.contains(&w) {
warn.push(w);
}
}
+258
View File
@@ -0,0 +1,258 @@
//! The style table in a `LIST stlt` of versions 7 to 15 (R45): the fill and outline records that a
//! style gives the objects that name it and have no fill or outline argument of their own.
use std::collections::{HashMap, HashSet};
use crate::Error;
use crate::bytes::{Rd, u32_at};
use crate::limits::Budget;
/// One style: its parent, and the fill and outline table entries it names (0: none).
#[derive(Clone, Copy)]
struct Style {
parent: u32,
fill: u32,
outline: u32,
}
/// The styles of a drawing: for each style id, the fill and outline records it gives, its
/// parents' included.
#[derive(Default)]
pub(crate) struct Styles {
fills: HashMap<u32, u32>,
outlines: HashMap<u32, u32>,
}
impl Styles {
/// The style table in body `b` of a `LIST stlt` of `version` (R45), or `None` when it doesn't
/// parse to its end. Its fill and outline entries and its styles count toward the chunks a
/// read takes.
pub(crate) fn read(b: &[u8], version: u16, budget: &mut Budget) -> Result<Option<Styles>, Error> {
let mut limit = None;
let styles = parse(b, version, &mut |n| match budget.take_chunks(n) {
Ok(()) => true,
Err(e) => {
limit = Some(e);
false
}
});
match limit {
Some(e) => Err(e),
None => Ok(styles),
}
}
/// The fill record that style `id` gives.
pub(crate) fn fill(&self, id: u32) -> Option<u32> {
self.fills.get(&id).copied()
}
/// The outline record that style `id` gives.
pub(crate) fn outline(&self, id: u32) -> Option<u32> {
self.outlines.get(&id).copied()
}
}
/// The style table in `b`. `take` is asked for each count of entries or styles before they are
/// read; a `false` stops the read.
fn parse(b: &[u8], version: u16, take: &mut dyn FnMut(usize) -> bool) -> Option<Styles> {
let mut r = Rd::new(b);
let count = r.u32()? as usize;
if count == 0 {
return (r.left() == 0).then(Styles::default);
}
// Fill entries carry 48 more bytes from version 13.
let fills = table(&mut r, if version >= 1300 { 60 } else { 12 }, take)?;
let outlines = table(&mut r, 12, take)?;
// The text style tables: fonts, alignments, spacings, two tables of fixed records, bullets,
// indents, hyphenation and drop caps, and from version 8.01 one more.
skip_table(&mut r, if version >= 1000 { 60 } else { 44 })?;
skip_table(&mut r, 12)?;
skip_table(&mut r, 52)?;
skip_table(&mut r, 152)?;
skip_table(&mut r, 784)?;
let bullets = r.u32()?;
for _ in 0..bullets {
bullet(&mut r, version)?;
}
skip_table(&mut r, 28)?;
skip_table(&mut r, if version >= 1300 { 36 } else { 32 })?;
skip_table(&mut r, 28)?;
if version >= 801 {
skip_table(&mut r, 12)?;
}
// Each style is at least 32 bytes.
if count > r.left() / 32 || !take(count) {
return None;
}
let mut styles = HashMap::new();
for _ in 0..count {
let (id, s) = style(&mut r, version)?;
styles.entry(id).or_insert(s);
}
if r.left() != 0 {
return None;
}
let mut work = 0;
Some(Styles { fills: resolve(&styles, &fills, |s| s.fill, &mut work), outlines: resolve(&styles, &outlines, |s| s.outline, &mut work) })
}
/// For each style, the record of `table` that its own entry names, or the nearest parent's where
/// its entry is 0. Each style is resolved once, and each path forgets only the styles on it, so a
/// chain of any length takes time in proportion to the styles; a chain that comes back to a style
/// on it, or reaches a style that isn't there, gives no record. `work` counts the styles visited
/// and forgotten.
fn resolve(styles: &HashMap<u32, Style>, table: &HashMap<u32, u32>, entry: impl Fn(&Style) -> u32, work: &mut usize) -> HashMap<u32, u32> {
// `None`: resolved to no record.
let mut done: HashMap<u32, Option<u32>> = HashMap::new();
let mut path = Vec::new();
let mut on_path = HashSet::new();
for &start in styles.keys() {
let mut id = start;
let found = loop {
*work += 1;
if let Some(&known) = done.get(&id) {
break known;
}
let Some(s) = styles.get(&id) else { break None };
// Back at a style on this path: a cycle.
if !on_path.insert(id) {
break None;
}
path.push(id);
match entry(s) {
0 => id = s.parent,
e => break table.get(&e).copied(),
}
};
for id in path.drain(..) {
*work += 1;
on_path.remove(&id);
done.insert(id, found);
}
}
done.into_iter().filter_map(|(id, r)| Some((id, r?))).collect()
}
/// A table of a u32 count and entries of `size` bytes, each a table id, 4 bytes and a record id.
fn table(r: &mut Rd, size: usize, take: &mut dyn FnMut(usize) -> bool) -> Option<HashMap<u32, u32>> {
let n = r.u32()? as usize;
if n > r.left() / size || !take(n) {
return None;
}
let mut out = HashMap::new();
for _ in 0..n {
let e = r.bytes(size)?;
out.entry(u32_at(e, 0)?).or_insert(u32_at(e, 8)?);
}
Some(out)
}
/// A table of a u32 count and entries of `size` bytes, passed over.
fn skip_table(r: &mut Rd, size: usize) -> Option<()> {
let n = r.u32()? as usize;
r.skip(n.checked_mul(size)?)
}
/// A bullet record, passed over: its length depends on a u32 inside it.
fn bullet(r: &mut Rd, version: u16) -> Option<()> {
r.skip(40)?;
if version >= 1300 {
if version >= 1400 {
r.skip(4)?;
}
let more = r.u32()?;
return r.skip(if more != 0 { 68 } else { 12 });
}
r.skip(if version >= 1000 { 28 } else { 20 })?;
let more = r.u32()?;
if more != 0 {
r.skip(8)?;
}
r.skip(8)
}
/// A style record: its kind (u32), id, parent, 8 bytes, a name length and the name (bytes before
/// version 12, UTF-16 units from it), the fill and outline entries, then the entries of text
/// styles (kinds 2 and 3).
fn style(r: &mut Rd, version: u16) -> Option<(u32, Style)> {
let kind = r.u32()?;
let (id, parent) = (r.u32()?, r.u32()?);
r.skip(8)?;
let len = r.u32()? as usize;
r.skip(len.checked_mul(if version >= 1200 { 2 } else { 1 })?)?;
let (fill, outline) = (r.u32()?, r.u32()?);
if kind > 1 {
r.skip(if version >= 801 { 20 } else { 16 })?;
}
if kind > 2 {
r.skip(20)?;
}
Some((id, Style { parent, fill, outline }))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Limits;
use crate::synth::{self, V};
fn read(b: &[u8], version: u16) -> Option<Styles> {
Styles::read(b, version, &mut Budget::new(Limits::default())).unwrap()
}
#[test]
fn styles_that_name_each_other_as_parents_end() {
let looped = [synth::Style { id: 0x10, parent: 0x11, fill: 0, outline: 0 }, synth::Style { id: 0x11, parent: 0x10, fill: 0, outline: 0 }];
let s = read(&synth::stlt_body(V(700), &[(0x100, 1)], &[], &looped, false), 700).unwrap();
assert_eq!((s.fill(0x10), s.outline(0x11), s.fill(0x12)), (None, None, None));
}
#[test]
fn a_long_chain_of_parents_reaches_the_style_that_names_an_entry() {
let mut chain = vec![synth::Style { id: 1, parent: 0, fill: 0x100, outline: 0 }];
chain.extend((2..=500).map(|id| synth::Style { id, parent: id - 1, fill: 0, outline: 0 }));
let s = read(&synth::stlt_body(V(1100), &[(0x100, 7)], &[], &chain, false), 1100).unwrap();
assert_eq!((s.fill(500), s.fill(250), s.outline(500)), (Some(7), Some(7), None));
}
/// A loop of 2,000 styles, which every walk into it follows around, leaves the walks of 20,000
/// other styles no more work than the styles they visit.
#[test]
fn one_long_walk_does_not_slow_the_walks_after_it() {
let mut styles: HashMap<u32, Style> = (1..=2000).map(|id| (id, Style { parent: id % 2000 + 1, fill: 0, outline: 0 })).collect();
styles.extend((10_001..=30_000).map(|id| (id, Style { parent: 0, fill: 0x100, outline: 0 })));
let table = HashMap::from([(0x100, 7)]);
let mut work = 0;
let fills = resolve(&styles, &table, |s| s.fill, &mut work);
assert_eq!((fills.get(&1), fills.get(&10_001), fills.len()), (None, Some(&7), 20_000));
assert!(work <= 4 * styles.len(), "{work}");
}
#[test]
fn an_entry_missing_from_its_table_names_no_record() {
let styles = [synth::Style { id: 0x10, parent: 0, fill: 0x101, outline: 0x200 }];
let s = read(&synth::stlt_body(V(1300), &[(0x100, 1)], &[(0x200, 2)], &styles, false), 1300).unwrap();
assert_eq!((s.fill(0x10), s.outline(0x10)), (None, Some(2)));
}
#[test]
fn counts_past_the_body_do_not_parse() {
let mut b = synth::stlt_body(V(900), &[], &[], &[], false);
b[..4].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(read(&b, 900).is_none());
let empty = 0u32.to_le_bytes();
assert!(read(&empty, 900).is_some());
assert!(read(&[], 900).is_none());
}
#[test]
fn entries_and_styles_count_toward_the_chunk_limit() {
let styles: Vec<_> = (1..=10).map(|id| synth::Style { id, parent: 0, fill: 0x100, outline: 0 }).collect();
let b = synth::stlt_body(V(1000), &[(0x100, 1)], &[], &styles, false);
let mut budget = Budget::new(Limits { chunks: 10, ..Limits::default() });
assert_eq!(Styles::read(&b, 1000, &mut budget).err(), Some(Error::Limit("chunk count")));
let mut budget = Budget::new(Limits { chunks: 11, ..Limits::default() });
assert!(Styles::read(&b, 1000, &mut budget).is_ok_and(|s| s.is_some()));
}
}
File diff suppressed because it is too large. Load diff
+287
View File
@@ -0,0 +1,287 @@
//! Synthetic `.cmx` files for tests and fuzz seeds, built from the layouts in `PROVENANCE.md` (R53
//! to R63). Not a `.cmx` writer: nothing checks that other programs open these files.
/// A chunk: its id, a u32 size, the body and a pad byte after an odd body (R53).
pub fn chunk(id: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut out = id.to_vec();
out.extend((body.len() as u32).to_le_bytes());
out.extend(body);
if body.len() % 2 == 1 {
out.push(0);
}
out
}
/// A `LIST` chunk of form `form`.
pub fn list(form: &[u8; 4], children: &[Vec<u8>]) -> Vec<u8> {
let mut body = form.to_vec();
body.extend(children.concat());
chunk(b"LIST", &body)
}
/// The RIFF form `CMX1` around `children`.
pub fn riff(children: &[Vec<u8>]) -> Vec<u8> {
let mut body = b"CMX1".to_vec();
body.extend(children.concat());
chunk(b"RIFF", &body)
}
/// The header (R54): `coord` is the coordinate size digit (`b'4'` or `b'2'`) and `meters` the size
/// of a coordinate unit. The header string and the system name, which the reader doesn't read,
/// are left as zeros.
pub fn cont(coord: u8, meters: f64) -> Vec<u8> {
let mut c = vec![0u8; 180];
c[48] = b'2';
c[52] = coord;
c[54] = b'2';
c[64..72].copy_from_slice(&meters.to_le_bytes());
chunk(b"cont", &c)
}
/// A field: its tag, a u16 length counting the 3 header bytes, then `data` (R55).
pub fn field(tag: u8, data: &[u8]) -> Vec<u8> {
let mut f = vec![tag];
f.extend(((data.len() + 3) as u16).to_le_bytes());
f.extend(data);
f
}
/// A field list: the fields, then 0xff (R55).
pub fn fields(fields: &[Vec<u8>]) -> Vec<u8> {
let mut l = fields.concat();
l.push(0xff);
l
}
/// A table chunk: a u16 count, then the entries (field lists) (R55).
pub fn table(id: &[u8; 4], entries: &[Vec<u8>]) -> Vec<u8> {
let mut d = (entries.len() as u16).to_le_bytes().to_vec();
d.extend(entries.concat());
chunk(id, &d)
}
/// A color entry in the older form: the model and palette bytes in field 1, the values in field 2
/// (R56).
pub fn color(model: u8, values: &[u8]) -> Vec<u8> {
fields(&[field(1, &[model, 5]), field(2, values)])
}
/// A color entry with a property list in field 10 whose color record (part 1) holds `model` and
/// the four value bytes `v` (R56).
pub fn color_record(model: u16, v: [u8; 4]) -> Vec<u8> {
color_record_named(model, v, None)
}
/// A color entry as [`color_record`], with a name part (part 3: a u32 count and UTF-16 units)
/// after the color when `name` is given (R56).
pub fn color_record_named(model: u16, v: [u8; 4], name: Option<&str>) -> Vec<u8> {
let mut part = vec![1u8];
part.extend(12u32.to_le_bytes());
part.extend(model.to_le_bytes());
part.extend(5u16.to_le_bytes());
part.extend([0; 4]);
part.extend(v);
if let Some(name) = name {
let units: Vec<u16> = name.encode_utf16().collect();
part.push(3);
part.extend((4 + 2 * units.len() as u32).to_le_bytes());
part.extend((units.len() as u32).to_le_bytes());
part.extend(units.iter().flat_map(|u| u.to_le_bytes()));
}
let mut rec = (part.len() as u32).to_le_bytes().to_vec();
rec.extend(part);
fields(&[field(10, &rec)])
}
/// A pen entry (R57): the width in coordinate units, an aspect of 100 and no angle, with the
/// identity matrix.
pub fn pen(width: u32) -> Vec<u8> {
let mut d = width.to_le_bytes().to_vec();
d.extend(100u16.to_le_bytes());
d.extend(0i32.to_le_bytes());
d.extend(1u16.to_le_bytes());
fields(&[field(1, &d)])
}
/// A line type entry (R57): its flags and the caps (low 4 bits) and join (high 4 bits).
pub fn line_type(flags: u8, caps_join: u8) -> Vec<u8> {
fields(&[field(1, &[flags, caps_join])])
}
/// A dash pattern entry (R57): the lengths in outline widths.
pub fn dashes(lengths: &[u16]) -> Vec<u8> {
let mut d = (lengths.len() as u16).to_le_bytes().to_vec();
d.extend(lengths.iter().flat_map(|l| l.to_le_bytes()));
fields(&[field(1, &d)])
}
/// An outline entry (R58): 1-based indexes of the line type, screen, color, arrowhead pair, pen and
/// dash pattern.
pub fn outline(parts: [u16; 6]) -> Vec<u8> {
fields(&[field(1, &parts.iter().flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())])
}
/// The arrowhead pairs chunk (R59): a u16 count, then start and end (u16 each).
pub fn arrowheads(pairs: &[(u16, u16)]) -> Vec<u8> {
let mut d = (pairs.len() as u16).to_le_bytes().to_vec();
for (s, e) in pairs {
d.extend(s.to_le_bytes());
d.extend(e.to_le_bytes());
}
chunk(b"rota", &d)
}
/// An instruction in the short form: a u16 size counting the whole instruction, the code, the
/// body (R60).
pub fn instr(code: i16, body: &[u8]) -> Vec<u8> {
let mut i = ((body.len() + 4) as u16).to_le_bytes().to_vec();
i.extend(code.to_le_bytes());
i.extend(body);
i
}
/// An instruction in the long form: 0xFFFF, a u32 size counting the whole instruction, the code,
/// the body (R60).
pub fn long_instr(code: i16, body: &[u8]) -> Vec<u8> {
let mut i = 0xFFFFu16.to_le_bytes().to_vec();
i.extend(((body.len() + 8) as u32).to_le_bytes());
i.extend(code.to_le_bytes());
i.extend(body);
i
}
/// Begin a page (R61), with its width and height in coordinate units in field 4 when given.
pub fn begin_page(size: Option<(u32, u32)>) -> Vec<u8> {
let mut f = vec![field(1, &[1, 0, 0, 0, 0, 0])];
if let Some((w, h)) = size {
let mut d = w.to_le_bytes().to_vec();
d.extend(h.to_le_bytes());
f.push(field(4, &d));
}
instr(9, &fields(&f))
}
/// Begin a page (R61) without a size of its own, with the drawing's left, top, right and bottom
/// edges in field 1.
pub fn begin_page_in_bounds(left: i32, top: i32, right: i32, bottom: i32) -> Vec<u8> {
let mut d = vec![1, 0, 0, 0, 0, 0];
for v in [left, top, right, bottom] {
d.extend(v.to_le_bytes());
}
instr(9, &fields(&[field(1, &d)]))
}
/// Begin a layer (R62) named in 8-bit characters in field 1 from byte 12, and in UTF-16 in
/// field 4 when `wide` is given.
pub fn begin_layer(name: &str, wide: Option<&str>) -> Vec<u8> {
let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0];
d.extend((name.len() as u16).to_le_bytes());
d.extend(name.bytes());
let mut f = vec![field(1, &d)];
if let Some(w) = wide {
let units: Vec<u16> = w.encode_utf16().collect();
let mut d = (units.len() as u32).to_le_bytes().to_vec();
d.extend(units.iter().flat_map(|u| u.to_le_bytes()));
f.push(field(4, &d));
}
instr(11, &fields(&f))
}
pub fn end_layer() -> Vec<u8> {
instr(12, &[])
}
pub fn end_page() -> Vec<u8> {
instr(10, &[])
}
pub fn begin_group() -> Vec<u8> {
instr(13, &fields(&[field(1, &[0; 26])]))
}
pub fn end_group() -> Vec<u8> {
instr(14, &[])
}
/// Rendering attributes (R63): a uniform fill of color `fill` and the outline `outline` (1-based
/// indexes; `None` leaves the part out of the mask), and `lens` sets the lens bit.
pub fn attrs(fill: Option<u16>, outline: Option<u16>, lens: bool) -> Vec<u8> {
let mask = u8::from(fill.is_some()) | (u8::from(outline.is_some()) << 1) | (u8::from(lens) << 2);
let mut a = vec![mask];
if let Some(c) = fill {
let mut v = 1u16.to_le_bytes().to_vec();
let mut uniform = c.to_le_bytes().to_vec();
uniform.extend(0u16.to_le_bytes());
v.extend(fields(&[field(1, &uniform)]));
a.extend(fields(&[field(1, &v)]));
}
if let Some(o) = outline {
a.extend(fields(&[field(1, &o.to_le_bytes())]));
}
a
}
/// Rendering attributes with a fill of type `kind` and no settings of its own.
pub fn attrs_fill_type(kind: u16) -> Vec<u8> {
let mut a = vec![1u8];
a.extend(fields(&[field(1, &kind.to_le_bytes())]));
a
}
/// A curve (R62): `attrs`, then a u16 count, the points (i32 x, y) and their type bytes.
pub fn curve(attrs: &[u8], points: &[(i32, i32)], types: &[u8]) -> Vec<u8> {
let mut g = (points.len() as u16).to_le_bytes().to_vec();
for (x, y) in points {
g.extend(x.to_le_bytes());
g.extend(y.to_le_bytes());
}
g.extend(types);
instr(67, &fields(&[field(1, attrs), field(2, &g), field(3, &[0; 16])]))
}
/// A closed square of side `side` with its lower left corner at (`x`, `y`).
pub fn square(attrs: &[u8], x: i32, y: i32, side: i32) -> Vec<u8> {
curve(attrs, &[(x, y), (x + side, y), (x + side, y + side), (x, y + side), (x, y)], &[0x0c, 0x44, 0x44, 0x44, 0x48])
}
/// A `page` chunk of `instructions`.
pub fn page(instructions: &[Vec<u8>]) -> Vec<u8> {
chunk(b"page", &instructions.concat())
}
/// The tables of [`sample`]: colors red (RGB), black (CMYK in percent) and blue (a color record,
/// blue, green, red); pens of 0.5 mm and 1 mm; line types solid with round caps and joins, none,
/// and dashed behind the fill; one dash pattern; three outlines; one empty arrowhead pair.
pub fn tables() -> Vec<Vec<u8>> {
vec![
table(b"rclr", &[color(5, &[255, 0, 0]), color(2, &[0, 0, 0, 100]), color_record(5, [255, 0, 0, 0])]),
table(b"rpen", &[pen(5_000), pen(10_000)]),
table(b"rott", &[line_type(2, 0x11), line_type(1, 0), line_type(2 | 4 | 8, 0x02)]),
table(b"rdot", &[dashes(&[3, 1])]),
table(b"rotl", &[outline([1, 1, 2, 1, 1, 1]), outline([2, 1, 2, 1, 1, 1]), outline([3, 1, 3, 1, 2, 1])]),
arrowheads(&[(0, 0)]),
]
}
/// One page of 210 x 297 mm with two layers: "Art" holds a red square outlined in black, then a
/// group of a square with no outline and a blue one with the dashed outline; "Top" holds a black
/// square drawn last. Units are 0.1 µm.
pub fn sample() -> Vec<u8> {
let p = page(&[
begin_page(Some((2_100_000, 2_970_000))),
begin_layer("Art", None),
square(&attrs(Some(1), Some(1), false), -500_000, -500_000, 1_000_000),
begin_group(),
square(&attrs(Some(2), Some(2), false), 0, 0, 100_000),
square(&attrs(Some(3), Some(3), false), 200_000, 0, 100_000),
end_group(),
end_layer(),
begin_layer("Top", Some("Top")),
square(&attrs(Some(2), None, false), 0, 0, 10_000),
end_layer(),
end_page(),
]);
let mut children = vec![cont(b'4', 1e-7), p];
children.extend(tables());
riff(&children)
}
+358
View File
@@ -0,0 +1,358 @@
//! Drawings of versions 1 and 2: the file before RIFF, which starts with `WL` (R40 to R44). A
//! header of offsets, the settings with the page's box, then one flat list of records: 28 bytes
//! for a group or a layer, and a longer record for each drawn object, which holds its matrix, fill,
//! outline and shape. The reader maps the rectangles, ellipses and curves onto one page with one
//! layer and keeps no groups.
use crate::bytes::{Rd, u32_at};
use crate::geometry;
use crate::layout::{self, Profile};
use crate::limits::Budget;
use crate::model::{Cap, Drawing, Flags, Geometry, Join, Layer, LayerKind, Matrix, Object, Outline, Page, Shape};
use crate::records::{self, coord, fixed};
use crate::riff::push;
use crate::{Error, Warning};
/// The header: the signature, a marker byte, a zero and five u32 offsets (R40).
const HEADER: usize = 28;
/// The marker bytes read after `WL` (R40): `e` for version 1, `l` and `m` for version 2.
const MARKERS: [u8; 3] = *b"elm";
/// Where the page's box lies after the start of the settings (R41).
const PAGE_BOX: usize = 2;
/// The bytes of a group or layer record (R42).
const GROUP: usize = 28;
/// The u32 that starts every record (R42).
const RECORD_START: u32 = 24;
/// The flag bit, in byte 26, of a drawn object (R42).
const DRAWN: u8 = 0x40;
/// The bytes after a drawn object's body size (R42).
const AFTER_BODY: usize = 32;
/// Where a drawn object's fields lie (R43, R44).
const POINT: usize = 32;
const KIND: usize = 60;
const OUTLINED: usize = 67;
const OUTLINE_WIDTH: usize = 68;
const OUTLINE_COLOR: usize = 74;
/// Where a drawn object's fill and shape lie, which differs between the markers (R43, R44).
#[derive(Clone, Copy)]
struct Fields {
fill_kind: usize,
shape: usize,
}
impl Fields {
fn of(marker: u8) -> Self {
if marker == b'e' { Fields { fill_kind: 94, shape: 114 } } else { Fields { fill_kind: 105, shape: 136 } }
}
/// The least a drawn object takes: its fixed fields and the 4 bytes of a shape's size.
fn least(self) -> usize {
self.shape + 4
}
}
/// Object types (R43).
const RECTANGLE: u8 = 0;
const ELLIPSE: u8 = 1;
const CURVE: u8 = 2;
const TEXT: u8 = 3;
/// Where the settings start, and where the records start and end, when `b` has a `WL` header
/// whose offsets fit the file.
fn header(b: &[u8]) -> Option<(usize, usize, usize)> {
if b.get(..2)? != b"WL" || !MARKERS.contains(b.get(2)?) || *b.get(3)? != 0 {
return None;
}
let (settings, start, end) = (u32_at(b, 4)? as usize, u32_at(b, 8)? as usize, u32_at(b, 12)? as usize);
(settings >= HEADER && settings <= start && start <= end && end <= b.len()).then_some((settings, start, end))
}
/// Does `b` start like a drawing of version 1 or 2? The two letters alone are not enough: the
/// marker byte, the zero after it and the record offsets must fit too.
pub(crate) fn is_wl(b: &[u8]) -> bool {
header(b).is_some()
}
pub(crate) fn drawing(b: &[u8], budget: &mut Budget) -> Result<Drawing, Error> {
let (settings, start, end) = header(b).ok_or(Error::NotCdr)?;
let marker = b.get(2).copied().ok_or(Error::NotCdr)?;
let fields = Fields::of(marker);
// Lengths are i16 in 1/1000 inch, as in version 3 (R5).
let p = layout::for_version(layout::OLDEST_RIFF).ok_or(Error::NotCdr)?;
let mut warn = Vec::new();
let mut objects = Vec::new();
let mut at = start;
// Every step takes at least a group record's bytes, so the file's size bounds the steps.
while end - at >= GROUP {
budget.take_chunk()?;
// A record that doesn't start as records do is past one whose length isn't known.
if u32_at(b, at) != Some(RECORD_START) {
break;
}
if b.get(at + 26).is_none_or(|flags| flags & DRAWN == 0) {
at += GROUP;
continue;
}
// A drawn object of another type than rectangle, ellipse, curve and text doesn't say its
// length in the same way, so the records after it can't be found.
if b.get(at + KIND).is_none_or(|kind| *kind > TEXT) {
push(&mut warn, Warning::UnsupportedObjects);
at = end;
break;
}
let len = Rd::at(b, at + 28).u16().map_or(0, |body| usize::from(body) + AFTER_BODY);
let Some(rec) = b.get(at..at + len).filter(|_| len >= fields.least() && at + len <= end) else {
push(&mut warn, Warning::Damaged);
at = end;
break;
};
at += len;
if !budget.take_object() {
push(&mut warn, Warning::TooDeep);
at = end;
break;
}
objects.extend(object(rec, fields, &p, budget, &mut warn));
}
if at != end {
push(&mut warn, Warning::Damaged);
}
let version = if marker == b'e' { 100 } else { 200 };
let layer = Layer { name: String::new(), kind: LayerKind::Drawing, flags: Flags::default(), objects, guides: Vec::new() };
let pages = vec![Page { size: None, layers: vec![layer] }];
Ok(Drawing { version, page_size: page_box(b, settings, &p), pages, master: Vec::new(), guides: Vec::new(), warnings: warn })
}
/// The page's size from its box (R41): left, top, right and bottom around the page's centre.
fn page_box(b: &[u8], settings: usize, p: &Profile) -> Option<(f64, f64)> {
let mut r = Rd::at(b, settings + PAGE_BOX);
let (left, top, right, bottom) = (coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?, coord(&mut r, p)?);
let (w, h) = ((right - left).abs(), (top - bottom).abs());
(w > 0.0 && h > 0.0).then_some((w, h))
}
/// One drawn object's record (R43, R44): a shape, or `None` with a warning for text, for an object
/// of another type and for a shape that can't be read.
fn object(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Object> {
// A curve left out at the coordinate limit is not damage.
budget.coordinates_refused();
let read = shape(rec, fields, p, budget, warn);
if read.is_none() && !budget.coordinates_refused() {
push(warn, Warning::Damaged);
}
read?.map(|s| Object::Shape(Box::new(s)))
}
/// The shape of a record. The outer `None` is a record that can't be read; the inner one an object
/// the reader leaves out, with its warning.
fn shape(rec: &[u8], fields: Fields, p: &Profile, budget: &mut Budget, warn: &mut Vec<Warning>) -> Option<Option<Shape>> {
let k = p.unit();
let mut r = Rd::at(rec, POINT);
let (x, y) = (f64::from(r.i16()?), f64::from(r.i16()?));
// x' = a x + b y + tx + x of the point, y' = c x + d y + ty + y of the point.
let (a, b, tx, c, d, ty) = (fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?, fixed(&mut r)?);
let matrix = Matrix([a, c, b, d, (tx + x) * k, (ty + y) * k]);
let body = rec.get(fields.shape..)?;
let geometry = match *rec.get(KIND)? {
RECTANGLE => rect(body, p)?,
ELLIPSE => {
let mut s = Rd::new(body);
let (w, h) = (coord(&mut s, p)?, coord(&mut s, p)?);
// Two angles follow. No source confirms how they make an arc, so an ellipse whose
// angles differ is left out; one whose angles are missing is damage.
let (from, to) = (s.i16()?, s.i16()?);
if from != to {
push(warn, Warning::UnsupportedObjects);
return Some(None);
}
Geometry::Ellipse { w, h }
}
CURVE => Geometry::Path(geometry::point_list(body, p, budget, warn)?),
_ => {
push(warn, Warning::UnsupportedObjects);
return Some(None);
}
};
let color_at = |at: usize, warn: &mut Vec<Warning>| Some(records::color5(rec.get(at..at + 5)?.try_into().ok()?, warn));
let fill = match *rec.get(fields.fill_kind)? {
0 => None,
1 => Some(color_at(fields.fill_kind + 1, warn)?),
_ => {
push(warn, Warning::UnsupportedFills);
None
}
};
let outline = if *rec.get(OUTLINED)? != 0 {
let width = f64::from(Rd::at(rec, OUTLINE_WIDTH).u16()?) * k;
Some(Outline {
width,
color: color_at(OUTLINE_COLOR, warn)?,
cap: Cap::Butt,
join: Join::Miter,
dashes: Vec::new(),
behind_fill: false,
scale_with: false,
})
} else {
None
};
Some(Some(Shape::new(geometry, matrix, fill, outline)))
}
/// A rectangle (R44): its width and height, then a corner radius, which is kept when it is at most
/// half the shorter side.
fn rect(body: &[u8], p: &Profile) -> Option<Geometry> {
let mut r = Rd::new(body);
let (w, h) = (coord(&mut r, p)?, coord(&mut r, p)?);
let radius = coord(&mut r, p).filter(|v| *v > 0.0 && *v <= w.abs().min(h.abs()) / 2.0).unwrap_or(0.0);
Some(Geometry::Rect { w, h, radii: [radius; 4] })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Limits;
use crate::model::Color;
use crate::synth::{self, WlShape};
fn read(b: &[u8]) -> Result<Drawing, Error> {
drawing(b, &mut Budget::new(Limits::default()))
}
#[test]
fn the_header_is_taken_only_when_its_offsets_fit() {
let file = synth::wl_file(b'e', (612.0, 792.0), &[synth::wl_group()]);
assert!(is_wl(&file));
// The two letters, a marker and a zero are not enough.
assert!(!is_wl(b"WLe\0"));
assert!(!is_wl(b"WLe\0 and then some text that is long enough to hold offsets"));
let with = |at: usize, v: u32| {
let mut f = file.clone();
f[at..at + 4].copy_from_slice(&v.to_le_bytes());
f
};
// Records that start inside the header, start after their end, or end past the file.
assert!(!is_wl(&with(8, 27)));
assert!(!is_wl(&with(8, file.len() as u32)));
assert!(!is_wl(&with(12, file.len() as u32 + 1)));
// Settings that start inside the header or after the records.
assert!(!is_wl(&with(4, 27)));
assert!(!is_wl(&with(4, 65)));
let mut other = file.clone();
other[2] = b'x';
assert!(!is_wl(&other));
// No sample shows the marker `d`, so it is not taken.
other[2] = b'd';
assert!(!is_wl(&other));
for marker in *b"lm" {
assert!(is_wl(&synth::wl_file(marker, (612.0, 792.0), &[synth::wl_group()])));
}
other[2] = b'e';
other[3] = 1;
assert!(!is_wl(&other));
}
#[test]
fn a_version_2_file_keeps_its_page_box_fill_and_shape_where_that_version_puts_them() {
let (red, black) = ([1, 0, 100, 100, 0], [1, 0, 0, 0, 100]);
let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 9.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some(red), Some((2.0, black)));
for marker in *b"elm" {
let file = synth::wl_file(marker, (720.0, 504.0), std::slice::from_ref(&rect));
// Version 2 files start their settings after a picture, not after the header.
assert_eq!(u32_at(&file, 4) == Some(28), marker == b'e');
let d = read(&file).unwrap();
let near = |a: f64, b: f64| (a - b).abs() < 0.02;
assert_eq!((d.version, d.warnings.clone()), (if marker == b'e' { 100 } else { 200 }, vec![]));
assert!(d.page_size.is_some_and(|(w, h)| near(w, 720.0) && near(h, 504.0)), "{:?}", d.page_size);
let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") };
assert!(
matches!(s.geometry, Geometry::Rect { w, h, radii } if near(w, 72.0) && near(h, 36.0) && near(radii[0], 9.0)),
"{}",
marker as char
);
assert_eq!(s.fill, Some(Color::Cmyk([0.0, 1.0, 1.0, 0.0])), "{}", marker as char);
assert!(s.outline.as_ref().is_some_and(|o| near(o.width, 2.0) && o.color == Color::Cmyk([0.0, 0.0, 0.0, 1.0])), "{}", marker as char);
}
}
#[test]
fn a_drawn_object_is_marked_by_its_flag_bit() {
let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], None, None);
let mut file = synth::wl_file(b'l', (612.0, 792.0), &[rect]);
// Files with the marker `l` set another flag bit beside it.
file[64 + 26] = 0xc0;
let d = read(&file).unwrap();
assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![]));
}
#[test]
fn the_walk_stops_where_records_can_no_longer_be_found() {
let unit = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
let rect = || synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, unit, None, None);
// An object of another type doesn't give its length in the same way.
let mut other = rect();
other[KIND] = 0xff;
let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[rect(), other, rect()])).unwrap();
assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::UnsupportedObjects]));
// A record that doesn't start as records do.
let mut lost = rect();
lost[0] = 0x84;
let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect(), lost, rect()])).unwrap();
assert_eq!((d.pages[0].layers[0].objects.len(), d.warnings), (1, vec![Warning::Damaged]));
}
#[test]
fn a_rectangle_keeps_a_radius_of_at_most_half_its_shorter_side() {
let p = layout::for_version(300).unwrap();
let body = |radius: i16| [1000i16, 500, radius].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>();
let radius_of = |b: &[u8]| match rect(b, &p) {
Some(Geometry::Rect { w, h, radii }) if (w - 72.0).abs() < 1e-9 && (h - 36.0).abs() < 1e-9 => radii[0],
other => panic!("{other:?}"),
};
assert!((radius_of(&body(200)) - 14.4).abs() < 1e-9);
for radius in [300, -5, 0] {
assert_eq!(radius_of(&body(radius)), 0.0, "{radius}");
}
// A record that ends after the size has square corners.
assert_eq!(radius_of(&body(200)[..4]), 0.0);
assert_eq!(rect(&body(200)[..3], &p), None);
}
#[test]
fn a_record_shorter_than_its_fields_ends_the_walk_as_damage() {
let rect = synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None);
let mut short = rect.clone();
// A body size that leaves less than the fixed fields.
short[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY - 1) as u16).to_le_bytes());
let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[rect.clone(), short, rect])).unwrap();
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
assert_eq!(d.warnings, vec![Warning::Damaged]);
}
#[test]
fn an_ellipse_without_its_angles_is_damage() {
let ellipse =
synth::wl_object(WlShape::Ellipse { w: 72.0, h: 36.0, angles: (0, 0) }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([1, 0, 0, 0, 100]), None);
let mut cut = ellipse.clone();
// A body size that ends the record after the ellipse's width and height.
cut[28..30].copy_from_slice(&((Fields::of(b'e').least() - AFTER_BODY) as u16).to_le_bytes());
cut.truncate(Fields::of(b'e').least());
let d = read(&synth::wl_file(b'e', (612.0, 792.0), &[ellipse, cut])).unwrap();
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
assert_eq!(d.warnings, vec![Warning::Damaged]);
}
#[test]
fn fill_types_other_than_uniform_and_unknown_inks_are_named() {
let mut textured =
synth::wl_object(WlShape::Rect { w: 72.0, h: 36.0, radius: 0.0 }, [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], Some([0, 9, 0, 50, 0]), None);
let d = read(&synth::wl_file(b'm', (612.0, 792.0), std::slice::from_ref(&textured))).unwrap();
let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") };
assert_eq!(s.fill, Some(Color::Spot { name: "Spot 0:9".into(), tint: 0.5, look: None }));
assert_eq!((d.version, d.warnings), (200, vec![Warning::SpotLooks]));
textured[Fields::of(b'e').fill_kind] = 5;
let d = read(&synth::wl_file(b'm', (612.0, 792.0), &[textured])).unwrap();
let Object::Shape(s) = &d.pages[0].layers[0].objects[0] else { panic!("group") };
assert_eq!((s.fill.clone(), d.warnings), (None, vec![Warning::UnsupportedFills]));
}
}
+308
View File
@@ -0,0 +1,308 @@
//! The ZIP archives of `.cdr` drawings from version 14 on (R24): the central directory, then stored
//! and deflated members read on request. Archives that span disks, ZIP64 archives and encrypted
//! members are refused; so are directories whose members overlap or repeat a name.
use std::borrow::Cow;
use std::io::Read as _;
use crate::Error;
use crate::bytes::Rd;
/// End of central directory record: signature and fixed length.
const END: u32 = 0x0605_4b50;
const END_LEN: usize = 22;
/// The longest archive comment, which the end record may be followed by.
const MAX_COMMENT: usize = 0xFFFF;
/// ZIP64 end of central directory locator, 20 bytes before the end record when present.
const ZIP64_LOCATOR: u32 = 0x0706_4b50;
/// Central directory header: signature and fixed length.
const CENTRAL: u32 = 0x0201_4b50;
const CENTRAL_LEN: usize = 46;
/// Local file header: signature and fixed length.
const LOCAL: u32 = 0x0403_4b50;
const LOCAL_LEN: usize = 30;
/// General purpose flag bit 0: the member is encrypted.
const ENCRYPTED: u16 = 1;
const STORED: u16 = 0;
const DEFLATED: u16 = 8;
/// What members packed by another method are refused as.
const OTHER_METHODS: &str = "package compression methods other than storing and deflate";
/// One member, as the central directory and its local header give it.
#[derive(Clone, Copy, Debug)]
struct Entry<'a> {
name: &'a [u8],
flags: u16,
method: u16,
crc: u32,
packed: usize,
size: usize,
/// Where its local header starts and where its packed bytes start.
header: usize,
data: usize,
}
/// An archive's directory over its bytes.
#[derive(Debug)]
pub(crate) struct Archive<'a> {
bytes: &'a [u8],
entries: Vec<Entry<'a>>,
/// The entries in name order, for lookups.
by_name: Vec<usize>,
}
/// Does `bytes` start with a local file header?
pub(crate) fn is_zip(bytes: &[u8]) -> bool {
bytes.starts_with(b"PK\x03\x04")
}
impl<'a> Archive<'a> {
/// The directory of `bytes`, holding at most `max_entries` members.
pub(crate) fn open(bytes: &'a [u8], max_entries: usize) -> Result<Self, Error> {
let end = find_end(bytes).ok_or(Error::Damaged("package directory"))?;
if end >= 20 && Rd::at(bytes, end - 20).u32() == Some(ZIP64_LOCATOR) {
return Err(Error::Unsupported("ZIP64 packages"));
}
let mut r = Rd::at(bytes, end + 4);
let dir = || Error::Damaged("package directory");
let (disk, dir_disk) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?);
let (on_disk, total) = (r.u16().ok_or_else(dir)?, r.u16().ok_or_else(dir)?);
let (dir_len, dir_at) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?);
if total == u16::MAX || dir_len == u32::MAX || dir_at == u32::MAX {
return Err(Error::Unsupported("ZIP64 packages"));
}
if disk != 0 || dir_disk != 0 || on_disk != total {
return Err(Error::Unsupported("packages split across files"));
}
let total = usize::from(total);
if total > max_entries {
return Err(Error::Limit("package member count"));
}
let (dir_at, dir_len) = (dir_at as usize, dir_len as usize);
let dir_end = dir_at.checked_add(dir_len).filter(|&e| e <= end).ok_or_else(dir)?;
let mut r = Rd::at(bytes, dir_at);
let mut entries = Vec::with_capacity(total);
for _ in 0..total {
let e = central_entry(bytes, &mut r, dir_end)?;
entries.push(e);
}
// Each member's bytes end before the next member's header and before the directory.
let mut order: Vec<&Entry> = entries.iter().collect();
order.sort_unstable_by_key(|e| e.header);
for (i, e) in order.iter().enumerate() {
let stop = order.get(i + 1).map_or(dir_at, |n| n.header);
if e.data.checked_add(e.packed).is_none_or(|x| x > stop) {
return Err(Error::Damaged("package members overlap"));
}
}
let mut by_name: Vec<usize> = (0..entries.len()).collect();
by_name.sort_unstable_by_key(|&i| entries.get(i).map(|e| e.name));
let name = |i: &usize| entries.get(*i).map(|e| e.name);
if by_name.windows(2).any(|w| name(&w[0]) == name(&w[1])) {
return Err(Error::Damaged("package member named twice"));
}
Ok(Archive { bytes, entries, by_name })
}
/// The member named `name`.
pub(crate) fn find(&self, name: &[u8]) -> Option<usize> {
let at = self.by_name.binary_search_by(|&i| self.entries.get(i).map(|e| e.name).cmp(&Some(name))).ok()?;
self.by_name.get(at).copied()
}
/// The size member `i`'s directory entry gives.
pub(crate) fn size(&self, i: usize) -> usize {
self.entries.get(i).map_or(0, |e| e.size)
}
/// How many members the archive holds.
pub(crate) fn count(&self) -> usize {
self.entries.len()
}
/// The bytes reading member `i` may inflate: its stated size when it is deflated, else 0.
pub(crate) fn inflate_cost(&self, i: usize) -> usize {
self.entries.get(i).filter(|e| e.method == DEFLATED).map_or(0, |e| e.size)
}
/// An error when member `i` is encrypted or packed by a method other than storing or deflate.
pub(crate) fn check(&self, i: usize) -> Result<(), Error> {
let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?;
if e.flags & ENCRYPTED != 0 {
return Err(Error::Unsupported("encrypted packages"));
}
if e.method != STORED && e.method != DEFLATED {
return Err(Error::Unsupported(OTHER_METHODS));
}
Ok(())
}
/// Member `i`'s bytes when they come to at most `limit`, and a deflated member's when they
/// also come to at most `inflate_left`. A stored member is borrowed; a deflated one inflates to
/// at most its stated size plus one byte, so a member that inflates past what it states stops
/// there. The length and CRC-32 must match the directory's.
pub(crate) fn read(&self, i: usize, limit: usize, inflate_left: usize) -> Result<Cow<'a, [u8]>, Error> {
self.check(i)?;
let e = self.entries.get(i).ok_or(Error::Damaged("package member"))?;
if e.size > limit {
return Err(Error::Limit("package member size"));
}
if e.method == DEFLATED && e.size > inflate_left {
return Err(Error::Limit("inflated size"));
}
let packed = self.bytes.get(e.data..e.data + e.packed).ok_or(Error::Damaged("package member"))?;
let out: Cow<'a, [u8]> = match e.method {
STORED if e.packed == e.size => Cow::Borrowed(packed),
STORED => return Err(Error::Damaged("package member")),
DEFLATED => {
let mut out = Vec::new();
let got = flate2::read::DeflateDecoder::new(packed)
.take(e.size as u64 + 1)
.read_to_end(&mut out)
.map_err(|_| Error::Damaged("package member"))?;
if got != e.size {
return Err(Error::Damaged("package member"));
}
Cow::Owned(out)
}
_ => return Err(Error::Unsupported(OTHER_METHODS)),
};
if crc32fast::hash(&out) != e.crc {
return Err(Error::Damaged("package member"));
}
Ok(out)
}
}
/// Where the end of central directory record starts: searched back from the end over at most the
/// longest comment, among the records whose comment reaches exactly to the end the first that
/// names members in a directory before it, else the first. A comment or a member may hold bytes
/// that look like an empty archive's end record.
fn find_end(bytes: &[u8]) -> Option<usize> {
let last = bytes.len().checked_sub(END_LEN)?;
let first = last.saturating_sub(MAX_COMMENT);
let mut found = None;
for at in (first..=last).rev() {
let mut r = Rd::at(bytes, at);
if r.u32() != Some(END) || r.skip(6).is_none() {
continue;
}
let (total, dir_len, dir_at, comment) = (r.u16(), r.u32(), r.u32(), r.u16());
if !comment.is_some_and(|c| at + END_LEN + usize::from(c) == bytes.len()) {
continue;
}
let names_members = total.is_some_and(|t| t > 0)
&& dir_len.zip(dir_at).is_some_and(|(len, dir)| {
(dir as usize).checked_add(len as usize).is_some_and(|e| e <= at) && Rd::at(bytes, dir as usize).u32() == Some(CENTRAL)
});
if names_members {
return Some(at);
}
found = found.or(Some(at));
}
found
}
/// The central directory entry at `r` (before `dir_end`) and its local header.
fn central_entry<'a>(bytes: &'a [u8], r: &mut Rd<'a>, dir_end: usize) -> Result<Entry<'a>, Error> {
let dir = || Error::Damaged("package directory");
if r.pos().checked_add(CENTRAL_LEN).is_none_or(|e| e > dir_end) || r.u32() != Some(CENTRAL) {
return Err(dir());
}
r.skip(4).ok_or_else(dir)?;
let flags = r.u16().ok_or_else(dir)?;
let method = r.u16().ok_or_else(dir)?;
r.skip(4).ok_or_else(dir)?;
let crc = r.u32().ok_or_else(dir)?;
let (packed, size) = (r.u32().ok_or_else(dir)?, r.u32().ok_or_else(dir)?);
let name_len = usize::from(r.u16().ok_or_else(dir)?);
let extra_len = usize::from(r.u16().ok_or_else(dir)?);
let comment_len = usize::from(r.u16().ok_or_else(dir)?);
let disk = r.u16().ok_or_else(dir)?;
r.skip(6).ok_or_else(dir)?;
let header = r.u32().ok_or_else(dir)?;
if packed == u32::MAX || size == u32::MAX || header == u32::MAX {
return Err(Error::Unsupported("ZIP64 packages"));
}
if disk != 0 {
return Err(Error::Unsupported("packages split across files"));
}
let name = r.bytes(name_len).ok_or_else(dir)?;
r.skip(extra_len).and_then(|()| r.skip(comment_len)).ok_or_else(dir)?;
if r.pos() > dir_end {
return Err(dir());
}
// The local header repeats the name; its own extra field may differ in length.
let header = header as usize;
let mut l = Rd::at(bytes, header);
let local = || Error::Damaged("package member header");
if l.u32() != Some(LOCAL) {
return Err(local());
}
// The signature, 22 bytes, then the name and extra field lengths.
l.skip(LOCAL_LEN - 8).ok_or_else(local)?;
let (local_name, local_extra) = (usize::from(l.u16().ok_or_else(local)?), usize::from(l.u16().ok_or_else(local)?));
if l.bytes(local_name) != Some(name) {
return Err(local());
}
l.skip(local_extra).ok_or_else(local)?;
Ok(Entry { name, flags, method, crc, packed: packed as usize, size: size as usize, header, data: l.pos() })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::synth::{Member, zip};
fn stored(name: &str, data: &[u8]) -> Member {
Member { name: name.into(), data: data.to_vec(), deflate: false }
}
#[test]
fn stored_and_deflated_members_read_back() {
let bytes = zip(&[stored("a", b"hello"), Member { name: "b".into(), data: vec![7; 5000], deflate: true }], b"");
let a = Archive::open(&bytes, 10).unwrap();
assert!(matches!(a.read(a.find(b"a").unwrap(), 100, 100).unwrap(), Cow::Borrowed(b"hello")));
assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 5000).unwrap().as_ref(), &[7; 5000][..]);
assert_eq!(a.read(a.find(b"b").unwrap(), 4999, 5000), Err(Error::Limit("package member size")));
assert_eq!(a.find(b"c"), None);
// What is left to inflate holds back deflated members only.
assert_eq!(a.read(a.find(b"b").unwrap(), 5000, 4999), Err(Error::Limit("inflated size")));
assert!(a.read(a.find(b"a").unwrap(), 100, 0).is_ok());
}
#[test]
fn the_end_record_is_found_behind_a_comment() {
let bytes = zip(&[stored("a", b"x")], &[b'c'; 300]);
assert!(Archive::open(&bytes, 10).is_ok());
// A comment longer than the record says leaves no end record to find.
let mut cut = bytes.clone();
cut.push(0);
assert_eq!(Archive::open(&cut, 10).unwrap_err(), Error::Damaged("package directory"));
// A comment that ends in bytes like an empty archive's end record: the record that names
// members in a directory is the archive's.
let mut fake = END.to_le_bytes().to_vec();
fake.resize(END_LEN, 0);
let bytes = zip(&[stored("a", b"x")], &fake);
let a = Archive::open(&bytes, 10).unwrap();
assert_eq!(a.count(), 1);
}
#[test]
fn a_member_whose_crc_or_length_is_wrong_is_damage() {
let bytes = zip(&[Member { name: "a".into(), data: vec![1; 64], deflate: true }], b"");
let a = Archive::open(&bytes, 10).unwrap();
// The directory's CRC-32 sits 16 bytes into its entry.
let dir_at = bytes.windows(4).position(|w| w == CENTRAL.to_le_bytes()).unwrap();
let mut bad = bytes.clone();
bad[dir_at + 16] ^= 1;
let b = Archive::open(&bad, 10).unwrap();
assert_eq!(b.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member"));
// A stated size one short: the inflate runs past it.
let mut short = bytes.clone();
short[dir_at + 24] -= 1;
let s = Archive::open(&short, 10).unwrap();
assert_eq!(s.read(0, 1000, 1000).unwrap_err(), Error::Damaged("package member"));
assert!(a.read(0, 1000, 1000).is_ok());
}
}
+65
View File
@@ -0,0 +1,65 @@
//! Read time of a large synthetic drawing. Run with
//! `cargo test --release -p craft-cdr --test it bench -- --ignored --nocapture`.
use craft_cdr::synth::{self, V, chunk, list};
use craft_cdr::{Limits, read};
/// A version 13 drawing of `n` curves of 22 points each, filled and outlined, compressed when
/// `compress`.
fn many_curves(n: usize, compress: bool) -> Vec<u8> {
let v = V(1300);
let red = synth::color(5, [0, 0, 255, 0]);
let black = synth::color(2, [0, 0, 0, 100]);
let styles = list(
b"doc ",
vec![
synth::mcfg(v, 612.0, 792.0),
list(b"filt", vec![chunk(b"fild", v.fill(1, &red))]),
list(b"otlt", vec![chunk(b"outl", v.outline(2, synth::Pen { line_type: 0, width: 1.0, cap: 0, join: 0 }, &black, &[]))]),
],
);
let objects: Vec<_> = (0..n)
.map(|i| {
let o = (i % 500) as f64;
// A move, then curves of two control points and an end point each.
let kind = |k: i32| {
if k == 0 {
0x08
} else if k % 3 == 0 {
0x80
} else {
0xC0
}
};
let pts: Vec<(f64, f64, u8)> = (0..22).map(|k| (o + f64::from(k), o + f64::from(k % 5), kind(k))).collect();
let args = vec![(20, 1u32.to_le_bytes().to_vec()), (10, 2u32.to_le_bytes().to_vec()), (30, v.points(&pts))];
synth::object(v, 3, &args, Some([1.0, 0.0, 0.0, 1.0, o, -o]))
})
.collect();
let page = synth::page(false, vec![synth::layer(v, [0, 0, 0, 0x98], "Art", objects)]);
let body = vec![styles, page];
let mut kids = vec![chunk(b"vrsn", 1300u16.to_le_bytes().to_vec())];
if compress {
kids.push(synth::cmpr(&body));
} else {
kids.extend(body);
}
synth::riff(1300, &kids)
}
#[test]
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
fn read_a_large_drawing() {
for compress in [false, true] {
let file = many_curves(50_000, compress);
let mut times = Vec::new();
for _ in 0..5 {
let t = std::time::Instant::now();
let d = read(&file, Limits::default()).unwrap();
times.push(t.elapsed().as_secs_f64() * 1000.0);
assert_eq!(d.pages.len(), 1);
}
times.sort_by(f64::total_cmp);
println!("compress={compress} bytes={} median_ms={:.1} min_ms={:.1}", file.len(), times[2], times[0]);
}
}
+568
View File
@@ -0,0 +1,568 @@
//! Reading synthetic `.cmx` files built from the layouts in `PROVENANCE.md` (R53 to R63), and
//! hostile ones.
use craft_cdr::model::{Cap, Color, Geometry, Join, Object, Shape};
use craft_cdr::synth_cmx::*;
use craft_cdr::{Error, Limits, Warning, is_cdr, is_cmx, read_cmx};
use proptest::prelude::*;
fn shape(o: &Object) -> &Shape {
match o {
Object::Shape(s) => s,
other => panic!("not a shape: {other:?}"),
}
}
/// The (x, y) bounds of a shape's path.
fn bounds(s: &Shape) -> (f64, f64, f64, f64) {
let Geometry::Path(p) = &s.geometry else { panic!("not a path") };
let mut b = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
for sp in &p.subpaths {
for pt in std::iter::once(sp.start).chain(sp.segments.iter().map(|s| match s {
craft_cdr::model::Segment::Line(p) | craft_cdr::model::Segment::Cubic(_, _, p) => *p,
})) {
b = (b.0.min(pt.x), b.1.min(pt.y), b.2.max(pt.x), b.3.max(pt.y));
}
}
b
}
fn near(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6
}
/// The file with `children` after a 32-bit header and the sample tables.
fn file(pages: &[Vec<u8>]) -> Vec<u8> {
let mut children = vec![cont(b'4', 1e-7)];
children.extend(pages.iter().cloned());
children.extend(tables());
riff(&children)
}
#[test]
fn a_cmx_file_is_told_from_a_cdr_drawing() {
let f = sample();
assert!(is_cmx(&f) && !is_cdr(&f));
let mut rifx = f.clone();
rifx[..4].copy_from_slice(b"RIFX");
assert!(is_cmx(&rifx));
assert!(!is_cmx(b"RIFF\0\0\0\0CDR9"));
assert_eq!(read_cmx(b"RIFF\0\0\0\0CDR9", Limits::default()), Err(Error::NotCmx));
}
#[test]
fn pages_layers_groups_and_curves() {
let d = read_cmx(&sample(), Limits::default()).unwrap();
assert_eq!(d.version, 0);
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
let page = &d.pages[0];
// 2,100,000 units of 0.1 µm are 210 mm.
let (w, h) = page.size.unwrap();
assert!(near(w, 210.0 / 25.4 * 72.0) && near(h, 297.0 / 25.4 * 72.0), "{w} {h}");
// The layer drawn last is in front: the model lists layers front to back.
let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, ["Top", "Art"]);
let art = &page.layers[1].objects;
assert_eq!(art.len(), 2);
// The group, drawn after the red square, is in front of it.
let Object::Group { objects: kids, .. } = &art[0] else { panic!("{:?}", art[0]) };
assert_eq!(kids.len(), 2);
let red = shape(&art[1]);
assert_eq!(red.fill, Some(Color::Rgb([1.0, 0.0, 0.0])));
// 1,000,000 units are 100 mm; the square's corner is 50 mm left of and below the center.
let mm = 72.0 / 25.4;
let b = bounds(red);
assert!(near(b.0, -50.0 * mm) && near(b.1, -50.0 * mm) && near(b.2, 50.0 * mm) && near(b.3, 50.0 * mm), "{b:?}");
let Geometry::Path(p) = &red.geometry else { panic!() };
assert!(p.subpaths.len() == 1 && p.subpaths[0].closed && p.subpaths[0].segments.len() == 4);
let o = red.outline.as_ref().unwrap();
assert!(near(o.width, 0.5 * mm));
assert_eq!((o.color.clone(), o.cap, o.join), (Color::Cmyk([0.0, 0.0, 0.0, 1.0]), Cap::Round, Join::Round));
assert!(o.dashes.is_empty() && !o.behind_fill && !o.scale_with);
// Line type 1 draws no outline.
let blue = shape(&kids[0]);
let black = shape(&kids[1]);
assert!(black.outline.is_none());
assert_eq!(black.fill, Some(Color::Cmyk([0.0, 0.0, 0.0, 1.0])));
// The color record's values are blue, green and red.
assert_eq!(blue.fill, Some(Color::Rgb([0.0, 0.0, 1.0])));
let o = blue.outline.as_ref().unwrap();
assert!(near(o.width, 1.0 * mm));
assert_eq!((o.dashes.clone(), o.behind_fill, o.cap, o.join), (vec![3.0, 1.0], true, Cap::Square, Join::Miter));
assert_eq!(page.layers[0].name, "Top");
}
#[test]
fn layer_names_and_layers_without_objects() {
let p = page(&[
begin_page(None),
begin_layer("Ebene 1", Some("Слой 1")),
square(&attrs(Some(1), None, false), 0, 0, 1000),
end_layer(),
begin_layer("Gitter", None),
end_layer(),
begin_layer("Caf\u{e9}", None),
square(&attrs(Some(1), None, false), 0, 0, 1000),
end_layer(),
end_page(),
]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let page = &d.pages[0];
assert_eq!(page.size, None);
// The empty layer is left out, and the UTF-16 name wins over the 8-bit one.
let names: Vec<&str> = page.layers.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, ["Caf\u{c3}\u{a9}", "Слой 1"]);
}
#[test]
fn objects_before_any_layer_get_one() {
let p = page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
assert_eq!(d.pages[0].layers.len(), 1);
// The layer is left unnamed, as a `.cdr` drawing's is; the importer names it by its place.
assert_eq!(d.pages[0].layers[0].name, "");
}
#[test]
fn a_page_without_a_size_takes_the_drawings_bounds() {
// A square of 100 mm whose bounds lie off the file's origin, above and to the right.
let p = page(&[
begin_page_in_bounds(1_000_000, 3_000_000, 2_000_000, 2_000_000),
begin_layer("L", None),
square(&attrs(Some(1), None, false), 1_000_000, 2_000_000, 1_000_000),
end_layer(),
end_page(),
]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let page = &d.pages[0];
let side = 100.0 / 25.4 * 72.0;
let (w, h) = page.size.unwrap();
assert!(near(w, side) && near(h, side), "{w} x {h}");
// The page is centered on the bounds, so the square fills it.
let (x0, y0, x1, y1) = bounds(shape(&page.layers[0].objects[0]));
assert!(near(x0, -side / 2.0) && near(x1, side / 2.0) && near(y0, -side / 2.0) && near(y1, side / 2.0), "{x0} {y0} {x1} {y1}");
}
#[test]
fn curves_and_open_groups() {
let c =
curve(&attrs(None, Some(1), false), &[(0, 0), (100, 0), (100, 100), (0, 100), (200, 200), (300, 200)], &[0x00, 0xc0, 0xc0, 0x84, 0x00, 0x44]);
// A group the layer leaves open closes with it.
let p = page(&[begin_page(None), begin_layer("L", None), begin_group(), c, end_layer()]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
let objects = &d.pages[0].layers[0].objects;
let Object::Group { objects: kids, .. } = &objects[0] else { panic!("{objects:?}") };
let s = shape(&kids[0]);
assert!(s.fill.is_none());
let Geometry::Path(p) = &s.geometry else { panic!() };
assert_eq!(p.subpaths.len(), 2);
assert!(matches!(p.subpaths[0].segments[..], [craft_cdr::model::Segment::Cubic(..)]));
assert!(!p.subpaths[1].closed);
}
#[test]
fn a_curve_without_its_points_is_reported() {
let p = page(&[begin_page(None), begin_layer("L", None), instr(67, &fields(&[field(1, &attrs(Some(1), None, false))])), end_layer()]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
}
#[test]
fn a_layer_name_too_short_to_read_in_utf_16_reads_in_8_bit() {
let mut d = vec![1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0];
d.extend(b"Art");
let layer = instr(11, &fields(&[field(1, &d), field(4, &[3, 0])]));
let p = page(&[begin_page(None), layer, square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
assert_eq!(d.pages[0].layers[0].name, "Art");
}
#[test]
fn what_is_not_read_is_reported() {
let other = |code: i16| instr(code, &fields(&[field(1, &[0; 8])]));
let p = page(&[
begin_page(None),
begin_layer("L", None),
other(66),
other(68),
other(20),
other(88),
square(&attrs_fill_type(2), 0, 0, 1000),
square(&attrs(Some(1), None, true), 0, 0, 1000),
end_layer(),
]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
for w in [Warning::UnsupportedObjects, Warning::UnsupportedFills, Warning::Lenses] {
assert!(d.warnings.contains(&w), "{w:?}: {:?}", d.warnings);
}
// A fill of another type leaves the curve unfilled; the curve is still read.
let objects = &d.pages[0].layers[0].objects;
assert_eq!(objects.len(), 2);
assert!(shape(&objects[1]).fill.is_none());
}
#[test]
fn colors_of_other_models_and_missing_entries() {
let mut children = vec![cont(b'4', 1e-7)];
children.push(page(&[
begin_page(None),
begin_layer("L", None),
square(&attrs(Some(1), None, false), 0, 0, 1000),
square(&attrs(Some(9), None, false), 0, 0, 1000),
square(&attrs(Some(2), None, false), 0, 0, 1000),
]));
children.push(table(b"rclr", &[color(7, &[1, 2, 3, 4]), color(3, &[255, 0, 0, 255])]));
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::UnknownColors) && d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
let objects = &d.pages[0].layers[0].objects;
assert_eq!(shape(&objects[0]).fill, Some(Color::Cmyk([1.0, 0.0, 0.0, 1.0])));
assert_eq!(shape(&objects[1]).fill, Some(Color::Rgb([0.0; 3])));
}
#[test]
fn gray_cmy_and_rgb_colors_of_the_older_fields() {
let mut children = vec![cont(b'4', 1e-7)];
children.push(page(&[
begin_page(None),
begin_layer("L", None),
square(&attrs(Some(1), None, false), 0, 0, 1000),
square(&attrs(Some(2), None, false), 0, 0, 1000),
square(&attrs(Some(3), None, false), 0, 0, 1000),
]));
children.push(table(b"rclr", &[color(9, &[51]), color(4, &[255, 0, 51]), color(5, &[255, 0, 0])]));
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
let objects = &d.pages[0].layers[0].objects;
// The model holds objects front to back: the RGB square, the CMY one, then the gray one.
assert_eq!(shape(&objects[0]).fill, Some(Color::Rgb([1.0, 0.0, 0.0])));
match (shape(&objects[1]).fill.clone(), shape(&objects[2]).fill.clone()) {
(Some(Color::Cmyk([c, m, y, k])), Some(Color::Gray(g))) => {
assert!((c - 1.0).abs() < 1e-6 && m == 0.0 && (y - 0.2).abs() < 1e-6 && k == 0.0, "{c} {m} {y} {k}");
assert!((g - 0.8).abs() < 1e-6, "{g}");
}
other => panic!("{other:?}"),
}
}
#[test]
fn outline_arrowheads_are_reported() {
let mut children = vec![cont(b'4', 1e-7)];
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)]));
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rota")));
children.push(arrowheads(&[(0, 2)]));
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.warnings, vec![Warning::Arrowheads]);
}
#[test]
fn a_long_instruction_and_a_jump_over_image_bytes() {
// The jump's target counts from the start of the file: header, `cont`, then the page body.
let before = riff(&[cont(b'4', 1e-7), page(&[])]).len() - 8;
let head = [begin_page(None), begin_layer("L", None)].concat();
let jump_len = 4 + 1 + 3 + 4;
let image = vec![0xEEu8; 37];
let target = (before + 8 + head.len() + jump_len + image.len()) as u32;
let jump = instr(111, &fields(&[field(1, &target.to_le_bytes())]));
assert_eq!(jump.len(), jump_len);
let body = [
head,
jump,
image,
long_instr(67, &curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48])[4..]),
end_layer(),
]
.concat();
let mut children = vec![cont(b'4', 1e-7), chunk(b"page", &body)];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
// The images jumped over are not read, and the warning says so.
assert_eq!(d.warnings, [Warning::UnsupportedObjects]);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn bytes_after_a_chunk_that_runs_short_are_passed_over() {
let stray = vec![0x10, 0x00, 0x16, 0x00, 0x01, 0x0b, 0x00, 0x01, 0, 0, 0, 0, 0, 0, 0, 0xff];
let mut children = vec![cont(b'4', 1e-7), stray, list(b"pgls", &[page(&[begin_page(None), square(&attrs(Some(1), None, false), 0, 0, 1000)])])];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn other_byte_orders_and_coordinate_sizes_are_refused() {
let mut f = sample();
f[..4].copy_from_slice(b"RIFX");
assert_eq!(read_cmx(&f, Limits::default()), Err(Error::Unsupported("big-endian CMX files")));
let mut children = vec![cont(b'2', 1e-3)];
children.extend(tables());
assert_eq!(read_cmx(&riff(&children), Limits::default()), Err(Error::Unsupported("CMX files with 16-bit coordinates")));
assert_eq!(read_cmx(&riff(&tables()), Limits::default()), Err(Error::Damaged("CMX header")));
assert_eq!(read_cmx(&riff(&[cont(b'9', 1e-7)]), Limits::default()), Err(Error::Damaged("CMX header")));
}
#[test]
fn a_header_without_a_usable_unit_reads_0_1_micrometers() {
for meters in [0.0, -1.0, f64::NAN, 2.0] {
let mut children = vec![cont(b'4', meters), page(&[begin_page(Some((2_100_000, 2_970_000)))])];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
let (w, _) = d.pages[0].size.unwrap();
assert!(near(w, 210.0 / 25.4 * 72.0), "{meters}: {w}");
}
}
#[test]
fn groups_past_the_depth_limit_are_left_out() {
let mut ins = vec![begin_page(None), begin_layer("L", None)];
for _ in 0..6 {
ins.push(begin_group());
}
ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000));
for _ in 0..6 {
ins.push(end_group());
}
ins.push(square(&attrs(Some(1), None, false), 0, 0, 1000));
let d = read_cmx(&file(&[page(&ins)]), Limits { depth: 3, ..Limits::default() }).unwrap();
assert!(d.warnings.contains(&Warning::TooDeep));
// The square after the groups is still read, beside the three groups kept.
let objects = &d.pages[0].layers[0].objects;
assert_eq!(objects.len(), 2);
let mut depth = 0;
let mut o = &objects[1];
while let Object::Group { objects: kids, .. } = o {
depth += 1;
match kids.first() {
Some(k) => o = k,
None => break,
}
}
assert_eq!(depth, 3);
}
#[test]
fn counts_past_the_limits_are_bounded() {
let ins: Vec<Vec<u8>> = std::iter::once(begin_page(None)).chain((0..50).map(|_| square(&attrs(Some(1), None, false), 0, 0, 1000))).collect();
let f = file(&[page(&ins)]);
let d = read_cmx(&f, Limits { objects: 10, ..Limits::default() }).unwrap();
assert_eq!(d.pages[0].layers[0].objects.len(), 10);
assert!(d.warnings.contains(&Warning::TooDeep));
let d = read_cmx(&f, Limits { coordinates: 12, ..Limits::default() }).unwrap();
assert_eq!(d.pages[0].layers[0].objects.len(), 2);
assert_eq!(read_cmx(&f, Limits { chunks: 20, ..Limits::default() }), Err(Error::Limit("chunk count")));
assert_eq!(read_cmx(&f, Limits { input: 10, ..Limits::default() }), Err(Error::Limit("input size")));
let dashed = |n: u16| {
let mut children = vec![cont(b'4', 1e-7)];
children.push(page(&[begin_page(None), square(&attrs(None, Some(3), false), 0, 0, 1000), square(&attrs(None, Some(3), false), 0, 0, 1000)]));
children.extend(tables());
read_cmx(&riff(&children), Limits { dashes: usize::from(n), ..Limits::default() }).unwrap()
};
let d = dashed(3);
let o: Vec<usize> = d.pages[0].layers[0].objects.iter().map(|o| shape(o).outline.as_ref().unwrap().dashes.len()).collect();
assert_eq!(o, [0, 2]);
assert!(d.warnings.contains(&Warning::TooDeep));
}
#[test]
fn a_curve_cut_short_keeps_the_points_it_holds() {
let mut c = curve(&attrs(Some(1), None, false), &[(0, 0), (10, 0), (10, 10)], &[0x0c, 0x44, 0x48]);
// Claim 9 points where 3 are stored: the field's own length still covers only 3.
let at = c.windows(2).position(|w| w == [3, 0]).unwrap();
c[at] = 9;
let p = page(&[begin_page(None), c]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged));
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn a_curve_that_lost_type_bytes_keeps_its_first_points() {
// Three whole points and only two of their type bytes.
let mut g = 3u16.to_le_bytes().to_vec();
for (x, y) in [(0i32, 0i32), (1_000_000, 0), (1_000_000, 1_000_000)] {
g.extend(x.to_le_bytes());
g.extend(y.to_le_bytes());
}
g.extend([0x0c, 0x44]);
let c = instr(67, &fields(&[field(1, &attrs(None, Some(1), false)), field(2, &g)]));
let d = read_cmx(&file(&[page(&[begin_page(None), c])]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
let Geometry::Path(p) = &shape(&d.pages[0].layers[0].objects[0]).geometry else { panic!() };
let side = 100.0 / 25.4 * 72.0;
assert!(near(p.subpaths[0].start.x, 0.0) && near(p.subpaths[0].start.y, 0.0));
match p.subpaths[0].segments[..] {
[craft_cdr::model::Segment::Line(e)] => assert!(near(e.x, side) && near(e.y, 0.0), "{e:?}"),
ref other => panic!("{other:?}"),
}
}
#[test]
fn a_file_cut_short_of_its_declared_size_is_reported() {
let mut f = file(&[]);
let declared = (f.len() as u32 - 8 + 100).to_le_bytes();
f[4..8].copy_from_slice(&declared);
let d = read_cmx(&f, Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
}
#[test]
fn a_page_that_ends_inside_an_instruction_is_reported() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer(), vec![1, 0]]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn a_chunk_64_bytes_past_stray_bytes_is_found() {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut children = vec![cont(b'4', 1e-7), [vec![1u8; 64], p].concat()];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn stray_letters_with_a_length_past_the_file_are_passed_over() {
let mut stray = b"abcd".to_vec();
stray.extend(0xFFFF_FF00u32.to_le_bytes());
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut children = vec![cont(b'4', 1e-7), [stray, p].concat()];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn a_dash_pattern_of_zero_lengths_draws_a_solid_line() {
let mut children = vec![cont(b'4', 1e-7)];
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(None, Some(1), false), 0, 0, 1000)]));
children.extend(tables().into_iter().filter(|t| !t.starts_with(b"rdot") && !t.starts_with(b"rotl")));
children.push(table(b"rdot", &[dashes(&[0, 0])]));
children.push(table(b"rotl", &[outline([3, 1, 2, 1, 1, 1])]));
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
let o = shape(&d.pages[0].layers[0].objects[0]).outline.clone().unwrap();
assert!(o.dashes.is_empty(), "{:?}", o.dashes);
}
#[test]
fn a_curve_field_that_lost_points_is_left_out() {
// Three points claimed, two whole points stored and the third cut inside its y: the type
// bytes can't be found, so no node types are read from coordinates.
let mut g = 3u16.to_le_bytes().to_vec();
for (x, y) in [(0i32, 0i32), (1_000_000, 0)] {
g.extend(x.to_le_bytes());
g.extend(y.to_le_bytes());
}
g.extend(1_000_000i32.to_le_bytes());
g.extend([0x40, 0x42]);
let c = instr(67, &fields(&[field(1, &attrs(Some(1), None, false)), field(2, &g)]));
let d = read_cmx(&file(&[page(&[begin_page(None), begin_layer("L", None), c])]), Limits::default()).unwrap();
assert!(d.warnings.contains(&Warning::Damaged), "{:?}", d.warnings);
assert!(d.pages[0].layers.is_empty(), "{:?}", d.pages[0].layers);
}
#[test]
fn a_chunk_whose_id_has_a_digit_is_found_after_stray_bytes() {
// Stray bytes, a chunk the reader passes over whose id ends in a digit, then the page.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 6];
b.extend(chunk(b"inf1", &[0; 70]));
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn padding_and_ids_with_impossible_lengths_are_not_taken_for_chunks() {
// After stray bytes, four spaces with a small length, or letters with a length past the list,
// come before the page: neither is taken for a chunk, so the page is found.
for filler in [b" \x08\x00\x00\x00".to_vec(), b"junk\x40\x42\x0f\x00".to_vec()] {
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut b = vec![1u8; 2];
b.extend(filler);
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
}
#[test]
fn after_stray_bytes_a_chunk_the_reader_passes_over_keeps_what_it_holds() {
// Stray bytes, then a chunk the reader passes over whose body starts with the letters of a
// page chunk, then the page: only the page is read.
let p = page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000), end_layer()]);
let mut inner = b"page".to_vec();
inner.extend(4u32.to_le_bytes());
inner.extend([0; 10]);
let mut b = vec![1u8; 2];
b.extend(chunk(b"inf1", &inner));
b.extend(p);
let mut children = vec![cont(b'4', 1e-7), b];
children.extend(tables());
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
assert!(d.warnings.is_empty(), "{:?}", d.warnings);
assert_eq!(d.pages.len(), 1);
assert_eq!(d.pages[0].layers[0].objects.len(), 1);
}
#[test]
fn a_canvas_or_a_container_is_reported() {
for bit in [8u8, 16] {
let mut a = attrs(Some(1), None, false);
a[0] |= bit;
let p = page(&[begin_page(None), begin_layer("L", None), square(&a, 0, 0, 1000), end_layer()]);
let d = read_cmx(&file(&[p]), Limits::default()).unwrap();
assert_eq!(d.warnings, vec![Warning::UnsupportedObjects], "{bit}");
assert!(shape(&d.pages[0].layers[0].objects[0]).fill.is_some());
}
}
#[test]
fn a_library_color_with_its_name_reads_as_a_spot_color() {
let mut children = vec![cont(b'4', 1e-7)];
children.push(page(&[begin_page(None), begin_layer("L", None), square(&attrs(Some(1), None, false), 0, 0, 1000)]));
children.push(table(b"rclr", &[color_record_named(5, [0, 0, 255, 0], Some("Brick 12"))]));
let d = read_cmx(&riff(&children), Limits::default()).unwrap();
match shape(&d.pages[0].layers[0].objects[0]).fill.clone() {
Some(Color::Spot { name, tint, look }) => {
assert_eq!((name.as_str(), tint), ("Brick 12", 1.0));
assert!(look.is_some());
}
other => panic!("{other:?}"),
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
#[test]
fn never_panics_on_garbage(bytes in prop::collection::vec(any::<u8>(), 0..2048)) {
let mut b = b"RIFF\0\0\0\0CMX1".to_vec();
b.extend(bytes);
let _ = read_cmx(&b, Limits::default());
}
#[test]
fn never_panics_on_mutated_samples(edits in prop::collection::vec((any::<usize>(), any::<u8>()), 1..24)) {
let mut b = sample();
let n = b.len();
for (at, v) in edits {
b[at % n] = v;
}
let _ = read_cmx(&b, Limits::default());
}
}
+8
View File
@@ -0,0 +1,8 @@
//! Integration tests: one test binary for the crate, one module per area.
// Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod bench;
mod cmx;
mod provenance;
mod read;
+43
View File
@@ -0,0 +1,43 @@
//! Every layout id the code cites (`R1` ...) has a row in `PROVENANCE.md`.
use std::collections::BTreeSet;
/// The ids `R<n>` in `text`.
fn ids(text: &str) -> BTreeSet<u32> {
let b = text.as_bytes();
let mut out = BTreeSet::new();
for (i, c) in b.iter().enumerate() {
let starts = *c == b'R' && (i == 0 || !b[i - 1].is_ascii_alphanumeric());
if !starts {
continue;
}
let digits: String = b[i + 1..].iter().take_while(|d| d.is_ascii_digit()).map(|d| *d as char).collect();
let ends = b.get(i + 1 + digits.len()).is_none_or(|d| !d.is_ascii_alphanumeric());
if !digits.is_empty() && ends {
out.insert(digits.parse().unwrap());
}
}
out
}
#[test]
fn every_cited_layout_has_a_row() {
let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
let table = std::fs::read_to_string(dir.join("PROVENANCE.md")).unwrap();
let rows: BTreeSet<u32> = table.lines().filter_map(|l| l.strip_prefix("| R")).filter_map(|l| l.split(' ').next()?.parse().ok()).collect();
let mut cited = BTreeSet::new();
for entry in std::fs::read_dir(dir.join("src")).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_some_and(|e| e == "rs") {
cited.extend(ids(&std::fs::read_to_string(&path).unwrap()));
}
}
assert!(!cited.is_empty());
let missing: Vec<_> = cited.difference(&rows).collect();
assert!(missing.is_empty(), "cited without a PROVENANCE.md row: {missing:?}");
}
#[test]
fn ids_are_found_only_as_whole_words() {
assert_eq!(ids("(R1, R12) RIFF R3x xR4 R"), BTreeSet::from([1, 12]));
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -9,6 +9,7 @@
pub mod controls;
pub mod crs;
pub mod crs_masks;
pub mod migration;
pub mod presets;
pub mod segmask;
pub mod settings;
+116
View File
@@ -0,0 +1,116 @@
//! Map PhotoCraft Camera Raw edit fields without changing the base processing version.
//!
//! The first supported field is `exposure` (EV) → `light.exposure` (EV). This is a
//! settings mapping, not a promise that two renderers produce the same pixels.
use std::{error::Error, fmt};
use serde_json::Value;
use crate::{DevelopSettings, controls};
/// The partially migrated settings and the supplied field names not yet mapped.
#[derive(Debug)]
pub struct Migration {
/// A copy of the base with only the supported fields applied.
pub settings: DevelopSettings,
/// Sorted source keys, including recognized controls not yet mapped and unknown controls.
/// Values are not included. The caller must preserve any original state it still needs.
pub unmapped_fields: Vec<String>,
}
/// Why a PhotoCraft Camera Raw settings object could not be migrated.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MigrationError {
/// The supplied settings are not a JSON object.
InvalidSettingsObject,
/// The supplied exposure is not a finite number in EV.
InvalidExposure,
/// The supplied exposure is outside the develop model's control range.
ExposureOutOfRange,
/// The develop model does not define its exposure control.
MissingExposureControl,
}
impl fmt::Display for MigrationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::InvalidSettingsObject => "Camera Raw edit fields must be an object",
Self::InvalidExposure => "exposure must be a finite number in EV",
Self::ExposureOutOfRange => "exposure is outside the develop control range",
Self::MissingExposureControl => "the develop model has no exposure control",
})
}
}
impl Error for MigrationError {}
/// Apply supported fields from a PhotoCraft Camera Raw settings object to an explicit base.
///
/// Supply edit fields only, not a PSD descriptor or transport metadata. Missing fields
/// are not defaults: an absent exposure leaves the baseline unchanged. Like a partial
/// preset this replaces only named controls, but does not normalize unrelated base fields.
///
/// # Errors
///
/// A non-object or an explicit exposure that is not a finite number within the shared
/// control range is rejected rather than silently replaced or clipped.
pub fn migrate_camera_raw(base: &DevelopSettings, fields: &Value) -> Result<Migration, MigrationError> {
let fields = fields.as_object().ok_or(MigrationError::InvalidSettingsObject)?;
let mut settings = base.clone();
if let Some(value) = fields.get("exposure") {
let valid = value.as_f64().filter(|v| v.is_finite()).ok_or(MigrationError::InvalidExposure)?;
let spec = controls::find("light.exposure").ok_or(MigrationError::MissingExposureControl)?;
if !(spec.min..=spec.max).contains(&valid) {
return Err(MigrationError::ExposureOutOfRange);
}
settings.light.exposure = valid;
}
let mut unmapped_fields: Vec<_> = fields.keys().filter(|key| key.as_str() != "exposure").cloned().collect();
unmapped_fields.sort_unstable();
Ok(Migration { settings, unmapped_fields })
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Process;
use serde_json::json;
#[test]
fn camera_raw_exposure_replaces_only_one_field_and_reports_the_rest() -> Result<(), MigrationError> {
// V7 is not the default: detect an accidental restamp to the latest process.
for process in [Process::V8, Process::V7] {
let mut base = DevelopSettings { process: process.version(), ..DevelopSettings::default() };
base.light.exposure = -0.75;
// Using a stored value outside today's control range detects whole-model normalization.
base.light.contrast = 123.0;
let result = migrate_camera_raw(&base, &json!({ "unknownField": [1, 2], "contrast": -38, "exposure": 1.15, "temperature": -26 }))?;
let mut expected = base.clone();
expected.light.exposure = 1.15;
assert_eq!(result.settings, expected);
assert_eq!(result.unmapped_fields, ["contrast", "temperature", "unknownField"]);
}
Ok(())
}
#[test]
fn camera_raw_exposure_absent_is_distinct_from_invalid() -> Result<(), MigrationError> {
let mut base = DevelopSettings::default();
base.light.exposure = -0.75;
let result = migrate_camera_raw(&base, &json!({ "contrast": -38 }))?;
assert_eq!(result.settings, base);
assert_eq!(result.unmapped_fields, ["contrast"]);
assert_eq!(migrate_camera_raw(&base, &json!([])).err(), Some(MigrationError::InvalidSettingsObject));
// JSON cannot represent a non-finite number; serde_json serializes it to null.
for invalid in [json!({ "exposure": null }), json!({ "exposure": "NaN" }), json!({ "exposure": f64::INFINITY })] {
assert_eq!(migrate_camera_raw(&base, &invalid).err(), Some(MigrationError::InvalidExposure));
}
assert_eq!(migrate_camera_raw(&base, &json!({ "exposure": 5.1 })).err(), Some(MigrationError::ExposureOutOfRange));
Ok(())
}
}
+588
View File
@@ -0,0 +1,588 @@
//! Scanner for Adobe Illustrator editing-data streams: PostScript-like tokens read line by line.
//!
//! - A line starting with `%_` holds tokens like any other line (they are marked [`Token::hidden`]:
//! readers of the printed format skip them as comments).
//! - Any other line starting with `%` is a [`Tok::Comment`] (the section markers).
//! - `%_` later in a line starts tokens too, hidden (a pseudo-comment operator after its
//! operands, as a gradient stop's `… 50 100 %_Bs`: AI7 spec §1.4.3); any other `%` later in a
//! line starts a comment that is skipped, but for a line of hex digits after `%_` (a hidden
//! blend's record), a hidden [`Tok::Comment`].
//! - The binary image data after `%%BeginData:` is one [`Tok::Data`]; the binary preview of a placed
//! file is one [`Tok::Preview`].
//! - A document included whole (`%%BeginDocument:` … `%%EndDocument` lines, DSC 3.0 p. 68, nested
//! ones counted, the counted payloads of `%%BeginData:` and `%%BeginBinary:` inside skipped) is
//! one [`Tok::Document`].
/// A token from an Illustrator editing-data stream.
#[derive(Clone, Debug, PartialEq)]
pub enum Tok<'a> {
Num(f64),
/// A literal `(…)` string, escapes undone.
Str(Vec<u8>),
/// A hexadecimal `<…>` string.
Hex(Vec<u8>),
/// A literal `/name`.
Name(&'a [u8]),
/// An operator (any other word, `[` and `]` included).
Word(&'a [u8]),
/// A comment line, without its first `%`.
Comment(&'a [u8]),
/// An image's samples: what follows `XI` in a `%%BeginData:` section.
Data(&'a [u8]),
/// A placed file's preview: what is between `%AI26_BeginPlacedObjectPreview` and its end.
Preview(&'a [u8]),
/// A document included whole: what is between `%%BeginDocument:`'s line and the line of the
/// `%%EndDocument` that ends it, or `None` when none does (the rest of the data is skipped).
Document(Option<&'a [u8]>),
}
/// A scanned token together with whether it came from a hidden `%_` line or suffix.
#[derive(Clone, Debug, PartialEq)]
pub struct Token<'a> {
pub tok: Tok<'a>,
/// Read from a `%_` line.
pub hidden: bool,
}
/// A placed file's preview (binary): (begin, end) markers.
const PREVIEW: (&[u8], &[u8]) = (b"%AI26_BeginPlacedObjectPreview", b"%AI26_EndPlacedObjectPreview");
/// A placed file's markers, which a hidden one has on `%_` lines.
const PLACE: [&[u8]; 2] = [b"%AI5_BeginPlace", b"%AI5_EndPlace"];
/// A path's note comments, also read on `%_` lines.
const NOTES: [&[u8]; 3] = [b"%AI3_Note:", b"%%Note:", b"%AI5_NoteMore:"];
/// The markers around a placed file's relative folder, which a hidden one has on `%_` lines too.
const RELATIVE: [&[u8]; 2] = [b"%AI28_BeginPlacedRelativePath", b"%AI28_EndPlacedRelativePath"];
/// A document included whole: (begin, end) markers.
const DOCUMENT: (&[u8], &[u8]) = (b"%%BeginDocument", b"%%EndDocument");
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() {
return Some(0);
}
hay.windows(needle.len()).position(|w| w == needle)
}
fn hex_decode(bytes: &[u8]) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(bytes.len() / 2);
let mut high: Option<u8> = None;
for &b in bytes {
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)
}
/// The line of `src` before the one that starts at `at`, without its line end, when it ends within
/// [`OPERAND_LINE`] bytes of `at` and is no longer than that.
fn previous_line(src: &[u8], at: usize) -> Option<&[u8]> {
let before = src.get(at.saturating_sub(OPERAND_LINE)..at)?;
let end = before.iter().rposition(|b| !is_eol(*b))? + 1;
let start = before.get(..end)?.iter().rposition(|b| is_eol(*b))? + 1;
before.get(start..end)
}
/// The longest line of an image's `XI` operands looked at.
const OPERAND_LINE: usize = 1024;
/// How many bytes the alpha channel of an image whose `XI` operands are on `line` takes (`[matrix]
/// llx lly urx ury w h bits type alpha …`, `%_` before them in a hidden object): a byte a pixel when
/// the alpha count isn't 0, else none (or when the operands aren't of that shape).
fn alpha_bytes(line: &[u8]) -> usize {
let line = line.strip_prefix(b"%_").unwrap_or(line);
let Some(after) = line.iter().rposition(|b| *b == b']').and_then(|i| line.get(i + 1..)) else { return 0 };
let nums: Vec<f64> = std::str::from_utf8(after).unwrap_or_default().split_whitespace().take(9).map_while(|w| w.parse().ok()).collect();
match (nums.get(4), nums.get(5), nums.get(8)) {
// At most the pixels the reader reads an image with.
(Some(&w), Some(&h), Some(&a)) if a > 0.0 && w >= 1.0 && h >= 1.0 && w * h <= (1u64 << 25) as f64 => (w * h) as usize,
_ => 0,
}
}
/// Where in `w` the `%%EndData` that ends an image's samples starts: the first one on a line whose
/// next line is `XH` (`%_XH` in a hidden object), as an image's is; else the first one that a line
/// end, or the end of `w`, follows.
fn end_data(w: &[u8]) -> Option<usize> {
const MARK: &[u8] = b"%%EndData";
let mut first = None;
let mut at = 0;
while let Some(i) = w.get(at..).and_then(|r| find(r, MARK)) {
let i = at + i;
let rest = w.get(i + MARK.len()..).unwrap_or_default();
if rest.first().is_none_or(|b| matches!(b, b'\r' | b'\n')) {
let next = rest.strip_prefix(b"\r").unwrap_or(rest);
let next = next.strip_prefix(b"\n").unwrap_or(next);
let next = next.strip_prefix(b"%_").unwrap_or(next);
if next.starts_with(b"XH") {
return Some(i);
}
first = first.or(Some(i));
}
at = i + 1;
}
first
}
fn is_space(b: u8) -> bool {
matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0')
}
fn is_delim(b: u8) -> bool {
matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%')
}
fn is_eol(b: u8) -> bool {
matches!(b, b'\r' | b'\n')
}
/// Scanner for Illustrator editing-data byte slices.
pub struct Lexer<'a> {
src: &'a [u8],
pos: usize,
/// The current line started with `%_`.
hidden: bool,
}
impl<'a> Lexer<'a> {
pub fn new(src: &'a [u8]) -> Self {
Self { src, pos: 0, hidden: false }
}
fn peek(&self) -> Option<u8> {
self.src.get(self.pos).copied()
}
/// The data from where the next token is looked for.
pub fn rest(&self) -> &'a [u8] {
self.src.get(self.pos..).unwrap_or_default()
}
fn at_line_start(&self) -> bool {
self.pos == 0 || self.src.get(self.pos - 1).is_some_and(|b| is_eol(*b))
}
/// The rest of the current line (without its end), the position moved past it.
fn line(&mut self) -> &'a [u8] {
let rest = self.rest();
let n = rest.iter().position(|b| is_eol(*b)).unwrap_or(rest.len());
self.pos += n;
rest.get(..n).unwrap_or_default()
}
/// [`Self::line`], the position moved past its end too (`\r`, `\n` or `\r\n`).
fn whole_line(&mut self) -> &'a [u8] {
let line = self.line();
if self.peek() == Some(b'\r') {
self.pos += 1;
}
if self.peek() == Some(b'\n') {
self.pos += 1;
}
line
}
/// Where the next token is looked for.
pub fn offset(&self) -> usize {
self.pos
}
/// Look for the next token at `pos` again (the end of the data at most).
pub fn seek(&mut self, pos: usize) {
self.pos = pos.min(self.src.len());
}
/// The data from `from` to `to` (empty where that isn't in it).
pub fn slice(&self, from: usize, to: usize) -> &'a [u8] {
self.src.get(from..to).unwrap_or_default()
}
/// Skip past the next `needle` (the end of data that isn't tokens) → what was skipped.
pub fn skip_past(&mut self, needle: &[u8]) -> &'a [u8] {
let rest = self.rest();
let n = find(rest, needle).map_or(rest.len(), |i| i + needle.len());
self.pos += n;
rest.get(..n).unwrap_or_default()
}
/// The next token; `None` at the end.
pub fn next_token(&mut self) -> Option<Token<'a>> {
loop {
let b = self.peek()?;
if is_eol(b) {
self.pos += 1;
self.hidden = false;
continue;
}
if is_space(b) {
self.pos += 1;
continue;
}
if b == b'%' {
let start = self.at_line_start();
// A pseudo-comment: `%_` at the line's start, or after operands.
if self.rest().starts_with(b"%_") && (start || self.rest().get(2).is_some_and(|b| b.is_ascii_alphabetic())) {
self.pos += 2;
self.hidden = true;
continue;
}
// Right after `%_` a section still starts (a hidden image's data, #1264).
let prefixed = self.hidden && self.pos >= 2 && self.src.get(self.pos - 2..self.pos) == Some(b"%_");
let line = self.line();
if (start || prefixed)
&& let Some(t) = self.special(line)
{
return Some(Token { hidden: prefixed, ..t });
}
if start {
return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: false });
}
// So does a hidden placed file: its `~` ends what `%_%AI5_BeginPlace` begins. And a
// hidden path's note.
if prefixed && PLACE.iter().chain(&NOTES).chain(&RELATIVE).any(|m| line.starts_with(m)) {
return Some(Token { tok: Tok::Comment(line.get(1..).unwrap_or_default()), hidden: true });
}
// And a line of hex digits, as a hidden blend's record is written (`%_%4443…`
// after its `XP`), like the plain one on `%` lines.
let digits = line.get(1..).unwrap_or_default();
if prefixed && !digits.trim_ascii_end().is_empty() && digits.trim_ascii_end().iter().all(u8::is_ascii_hexdigit) {
return Some(Token { tok: Tok::Comment(digits), hidden: true });
}
// A comment later in a line.
continue;
}
let hidden = self.hidden;
self.pos += 1;
let tok = match b {
b'(' => Tok::Str(self.string()),
b'<' => {
let rest = self.rest();
let end = rest.iter().position(|b| *b == b'>').unwrap_or(rest.len());
self.pos += (end + 1).min(rest.len());
// Malformed digits read as an empty string.
Tok::Hex(rest.get(..end).and_then(hex_decode).unwrap_or_default())
}
b'[' | b']' | b'{' | b'}' | b')' | b'>' => Tok::Word(self.src.get(self.pos - 1..self.pos).unwrap_or_default()),
b'/' => Tok::Name(self.word()),
_ => {
self.pos -= 1;
let w = self.word();
match number(w) {
Some(v) => Tok::Num(v),
None => Tok::Word(w),
}
}
};
return Some(Token { tok, hidden });
}
}
/// The token a comment line stands for when it starts a section read differently: image data
/// (`%%BeginData:` followed by `XI`), a placed file's preview and skipped binary sections.
fn special(&mut self, line: &'a [u8]) -> Option<Token<'a>> {
if line.starts_with(PREVIEW.0) {
let from = self.pos;
let after = find(self.rest(), PREVIEW.1).map_or(self.src.len(), |i| self.pos + i);
self.pos = after;
self.line();
return Some(Token { tok: Tok::Preview(self.slice(from, after)), hidden: false });
}
if line.starts_with(DOCUMENT.0) {
return Some(Token { tok: Tok::Document(self.document()), hidden: false });
}
let n = line.strip_prefix(b"%%BeginData:")?;
let n: usize = std::str::from_utf8(n).ok()?.split_whitespace().next()?.parse().ok()?;
// The count starts after the comment's line end character (a following `\n` counts).
let from = self.pos + 1;
let region = self.src.get(from..)?;
let mut skip = region.iter().take_while(|b| is_space(**b)).count();
// A hidden object's section is on `%_` lines up to its samples: `%_XI`, then `%_%%EndData`.
let hidden = region.get(skip..)?.starts_with(b"%_XI");
if hidden {
skip += 2;
} else if !region.get(skip..)?.starts_with(b"XI") {
return None;
}
let mut data = from + skip + 2;
match (self.src.get(data), self.src.get(data + 1)) {
(Some(b'\r'), Some(b'\n')) => data += 2,
(Some(b'\r' | b'\n'), _) => data += 1,
_ => {}
}
// The count leaves out an alpha channel: the data ends where `%%EndData` starts, the first one
// that a line end or the end of the data follows (samples can hold the marker's bytes).
let declared = from.saturating_add(n).min(self.src.len()).max(data);
// The alpha channel the line before gives the image (its `XI` operands) follows the counted
// samples: the marker is looked for after it.
let line_start = self.pos.saturating_sub(line.len());
let line_start = if line_start >= 2 && self.src.get(line_start - 2..line_start) == Some(b"%_") { line_start - 2 } else { line_start };
let alpha = previous_line(self.src, line_start).map_or(0, alpha_bytes);
let start = if alpha > 0 { declared.saturating_add(alpha).saturating_sub(2) } else { declared.saturating_sub(4) }.max(data);
let stop = declared.saturating_add(n.saturating_mul(2)).saturating_add(64).max(start.saturating_add(64)).min(self.src.len());
let end = match self.src.get(start..stop).and_then(end_data) {
Some(i) => start + i,
None => declared,
};
self.pos = end;
let samples = self.src.get(data..end).unwrap_or_default();
let samples = if hidden { samples.strip_suffix(b"%_").unwrap_or(samples) } else { samples };
Some(Token { tok: Tok::Data(samples), hidden: false })
}
/// After a `%%BeginDocument:` line: the document up to the start of the `%%EndDocument` line
/// that ends it, the position moved past that line. A `%%BeginDocument:` line inside starts a
/// nested document, and the bytes a `%%BeginData:` or `%%BeginBinary:` line inside counts are
/// skipped (DSC 3.0 pp. 68 and 72): a marker in them ends nothing. `None` when no line ends it:
/// the position moves to the end of the data.
fn document(&mut self) -> Option<&'a [u8]> {
// The rest of the `%%BeginDocument:` line is its end; the line after the document starts
// tokens afresh (not hidden unless it starts with `%_`).
self.whole_line();
self.hidden = false;
let from = self.pos;
let mut depth = 0usize;
while self.pos < self.src.len() {
let start = self.pos;
// A hidden object's document is on `%_` lines.
let line = self.whole_line();
let line = line.strip_prefix(b"%_").unwrap_or(line);
if line.starts_with(DOCUMENT.1) {
if depth == 0 {
return Some(self.slice(from, start));
}
depth -= 1;
} else if line.starts_with(DOCUMENT.0) {
depth = depth.saturating_add(1);
} else if let Some(n) = line.strip_prefix(b"%%BeginData:").or_else(|| line.strip_prefix(b"%%BeginBinary:")) {
self.skip_counted(n);
}
}
None
}
/// Skip what a `%%BeginData:` or `%%BeginBinary:` comment counts (`n`, its text after the
/// colon): `count [type [Bytes|Lines]]`, bytes unless it says `Lines`.
fn skip_counted(&mut self, n: &[u8]) {
let mut words = std::str::from_utf8(n).unwrap_or_default().split_whitespace();
let Some(count) = words.next().and_then(|c| c.parse::<usize>().ok()) else { return };
if words.nth(1).is_some_and(|unit| unit.eq_ignore_ascii_case("lines")) {
for _ in 0..count {
if self.pos >= self.src.len() {
break;
}
self.whole_line();
}
} else {
// The count starts after the comment's line end, which `document` has passed.
self.pos = self.pos.saturating_add(count).min(self.src.len());
}
}
/// A regular token's characters.
fn word(&mut self) -> &'a [u8] {
let start = self.pos;
while let Some(b) = self.peek() {
if is_space(b) || is_delim(b) {
break;
}
self.pos += 1;
}
self.src.get(start..self.pos).unwrap_or_default()
}
/// A literal string after its `(` (an unterminated one ends with the data).
fn string(&mut self) -> Vec<u8> {
let mut out = vec![];
let mut depth = 0usize;
while let Some(b) = self.peek() {
self.pos += 1;
match b {
b'(' => {
depth += 1;
out.push(b);
}
b')' if depth == 0 => break,
b')' => {
depth -= 1;
out.push(b);
}
b'\\' => {
let Some(e) = self.peek() else { break };
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),
}
}
_ => out.push(b),
}
}
out
}
}
/// A finite number token (`12`, `-3.5`, `.5`, `1e-3`), or `None`.
pub fn number(w: &[u8]) -> Option<f64> {
let first = *w.first()?;
if !(first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.')) {
return None;
}
if w.iter().any(|b| b.is_ascii_alphabetic() && !matches!(b, b'e' | b'E')) {
return None;
}
let v: f64 = std::str::from_utf8(w).ok()?.parse().ok()?;
v.is_finite().then_some(v)
}
#[cfg(test)]
mod tests {
use super::*;
fn all(src: &[u8]) -> Vec<Token<'_>> {
let mut l = Lexer::new(src);
std::iter::from_fn(|| l.next_token()).collect()
}
fn t(tok: Tok<'_>, hidden: bool) -> Token<'_> {
Token { tok, hidden }
}
#[test]
fn hidden_lines_and_comments() {
let toks = all(b"%AI5_BeginLayer\r\n1 (a\\)b) Ln\r%_/X : ;\n0 %_BS\n<4142>\n");
assert_eq!(
toks,
vec![
t(Tok::Comment(b"AI5_BeginLayer"), false),
t(Tok::Num(1.0), false),
t(Tok::Str(b"a)b".to_vec()), false),
t(Tok::Word(b"Ln"), false),
t(Tok::Name(b"X"), true),
t(Tok::Word(b":"), true),
t(Tok::Word(b";"), true),
t(Tok::Num(0.0), false),
// A pseudo-comment operator after its operands.
t(Tok::Word(b"BS"), true),
t(Tok::Hex(b"AB".to_vec()), false),
]
);
}
#[test]
fn a_percent_later_in_a_line_is_a_comment_unless_an_operator_follows_it() {
let toks = all(b"1 % a note (\n2 %_Bs\n3 %_ 4\n");
let words: Vec<_> = toks.iter().map(|t| (t.tok.clone(), t.hidden)).collect();
assert_eq!(words, [(Tok::Num(1.0), false), (Tok::Num(2.0), false), (Tok::Word(b"Bs"), true), (Tok::Num(3.0), false)]);
// A hidden line of hex digits (a hidden blend's record) is a comment; other text after
// `%_%` stays skipped.
let toks = all(b"%_%44434241\n%_% not hex\n%_%\n1\n");
assert_eq!(toks, [t(Tok::Comment(b"44434241"), true), t(Tok::Num(1.0), false)]);
}
#[test]
fn image_data_is_one_token() {
// The count starts after the comment's `\r`: `\nXI\n` and 3 samples; an alpha channel
// after them isn't counted.
let src = b"[1 0 0 1 0 0] XI\r\n%%BeginData: 7\r\nXI\n(%)A%%EndData\r\nXH\r\n";
let toks = all(src);
assert!(toks.contains(&t(Tok::Data(b"(%)A"), false)), "{toks:?}");
assert_eq!(toks.last(), Some(&t(Tok::Word(b"XH"), false)));
// #1264: on `%_` lines too, where the samples would otherwise be read as tokens.
let toks = all(b"%_[1 0 0 1 0 0] XI\r%_%%BeginData: 7\rXI\n(U)A%%EndData\r%_XH\ru\r");
assert!(toks.contains(&t(Tok::Data(b"(U)A"), true)), "{toks:?}");
assert_eq!(toks.last(), Some(&t(Tok::Word(b"u"), false)), "{toks:?}");
// A section of hex lines is comments.
let toks = all(b"%%BeginData: 9 Hex Bytes\r\n%00FF\r\n%%EndData\r\n1\r\n");
assert_eq!(toks.last(), Some(&t(Tok::Num(1.0), false)));
// On `%_` lines (an opacity mask's image, say) too: a `(` in the samples starts no string.
let toks = all(b"%_XI\r%_%%BeginData: 4\r%_XI\r(\x00\x00\x00%_%%EndData\r%_XH\r1\r");
assert!(toks.contains(&t(Tok::Data(b"(\x00\x00\x00"), true)), "{toks:?}");
assert_eq!(toks.last(), Some(&t(Tok::Num(1.0), false)));
}
#[test]
fn binary_sections_are_one_token() {
let toks = all(b"%AI26_BeginPlacedObjectPreview\r\n2 1 (\x00\xff\r\n%AI26_EndPlacedObjectPreview\r\nN\r\n");
assert_eq!(toks, vec![t(Tok::Preview(b"\r\n2 1 (\x00\xff\r\n"), false), t(Tok::Word(b"N"), false)]);
let toks = all(b"%%BeginDocument: a.eps\n(\x00 frobnicate\n%%EndDocument\nN\n");
assert_eq!(toks, vec![t(Tok::Document(Some(b"(\x00 frobnicate\n")), false), t(Tok::Word(b"N"), false)]);
// One that doesn't end takes the rest.
assert_eq!(all(b"%AI26_BeginPlacedObjectPreview\r1 (").len(), 1);
}
#[test]
fn an_included_document_ends_at_its_own_end_line() {
// A nested document, `%%EndDocument` later in a line and in counted data end nothing; `\r\n`,
// `\r` and `\n` lines alike.
let body = b"1 0 0 setrgbcolor\r\n%%BeginDocument: inner.eps\r(%%EndDocument) pop\r%%EndDocument\r\n\
%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%BeginBinary: 14\n%%EndDocument\n\
%%BeginData: 1 Hex Lines\n%%EndDocument\n";
let mut src = b"%%BeginDocument: outer.eps\r\n".to_vec();
src.extend_from_slice(body);
src.extend_from_slice(b"%%EndDocument\r\n~\r\n");
assert_eq!(all(&src), vec![t(Tok::Document(Some(body)), false), t(Tok::Word(b"~"), false)]);
// On a hidden object's `%_` lines.
let toks = all(b"%_%%BeginDocument: a.eps\r%_1 0 0 setrgbcolor\r%_%%EndDocument\r%_~\r");
assert_eq!(toks, vec![t(Tok::Document(Some(b"%_1 0 0 setrgbcolor\r")), true), t(Tok::Word(b"~"), true)]);
// The line after it is hidden only when it starts with `%_`.
let toks = all(b"%_%%BeginDocument: a.eps\r%_%%EndDocument\rN\r");
assert_eq!(toks, vec![t(Tok::Document(Some(b"")), true), t(Tok::Word(b"N"), false)]);
}
#[test]
fn an_included_document_that_doesnt_end_takes_the_rest() {
for src in [&b"%%BeginDocument: a.eps\n%%BeginDocument: b.eps\n%%EndDocument\n~\n"[..], b"%%BeginDocument: a.eps\n%%BeginData: 99999999999\n"]
{
assert_eq!(all(src), vec![t(Tok::Document(None), false)]);
}
}
#[test]
fn skip_past_data() {
let mut l = Lexer::new(b"/Binary : /ASCII85Decode ,\r\n%_(abc[%\r\n%x~>\r\n%_; 1");
for _ in 0..4 {
l.next_token();
}
assert_eq!(l.skip_past(b"~>"), b"\r\n%_(abc[%\r\n%x~>");
assert_eq!(l.next_token().map(|t| t.tok), Some(Tok::Word(b";")));
assert_eq!(l.next_token().map(|t| t.tok), Some(Tok::Num(1.0)));
}
#[test]
fn hostile_input_ends() {
for src in [&b"(unterminated \\"[..], b"<12", b"%%BeginData: 99999999999\r\nXI", b"%%BeginData: 5\rXI\r", b"/", b"1e999 nan"] {
let toks = all(src);
assert!(toks.len() < 10);
}
}
}
+1
View File
@@ -15,6 +15,7 @@
//! against the file, scans are bounded, and nothing panics.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod ai_lex;
pub mod ascii85;
mod container;
mod dsc;
+4 -2
View File
@@ -13,12 +13,14 @@ workspace = true
[features]
# Reading and writing pixels through the `exr` crate (BSD-3-Clause). The naming and Cryptomatte
# modules need none of it.
decode = ["dep:exr", "dep:half", "dep:thiserror", "dep:flate2"]
decode = ["dep:exr", "dep:half", "dep:thiserror", "zlib-inflate"]
# Bounded scanline inflation without the full EXR pixel reader.
zlib-inflate = ["dep:flate2"]
[dependencies]
serde_json = { workspace = true }
exr = { version = "1.73", default-features = false, optional = true }
half = { version = "2", optional = true }
thiserror = { workspace = true, optional = true }
# zlib for deep ZIPS chunks, which the `exr` crate does not read.
# zlib for scanline payloads and deep ZIPS chunks, which the `exr` crate does not read.
flate2 = { version = "1", default-features = false, features = ["rust_backend"], optional = true }
+1 -1
View File
@@ -22,7 +22,7 @@
/// Scanline OpenEXR writer using a caller-supplied linearization table.
pub mod rgba8;
/// RFC 1950/1951 compressor for ZIP-compressed EXR chunks.
/// RFC 1950/1951 compression and bounded inflation for EXR chunks.
pub mod zlib;
pub mod channels;
+59
View File
@@ -40,6 +40,39 @@ pub fn zlib(data: &[u8], tables: &mut Tables) -> Vec<u8> {
w.out
}
/// Inflate a zlib-wrapped scanline payload to exactly `expected` bytes. The caller
/// derives that size from the chunk's geometry and applies its chunk limit first.
/// The legacy scanline reader allows an absent or invalid Adler-32 trailer. The
/// zlib header and the complete DEFLATE payload are still required.
#[cfg(feature = "zlib-inflate")]
pub fn inflate_exact_without_checksum(src: &[u8], expected: usize) -> std::io::Result<Vec<u8>> {
use flate2::{Decompress, FlushDecompress, Status};
use std::io::{Error, ErrorKind};
let [cmf, flg, deflate @ ..] = src else {
return Err(Error::new(ErrorKind::UnexpectedEof, "truncated zlib header"));
};
let (cmf, flg) = (*cmf, *flg);
if cmf & 0x0f != 8 || cmf >> 4 > 7 || !u16::from_be_bytes([cmf, flg]).is_multiple_of(31) {
return Err(Error::new(ErrorKind::InvalidData, "not a zlib stream"));
}
if flg & 0x20 != 0 {
return Err(Error::new(ErrorKind::InvalidData, "zlib preset dictionary"));
}
// One extra byte distinguishes overflow from an exactly full output buffer
// while leaving room for the inflater to finish the stream.
let capacity = expected.checked_add(1).ok_or_else(|| Error::other("zlib output size overflow"))?;
let mut output = Vec::new();
output.try_reserve_exact(capacity).map_err(Error::other)?;
let mut inflater = Decompress::new(false);
let status = inflater.decompress_vec(deflate, &mut output, FlushDecompress::Finish).map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
if status != Status::StreamEnd || output.len() != expected {
return Err(Error::new(ErrorKind::InvalidData, "incomplete or wrong-size zlib output"));
}
Ok(output)
}
/// Adler-32 (RFC 1950 §9); 5552 bytes is the longest run that cannot overflow the sums.
fn adler32(data: &[u8]) -> u32 {
let (mut a, mut b) = (1_u32, 0_u32);
@@ -473,6 +506,32 @@ fn rle_lengths(lens: &[u8]) -> Vec<(u8, u8)> {
mod tests {
use super::*;
#[cfg(feature = "zlib-inflate")]
#[test]
fn exact_inflate_keeps_scanline_checksum_compatibility() {
let expected = vec![0x42; 4096];
let mut stream = zlib(&expected, &mut Tables::default());
let footer_start = stream.len() - 4;
assert_eq!(inflate_exact_without_checksum(&stream, expected.len()).unwrap(), expected);
stream[footer_start..].fill(0);
assert_eq!(inflate_exact_without_checksum(&stream, expected.len()).unwrap(), expected);
assert_eq!(inflate_exact_without_checksum(&stream[..footer_start], expected.len()).unwrap(), expected);
}
#[cfg(feature = "zlib-inflate")]
#[test]
fn exact_inflate_refuses_incomplete_and_wrong_length_streams() {
let stream = zlib(&[0x42; 4096], &mut Tables::default());
assert!(inflate_exact_without_checksum(&stream, 4095).is_err());
assert!(inflate_exact_without_checksum(&stream, 4097).is_err());
assert!(inflate_exact_without_checksum(&stream, usize::MAX).is_err());
assert!(inflate_exact_without_checksum(&stream[..stream.len() - 6], 4096).is_err());
assert!(inflate_exact_without_checksum(&stream[1..], 4096).is_err());
let mut dictionary_header = stream;
dictionary_header[..2].copy_from_slice(&[0x78, 0x20]);
assert!(inflate_exact_without_checksum(&dictionary_header, 4096).is_err());
}
/// A minimal inflater (RFC 1951), only to check the encoder; returns None on any error.
pub(crate) fn inflate(z: &[u8]) -> Option<Vec<u8>> {
let (cmf, flg) = (*z.first()?, *z.get(1)?);
+98 -4
View File
@@ -7,7 +7,7 @@
//! decoding then stops at [`FrameLimits::max_frames`] frames or [`FrameLimits::max_bytes`] of kept
//! pictures, or at the first damaged frame after the first, and [`Animation::stop`] says which.
use std::io::Cursor;
use std::io::{self, BufReader, Cursor, Read, Seek, SeekFrom};
use image::codecs::gif::GifDecoder;
use image::{AnimationDecoder, ImageDecoder};
@@ -75,7 +75,7 @@ pub struct Animation {
pub enum FrameError {
/// Not a GIF, or the first frame does not decode.
Malformed(String),
/// The canvas is over [`FrameLimits::max_canvas_bytes`] or more than the file can hold.
/// A configured budget cannot fit the first frame, or the file cannot back its canvas.
LimitExceeded(String),
}
@@ -96,7 +96,9 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result<Animation, Fram
return Err(FrameError::LimitExceeded("the frame limit is zero".into()));
}
let inspect_limit = limits.max_frames.saturating_add(1);
let info = crate::scan(bytes, inspect_limit).ok_or_else(|| FrameError::Malformed("not a GIF".into()))?;
let mut text_controls = Vec::new();
let info = crate::scan_with_text_controls(bytes, inspect_limit, |offset| text_controls.push(offset))
.ok_or_else(|| FrameError::Malformed("not a GIF".into()))?;
let has_more = if info.frames.len() > limits.max_frames {
Some(true)
} else if info.complete {
@@ -117,8 +119,12 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result<Animation, Fram
if !crate::plausible(info.bytes_to_back(4, 1 << 28), bytes.len(), 1 << 14) {
return Err(FrameError::LimitExceeded(format!("a {} byte file cannot hold a {width}x{height} picture", bytes.len())));
}
if canvas > limits.max_bytes {
return Err(FrameError::LimitExceeded(format!("the first frame needs {canvas} retained bytes but the limit is {}", limits.max_bytes)));
}
let malformed = |e: image::ImageError| FrameError::Malformed(e.to_string());
let mut decoder = GifDecoder::new(Cursor::new(bytes)).map_err(malformed)?;
let input = DecoderInput { bytes: Cursor::new(bytes), text_controls };
let mut decoder = GifDecoder::new(BufReader::new(input)).map_err(malformed)?;
let mut il = image::Limits::default();
il.max_alloc = Some(max_decode_bytes);
decoder.set_limits(il).map_err(malformed)?;
@@ -126,6 +132,35 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result<Animation, Fram
collect(width, height, decoder.into_frames().take(limits.max_frames), limits, has_more)
}
/// Present default flags, delay and transparent index for controls consumed by
/// skipped text blocks. Keep offsets stable and copy only the bytes being read.
struct DecoderInput<'a> {
bytes: Cursor<&'a [u8]>,
text_controls: Vec<usize>,
}
impl Read for DecoderInput<'_> {
fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
let start = usize::try_from(self.bytes.position()).unwrap_or(usize::MAX);
let count = self.bytes.read(output)?;
if count == 0 {
return Ok(0);
}
let end = start + count;
let first = self.text_controls.partition_point(|&offset| offset + 4 <= start);
for &offset in self.text_controls[first..].iter().take_while(|&&offset| offset < end) {
output[offset.saturating_sub(start)..(offset + 4).min(end) - start].fill(0);
}
Ok(count)
}
}
impl Seek for DecoderInput<'_> {
fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
self.bytes.seek(position)
}
}
/// Reads the optional ICC application extension without decoding frame pixels. As in the image
/// decoder, a malformed optional profile is ignored and returned as `None`.
pub fn icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
@@ -218,6 +253,52 @@ mod tests {
a.frames.iter().map(|f| (f.rgba[0], f.delay_ms)).collect()
}
#[test]
fn plain_text_control_does_not_change_the_decoded_images() {
let mut bytes = Vec::new();
{
let mut encoder = gif::Encoder::new(&mut bytes, 2, 2, &[255, 0, 0, 0, 0, 255]).unwrap();
for (index, delay, transparent) in [(0, 23, Some(0)), (1, 7, None)] {
let frame = gif::Frame {
width: 2,
height: 2,
delay,
transparent,
dispose: gif::DisposalMethod::Previous,
buffer: vec![index; 4].into(),
..gif::Frame::default()
};
encoder.write_frame(&frame).unwrap();
}
}
let first_image = crate::scan(&bytes, 1).unwrap().frames[0].offset;
let text = [0x21, 0x01, 12, 0, 0, 0, 0, 2, 0, 2, 0, 1, 1, 1, 0, 1, b'X', 0];
bytes.splice(first_image..first_image, text);
let animation = read_frames(&bytes, &FrameLimits::default()).unwrap();
assert_eq!(animation.frames.len(), 2);
let first = &animation.frames[0];
assert_eq!((&first.rgba[..4], first.delay_ms), (&[255, 0, 0, 255][..], 0));
let second = &animation.frames[1];
assert_eq!((&second.rgba[..4], second.delay_ms), (&[0, 0, 255, 255][..], 70));
}
#[test]
fn text_control_can_span_decoder_reads() {
let bytes: Vec<u8> = (1..=16).collect();
let mut input = DecoderInput { bytes: Cursor::new(&bytes), text_controls: vec![3, 10] };
let mut prefix = [0; 5];
input.read_exact(&mut prefix).unwrap();
assert_eq!(prefix, [1, 2, 3, 0, 0]);
let mut tail = Vec::new();
input.read_to_end(&mut tail).unwrap();
assert_eq!(tail, [0, 0, 8, 9, 10, 0, 0, 0, 0, 15, 16]);
input.seek(SeekFrom::Start(6)).unwrap();
let mut around = [0; 4];
input.read_exact(&mut around).unwrap();
assert_eq!(around, [0, 8, 9, 10]);
}
#[test]
fn every_frame_with_its_delay() {
let a = read_frames(&gif(&[(10, 5), (200, 10), (10, 0)]), &FrameLimits::default()).unwrap();
@@ -313,6 +394,19 @@ mod tests {
);
}
#[test]
fn retained_byte_budget_must_fit_one_frame() {
let bytes = gif(&[(10, 5), (200, 10)]);
let first_frame_bytes = 3 * 2 * 4;
let limits = FrameLimits { max_bytes: first_frame_bytes - 1, ..FrameLimits::default() };
assert!(matches!(read_frames(&bytes, &limits), Err(FrameError::LimitExceeded(_))));
let limits = FrameLimits { max_bytes: first_frame_bytes, ..limits };
let animation = read_frames(&bytes, &limits).unwrap();
assert_eq!(reds(&animation), [(10, 50)]);
assert_eq!(animation.stop, Stop::ByteLimit);
}
#[test]
fn merged_frames_still_report_the_decode_frame_limit() {
let bytes = gif(&[(10, 5), (10, 7), (200, 1)]);
+22 -1
View File
@@ -107,6 +107,12 @@ fn skip_sub_blocks(b: &[u8], mut at: usize) -> Option<usize> {
/// `None` when `bytes` is not a GIF or ends inside its Logical Screen Descriptor. A file that
/// breaks off later gives what was read, with [`Info::complete`] false.
pub fn scan(bytes: &[u8], max_frames: usize) -> Option<Info> {
scan_with_text_controls(bytes, max_frames, |_| {})
}
// Report the control payloads that the image decoder would carry past a text block
// to an image without a control of its own.
fn scan_with_text_controls(bytes: &[u8], max_frames: usize, mut text_control: impl FnMut(usize)) -> Option<Info> {
let b = bytes;
if !sniff(b) {
return None;
@@ -116,8 +122,10 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option<Info> {
b.get(12)?;
let mut info = Info { width, height, global_table: packed & 0x80 != 0, frames: Vec::new(), complete: false, loop_count: None };
let mut at = 13 + table_len(packed);
// What the last Graphic Control Extension said, for the next image.
// What the last Graphic Control Extension said, for the next rendering block.
let (mut delay_cs, mut transparent, mut disposal) = (0u16, None, 0u8);
let mut control_offset = None;
let mut text_control_offset = None;
// Each step either finishes the walk or moves `at` forward, so this ends with the file.
let mut step = || -> Option<bool> {
match *b.get(at)? {
@@ -132,6 +140,8 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option<Info> {
delay_cs = u16_at(b, body + 2)?;
transparent = (flags & 0x01 != 0).then_some(*b.get(body + 4)?);
disposal = (flags >> 2) & 7;
control_offset = Some(body + 1);
text_control_offset = None;
}
// Application Extension NETSCAPE2.0 (or ANIMEXTS1.0): sub-block 3, 1, loop count.
if label == 0xFF
@@ -141,6 +151,13 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option<Info> {
info.loop_count = u16_at(b, body + 14);
}
at = skip_sub_blocks(b, body)?;
// GIF89a §12: a Plain Text Extension consumes the pending graphic control.
if label == 0x01 {
(delay_cs, transparent, disposal) = (0, None, 0);
if let Some(offset) = control_offset.take() {
text_control_offset = Some(offset);
}
}
Some(true)
}
// Image Descriptor: separator, left, top, width, height, packed fields, then the
@@ -162,6 +179,10 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option<Info> {
local_table: packed & 0x80 != 0,
});
(delay_cs, transparent, disposal) = (0, None, 0);
control_offset = None;
if let Some(offset) = text_control_offset.take() {
text_control(offset);
}
at = skip_sub_blocks(b, (at + 10).checked_add(table_len(packed))?.checked_add(1)?)?;
Some(true)
}
+36
View File
@@ -75,6 +75,42 @@ fn the_first_frames_table_and_transparent_entry() {
assert_eq!(palette(&gif(&l, Some(9), None)), Some((l.to_vec(), None)));
}
#[test]
fn graphic_control_ends_at_plain_text() {
let mut bytes = Vec::new();
let colors = [0, 0, 0, 255, 0, 0];
{
let mut encoder = gif::Encoder::new(&mut bytes, 2, 2, &colors).unwrap();
let frame = gif::Frame {
width: 2,
height: 2,
delay: 23,
transparent: Some(1),
dispose: gif::DisposalMethod::Previous,
buffer: std::borrow::Cow::Borrowed(&[0; 4]),
..gif::Frame::default()
};
encoder.write_frame(&frame).unwrap();
}
let image_start = scan(&bytes, 1).unwrap().frames[0].offset;
// A comment does not consume the control that precedes it.
let comment = [0x21, 0xfe, 1, b'x', 0];
bytes.splice(image_start..image_start, comment);
let before = scan(&bytes, 1).unwrap();
let first = before.frames[0];
assert_eq!((first.delay_cs, first.transparent, first.disposal), (23, Some(1), 3));
assert_eq!(palette(&bytes).unwrap().1, Some(1));
// A 2×2 plain text grid with 1×1 cells and one character consumes it.
let text = [0x21, 0x01, 12, 0, 0, 0, 0, 2, 0, 2, 0, 1, 1, 1, 0, 1, b'X', 0];
bytes.splice(first.offset..first.offset, text);
let after = scan(&bytes, 1).unwrap();
assert!(after.complete);
let first = after.frames[0];
assert_eq!((first.delay_cs, first.transparent, first.disposal), (0, None, 0));
assert_eq!(palette(&bytes).unwrap(), (vec![[0, 0, 0], [255, 0, 0]], None));
}
#[test]
fn no_table_or_not_a_gif_is_none() {
assert_eq!(palette(&gif(&[], None, None)), None, "no table at all");
+1
View File
@@ -1,4 +1,5 @@
//! Header-only PNG inspection without inflating image data.
pub use crate::resolution_probe::png_pixels_per_meter as pixels_per_meter;
use crate::{CodecError, Format};
fn err(message: &str) -> CodecError {
CodecError::malformed(Format::Png, message)
+126 -5
View File
@@ -1,4 +1,4 @@
//! Explicit verbatim EXIF and JPEG APP metadata helpers for callers that preserve stored orientation.
//! Explicit PNG density, verbatim EXIF and JPEG APP metadata helpers for encoded images.
//! Normal encoder APIs still normalize metadata for upright pixels; callers opt in to these helpers.
use crate::{CodecError, Format};
@@ -100,15 +100,88 @@ fn jpeg_exif_payload(jpeg: &[u8]) -> Option<std::ops::Range<usize>> {
}
}
const PNG_IHDR_END: usize = 33;
/// A complete PNG pHYs chunk in pixels per metre, including the length, type and CRC.
///
/// Both axes must be nonzero. The caller chooses the conversion from PPI to raw pixels per metre.
/// The payload follows [PNG Third Edition, pHYs](https://www.w3.org/TR/png-3/#11pHYs).
pub fn png_pixels_per_meter_chunk((x, y): (u32, u32)) -> Result<[u8; 21], CodecError> {
if x == 0 || y == 0 {
return Err(error(Format::Png, "PNG density requires two nonzero axes"));
}
let mut chunk = [0; 21];
chunk[..4].copy_from_slice(&9u32.to_be_bytes());
chunk[4..8].copy_from_slice(b"pHYs");
chunk[8..12].copy_from_slice(&x.to_be_bytes());
chunk[12..16].copy_from_slice(&y.to_be_bytes());
chunk[16] = 1;
let crc = crc32fast::hash(&chunk[4..17]);
chunk[17..].copy_from_slice(&crc.to_be_bytes());
Ok(chunk)
}
/// Insert one pHYs chunk after IHDR and remove the old density chunks through IEND.
///
/// The PNG signature and chunk boundaries must be intact through a zero-length IEND.
/// The rewrite preserves all other bytes, including trailing bytes, and leaves existing CRCs
/// and image data as supplied. It bounds the returned file by `max_bytes` and never inflates pixels.
pub fn with_png_pixels_per_meter(png: &[u8], resolution: (u32, u32), max_bytes: usize) -> Result<Vec<u8>, CodecError> {
let density = png_pixels_per_meter_chunk(resolution)?;
let header = png
.get(..PNG_IHDR_END)
.filter(|h| h.starts_with(b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR"))
.ok_or_else(|| CodecError::malformed(Format::Png, "PNG signature or IHDR is missing"))?;
let mut at = PNG_IHDR_END;
let mut removed = 0;
let end = loop {
let chunk = png_chunk_at(png, at).ok_or_else(|| CodecError::malformed(Format::Png, "truncated PNG chunk or missing IEND"))?;
if chunk.len() - 12 > i32::MAX as usize {
return Err(CodecError::malformed(Format::Png, "PNG chunk length exceeds 31 bits"));
}
at += chunk.len();
match &chunk[4..8] {
b"pHYs" => removed += chunk.len(),
b"IEND" if chunk.len() == 12 => break at,
b"IEND" => return Err(CodecError::malformed(Format::Png, "nonempty IEND")),
_ => {}
}
};
let size = (png.len() - removed)
.checked_add(density.len())
.filter(|&size| size <= max_bytes)
.ok_or_else(|| CodecError::LimitExceeded("PNG density rewrite byte budget".into()))?;
let mut out = Vec::new();
out.try_reserve_exact(size).map_err(|_| CodecError::LimitExceeded("PNG density rewrite allocation".into()))?;
out.extend_from_slice(header);
out.extend_from_slice(&density);
let (datastream, trailing) = png.split_at(end);
let mut at = PNG_IHDR_END;
while let Some(chunk) = png_chunk_at(datastream, at) {
if &chunk[4..8] != b"pHYs" {
out.extend_from_slice(chunk);
}
at += chunk.len();
}
out.extend_from_slice(trailing);
Ok(out)
}
fn png_chunk_at(png: &[u8], at: usize) -> Option<&[u8]> {
let rest = png.get(at..)?;
let size = u32::from_be_bytes(*rest.first_chunk()?) as usize;
rest.get(..size.checked_add(12)?)
}
/// Replace the existing PNG eXIf chunk, preserving the other chunks and recomputing its CRC.
/// No chunk is inserted when one is absent.
pub fn replace_png_exif(png: &mut Vec<u8>, exif: &[u8]) -> Result<(), CodecError> {
let len = u32::try_from(exif.len()).map_err(|_| error(Format::Png, "EXIF too large"))?;
let mut p = 8usize;
while let Some(bytes) = p.checked_add(4).and_then(|end| png.get(p..end)) {
let size = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
let Some(end) = p.checked_add(12).and_then(|v| v.checked_add(size)).filter(|end| *end <= png.len()) else { break };
if png.get(p + 4..p + 8) == Some(b"eXIf") {
while let Some(existing) = png_chunk_at(png, p) {
let end = p + existing.len();
if &existing[4..8] == b"eXIf" {
let mut chunk = Vec::new();
chunk.extend_from_slice(&len.to_be_bytes());
chunk.extend_from_slice(b"eXIf");
@@ -305,6 +378,54 @@ mod tests {
assert_eq!(no_marker, before);
}
#[test]
fn png_density_chunk_uses_raw_values_and_the_expected_crc() {
let expected = b"\0\0\0\x09pHYs\0\0\x2e\x23\0\0\x17\x12\x01\x95\x42\xe6\xdb";
assert_eq!(&png_pixels_per_meter_chunk((11_811, 5_906)).unwrap(), expected);
assert!(png_pixels_per_meter_chunk((0, 5_906)).is_err());
assert!(png_pixels_per_meter_chunk((11_811, 0)).is_err());
}
#[test]
fn png_density_edit_replaces_duplicates_and_keeps_encoded_bytes() {
let image = crate::Image::from_u8(2, 1, crate::ChannelLayout::Rgb, vec![19, 33, 51, 98, 80, 61]).unwrap();
let png = crate::encode(&image, Format::Png, &crate::EncodeOptions::default()).unwrap();
let old_density = b"\0\0\0\x09pHYs\0\0\x2e\x23\0\0\x17\x12\x01\x95\x42\xe6\xdb";
let trail = b"container trailer";
let iend = png.len() - 12;
// The second obsolete density occurs too late. The rewrite leaves one legal chunk.
let input = [&png[..33], old_density, &png[33..iend], old_density, &png[iend..], trail].concat();
let resolution = (200_003, 93_511);
let added = png_pixels_per_meter_chunk(resolution).unwrap();
let expected = [&png[..33], &added, &png[33..], trail].concat();
let edited = with_png_pixels_per_meter(&input, resolution, expected.len()).unwrap();
assert_eq!(edited, expected);
assert_eq!(crate::png_probe::pixels_per_meter(&edited), Some(resolution));
let original = crate::decode(&png).unwrap();
let changed = crate::decode(&edited[..edited.len() - trail.len()]).unwrap();
assert_eq!(changed.data(), original.data());
assert!(matches!(with_png_pixels_per_meter(&input, resolution, expected.len() - 1), Err(CodecError::LimitExceeded(_))));
assert_eq!(with_png_pixels_per_meter(&edited, resolution, edited.len()).unwrap(), edited);
}
#[test]
fn png_density_edit_rejects_truncation_and_limits_insertion() {
let image = crate::Image::from_u8(1, 1, crate::ChannelLayout::Rgb, vec![10, 20, 30]).unwrap();
let png = crate::encode(&image, Format::Png, &crate::EncodeOptions::default()).unwrap();
let resolution = (2_835, 2_836);
for end in 0..png.len() {
assert!(with_png_pixels_per_meter(&png[..end], resolution, usize::MAX).is_err(), "prefix {end}");
}
let mut damaged = png.clone();
damaged[0] = 0;
assert!(with_png_pixels_per_meter(&damaged, resolution, usize::MAX).is_err());
assert!(with_png_pixels_per_meter(&png, (0, 300), usize::MAX).is_err());
assert!(matches!(with_png_pixels_per_meter(&png, resolution, png.len() + 20), Err(CodecError::LimitExceeded(_))));
let edited = with_png_pixels_per_meter(&png, resolution, png.len() + 21).unwrap();
assert_eq!(edited.len(), png.len() + 21);
assert_eq!(crate::png_probe::pixels_per_meter(&edited), Some(resolution));
}
#[test]
fn jpeg_segments_keep_order_and_enforce_limits() {
let parts = jpeg_segments(JpegMetadata { exif: Some(EXIF), xmp: Some("<x/>"), icc: Some(&[1, 2]), ppi: Some(300) }).unwrap();
+14 -4
View File
@@ -69,14 +69,19 @@ fn le_i32(b: &[u8], at: usize) -> Option<i32> {
Some(i32::from_le_bytes(b.get(at..at.checked_add(4)?)?.try_into().ok()?))
}
fn png_phys(bytes: &[u8]) -> Option<(f32, f32)> {
/// Raw PNG `pHYs` pixels per metre `(x, y)` before any DPI snapping, when the chunk precedes
/// `IDAT`/`IEND` within the shared chunk limit, has unit `1` (metre), and both axes are nonzero.
pub fn png_pixels_per_meter(bytes: &[u8]) -> Option<(u32, u32)> {
if !bytes.starts_with(PNG_SIGNATURE) {
return None;
}
let mut pos = PNG_SIGNATURE.len();
for _ in 0..MAX_CHUNKS {
let len = usize::try_from(be_u32(bytes, pos)?).ok()?;
let data = pos.checked_add(8)?;
match bytes.get(pos.checked_add(4)?..data)? {
// A `pHYs` chunk holds exactly nine bytes; the whole chunk, CRC included, must be there.
b"pHYs" if len == 9 => return bytes.get(data..data.checked_add(13)?).and_then(|chunk| phys(chunk.get(..9)?)),
b"pHYs" if len == 9 => return bytes.get(data..data.checked_add(13)?).and_then(|chunk| phys_ppm(chunk.get(..9)?)),
b"pHYs" => return None,
b"IDAT" | b"IEND" => return None,
_ => pos = data.checked_add(len)?.checked_add(4)?,
@@ -85,15 +90,20 @@ fn png_phys(bytes: &[u8]) -> Option<(f32, f32)> {
None
}
fn png_phys(bytes: &[u8]) -> Option<(f32, f32)> {
let (x, y) = png_pixels_per_meter(bytes)?;
Some((png::dpi_of_ppm(x), png::dpi_of_ppm(y)))
}
/// `pHYs`: pixels per unit in x and y, then the unit (1 = metre; 0 = aspect ratio only).
fn phys(data: &[u8]) -> Option<(f32, f32)> {
fn phys_ppm(data: &[u8]) -> Option<(u32, u32)> {
let (x, y) = (be_u32(data, 0)?, be_u32(data, 4)?);
// As the decoder does: a zero count, or a unit other than the metre, records no resolution,
// so the `eXIf` resolution can still answer.
if *data.get(8)? != 1 || x == 0 || y == 0 {
return None;
}
Some((png::dpi_of_ppm(x), png::dpi_of_ppm(y)))
Some((x, y))
}
/// The resolution of a PNG's `eXIf` chunk, read by the decoder's own header probe.
@@ -301,3 +301,21 @@ fn png_zero_phys_leaves_the_exif_resolution() {
assert_eq!(file_resolution(&png(&[zero(0, 0), exif.clone()])), Some((600.0, 600.0)));
assert_eq!(file_resolution(&png(&[zero(11_811, 0), exif])), Some((600.0, 600.0)));
}
#[test]
fn png_pixels_per_meter_preserves_raw_values_and_shared_chunk_limit() {
assert_eq!(crate::png_probe::pixels_per_meter(&png(&[phys(1181, 2362, 1)])), Some((1181, 2362)));
assert_eq!(crate::png_probe::pixels_per_meter(&png(&[phys(1181, 1181, 0)])), None);
assert_eq!(crate::png_probe::pixels_per_meter(&png(&[phys(0, 1181, 1)])), None);
assert_eq!(crate::png_probe::pixels_per_meter(b"not a png"), None);
assert_eq!(crate::png_probe::pixels_per_meter(&png(&[png_chunk(b"IDAT", &[]), phys(1181, 1181, 1)])), None);
let text = png_chunk(b"tEXt", b"k\x00v");
let mut at_limit = vec![text.clone(); super::MAX_CHUNKS - 2];
at_limit.push(phys(1181, 1181, 1));
assert_eq!(crate::png_probe::pixels_per_meter(&png(&at_limit)), Some((1181, 1181)));
let mut past_limit = vec![text; super::MAX_CHUNKS - 1];
past_limit.push(phys(1181, 1181, 1));
assert_eq!(crate::png_probe::pixels_per_meter(&png(&past_limit)), None);
}
+111
View File
@@ -0,0 +1,111 @@
//! Cooperative cancellation of media requests.
//!
//! A request worker installs a flag with [`with_cancel`]. Readers poll [`cancelled`] at
//! their existing interruption points and can return [`crate::MediaError::Cancelled`].
//! Use [`Context`] to carry the same flag to another worker.
use std::cell::RefCell;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
thread_local! {
static CURRENT: RefCell<Option<Arc<AtomicBool>>> = const { RefCell::new(None) };
}
/// Run `f` with this cancellation flag, restoring the preceding state when the scope ends.
pub fn with_cancel<R>(flag: &Arc<AtomicBool>, f: impl FnOnce() -> R) -> R {
Context(Some(Arc::clone(flag))).run(f)
}
/// Whether the flag installed on this thread has been set. An empty context is never cancelled.
pub fn cancelled() -> bool {
CURRENT.with_borrow(|flag| flag.as_ref().is_some_and(|flag| flag.load(Ordering::Relaxed)))
}
/// A captured cancellation scope that can be carried to another thread.
///
/// It holds the flag itself, so cancellation after capture is visible to the worker.
/// A default context has no flag.
#[derive(Clone, Default)]
pub struct Context(Option<Arc<AtomicBool>>);
impl Context {
/// Capture this thread's current cancellation scope.
pub fn current() -> Self {
Self(CURRENT.with_borrow(Clone::clone))
}
/// Run `f` with this context, even when empty. Restore the previous context on return or unwind.
pub fn run<R>(self, f: impl FnOnce() -> R) -> R {
struct Restore(Option<Arc<AtomicBool>>);
impl Drop for Restore {
fn drop(&mut self) {
CURRENT.with_borrow_mut(|flag| *flag = self.0.take());
}
}
let _restore = Restore(CURRENT.with_borrow_mut(|flag| std::mem::replace(flag, self.0)));
f()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn live_flag_is_scoped_and_nested_contexts_can_mask_it() {
let outer = Arc::new(AtomicBool::new(false));
let inner = Arc::new(AtomicBool::new(false));
assert!(!cancelled());
with_cancel(&outer, || {
assert!(!cancelled());
outer.store(true, Ordering::Relaxed);
assert!(cancelled());
with_cancel(&inner, || assert!(!cancelled()));
assert!(cancelled());
Context::default().run(|| assert!(!cancelled()));
assert!(cancelled());
});
assert!(!cancelled());
}
#[test]
fn unwind_restores_the_enclosing_flag() {
let outer = Arc::new(AtomicBool::new(false));
let inner = Arc::new(AtomicBool::new(true));
with_cancel(&outer, || {
let result = std::panic::catch_unwind(|| with_cancel(&inner, || panic!("request failed")));
assert!(result.is_err());
assert!(!cancelled());
outer.store(true, Ordering::Relaxed);
assert!(cancelled());
});
assert!(!cancelled());
}
#[test]
fn captured_flag_is_live_on_the_worker_and_restores_its_context() {
let request = Arc::new(AtomicBool::new(false));
let context = with_cancel(&request, Context::current);
request.store(true, Ordering::Relaxed);
std::thread::spawn(move || {
let worker = Arc::new(AtomicBool::new(false));
with_cancel(&worker, || {
assert!(context.clone().run(cancelled));
assert!(!cancelled());
let result = std::panic::catch_unwind(|| context.run(|| panic!("delegate failed")));
assert!(result.is_err());
assert!(!cancelled());
worker.store(true, Ordering::Relaxed);
assert!(cancelled());
});
assert!(!cancelled());
})
.join()
.unwrap();
assert!(!cancelled());
}
}
+2
View File
@@ -26,6 +26,8 @@ use craft_media::ByteSource;
use craft_time::{FrameRate, Tick};
use serde::{Deserialize, Serialize};
pub mod cancel;
/// Errors from opening or reading a media source.
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
pub enum MediaError {
+2
View File
@@ -18,6 +18,7 @@ mod config_fields;
mod demux;
mod error;
mod mux;
mod rtmd;
pub use crate::source::{ByteSource, ReadSeekSource};
pub use bytes::FourCc;
@@ -30,3 +31,4 @@ pub use config_fields::{avcc_length_size, dac3_layout, dec3_layout, esds_object_
pub use demux::{Edit, Metadata, Mp4File, Sample, SampleGroup, Track, TrackKind, open};
pub use error::{Error, Result};
pub use mux::{Brand, FragmentedWriter, Mp4Writer, TrackConfig, WriteSample, WriterOptions};
pub use rtmd::{SONY_RTMD_TIMECODE_PREFIX_LEN, SonyRtmdTimecode, parse_sony_rtmd_timecode};
+81
View File
@@ -0,0 +1,81 @@
//! Sony XAVC timed metadata's recorded-timecode fields.
//!
//! Wire layout and accepted labels follow the existing Craft implementation in FilmCraft
//! (crates/codecs/src/mp4.rs and its synthetic mp4_rtmd integration tests, revision 3f137a7e).
//! This parser does not choose a sample or determine a track's presentation origin.
/// Bytes needed from the start of a Sony real-time metadata sample.
pub const SONY_RTMD_TIMECODE_PREFIX_LEN: usize = 18;
/// A Sony real-time metadata timecode label, before conversion to a frame count.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SonyRtmdTimecode {
/// Hour within the day.
pub hours: u8,
/// Minute within the hour.
pub minutes: u8,
/// Second within the minute.
pub seconds: u8,
/// Frame label within the second.
pub frames: u8,
/// Whether the sample signals drop-frame numbering.
pub drop_frame: bool,
}
/// Read the recorded label from a Sony `rtmd` sample prefix.
///
/// `frame_base` is the nominal integer frame count per second for the associated video;
/// `supports_drop_frame` says whether its rate supports drop-frame numbering. Preserve the
/// recorded flag even for a rate that does not support it. Reject skipped labels only when
/// drop-frame numbering applies; choosing a timeline origin is the caller's responsibility.
pub fn parse_sony_rtmd_timecode(prefix: &[u8], frame_base: u32, supports_drop_frame: bool) -> Option<SonyRtmdTimecode> {
let &[hours, minutes, seconds, flag, frames] = prefix.get(13..SONY_RTMD_TIMECODE_PREFIX_LEN)? else { return None };
let drop_frame = flag != 0;
if hours >= 24 || minutes >= 60 || seconds >= 60 || u32::from(frames) >= frame_base {
return None;
}
if drop_frame && supports_drop_frame && seconds == 0 && !minutes.is_multiple_of(10) && u32::from(frames) < frame_base / 15 {
return None;
}
Some(SonyRtmdTimecode { hours, minutes, seconds, frames, drop_frame })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sony_rtmd_parses_only_the_fixed_prefix() {
let mut prefix = [0u8; SONY_RTMD_TIMECODE_PREFIX_LEN + 1];
prefix[13..18].copy_from_slice(&[3, 37, 12, 0, 34]);
prefix[18] = 255;
let expected = Some(SonyRtmdTimecode { hours: 3, minutes: 37, seconds: 12, frames: 34, drop_frame: false });
assert_eq!(parse_sony_rtmd_timecode(&prefix[..17], 60, true), None);
assert_eq!(parse_sony_rtmd_timecode(&prefix[..18], 60, true), expected);
assert_eq!(parse_sony_rtmd_timecode(&prefix, 60, true), expected);
}
#[test]
fn sony_rtmd_rejects_out_of_range_labels() {
for (index, value) in [(13, 24), (14, 60), (15, 60), (17, 24)] {
let mut prefix = [0; 18];
prefix[index] = value;
assert_eq!(parse_sony_rtmd_timecode(&prefix, 24, false), None);
}
assert_eq!(parse_sony_rtmd_timecode(&[0; 18], 0, false), None);
}
#[test]
fn sony_rtmd_drop_frame_labels_follow_the_rate() {
let mut prefix = [0; 18];
// Any nonzero flag is retained. At 59.94 the first four labels at minute one are skipped.
prefix[13..18].copy_from_slice(&[0, 1, 0, 2, 3]);
assert_eq!(parse_sony_rtmd_timecode(&prefix, 60, true), None);
assert!(parse_sony_rtmd_timecode(&prefix, 24, false).is_some_and(|code| code.drop_frame));
prefix[17] = 4;
assert!(parse_sony_rtmd_timecode(&prefix, 60, true).is_some_and(|code| code.frames == 4 && code.drop_frame));
prefix[14] = 10;
prefix[17] = 0;
assert!(parse_sony_rtmd_timecode(&prefix, 60, true).is_some_and(|code| code.frames == 0));
}
}
+1
View File
@@ -12,6 +12,7 @@ workspace = true
[dependencies]
craft-cfb = { workspace = true }
craft-codepage = { workspace = true }
craft-drawingml = { workspace = true }
craft-pptx = { workspace = true }
log = { workspace = true }
+33 -2
View File
@@ -38,7 +38,8 @@ PowerPoint 95 (7.0) files use the same compound file and many of the same record
16-byte record header and a single record tree with no edit chain. A file whose `PowerPoint
Document` stream starts with that tree is read on its own path; anything else takes the
PowerPoint 97 path. The tree's Document must hold its DocumentAtom, which counts the slides;
`import_checked` names the slides that count says a cut-short file is missing ("slide 3"). What
`import_checked` names the slides a cut-short file is missing ("slide 3"): those the count says it
should hold, and any cut off after its header, which is left out. What
was learned of the format came from files PowerPoint 95 itself wrote,
one feature per file, and the public [MS-PPT] numbering where the records keep it.
@@ -47,7 +48,37 @@ master wearing the file's colour scheme, and its background when that isn't the
its slides in order with their master, layout type and, when a slide doesn't follow the master's,
its own background: a solid colour, or none when the slide's background has no fill. A slide also
says whether it shows the master's objects and whether it uses the master's colour scheme or its
own. The slides are empty: shapes, placeholders and their text, pictures and notes come later.
own. Slides hold
their placeholders (title, body, centred title, subtitle, and the date, footer and slide number)
and text boxes, each with its box and its text: the text's anchoring (top, middle or bottom, and
whether it's centred across) and word wrap, paragraphs with their level, alignment (justified
included), line spacing, space before and after (in lines or points), bullet character and the
indents of the text's ruler, and runs with their font, size, bold, italic, underline and colour
(an RGB or a colour scheme slot). The text is Windows-1252. The master's placeholders set where the
default master's placeholders go, and its date, footer and slide number those of every layout. The
master's text styles become its title, body and other styles, level by level. Shapes and lines
read too: all 24 of PowerPoint 95's shapes (rectangle, rounded rectangle, ellipse, diamond, the
two triangles, parallelogram, trapezoid, hexagon, octagon, plus, five-point star, the arrow and
the thick arrow in their four directions, home plate, cube, balloon and seal) as DrawingML presets
with their adjust values (the trapezoid, wide at the top in PowerPoint 95, as its own outline, so
its text stays upright), each with its fill (or none), its line (or none) with its colour, its
width (the six line styles, 1 to 10 pt) and its dots or dashes, and its shadow with the shadow's
colour, offset and transparency; and lines from their start to their end, with their arrowheads.
A shape code no probe showed reads as a rectangle. PowerPoint 95 measures angles
counter-clockwise, DrawingML clockwise, so each is negated. A shape's geometry holds its outline
as drawn, quarter-turns and mirror included, so its angle and flips come from there (a box turned
by an odd number of quarter-turns is turned back); the rectangle, rounded rectangle and ellipse
take the angle the user set. A shape that draws nothing but text is a text box; a shape's text is
read as a text box's is. PowerPoint 95 lays it out in the box the geometry holds, turned by the
text's own angle, so the text of a shape turned before it was typed stays upright: such text is
`upright`, at its own angle, with its insets on that box's edges (a balloon's measured from its
body). A preset with a text rectangle of its own, such as an arrow's shaft, applies the insets
inside that rectangle, where PowerPoint 95 measures them from the whole box, so such text can sit
off from where PowerPoint 95 puts it. Freeforms read as custom paths through their points, in
their box, with
their format's fill, line and shadow, and open ones with their arrowheads. Groups read as groups
of their members, which keep their places on the slide (PowerPoint 95 can't turn or flip a
group), nested up to 32 deep. Pictures and notes come later.
The caller's `craft_pptx::Defaults` supplies the master each of the file's masters starts from:
its layouts and placeholders. The file's masters then place and style the placeholders that
+43 -33
View File
@@ -177,6 +177,41 @@ pub fn convert<'a>(d: &Doc<'a>, pictures: &'a [u8], app: &'a dyn Defaults) -> Pr
cx.p
}
/// A main master's placeholder of `kind` at `x`: the box of the default master's placeholder of
/// the same family. The footer row (date, footer, slide number) sits in the same place on every
/// layout, with the master's look: `look` gives its first paragraph, whose alignment and first
/// run's size and colour (its end mark's, when it is empty) the master's and layouts' footer
/// placeholders take. `look` is called only
/// for the footer row, and only when the default master has such a placeholder.
pub(crate) fn place_placeholder(master: &mut Master, kind: PhType, x: Xfrm, look: impl FnOnce() -> Option<Paragraph>) {
let Some(s) = master.shapes.iter_mut().find(|s| s.ph_type().is_some_and(|t| same_family(t, kind))) else { return };
s.xfrm = Some(x);
if matches!(kind, PhType::Date | PhType::Footer | PhType::SlideNum) {
let look = look();
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);
let first = p.runs.first().map_or(&p.end_props, |r| &r.props);
level.run.size = first.size.or(level.run.size);
level.run.fill = first.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);
}
}
}
}
}
/// A master's first layout of each layout type, and its first layout.
pub(crate) type LayoutTable = (Vec<(LayoutType, LayoutId)>, Option<LayoutId>);
@@ -267,37 +302,10 @@ impl<'a> Ctx<'a> {
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);
}
}
}
}
if let (Some(kind), Some(x)) = (ph_type(ph.kind), raw.anchor.map(|a| xfrm(&a, TOP, 0.0, false, false))) {
place_placeholder(&mut master, kind, x, || {
self.shape(raw, &scope, 0, TOP).and_then(|c| c.text).and_then(|t| t.paragraphs.into_iter().next())
});
}
continue;
}
@@ -931,7 +939,9 @@ impl<'a> Ctx<'a> {
para.runs.push(Run::with(String::from_utf16_lossy(&units), props));
i = j;
}
para.end_props = first;
// The paragraph mark's own formatting, as PowerPoint reads it: the character run at the
// CR, or at the text's end for the last paragraph.
para.end_props = self.run_props(&cf_at(end), &scope.scheme);
para.normalize();
out.push(para);
if end >= total {
@@ -1148,7 +1158,7 @@ fn ph_type(kind: u8) -> Option<PhType> {
})
}
fn same_family(a: PhType, b: PhType) -> bool {
pub(crate) fn same_family(a: PhType, b: PhType) -> bool {
let title = |t| matches!(t, PhType::Title | PhType::CtrTitle);
a == b || (title(a) && title(b))
}
+8 -4
View File
@@ -172,18 +172,22 @@ 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);
adj.push(round_rect_adjust(v as i32));
}
return Geom::Preset { name: name.into(), adj };
}
custom_path(props).map(|paths| Geom::Custom { paths }).unwrap_or_default()
}
/// A rounded rectangle's corner: a 21600 coordinate in OfficeArt, a 100000 fraction of the shorter
/// side in DrawingML.
pub(crate) fn round_rect_adjust(v: i32) -> f64 {
f64::from(v).clamp(0.0, 10800.0) / 21600.0 * 100_000.0
}
/// `msosptTrapezoid`. It has no preset: DrawingML's `trapezoid` is wide at the bottom, OfficeArt's
/// at the top.
const TRAPEZOID: u16 = 8;
@@ -192,7 +196,7 @@ const TRAPEZOID: u16 = 8;
/// bottom edge inset by `adjust` (5400 unless the file says otherwise) at each end. PowerPoint
/// writes the shape the same way when it saves a `.ppt` trapezoid as `.pptx`. A preset flipped
/// upright would turn the shape's text upside down.
fn trapezoid(adjust: Option<u32>) -> Geom {
pub(crate) fn trapezoid(adjust: Option<u32>) -> Geom {
let a = adjust.map_or(5400, |v| (v as i32).clamp(0, 10800));
let d = format!("M 0 0 L {a} 21600 L {} 21600 L 21600 0 Z", 21600 - a);
Geom::Custom { paths: vec![CustomPath { w: 21600.0, h: 21600.0, d, ..Default::default() }] }
+8 -6
View File
@@ -8,11 +8,13 @@
//! place and style. There is no `.ppt` writer.
//!
//! PowerPoint 95 files (a different record framing, learned from files PowerPoint 95 wrote) read
//! as far as their slide size, masters with their colour schemes and backgrounds, and slides with
//! their order, master, layout type and background; their shapes, text, pictures and notes are
//! not read yet, so the slides are empty. Older formats aren't read: a compound file in neither
//! framing is refused as too old when its current user record has neither of [MS-PPT]'s tokens
//! and it has no edit record, and a file that isn't a compound file is not a presentation.
//! as far as their slide size, masters with their colour schemes, backgrounds, placeholder boxes
//! and text styles, and slides with their order, master, layout type, background, placeholders
//! and text boxes with formatted, anchored text, and shapes and lines with their fill, line and
//! shadow; their pictures and notes are not read yet. Older formats aren't read: a compound file
//! in neither framing is refused as too old when its current user record has neither of
//! [MS-PPT]'s tokens and it has no edit record, and a file that isn't a compound file is not a
//! presentation.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
@@ -78,7 +80,7 @@ pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presenta
// PowerPoint 97 path, which refuses older formats as too old.
if let Some(document) = ppt95::document(&stream) {
let p = ppt95::convert(&document, defaults);
let lost = ppt95::lost(&document, &p);
let lost = ppt95::lost(&document);
return Ok((p, lost));
}
let current_user = file.read_path_capped("Current User", cap).unwrap_or_default();
+449 -18
View File
@@ -6,16 +6,62 @@
//! (a type-3 root holding the Document, 1000), with no edit chain or persist directory.
//!
//! Read so far: the slide size, the masters with their colour schemes and backgrounds, and the
//! slides in order with their master, layout type and background. Shapes, text, pictures and
//! notes are not read yet, so slides come out empty.
//! slides in order with their master, layout type and background, holding their placeholders, text
//! boxes, shapes, lines, freeforms and groups, with the text, its character and paragraph
//! formatting (spacing and justified alignment included) and its anchoring ([`text`]).
//!
//! A page's object list (3000) holds shapes (3008), placeholders (3010, which add a 3011 atom: the
//! type, the size, then the index), lines (3014), freeforms (3016) and groups (3001). A shape or
//! placeholder has its geometry (3009): the shape code (its low byte; the byte above orients the
//! outline) and its adjust value, the box as left, top, right and bottom in master units (576 per
//! inch) measured from the slide's centre, then what is left of the angle after whole
//! quarter-turns, in sixteenths of a degree, counter-clockwise. A line holds 3015: its start and
//! end points, in the same units, and 3007: its arrowheads. Shapes and lines have a format (3005)
//! with their fill, line width, dashes and colour, and shadow with its offset ([`shape`]). The 24
//! shapes of the object model read as DrawingML presets, turned and flipped as drawn; a code no
//! probe showed is a rectangle. A shape that draws nothing but its text is a text box.
//!
//! A freeform holds 3017: its box (left, top, right, bottom, as a shape's), the same box again,
//! the point count and, in its low byte, 1 when it is closed; 3007, its arrowheads; its format; and
//! 3035, its points: a u16 count, then x and y as i32s, in master units from the slide's centre. A
//! closed freeform leaves out the point that repeats its first. It reads as a custom path in its
//! box ([`shape::freeform_path`]). The format's angle is not read for freeforms: no probe turned or
//! flipped one, and the two boxes of 3017 matched in every file PowerPoint 95 wrote.
//!
//! A group (3001) holds a 3002 atom and a list (2000) whose count (2001) is followed by its
//! members, read as the page's objects are, groups included. Its members keep their places on the
//! slide; the group has no box or transform of its own (PowerPoint 95 can't turn or flip one), so
//! it reads as a group whose box is the union of its members' and whose child space is that same
//! box. Groups deeper than [`MAX_DEPTH`] are left out, and members count towards the page's object
//! cap.
//!
//! PowerPoint 95 numbers placeholders its own way: on the master 1 title, 2 body, 6 date, 7 slide
//! number and 8 footer; on slides 0x0C title, 0x0D body, 0x0F centred title and 0x10 subtitle. A
//! placeholder of any other type keeps its text as a text box. The master's placeholders place the
//! caller's default master's, and the footer row places every layout's, as the PowerPoint 97 path
//! does.
//!
//! The master's text styles (the Environment's 4052 atoms, one per text type) become the master's
//! title, body and other styles. Slide text carries its own formatting in full, so these matter
//! for text added later.
//!
//! Not read yet: pictures and notes.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use craft_pptx::{Background, ColorRef, Defaults, Fill, LayoutType, Master, Presentation, Rgba, Size, Slide, SlideId};
use craft_pptx::{
Background, ColorRef, Defaults, Effects, Fill, Geom, LayoutType, Line, Master, PhType, Placeholder, Presentation, Rgba, Shape, ShapeId,
ShapeKind, Size, Slide, SlideId, TextBody, Xfrm,
};
use crate::convert::{Scheme, layout_kind, layout_table, page_side, scheme_theme};
use crate::convert::{Scheme, layout_kind, layout_table, page_side, place_placeholder, same_family, scheme_theme};
use crate::record::u32_at;
use shape::Look;
use text::Env;
mod shape;
mod text;
/// Record types.
mod rt {
@@ -31,8 +77,19 @@ mod rt {
pub const LIST: u32 = 2000;
pub const COLOR_SCHEME: u32 = 2031;
pub const OBJECTS: u32 = 3000;
pub const GROUP: u32 = 3001;
pub const FORMAT: u32 = 3005;
pub const SHAPE: u32 = 3008;
pub const GEOMETRY: u32 = 3009;
pub const PLACEHOLDER: u32 = 3010;
pub const PLACEHOLDER_ATOM: u32 = 3011;
pub const LINE: u32 = 3014;
pub const ARROWHEADS: u32 = 3007;
pub const LINE_ATOM: u32 = 3015;
pub const FREEFORM: u32 = 3016;
pub const FREEFORM_ATOM: u32 = 3017;
pub const POINTS: u32 = 3035;
pub const TEXT: u32 = 4001;
}
/// "No instance".
@@ -45,7 +102,16 @@ const SLIDE_COUNT: usize = 32;
/// Masters read at most. Each becomes a copy of the caller's default master with its layouts, so
/// the cap is lower than for slides; PowerPoint 95 writes one.
const MAX_MASTERS: usize = 256;
/// The fill colour's fourth byte when the colour is the RGB given, not a scheme slot.
/// Objects read from one slide or master at most, group members included.
const MAX_OBJECTS: usize = 1 << 14;
/// Groups nest at most this deep, as the PowerPoint 97 path's containers do; deeper ones are left
/// out, so a damaged file can't make the conversion recurse without bound.
const MAX_DEPTH: usize = crate::record::MAX_DEPTH;
/// Points read from one freeform at most, as for the PowerPoint 97 path's freeforms.
const MAX_POINTS: usize = 8192;
/// Master units (576 per inch) per point.
const MU: f64 = 8.0;
/// A colour's fourth byte when the colour is the RGB given, not a scheme slot.
const RGB_GIVEN: u8 = 0xFE;
/// PowerPoint 95's default colour scheme, for a slide or master without one.
@@ -65,6 +131,8 @@ const DEFAULT_SCHEME: Scheme = [
pub struct Rec<'a> {
pub kind: u32,
pub instance: u32,
/// The fourth word: a per-type tag, which tells some records of one type apart.
pub tag: u32,
/// The body, clipped to the input (a truncated last record keeps what is there).
pub data: &'a [u8],
}
@@ -72,11 +140,10 @@ pub struct Rec<'a> {
impl<'a> Rec<'a> {
pub fn at(bytes: &'a [u8], at: usize) -> Option<Rec<'a>> {
let word = |k: usize| u32_at(bytes, at.checked_add(k * 4)?);
// The fourth word, a tag, isn't needed yet; it must be there for the header to be whole.
let (kind, instance, len, _tag) = (word(0)?, word(1)?, word(2)?, word(3)?);
let (kind, instance, len, tag) = (word(0)?, word(1)?, word(2)?, word(3)?);
let start = at.checked_add(16)?;
let end = start.saturating_add(len as usize).min(bytes.len());
Some(Rec { kind, instance, data: bytes.get(start..end)? })
Some(Rec { kind, instance, tag, data: bytes.get(start..end)? })
}
/// The body read as records. Only called on the types that are containers; the walk never
@@ -130,13 +197,28 @@ pub fn document(stream: &[u8]) -> Option<Rec<'_>> {
Some(document)
}
/// The slides the DocumentAtom counts but the file doesn't hold, by position ("slide 3"): what a
/// truncated file lost. Empty for a whole file.
pub fn lost(document: &Rec, p: &Presentation) -> Vec<String> {
/// Whether a slide record holds what PowerPoint 95 writes first in every slide, its SlideAtom
/// (1007), whole enough to give the slide's id and its master's. One without it kept nothing (a
/// file cut short just after the slide's header, or the atom's): it is left out and named as lost.
fn kept(slide: &Rec) -> bool {
slide.child(rt::SLIDE_ATOM).and_then(|a| a.u32(4)).is_some()
}
/// The slides a truncated or damaged file lost, by position ("slide 3"): those listed without their
/// SlideAtom, and those the DocumentAtom counts past the ones listed. Empty for a whole file.
pub fn lost(document: &Rec) -> Vec<String> {
let count = document.child(rt::DOCUMENT_ATOM).and_then(|a| a.u32(SLIDE_COUNT)).map_or(0, |c| c as usize);
let read = p.slides.len();
let listed: Vec<bool> = document
.children()
.filter(|r| r.kind == rt::LIST)
.flat_map(|list| list.children().filter(|r| r.kind == rt::SLIDE))
.take(MAX_SLIDES)
.map(|r| kept(&r))
.collect();
let empty = listed.iter().enumerate().filter(|(_, k)| !**k).map(|(i, _)| i + 1);
// At most as many as could have been read, so a damaged count can't make a huge list.
(read + 1..=count.min(read + MAX_SLIDES)).map(|n| format!("slide {n}")).collect()
let missing = listed.len() + 1..=count.min(listed.len() + MAX_SLIDES);
empty.chain(missing).map(|n| format!("slide {n}")).collect()
}
/// What a slide or master says about itself.
@@ -189,9 +271,316 @@ fn background(rec: &Rec, scheme: &Scheme) -> Option<Fill> {
if format.u8(12)? == 0xFF {
return Some(Fill::None);
}
let (r, g, b, index) = (format.u8(20)?, format.u8(21)?, format.u8(22)?, format.u8(23)?);
let color = if index == RGB_GIVEN { Rgba::rgb(r, g, b) } else { *scheme.get(usize::from(index))? };
Some(Fill::solid(ColorRef::rgb(color)))
Some(Fill::solid(ColorRef::rgb(shape::color(&format, 20, scheme)?)))
}
/// A PowerPoint 95 placeholder number as a placeholder type. PowerPoint 95 numbers them its own
/// way, not as [MS-PPT] does: 1 to 8 on the master, 0x0C and up on slides.
fn ph_type(kind: u8) -> Option<PhType> {
Some(match kind {
0x01 | 0x0C => PhType::Title,
0x02 | 0x0D => PhType::Body,
0x06 => PhType::Date,
0x07 => PhType::SlideNum,
0x08 => PhType::Footer,
0x0F => PhType::CtrTitle,
0x10 => PhType::SubTitle,
_ => return None,
})
}
/// One object of a page's list, read but not given an id yet.
struct Object {
/// A placeholder (3010), whether or not its type is known.
placeholder: bool,
/// The placeholder it is, when its type is known.
ph: Option<Placeholder>,
xfrm: Xfrm,
text: Option<TextBody>,
/// The ruler slot its text names.
ruler: Option<u32>,
/// A shape's preset (a rectangle for a shape code no probe showed): `None` for a placeholder.
geom: Option<Geom>,
/// How a shape or line is drawn (a placeholder's is left to its layout).
look: Look,
kind: Kind,
}
/// What an object is, beyond its box, text, geometry and look.
enum Kind {
/// A shape (3008) or placeholder (3010).
Shape,
/// A line (3014).
Line,
/// A freeform (3016).
Freeform,
/// A group (3001) and its members.
Group(Vec<Object>),
}
/// Reads a page's objects, counting them against [`MAX_OBJECTS`] across its groups.
struct Reader<'e> {
env: &'e Env,
scheme: &'e Scheme,
size: Size,
/// Objects still to be read on this page.
left: usize,
}
impl Reader<'_> {
/// The objects of a page's object list.
fn page(env: &Env, scheme: &Scheme, size: Size, page: &Rec) -> Vec<Object> {
let mut reader = Reader { env, scheme, size, left: MAX_OBJECTS };
page.child(rt::OBJECTS).map(|l| reader.list(&l, 0)).unwrap_or_default()
}
/// The shapes, placeholders, lines, freeforms and groups of a list `depth` groups down.
fn list(&mut self, list: &Rec, depth: usize) -> Vec<Object> {
let mut out = vec![];
for r in list.children().filter(|r| matches!(r.kind, rt::SHAPE | rt::PLACEHOLDER | rt::LINE | rt::FREEFORM | rt::GROUP)) {
let Some(left) = self.left.checked_sub(1) else {
log::warn!("ppt: a PowerPoint 95 page has more than {MAX_OBJECTS} objects; the rest are left out");
break;
};
self.left = left;
out.extend(match r.kind {
rt::GROUP => self.group(&r, depth),
rt::FREEFORM => freeform(&r, self.env, self.scheme, self.size),
_ => object(&r, self.env, self.scheme, self.size),
});
}
out
}
/// A group `depth` groups down, with its members read as the page's objects are. The walk
/// recurses once per group, so a group nested deeper than [`MAX_DEPTH`] is left out.
fn group(&mut self, r: &Rec, depth: usize) -> Option<Object> {
if depth >= MAX_DEPTH {
log::warn!("ppt: PowerPoint 95 groups nest deeper than {MAX_DEPTH}; the deeper ones are left out");
return None;
}
let members = self.list(&r.child(rt::LIST)?, depth + 1);
Some(Object {
placeholder: false,
ph: None,
xfrm: Xfrm::default(),
text: None,
ruler: None,
geom: None,
look: Look::none(),
kind: Kind::Group(members),
})
}
}
/// A box from master units about the slide's centre (left, top, right, bottom, either way round)
/// to points from its top left corner.
fn xfrm_of([l, t, right, b]: [i32; 4], size: Size) -> Xfrm {
let x = |v: i32| f64::from(v) / MU + size.width / 2.0;
let y = |v: i32| f64::from(v) / MU + size.height / 2.0;
Xfrm { x: x(l).min(x(right)), y: y(t).min(y(b)), w: (x(right) - x(l)).abs(), h: (y(b) - y(t)).abs(), rot: 0.0, flip_h: false, flip_v: false }
}
/// A line: the box its ends span, flipped so that it runs from its start to its end, drawn as its
/// format says (1 pt in the scheme's text and lines colour without one), with its arrowheads.
fn line(r: &Rec, scheme: &Scheme, size: Size) -> Option<Object> {
let a = r.child(rt::LINE_ATOM)?;
let (x1, y1, x2, y2) = (a.i32(0)?, a.i32(4)?, a.i32(8)?, a.i32(12)?);
let mut xfrm = xfrm_of([x1, y1, x2, y2], size);
(xfrm.flip_h, xfrm.flip_v) = (x2 < x1, y2 < y1);
let mut look = match r.child(rt::FORMAT) {
Some(f) => shape::look(&f, scheme),
None => Look { line: shape::line_of(scheme[1], None), ..Look::none() },
};
// A line has no inside to fill.
look.fill = Fill::None;
if let Some(heads) = r.child(rt::ARROWHEADS).filter(|_| look.line != Line::none()) {
shape::arrowheads(&mut look.line, &heads);
}
let geom = Some(Geom::Preset { name: "line".into(), adj: vec![] });
Some(Object { placeholder: false, ph: None, xfrm, text: None, ruler: None, geom, look, kind: Kind::Line })
}
/// A freeform: its points as a path in its box, drawn as its format says (1 pt in the scheme's
/// text and lines colour without one), with its arrowheads when it is open. One of fewer than two
/// points draws nothing and is left out; one flagged closed with fewer than three is drawn open.
fn freeform(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option<Object> {
let a = r.child(rt::FREEFORM_ATOM)?;
let sides = [a.i32(0)?, a.i32(4)?, a.i32(8)?, a.i32(12)?];
let points = r.child(rt::POINTS).map(|p| points(&p)).unwrap_or_default();
if points.len() < 2 {
return None;
}
// Only the low byte is the flag: PowerPoint 95 leaves whatever was there in the bytes above.
let closed = a.u8(36) == Some(1) && points.len() >= 3;
let mut look = match r.child(rt::FORMAT) {
Some(f) => shape::look(&f, scheme),
None => Look { line: shape::line_of(scheme[1], None), ..Look::none() },
};
if let Some(heads) = r.child(rt::ARROWHEADS).filter(|_| !closed && look.line != Line::none()) {
shape::arrowheads(&mut look.line, &heads);
}
let geom = Some(shape::freeform_path(&points, sides, closed));
let container = r.child(rt::TEXT);
let text = container.and_then(|c| text::text_body(&c, env, scheme, Some(sides), true));
let ruler = container.and_then(|c| text::ruler_slot(&c));
Some(Object { placeholder: false, ph: None, xfrm: xfrm_of(sides, size), text, ruler, geom, look, kind: Kind::Freeform })
}
/// A 3035 atom's points: a u16 count, then x and y as i32s. No more than the record holds, nor
/// than [`MAX_POINTS`].
fn points(r: &Rec) -> Vec<(i32, i32)> {
let count = crate::record::u16_at(r.data, 0).map_or(0, usize::from);
(0..count.min(MAX_POINTS)).map_while(|i| Some((r.i32(2 + i * 8)?, r.i32(6 + i * 8)?))).collect()
}
/// A shape, placeholder or line: its box, its placeholder atom, its text, and a shape's preset and
/// look.
fn object(r: &Rec, env: &Env, scheme: &Scheme, size: Size) -> Option<Object> {
if r.kind == rt::LINE {
return line(r, scheme, size);
}
let g = r.child(rt::GEOMETRY)?;
let sides = [g.i32(12)?, g.i32(16)?, g.i32(20)?, g.i32(24)?];
let mut xfrm = xfrm_of(sides, size);
let format = r.child(rt::FORMAT);
let placeholder = r.kind == rt::PLACEHOLDER;
// The shape code is the low byte; for codes of 0 and up the byte above it orients the outline.
let code = g.u8(0).map(|c| c as i8);
let drawn = g.i32(28).unwrap_or(0);
match code {
Some(c) if c >= 0 && !placeholder => shape::orient_drawn(&mut xfrm, g.u8(1).unwrap_or(0), drawn),
// The angle the user set is the format's; the geometry's is what quarter-turns leave of it.
_ => shape::orient(&mut xfrm, drawn, format.and_then(|f| f.i32(48)).unwrap_or(drawn)),
}
let ph = r.child(rt::PLACEHOLDER_ATOM).filter(|_| placeholder).and_then(|a| {
let size = match a.u8(1) {
Some(1) => Some("half".into()),
Some(2) => Some("quarter".into()),
_ => None,
};
Some(Placeholder { kind: ph_type(a.u8(0)?)?, idx: a.u32(4).unwrap_or(0), size, ..Default::default() })
});
let container = r.child(rt::TEXT);
let mut text = container.and_then(|c| text::text_body(&c, env, scheme, Some(sides), ph.is_none()));
// The quarter-turns between the box the geometry holds and the shape's own.
let quarters = shape::quarter_turns(&xfrm, drawn);
let ruler = container.and_then(|c| text::ruler_slot(&c));
let (mut geom, mut look) = (None, Look::none());
if !placeholder {
let height = xfrm.h;
geom = code.map(|c| shape::geometry(c, g.i32(4), &mut xfrm));
// A balloon's box is its body, above its tail: the text's edge there stays where it was. The
// cut is the shape's bottom, which is the held box's edge `quarters` on from the bottom.
if let Some(b) = text.as_mut().map(|t| &mut t.body).filter(|_| height != xfrm.h) {
let inset = [&mut b.inset_l, &mut b.inset_t, &mut b.inset_r, &mut b.inset_b].into_iter().nth((3 + quarters) % 4);
if let Some(inset) = inset {
*inset = inset.map(|v| (v - (height - xfrm.h)).max(0.0));
}
}
if let Some(f) = format {
look = shape::look(&f, scheme);
}
}
// PowerPoint 95 lays a shape's text out in the box the geometry holds, turned by the text's own
// angle (4003 +16, the geometry's own angle in every probe): quarter-turns folded into that box
// don't turn the text. When the shape ends up at another angle (its box turned back, or the
// half-turn a mirrored trapezoid takes), the text is upright on the slide, at its own angle,
// with its insets on the held box's edges by name, as PowerPoint lays out `upright` text
// (checked in PowerPoint 16 against PowerPoint 95's renderings).
let angle = shape::clockwise(i64::from(container.and_then(|c| text::angle(&c)).unwrap_or(drawn)));
if let Some(t) = text.as_mut().filter(|_| (xfrm.rot - angle).rem_euclid(360.0) != 0.0) {
t.body.upright = Some(true);
t.body.rot = Some(angle).filter(|r| *r != 0.0);
}
Some(Object { placeholder, ph, xfrm, text, ruler, geom, look, kind: Kind::Shape })
}
/// An object as a shape: a placeholder of a known type; a text box when it draws nothing but its
/// text; else a shape or line that draws something. One that draws nothing is left out. A
/// placeholder of an unknown type keeps its text as a text box.
fn shape(p: &mut Presentation, o: Object) -> Option<Shape> {
if let Kind::Group(members) = o.kind {
return group(p, members);
}
let Some(ph) = o.ph else {
let text = o.text.filter(|t| !t.is_empty());
if text.is_some() && !o.look.drawn() {
let mut xfrm = o.xfrm;
(xfrm.flip_h, xfrm.flip_v) = (false, false);
return Some(Shape {
id: ShapeId(p.alloc_id()?),
name: "Text Box".into(),
xfrm: Some(xfrm),
text_box: true,
fill: Some(Fill::None),
line: Some(Line::none()),
text,
..Default::default()
});
}
let geom = o.geom.filter(|_| o.look.drawn())?;
let id = p.alloc_id()?;
let Look { fill, line, shadow, .. } = o.look;
return Some(Shape {
id: ShapeId(id),
name: match o.kind {
Kind::Line => format!("Line {id}"),
Kind::Freeform => format!("Freeform {id}"),
_ => format!("Shape {id}"),
},
xfrm: Some(o.xfrm),
geom,
fill: Some(fill),
line: Some(line),
effects: shadow.map(|s| Effects { outer_shadow: Some(s), ..Default::default() }),
text,
..Default::default()
});
};
let name = match ph.kind {
PhType::Title | PhType::CtrTitle => "Title",
PhType::SubTitle => "Subtitle",
PhType::Date => "Date",
PhType::Footer => "Footer",
PhType::SlideNum => "Slide Number",
_ => "Text",
};
// An empty placeholder draws nothing (its prompt shows only while editing).
let text = Some(o.text.unwrap_or_default());
Some(Shape { id: ShapeId(p.alloc_id()?), name: name.into(), xfrm: Some(o.xfrm), ph: Some(ph), text, ..Default::default() })
}
/// A group of the shapes its members are, in the box they span, which is also its child space, so
/// the members keep their places on the slide. A group none of whose members draws anything is
/// left out.
///
/// A nested group recurses here directly, not through [`shape`], whose frame is far larger: the
/// recursion is bounded by [`MAX_DEPTH`], and each level should cost the stack little.
fn group(p: &mut Presentation, members: Vec<Object>) -> Option<Shape> {
let id = p.alloc_id()?;
let mut children = Vec::with_capacity(members.len());
for m in members {
let s = match m.kind {
Kind::Group(inner) => group(p, inner),
_ => shape(p, m),
};
children.extend(s);
}
let mut boxes = children.iter().filter_map(|c| c.xfrm);
let first = boxes.next()?;
let (mut l, mut t, mut r, mut b) = (first.x, first.y, first.x + first.w, first.y + first.h);
for x in boxes {
(l, t, r, b) = (l.min(x.x), t.min(x.y), r.max(x.x + x.w), b.max(x.y + x.h));
}
let xfrm = Xfrm::new(l, t, r - l, b - t);
Some(Shape {
id: ShapeId(id),
name: format!("Group {id}"),
xfrm: Some(xfrm),
kind: ShapeKind::Group { children, child: xfrm },
..Default::default()
})
}
/// Build the presentation from a PowerPoint 95 Document container.
@@ -202,6 +591,8 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation {
let mut p = Presentation { slide_size: size, default_text_style: app.default_text_style(), next_id: 256, ..Default::default() };
p.notes_size = Size::new(page_side(field(8), 540.0), page_side(field(12), 720.0));
let env = Env::new(document);
// The lists are told apart by what they hold, in whatever order they come.
let (mut slides, mut masters) = (vec![], vec![]);
for list in document.children().filter(|r| r.kind == rt::LIST) {
@@ -222,6 +613,42 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation {
let index = p.masters.len();
// The scheme's background is what the master shows anyway.
master.background = background(&m.rec, &scheme).filter(|f| *f != Fill::solid(ColorRef::rgb(scheme[0]))).map(|fill| Background::Fill { fill });
// The master's placeholders set where new slides' placeholders go: the first of each
// family places the default master's. Its other objects are the master's own shapes.
let mut placed: Vec<PhType> = vec![];
// The rulers of the master's title and body, which give their styles' margins.
let (mut title_ruler, mut body_ruler) = (None, None);
for o in Reader::page(&env, &scheme, size, &m.rec) {
if o.placeholder {
if let Some(kind) = o.ph.as_ref().map(|ph| ph.kind).filter(|k| !placed.iter().any(|d| same_family(*d, *k))) {
placed.push(kind);
match kind {
PhType::Title | PhType::CtrTitle => title_ruler = o.ruler,
PhType::Body => body_ruler = o.ruler,
_ => {}
}
let text = o.text;
place_placeholder(&mut master, kind, o.xfrm, || text.and_then(|t| t.paragraphs.into_iter().next()));
}
continue;
}
if let Some(s) = shape(&mut p, o) {
master.shapes.push(s);
}
}
// The master's text styles replace the defaults' first five levels.
for (style, ty, ruler) in [
(&mut master.title_style, text::TITLE, title_ruler),
(&mut master.body_style, text::BODY, body_ruler),
(&mut master.other_style, text::OTHER, None),
] {
let Some(read) = text::master_style(&env, &scheme, ty, ruler) else { continue };
for level in 0..5u8 {
if let Some(l) = read.level(level) {
style.set(level, l.clone());
}
}
}
p.masters.push(Arc::new(master));
by_id.entry(m.id).or_insert((index, scheme));
}
@@ -231,7 +658,7 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation {
}
let layouts: Vec<_> = p.masters.iter().map(|m| layout_table(m, &HashSet::new())).collect();
for s in &slides {
for s in slides.iter().filter(|s| kept(&s.rec)) {
// An unknown master is the first one.
let (index, master_scheme) =
by_id.get(&s.master_id).copied().unwrap_or((0, masters.first().and_then(|m| m.scheme).unwrap_or(DEFAULT_SCHEME)));
@@ -243,7 +670,11 @@ pub fn convert(document: &Rec, app: &dyn Defaults) -> Presentation {
let scheme = if s.follow_scheme { master_scheme } else { s.scheme.unwrap_or(master_scheme) };
let background = if s.follow_background { None } else { background(&s.rec, &scheme).map(|fill| Background::Fill { fill }) };
let Some(id) = p.alloc_id() else { break };
p.slides.push(Arc::new(Slide { id: SlideId(id), layout, background, show_master_shapes: s.follow_objects, ..Default::default() }));
let mut shapes = vec![];
for o in Reader::page(&env, &scheme, size, &s.rec) {
shapes.extend(shape(&mut p, o));
}
p.slides.push(Arc::new(Slide { id: SlideId(id), layout, background, shapes, show_master_shapes: s.follow_objects, ..Default::default() }));
}
p
}
+290
View File
@@ -0,0 +1,290 @@
//! PowerPoint 95 shapes: the shape code of a geometry record (3009) as a DrawingML preset, and a
//! format record (3005) as fill, line and shadow, learned from files PowerPoint 95 wrote and the
//! slides it rendered from them.
//!
//! The shape code is the low byte of the geometry's first word, the [MS-ODRAW] shape type less 4,
//! so the [`geom`] table names its preset: −3 to 8 are the object model's shapes 1 to 12, and 9
//! to 14 its shapes 13 to 24 (an arrow and a thick arrow, which turn and mirror into the other
//! three directions, a home plate, a cube, a balloon and a seal). The adjust value after it is a
//! coordinate in the shape's 21600-unit square, as OfficeArt's are. A code no probe showed is a
//! rectangle.
//!
//! A format record holds the line (+0 0xFF for none, +1 its dash style, +3 its style less one,
//! which sets its width, +4 its colour), the fill (+12 0xFF for none, +20 its colour) and the
//! shadow (+28 0x00 when on and 0xFF when off, +29 2 when semi-transparent, +30 its colour, +36 and
//! +40 how far it falls right and down in master units), then the angle the user set at +48 and
//! the flips the user set at +52. Each colour is R, G, B and an index: 0xFE for the RGB itself,
//! else a slot of the colour scheme.
//!
//! Angles are in sixteenths of a degree and run counter-clockwise, where DrawingML's run clockwise.
//! The geometry record holds the outline as drawn: for a shape code of 0 and up, the byte above it
//! holds whole counter-clockwise quarter-turns in bits 4 and 5 and a horizontal mirror, made after
//! the turn, in bit 6; its own angle is what is left over, and its box is the outline's turned
//! box. That is all a shape needs ([`orient_drawn`]), the user's angle and flips included. The
//! rectangle, rounded rectangle and ellipse (codes −3 to −1, whose byte above is the sign) and
//! placeholders take their angle from the format, and the quarter-turns from the difference
//! ([`orient`]); flips don't change their outlines. A line's 3007 atom holds its arrowheads
//! ([`arrowheads`]). A freeform's points become a custom path in its box ([`freeform_path`]).
use craft_pptx::style::{Dash, LineEnd, Shadow};
use craft_pptx::{ColorRef, ColorTransform, CustomPath, Fill, Geom, Line, Rgba, Xfrm};
use super::{MU, RGB_GIVEN, Rec};
use crate::convert::Scheme;
use crate::geom;
/// The widths of line styles 1 to 6 (the format holds the style less one), in points: the pens
/// PowerPoint 95 drew them with were 8, 16, 32, 48, 64 and 80 master units wide.
const LINE_WIDTHS: [f64; 6] = [1.0, 2.0, 4.0, 6.0, 8.0, 10.0];
/// How far a shadow falls right and down without a full format, in master units: 6 pt, the
/// default every new shape has.
const SHADOW_OFFSET: i32 = 48;
/// The farthest a shadow falls on either axis, in master units (10 in, wider than any slide), so a
/// damaged offset can't send it off to infinity.
const MAX_SHADOW_OFFSET: i32 = 5760;
/// A semi-transparent shadow's opacity, in DrawingML's 100000ths.
const SEMI_TRANSPARENT: i32 = 50_000;
/// A whole turn and a quarter-turn in sixteenths of a degree.
const TURN: i64 = 360 * 16;
const QUARTER: i64 = TURN / 4;
/// How a shape is drawn.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Look {
pub fill: Fill,
pub line: Line,
pub shadow: Option<Shadow>,
}
impl Look {
/// Nothing drawn: what a shape with no format record shows.
pub(super) fn none() -> Look {
Look { fill: Fill::None, line: Line::none(), shadow: None }
}
/// Whether the shape draws anything of its own (its text aside).
pub(super) fn drawn(&self) -> bool {
self.fill != Fill::None || self.line != Line::none() || self.shadow.is_some()
}
}
/// A format record's colour at `at`: R, G, B, then 0xFE or a slot of `scheme`.
pub(super) fn color(format: &Rec, at: usize, scheme: &Scheme) -> Option<Rgba> {
let (r, g, b, index) = (format.u8(at)?, format.u8(at + 1)?, format.u8(at + 2)?, format.u8(at + 3)?);
if index == RGB_GIVEN { Some(Rgba::rgb(r, g, b)) } else { scheme.get(usize::from(index)).copied() }
}
/// A line of `color` in the style and dashes of `format`: 1 pt and solid without one, or for a
/// style or dash value no probe showed.
pub(super) fn line_of(color: Rgba, format: Option<&Rec>) -> Line {
let width = format.and_then(|f| f.u8(3)).and_then(|s| LINE_WIDTHS.get(usize::from(s))).copied().unwrap_or(1.0);
let mut line = Line::solid(ColorRef::rgb(color), width);
let dash = match format.and_then(|f| f.u8(1)) {
Some(1) => Some("sysDot"),
Some(2) => Some("dash"),
Some(3) => Some("lgDash"),
Some(4) => Some("dashDot"),
_ => None,
};
line.dash = dash.map(|name| Dash::Preset { name: name.into() });
line
}
/// A line's arrowheads from its 3007 atom: +0 the start's, +1 the end's. 4 is a small swept-back
/// head, 1 a longer and wider one; 0, and any value no probe showed, is none.
pub(super) fn arrowheads(line: &mut Line, atom: &Rec) {
let end = |v: Option<u8>| {
let (kind, size) = match v? {
4 => ("stealth", "med"),
1 => ("triangle", "lg"),
_ => return None,
};
Some(LineEnd { kind: kind.into(), w: size.into(), len: size.into() })
};
(line.head, line.tail) = (end(atom.u8(0)), end(atom.u8(1)));
}
/// A format record as fill, line and shadow (the angle and flips are read with the box,
/// [`orient`] and [`orient_drawn`]). A part whose flag or colour is cut off or names no scheme
/// slot is not drawn.
pub(super) fn look(format: &Rec, scheme: &Scheme) -> Look {
let on = |flag: usize, at: usize| format.u8(flag).filter(|&f| f != 0xFF).and_then(|_| color(format, at, scheme));
let shadow = format.u8(28).filter(|&f| f == 0).and_then(|_| color(format, 30, scheme)).map(|c| shadow_of(format, c));
Look {
fill: on(12, 20).map_or(Fill::None, |c| Fill::solid(ColorRef::rgb(c))),
line: on(0, 4).map_or_else(Line::none, |c| line_of(c, Some(format))),
shadow,
}
}
/// A shadow of `color` falling as far as the format's +36 (right) and +40 (down) say, in master
/// units, semi-transparent when +29 is 2: a distance and a direction clockwise from the right.
fn shadow_of(format: &Rec, color: Rgba) -> Shadow {
let offset = |at: usize| f64::from(format.i32(at).unwrap_or(SHADOW_OFFSET).clamp(-MAX_SHADOW_OFFSET, MAX_SHADOW_OFFSET)) / MU;
let (dx, dy) = (offset(36), offset(40));
let color = ColorRef::rgb(color);
Shadow {
color: if format.u8(29) == Some(2) { color.with(ColorTransform::Alpha(SEMI_TRANSPARENT)) } else { color },
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,
}
}
/// Swap a box's width and height about its centre: from a box turned a quarter to the unturned.
fn turn_back(xfrm: &mut Xfrm) {
let (cx, cy) = (xfrm.x + xfrm.w / 2.0, xfrm.y + xfrm.h / 2.0);
(xfrm.w, xfrm.h) = (xfrm.h, xfrm.w);
(xfrm.x, xfrm.y) = (cx - xfrm.w / 2.0, cy - xfrm.h / 2.0);
}
/// The quarter-turns clockwise, 0 to 3, that take the unturned box `xfrm` gives (after [`orient`] or
/// [`orient_drawn`]) to the box the geometry record holds: `xfrm`'s angle less the geometry's own,
/// `drawn`, which the record's box doesn't include.
pub(super) fn quarter_turns(xfrm: &Xfrm, drawn: i32) -> usize {
let cw = (xfrm.rot - clockwise(i64::from(drawn))).rem_euclid(360.0);
// 0 to 4 quarters, 4 being a whole turn.
[0, 1, 2, 3, 0][((cw / 90.0).round() as usize).min(4)]
}
/// A counter-clockwise angle in sixteenths of a degree as DrawingML's clockwise degrees, 0 to 360.
pub(super) fn clockwise(ccw: i64) -> f64 {
((-ccw).rem_euclid(TURN) as f64) / 16.0
}
/// Give `xfrm`, the geometry record's box, the counter-clockwise angle `turn` the user set, given
/// the angle `drawn` the geometry record holds (both in sixteenths of a degree): for shapes whose
/// geometry has no orientation bits. The quarter-turns between the two are folded into the drawn
/// box: after an odd number of them it is the turned box, so it is turned back about its centre.
pub(super) fn orient(xfrm: &mut Xfrm, drawn: i32, turn: i32) {
let quarters = (i64::from(turn) - i64::from(drawn) + QUARTER / 2).div_euclid(QUARTER).rem_euclid(4);
if quarters % 2 == 1 {
turn_back(xfrm);
}
xfrm.rot = clockwise(i64::from(turn));
}
/// Give `xfrm`, the geometry record's box, the transform the orientation bits `bits` (the byte
/// above a shape code of 0 and up) and the geometry's own angle `drawn` say: the preset turned
/// `(bits >> 4) & 3` quarter-turns counter-clockwise, then mirrored across when bit 0x40 is set,
/// then turned by `drawn`, counter-clockwise, about the box's centre. The box is the outline's
/// after the quarter-turns, so after an odd number of them it is turned back.
///
/// DrawingML flips first and then turns clockwise. Without the mirror that is no flip and the
/// whole angle negated. With it, a mirror after a counter-clockwise turn by `q` is the same as a
/// clockwise turn by `q` after the mirror, so it is a horizontal flip, turned clockwise by `q`
/// less `drawn`.
pub(super) fn orient_drawn(xfrm: &mut Xfrm, bits: u8, drawn: i32) {
let quarters = i64::from((bits >> 4) & 3) * QUARTER;
let mirror = bits & 0x40 != 0;
if bits & 0x10 != 0 {
turn_back(xfrm);
}
let ccw = if mirror { i64::from(drawn) - quarters } else { quarters + i64::from(drawn) };
xfrm.rot = clockwise(ccw);
(xfrm.flip_h, xfrm.flip_v) = (mirror, false);
}
/// PowerPoint 95's trapezoid flipped top to bottom, as its default is drawn: wide at the top, each
/// bottom corner inset by the adjust value (0 to half the side, a quarter by default). The outline
/// the PowerPoint 97 path gives OfficeArt's trapezoid; a negative adjust value is 0, as there.
fn trapezoid_top(adjust: Option<i32>) -> Geom {
geom::trapezoid(adjust.map(|v| u32::try_from(v).unwrap_or(0)))
}
/// A freeform's points as a path in its box `sides` (left, top, right and bottom, either way
/// round), all in master units from the slide's centre: a move to the first point, lines to the
/// rest, and a close when `closed`. The path's size is the box's (at least one unit each way, so a
/// flat freeform still has a coordinate space), its points measured from the box's top left.
pub(super) fn freeform_path(points: &[(i32, i32)], [l, t, r, b]: [i32; 4], closed: bool) -> Geom {
let (left, top) = (f64::from(l.min(r)), f64::from(t.min(b)));
let (w, h) = ((f64::from(r) - f64::from(l)).abs().max(1.0), (f64::from(b) - f64::from(t)).abs().max(1.0));
let mut d = String::new();
for (i, &(x, y)) in points.iter().enumerate() {
let cmd = if i == 0 { "M" } else { " L" };
d.push_str(&format!("{cmd} {} {}", f64::from(x) - left, f64::from(y) - top));
}
if closed {
d.push_str(" Z");
}
Geom::Custom { paths: vec![CustomPath { w, h, d, ..Default::default() }] }
}
/// The share of its square a balloon's body takes, from the top; the tail reaches the bottom.
const BALLOON_BODY: f64 = 5.0 / 6.0;
/// The geometry for a shape code with its adjust value, in `xfrm`, the box already turned and
/// flipped ([`orient`], [`orient_drawn`]): a preset, or the trapezoid's own outline. A code no
/// probe showed is a rectangle.
///
/// An OfficeArt adjust value is a coordinate in the shape's 21600-unit square, stretched to the box
/// on each axis; a DrawingML one is a 100000 fraction of the width (the triangle's apex), the
/// height or the shorter side. Where PowerPoint 95 has no adjust value for a part, the proportion
/// is the one it drew: the arrow's shaft is half the height, the thick arrow's three quarters.
///
/// Two shapes change `xfrm`. A mirrored trapezoid (its default) is the outline wide at the top,
/// unflipped and turned a half-turn further: a horizontal flip is a vertical one turned a
/// half-turn, and the vertical one is in the outline, so its text stays upright. The balloon's box
/// is its body only, as DrawingML's callout's is, its tail reaching out below ([`balloon`]).
pub(super) fn geometry(code: i8, adjust: Option<i32>, xfrm: &mut Xfrm) -> Geom {
let kind = u16::try_from(i16::from(code) + 4).ok().filter(|_| (-3..=14).contains(&code));
// PowerPoint 95's trapezoid unmirrored is DrawingML's preset, wide at the bottom; the PowerPoint
// 97 path's table has no preset for it, OfficeArt's being wide at the top.
let Some(name) = kind.and_then(|k| if k == 8 { Some("trapezoid") } else { geom::preset_name(k) }) else {
log::warn!("ppt: PowerPoint 95 shape code {code} is not known; read as a rectangle");
return Geom::Preset { name: "rect".into(), adj: vec![] };
};
let (w, h) = (xfrm.w, xfrm.h);
let fraction = |v: i32, max: i32| f64::from(v.clamp(0, max)) / 21600.0 * 100_000.0;
// A horizontal length: a share of the width, as a share of the shorter side.
let ss = w.min(h);
let across = |v: i32, max: i32| if ss > 0.0 && w.is_finite() { fraction(v, max) * w / ss } else { fraction(v, max) };
// The length from a horizontal coordinate to the right side.
let to_right = |v: i32| across(21600 - v.clamp(0, 21600), 21600);
let adj: Vec<f64> = match (kind, adjust) {
(Some(8), _) if xfrm.flip_h => {
xfrm.flip_h = false;
xfrm.rot = (xfrm.rot + 180.0) % 360.0;
return trapezoid_top(adjust);
}
(Some(13), _) => vec![50_000.0, to_right(adjust.unwrap_or(10800))],
(Some(14), _) => vec![75_000.0, to_right(adjust.unwrap_or(10800))],
(Some(17), _) => return balloon(adjust, xfrm),
(_, None) => vec![],
(Some(2), Some(v)) => vec![geom::round_rect_adjust(v)],
(Some(5 | 16), Some(v)) => vec![fraction(v, 21600)],
(Some(7), Some(v)) => vec![across(v, 21600)],
(Some(8 | 9), Some(v)) => vec![across(v, 10800)],
(Some(10 | 11), Some(v)) => vec![fraction(v, 10800)],
(Some(15), Some(v)) => vec![to_right(v)],
_ => vec![],
};
Geom::Preset { name: name.into(), adj }
}
/// The balloon: a rounded body over the top five sixths of its square, with a tail from its bottom
/// edge to the square's bottom at the adjust value across (1800, a twelfth, by default). As in
/// DrawingML's callout, its box becomes the body, moved along the shape's own vertical axis so the
/// body stays where it was drawn, and the tail's tip is given from the body's centre.
fn balloon(adjust: Option<i32>, xfrm: &mut Xfrm) -> Geom {
let tip = f64::from(adjust.unwrap_or(1800).clamp(0, 21600)) / 21600.0;
let (w, h) = (xfrm.w, xfrm.h);
let body = h * BALLOON_BODY;
// The body's centre is (h − body) / 2 above the box's, on the shape's own axis, turned with it.
let (sin, cos) = xfrm.rot.to_radians().sin_cos();
let up = (h - body) / 2.0;
let (cx, cy) = (xfrm.x + w / 2.0 + up * sin, xfrm.y + h / 2.0 - up * cos);
(xfrm.x, xfrm.y, xfrm.h) = (cx - w / 2.0, cy - body / 2.0, body);
// The corners are rounded a sixth of the square's shorter side.
let ss = w.min(body);
let radius = if ss > 0.0 && ss.is_finite() { w.min(h) / 6.0 / ss * 100_000.0 } else { 16_667.0 };
let below = (1.0 / BALLOON_BODY - 0.5) * 100_000.0;
Geom::Preset { name: "wedgeRoundRectCallout".into(), adj: vec![(tip - 0.5) * 100_000.0, below, radius] }
}
File diff suppressed because it is too large. Load diff
+460
View File
@@ -0,0 +1,460 @@
//! PowerPoint 95 text: a shape's text container (4001) and the document's font and ruler tables,
//! learned from files PowerPoint 95 wrote.
//!
//! A text container holds a header (4000) and a body: 4002 on slides, 4068 on the master's
//! placeholders. The body holds a text atom (4003: the text type, then the text rectangle), a
//! ruler reference (4021) and the runs (4064). The runs are the characters (2030 tagged 0x35,
//! Windows-1252 bytes, `\r` between paragraphs), then three 2028 containers, each holding a 2030
//! atom of fixed-size entries: character runs (tag 0x2f, 44 bytes), paragraph runs (0x30, 72
//! bytes) and one entry for the whole text (0x31, not read). Each set of runs covers the text and
//! one more character, the last paragraph's end. The text atom's +4 flags hold word wrap (bit 2),
//! and its +8 byte the anchoring: bits 4–5 top, middle or bottom, bit 1 clear for centred across.
//!
//! The Environment (1010) holds the fonts (2005) and the rulers (4016) as lists of slots: each
//! slot is what comes before a 2017 record, and an empty slot holds a 2018. A run's font and a
//! text's ruler are slot numbers. It also holds the master's text styles: a 1028 container of
//! 4052 atoms, one per text type (0 title, 1 body, 2 notes, 4 other), each five levels of
//! character formatting (24 bytes from +16) and five of paragraph formatting (52 bytes from
//! +160), laid out as in the runs. Slide text carries its formatting in full, as copies of these.
use std::cell::Cell;
use craft_pptx::text::{Align, Anchor, BodyProps, Bullet, LevelStyle, ListStyle, ParaProps, RunKind, Spacing};
use craft_pptx::{ColorRef, Fill, Paragraph, Rgba, Run, RunProps, TextBody};
use super::{MU, RGB_GIVEN, Rec};
use crate::convert::Scheme;
/// Record types.
mod rt {
pub const ENVIRONMENT: u32 = 1010;
pub const SLOT_END: u32 = 2017;
pub const FONTS: u32 = 2005;
pub const RUN_TABLE: u32 = 2028;
pub const ATOM: u32 = 2030;
pub const RULERS: u32 = 4016;
pub const RULER_ATOM: u32 = 4019;
pub const RULER_REF: u32 = 4021;
pub const FONT: u32 = 4022;
pub const FONT_ATOM: u32 = 4023;
pub const TEXT_BODY: u32 = 4002;
pub const TEXT_ATOM: u32 = 4003;
pub const RUNS: u32 = 4064;
pub const MASTER_TEXT_BODY: u32 = 4068;
pub const RULER: u32 = 4069;
pub const STYLES: u32 = 1028;
pub const STYLE: u32 = 4052;
}
/// The fourth words telling a text's atoms apart.
mod tag {
pub const CHARS: u32 = 0x35;
pub const CHAR_RUNS: u32 = 0x2F;
pub const PARA_RUNS: u32 = 0x30;
}
const CHAR_RUN: usize = 44;
const PARA_RUN: usize = 72;
/// Where a character run's formatting starts (its font), and a paragraph run's (its bullet flag).
const CHAR_AT: usize = 20;
const PARA_AT: usize = 20;
/// A master style's levels: character formatting from +16, 24 bytes each, and paragraph
/// formatting from +160, 52 bytes each.
const STYLE_CHARS: usize = 16;
const STYLE_CHAR: usize = 24;
const STYLE_PARAS: usize = 160;
const STYLE_PARA: usize = 52;
/// The master styles read: text types 0 to 8.
const STYLE_TYPES: usize = 9;
/// The text types whose styles the master's title, body and other styles take.
pub(super) const TITLE: usize = 0;
pub(super) const BODY: usize = 1;
pub(super) const OTHER: usize = 4;
/// Characters read from one text at most: far beyond what PowerPoint 95 puts in a shape, so a
/// huge character atom can't make a huge text body.
pub(super) const MAX_CHARS: usize = 1 << 20;
/// Paragraphs and runs made from the whole document's text at most. Each is about 2 to 4 KB, so
/// a text of nothing but paragraph or line breaks would otherwise make gigabytes from a megabyte
/// of file. That is far more than any PowerPoint 95 file probed holds.
pub(super) const MAX_TEXT_ITEMS: usize = 1 << 16;
/// Font and ruler slots read at most.
const MAX_SLOTS: usize = 4096;
/// Indent levels: PowerPoint 95 has five.
const LEVELS: usize = 5;
/// Each level's left margin and first-line indent, in master units from the text's left edge.
type Ruler = [(i32, i32); LEVELS];
/// What text in the document draws on: the font faces and rulers, by slot.
#[derive(Default)]
pub(super) struct Env {
fonts: Vec<Option<String>>,
rulers: Vec<Option<Ruler>>,
/// The master's text styles by text type: each level's character and paragraph formatting.
styles: Vec<Option<[(CharRun, ParaRun); LEVELS]>>,
/// Paragraphs and runs made so far, against [`MAX_TEXT_ITEMS`].
items: Cell<usize>,
}
impl Env {
/// Counts one more paragraph or run; `false` once the document's text has made
/// [`MAX_TEXT_ITEMS`], when the rest of its text is left out.
fn take_item(&self) -> bool {
let n = self.items.get();
if n == MAX_TEXT_ITEMS {
log::warn!("ppt: PowerPoint 95 text passes {MAX_TEXT_ITEMS} paragraphs and runs; the rest is left out");
}
self.items.set(n.saturating_add(1));
n < MAX_TEXT_ITEMS
}
pub(super) fn new(document: &Rec) -> Env {
let Some(environment) = document.child(rt::ENVIRONMENT) else { return Env::default() };
// There may be more than one font list; the first that holds a face is the table.
let fonts = environment
.children()
.filter(|r| r.kind == rt::FONTS)
.map(|list| slots(&list, rt::FONT, |f| f.child(rt::FONT_ATOM).map(|a| face(&a))))
.find(|f| f.iter().flatten().any(|face| !face.is_empty()))
.unwrap_or_default();
let rulers =
environment.child(rt::RULERS).map(|list| slots(&list, rt::RULER, |r| r.child(rt::RULER_ATOM).map(|a| ruler(&a)))).unwrap_or_default();
let styles = environment
.child(rt::STYLES)
.map(|list| list.children().filter(|r| r.kind == rt::STYLE).take(STYLE_TYPES).map(|r| style(&r)).collect())
.unwrap_or_default();
Env { fonts, rulers, styles, items: Cell::new(0) }
}
}
/// A master style atom's five levels, when the atom holds them all.
fn style(r: &Rec) -> Option<[(CharRun, ParaRun); LEVELS]> {
let b = r.data.get(..STYLE_PARAS + LEVELS * STYLE_PARA)?;
Some(std::array::from_fn(|i| (char_run(b, STYLE_CHARS + i * STYLE_CHAR, 0), para_run(b, STYLE_PARAS + i * STYLE_PARA, 0))))
}
/// The master's style for text type `ty` as a list style. `ruler` is the ruler slot of the
/// master's placeholder holding that text, which gives each level's margins. `None` when the
/// file has no such style.
pub(super) fn master_style(env: &Env, scheme: &Scheme, ty: usize, ruler: Option<u32>) -> Option<ListStyle> {
let levels = env.styles.get(ty)?.as_ref()?;
let ruler = ruler.and_then(|i| env.rulers.get(i as usize)).copied().flatten();
let mut ls = ListStyle::default();
for (i, (c, p)) in (0u8..).zip(levels) {
let para = para_props(Some(p), ruler.as_ref().and_then(|r| r.get(usize::from(i))));
ls.set(i, LevelStyle { para, run: run_props(c, env, scheme) });
}
Some(ls)
}
/// The angle a text container's text is drawn at (4003 +16), counter-clockwise in sixteenths of a
/// degree: the geometry's own angle in every probe, whatever quarter-turns its box holds.
pub(super) fn angle(container: &Rec) -> Option<i32> {
let body = container.children().find(|r| r.kind == rt::TEXT_BODY || r.kind == rt::MASTER_TEXT_BODY)?;
body.child(rt::TEXT_ATOM)?.i32(16)
}
/// The ruler slot a text container's body names.
pub(super) fn ruler_slot(container: &Rec) -> Option<u32> {
let body = container.children().find(|r| r.kind == rt::TEXT_BODY || r.kind == rt::MASTER_TEXT_BODY)?;
body.child(rt::RULER_REF)?.u32(0)
}
/// A slot list's entries of `kind`, read by `read`: an entry is the slot of the 2017 records
/// before it.
fn slots<T>(list: &Rec, kind: u32, read: impl Fn(&Rec) -> Option<T>) -> Vec<Option<T>> {
let mut out = vec![];
let mut current = None;
for r in list.children() {
if r.kind == rt::SLOT_END {
if out.len() >= MAX_SLOTS {
break;
}
out.push(current.take());
} else if r.kind == kind && current.is_none() {
current = read(&r);
}
}
out
}
/// A `FontEntityAtom`'s face: a LOGFONT, whose name is the NUL-terminated Windows-1252 bytes from
/// +28.
fn face(a: &Rec) -> String {
let name = a.data.get(28..).unwrap_or(&[]);
name.iter().take(32).take_while(|&&b| b != 0).map(|&b| craft_codepage::cp1252(b)).collect()
}
/// A ruler atom: each level's left margin, then its first-line indent, as i32s.
fn ruler(a: &Rec) -> Ruler {
let mut out = [(0, 0); LEVELS];
for (i, level) in out.iter_mut().enumerate() {
*level = (a.i32(i * 8).unwrap_or(0), a.i32(i * 8 + 4).unwrap_or(0));
}
out
}
/// A character run: its length and the formatting it gives in full.
#[derive(Clone, Copy)]
struct CharRun {
len: u32,
font: u16,
size: u16,
style: u16,
color: [u8; 4],
}
/// A paragraph run.
#[derive(Clone, Copy)]
struct ParaRun {
len: u32,
bullet: bool,
bullet_char: u8,
align: u8,
level: u8,
/// Line spacing, space before and after: a percentage of a line, or minus a size in points.
line: Option<i32>,
before: Option<i32>,
after: Option<i32>,
}
/// A character run's formatting from `at` (its font): font, size, style bits, then the colour.
fn char_run(e: &[u8], at: usize, len: u32) -> CharRun {
CharRun {
len,
font: u16_at(e, at),
size: u16_at(e, at + 4),
style: u16_at(e, at + 8),
color: [0, 1, 2, 3].map(|k| e.get(at + 10 + k).copied().unwrap_or(0)),
}
}
/// A paragraph run's formatting from `at` (its bullet flag): the bullet character at +6, the
/// level at +24, the alignment at +28, then line spacing, space before and space after.
fn para_run(e: &[u8], at: usize, len: u32) -> ParaRun {
let i32_at = |k: usize| crate::record::u32_at(e, at + k).map(|v| v as i32);
ParaRun {
len,
bullet: e.get(at).is_some_and(|&b| b != 0),
bullet_char: e.get(at + 6).copied().unwrap_or(0),
level: e.get(at + 24).copied().unwrap_or(0),
align: e.get(at + 28).copied().unwrap_or(0),
line: i32_at(32),
before: i32_at(36),
after: i32_at(40),
}
}
fn u16_at(b: &[u8], at: usize) -> u16 {
crate::record::u16_at(b, at).unwrap_or(0)
}
fn u32_at(b: &[u8], at: usize) -> u32 {
crate::record::u32_at(b, at).unwrap_or(0)
}
/// A run table's entries of `size` bytes, read while they cover less than `total` characters, so
/// there are at most `total` of them.
fn entries<'a>(runs: &Rec<'a>, kind: u32, size: usize, total: u32) -> Vec<&'a [u8]> {
let mut out = vec![];
let mut covered = 0u32;
let tables = runs.children().filter(|r| r.kind == rt::RUN_TABLE && r.tag == kind);
for atom in tables.flat_map(|t| t.children().filter(|a| a.kind == rt::ATOM)) {
for e in atom.data.chunks_exact(size) {
if covered >= total {
return out;
}
// A run of no characters formats nothing, so it is skipped rather than counted.
let len = u32_at(e, 0);
if len == 0 {
continue;
}
covered = covered.saturating_add(len);
out.push(e);
}
}
out
}
/// Where each run starts: a running sum of their lengths, so never decreasing.
fn starts(lens: impl Iterator<Item = u32>) -> Vec<usize> {
let mut at = 0usize;
lens.map(|n| {
let s = at;
at = at.saturating_add(n as usize);
s
})
.collect()
}
/// The run holding character `i`.
fn run_at(starts: &[usize], i: usize) -> Option<usize> {
starts.partition_point(|&s| s <= i).checked_sub(1)
}
/// A shape's text. `shape` is its box (left, top, right, bottom in master units), from which the
/// text rectangle gives the insets. `None` when the container holds no text body.
pub(super) fn text_body(container: &Rec, env: &Env, scheme: &Scheme, shape: Option<[i32; 4]>, text_box: bool) -> Option<TextBody> {
let body = container.children().find(|r| r.kind == rt::TEXT_BODY || r.kind == rt::MASTER_TEXT_BODY)?;
let runs = body.child(rt::RUNS);
let chars: Vec<char> = runs
.and_then(|r| r.children().find(|a| a.kind == rt::ATOM && a.tag == tag::CHARS))
.map(|a| a.data.iter().take(MAX_CHARS).map(|&b| craft_codepage::cp1252(b)).collect())
.unwrap_or_default();
// The runs cover the text and its last paragraph's end.
let total = u32::try_from(chars.len()).unwrap_or(u32::MAX).saturating_add(1);
let char_runs: Vec<CharRun> = runs
.map(|r| entries(&r, tag::CHAR_RUNS, CHAR_RUN, total))
.unwrap_or_default()
.into_iter()
.map(|e| char_run(e, CHAR_AT, u32_at(e, 0)))
.collect();
let para_runs: Vec<ParaRun> = runs
.map(|r| entries(&r, tag::PARA_RUNS, PARA_RUN, total))
.unwrap_or_default()
.into_iter()
.map(|e| para_run(e, PARA_AT, u32_at(e, 0)))
.collect();
let ruler = body.child(rt::RULER_REF).and_then(|r| r.u32(0)).and_then(|i| env.rulers.get(i as usize)).copied().flatten();
let mut props = BodyProps::default();
if text_box {
props.anchor = Some(Anchor::Top);
props.wrap = Some(true);
}
let atom = body.child(rt::TEXT_ATOM);
if let Some(flags) = atom.and_then(|a| a.u8(4)) {
props.wrap = Some(flags & 4 != 0);
}
if let Some(a) = atom.and_then(|a| a.u8(8)) {
// Bits 4–5: top, middle or bottom; bit 1 clear: centred across. Bit 0 is always set.
let anchor = match (a >> 4) & 3 {
0 => Some(Anchor::Top),
1 => Some(Anchor::Middle),
2 => Some(Anchor::Bottom),
_ => None,
};
if anchor.is_some() {
props.anchor = anchor;
props.anchor_ctr = Some(a & 2 == 0);
}
}
if let (Some(atom), Some([l, t, r, b])) = (atom, shape) {
// The text rectangle, inside the shape's box.
let inset = |from: i32, to: Option<i32>, sign: f64| {
to.map(|to| (f64::from(to) - f64::from(from)) * sign / MU).filter(|v| v.is_finite() && (0.0..=1000.0).contains(v))
};
props.inset_l = inset(l, atom.i32(20), 1.0);
props.inset_t = inset(t, atom.i32(24), 1.0);
props.inset_r = inset(r, atom.i32(28), -1.0);
props.inset_b = inset(b, atom.i32(32), -1.0);
}
Some(TextBody { body: props, paragraphs: paragraphs(&chars, &char_runs, &para_runs, ruler.as_ref(), env, scheme), ..Default::default() })
}
fn paragraphs(chars: &[char], char_runs: &[CharRun], para_runs: &[ParaRun], ruler: Option<&Ruler>, env: &Env, scheme: &Scheme) -> Vec<Paragraph> {
let total = chars.len();
let para_starts = starts(para_runs.iter().map(|r| r.len));
let char_starts = starts(char_runs.iter().map(|r| r.len));
let props_at = |i: usize| run_at(&char_starts, i).and_then(|k| char_runs.get(k)).map(|r| run_props(r, env, scheme)).unwrap_or_default();
let mut out = vec![];
let mut start = 0usize;
loop {
if !env.take_item() {
break;
}
let end = chars.get(start..).and_then(|rest| rest.iter().position(|&c| c == '\r')).map_or(total, |e| start + e);
let pr = run_at(&para_starts, start).and_then(|i| para_runs.get(i));
let level = pr.map_or(0, |r| r.level.min(LEVELS as u8 - 1));
let mut para = Paragraph { level, props: para_props(pr, ruler.and_then(|r| r.get(usize::from(level)))), ..Default::default() };
let mut i = start;
while i < end {
if !env.take_item() {
break;
}
let props = props_at(i);
if chars.get(i) == Some(&'\u{b}') {
para.runs.push(Run { text: String::new(), props, kind: RunKind::Break });
i += 1;
continue;
}
// A text run: up to the next format change, line 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 && chars.get(j) != Some(&'\u{b}') {
j += 1;
}
let j = j.max(i + 1);
let text: String = chars.get(i..j).unwrap_or(&[]).iter().filter(|&&c| c >= ' ' || c == '\t').collect();
para.runs.push(Run::with(text, props));
i = j;
}
// The paragraph mark's own formatting: the character run at the CR (PowerPoint 95 gives
// it one of its own when it differs), or the last run for the last paragraph.
para.end_props = props_at(end);
para.normalize();
out.push(para);
if end >= total {
break;
}
start = end + 1;
}
out
}
/// A character run's formatting, which PowerPoint 95 gives in full: font, size, bold, italic,
/// underline and colour (an RGB, or a slot of the colour scheme).
fn run_props(r: &CharRun, env: &Env, scheme: &Scheme) -> RunProps {
let [red, g, b, index] = r.color;
let color = if index == RGB_GIVEN { Some(Rgba::rgb(red, g, b)) } else { scheme.get(usize::from(index)).copied() };
RunProps {
font: env.fonts.get(usize::from(r.font)).cloned().flatten().filter(|f| !f.is_empty()),
size: Some(f64::from(r.size)).filter(|s| (1.0..=4000.0).contains(s)),
bold: Some(r.style & 1 != 0),
italic: Some(r.style & 2 != 0),
underline: Some(if r.style & 4 != 0 { "sng" } else { "none" }.into()),
fill: color.map(|c| Fill::solid(ColorRef::rgb(c))),
..Default::default()
}
}
/// The most points of spacing DrawingML holds (its `spcPts` reaches 158400 hundredths), as the
/// writer clamps it, so an imported value survives export.
const MAX_SPACING_PTS: f64 = 1584.0;
/// A paragraph run's spacing: a percentage of a line when positive, else minus a size in points.
/// Bounded, so a hostile value can't push text off any page.
fn spacing(v: i32) -> Spacing {
if v >= 0 { Spacing::Pct((f64::from(v) / 100.0).min(100.0)) } else { Spacing::Pts((-f64::from(v)).min(MAX_SPACING_PTS)) }
}
/// A paragraph run's alignment, spacing and bullet, and the margins its level has in the text's
/// ruler.
fn para_props(r: Option<&ParaRun>, level: Option<&(i32, i32)>) -> ParaProps {
let mut p = ParaProps::default();
if let Some(r) = r {
p.align = match r.align {
0 => Some(Align::Left),
1 => Some(Align::Center),
2 => Some(Align::Right),
3 => Some(Align::Justify),
_ => None,
};
p.line_spacing = r.line.map(spacing);
p.space_before = r.before.map(spacing);
p.space_after = r.after.map(spacing);
p.bullet = Some(if r.bullet {
let c = if r.bullet_char >= 0x20 { craft_codepage::cp1252(r.bullet_char) } else { '•' };
Bullet::Char { char: c.to_string() }
} else {
Bullet::None
});
}
if let Some(&(left, first)) = level {
// Bounded, so a hostile ruler can't push text off any page.
let (left, first) = ((f64::from(left) / MU).clamp(0.0, 4000.0), (f64::from(first) / MU).clamp(0.0, 4000.0));
p.margin_left = Some(left);
p.indent = Some(first - left);
}
p
}
+30
View File
@@ -723,6 +723,36 @@ fn a_shadowed_run_keeps_its_shadow() {
assert!(runs[1].props.shadow.is_none());
}
/// A paragraph's end mark keeps the formatting of the character run at its CR, not of the
/// paragraph's first character, as PowerPoint reads a .ppt PowerPoint saved: "AB\rCD" at 40 pt
/// with A and C at 24 ends each paragraph at 40; at 24 with only the first CR at 40, its first
/// paragraph ends at 40 and its second at 24.
#[test]
fn a_paragraphs_end_mark_keeps_the_formatting_at_its_cr() {
let end_sizes = |runs: &[(u32, u16)]| {
let mut style = vec![];
style.extend_from_slice(&6u32.to_le_bytes());
style.extend_from_slice(&0u16.to_le_bytes());
style.extend_from_slice(&pf_bytes(0, false));
for (n, size) in runs {
style.extend_from_slice(&n.to_le_bytes());
style.extend_from_slice(&0x2_0000u32.to_le_bytes()); // mask: size
style.extend_from_slice(&size.to_le_bytes());
}
let tb = container(
rt::SP_CONTAINER,
0,
&[fsp(202, 2049, 0xA00), anchor(0, 0, 1000, 1000), text_box(4, "AB\rCD", &[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();
p.slides[0].shapes[0].text.as_ref().unwrap().paragraphs.iter().map(|para| para.end_props.size).collect::<Vec<_>>()
};
assert_eq!(end_sizes(&[(1, 24), (2, 40), (1, 24), (2, 40)]), [Some(40.0), Some(40.0)]);
assert_eq!(end_sizes(&[(2, 24), (1, 40), (3, 24)]), [Some(40.0), Some(24.0)]);
}
/// `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.
+29
View File
@@ -153,6 +153,9 @@ const MAX_GSTACK: usize = 10_000;
const MAX_NAME_DEPTH: usize = 48;
const MAX_CALL_DEPTH: usize = 48;
/// A dictionary entry's previous state recorded for `restore`: (dict, key, previous entry).
type JournalEntry = (PDict, crate::read::obj::Key, Option<(Obj, Obj)>);
pub struct Interp {
pub o: Vec<Obj>,
pub d: Vec<PDict>,
@@ -162,6 +165,10 @@ pub struct Interp {
pub gstack: Vec<GState>,
/// Graphics-state depths that `save` objects restore to.
pub saves: Vec<usize>,
/// Journal lengths at each open `save`, so `restore` puts dictionary entries back.
pub journal_marks: Vec<usize>,
/// Dictionary entries changed while a `save` is open: (dict, key, previous entry).
pub journal: Vec<JournalEntry>,
pub gstates: Vec<GState>,
pub systemdict: PDict,
pub globaldict: PDict,
@@ -216,6 +223,8 @@ impl Interp {
gs: GState::default(),
gstack: Vec::new(),
saves: Vec::new(),
journal_marks: Vec::new(),
journal: Vec::new(),
gstates: Vec::new(),
systemdict,
globaldict,
@@ -728,6 +737,26 @@ impl Interp {
self.gs = g;
}
}
/// Put `key -> value` in `dict`, journaling the prior entry while a `save` is open.
pub fn dict_put(&mut self, dict: &PDict, key: Obj, value: Obj) -> R {
let (k, old) = dict.put_ret(key, value);
if !self.saves.is_empty() {
self.alloc(2 * std::mem::size_of::<Obj>())?;
self.journal.push((dict.clone(), k, old));
}
Ok(())
}
/// Remove `key` from `dict`, journaling the prior entry while a `save` is open.
pub fn dict_remove(&mut self, dict: &PDict, key: &crate::read::obj::Key) -> R {
let old = dict.remove_ret(key);
if !self.saves.is_empty() && old.is_some() {
self.alloc(2 * std::mem::size_of::<Obj>())?;
self.journal.push((dict.clone(), key.clone(), old));
}
Ok(())
}
}
/// A six-number array as a matrix.
+18
View File
@@ -158,6 +158,12 @@ impl PDict {
self.0.borrow_mut().map.insert(k, (key, v));
}
pub fn put_ret(&self, key: Obj, v: Obj) -> (Key, Option<(Obj, Obj)>) {
let k = key.key();
let old = self.0.borrow_mut().map.insert(k.clone(), (key, v));
(k, old)
}
pub fn put_name(&self, n: &[u8], v: Obj) {
self.put(Obj::Name(name(n), false), v);
}
@@ -166,6 +172,18 @@ impl PDict {
self.0.borrow_mut().map.remove(k);
}
pub fn remove_ret(&self, k: &Key) -> Option<(Obj, Obj)> {
self.0.borrow_mut().map.remove(k)
}
pub fn restore_entry(&self, k: Key, old: Option<(Obj, Obj)>) {
let mut inner = self.0.borrow_mut();
match old {
Some(entry) => inner.map.insert(k, entry),
None => inner.map.remove(&k),
};
}
pub fn len(&self) -> usize {
self.0.borrow().map.len()
}
+6 -9
View File
@@ -68,7 +68,7 @@ pub fn copy(ip: &mut Interp) -> R {
ip.charge(src.len() as u64)?;
ip.alloc(src.len().saturating_mul(2 * OBJ_BYTES))?;
for (k, v) in src.entries() {
dst.put(k, v);
ip.dict_put(&dst, k, v)?;
}
ip.push(Obj::Dict(dst))
}
@@ -739,8 +739,8 @@ pub fn def(ip: &mut Interp) -> R {
let k = ip.pop()?;
key_cost(ip, &k)?;
ip.alloc(2 * OBJ_BYTES)?;
ip.current_dict()?.put(k, v);
Ok(())
let d = ip.current_dict()?;
ip.dict_put(&d, k, v)
}
pub fn load(ip: &mut Interp) -> R {
@@ -759,8 +759,7 @@ pub fn store(ip: &mut Interp) -> R {
key_cost(ip, &k)?;
let key = k.key();
let d = ip.d.iter().rev().find(|d| d.known(&key)).cloned().map_or_else(|| ip.current_dict(), Ok)?;
d.put(k, v);
Ok(())
ip.dict_put(&d, k, v)
}
pub fn get(ip: &mut Interp) -> R {
@@ -802,8 +801,7 @@ pub fn put(ip: &mut Interp) -> R {
Obj::Dict(d) => {
key_cost(ip, &k)?;
ip.alloc(2 * OBJ_BYTES)?;
d.put(k, v);
Ok(())
ip.dict_put(&d, k, v)
}
Obj::Array(a, _) => {
let i = usize::try_from(int_of(&k)?).map_err(|_| PsErr::Ps("rangecheck"))?;
@@ -829,8 +827,7 @@ pub fn undef(ip: &mut Interp) -> R {
let k = ip.pop()?;
key_cost(ip, &k)?;
let d = ip.pop_dict()?;
d.remove(&k.key());
Ok(())
ip.dict_remove(&d, &k.key())
}
pub fn where_(ip: &mut Interp) -> R {
+6
View File
@@ -35,6 +35,7 @@ pub fn initgraphics(ip: &mut Interp) -> R {
pub fn save(ip: &mut Interp) -> R {
ip.gsave()?;
ip.saves.push(ip.gstack.len());
ip.journal_marks.push(ip.journal.len());
let n = ip.saves.len();
ip.push(Obj::Save(n))
}
@@ -45,7 +46,12 @@ pub fn restore(ip: &mut Interp) -> R {
return err("invalidrestore");
}
let depth = ip.saves.get(n - 1).copied().unwrap_or(0);
let mark = ip.journal_marks.get(n - 1).copied().unwrap_or(0);
ip.saves.truncate(n - 1);
ip.journal_marks.truncate(n - 1);
for (dict, key, old) in ip.journal.drain(mark..).rev() {
dict.restore_entry(key, old);
}
// Back to the state saved with it (save did a gsave, leaving `depth` states stacked).
while ip.gstack.len() >= depth.max(1) {
let Some(g) = ip.gstack.pop() else { break };
+44
View File
@@ -776,3 +776,47 @@ fn the_web_gets_smaller_default_limits() {
assert!(l.memory <= 1 << 30 && l.steps <= 50_000_000);
}
}
#[test]
fn restore_undoes_dictionary_changes() {
let (_, conv) = run("/Depth 2 dict def Depth /open 0 put \
/enter { save Depth /open get 1 add dup 8 gt { rangecheck } if Depth exch /open exch put } def \
1 1 50 { pop enter 0 0 1 1 rectfill restore } for \
Depth /open get 0 eq { 10 10 5 5 rectfill } if");
assert!(conv.warnings.is_empty(), "{:?}", conv.warnings);
let (c, conv) = run("/a 1 def /d 2 dict def d /k 1 put save /a 2 def /b 3 def d /k 2 put d /k undef \
1 dict dup /z 9 put d copy pop /a 4 store restore \
a 1 eq /b where not and d /k get 1 eq and d /z known not and { 0 0 10 10 rectfill } if");
assert!(conv.warnings.is_empty(), "{:?}", conv.warnings);
assert!(c.lines().any(|l| l == "f"), "{c}");
let (c, _) = run("save dup restore { restore } stopped { 0 0 10 10 rectfill } if");
assert!(c.lines().any(|l| l == "f"), "{c}");
}
#[test]
fn prolog_keeps_builtin_cmyk_with_where() {
let (c, conv) = run("/setcmykcolor where { pop } { /setcmykcolor { pop pop pop pop 0 1 0 setrgbcolor } def } ifelse \
0 1 1 0 setcmykcolor 0 0 10 10 rectfill");
assert!(conv.warnings.is_empty(), "{:?}", conv.warnings);
assert!(c.contains("0 1 1 0 k\n"), "{c}");
let (c, conv) = run("0.1 0.2 0.3 0.4 setcmykcolor currentcmykcolor \
0.4 eq exch 0.3 eq and exch 0.2 eq and exch 0.1 eq and { 0 0 10 10 rectfill } if");
assert!(conv.warnings.is_empty(), "{:?}", conv.warnings);
assert!(c.lines().any(|l| l == "f"), "{c}");
}
#[test]
fn readline_partial_line_and_eof() {
let (c, conv) = run("/s 16 string def currentfile 0 (END) /SubFileDecode filter s readline\n\
okEND { (ok) eq { 0 0 10 10 rectfill } if } { pop } ifelse");
assert!(conv.warnings.is_empty(), "{:?}", conv.warnings);
assert!(c.lines().any(|l| l == "f"), "{c}");
let (c, conv) = run("/s 16 string def currentfile 0 (END) /SubFileDecode filter s readline\n\
END not exch length 0 eq and { 0 0 10 10 rectfill } if");
assert!(conv.warnings.is_empty(), "{:?}", conv.warnings);
assert!(c.lines().any(|l| l == "f"), "{c}");
}
+156 -6
View File
@@ -514,15 +514,24 @@ fn read_count(r: &mut Reader<'_>, v: Version) -> Result<usize> {
Ok(if v.is_psb() { r.u32()? as usize } else { r.u16()? as usize })
}
/// Reads `rows` RLE byte-count entries (`u16` for PSD, `u32` for PSB) from `data`,
/// returning the parsed counts and the remaining row-payload slice.
pub fn read_rle_row_counts(data: &[u8], rows: usize, version: Version) -> Result<(Vec<usize>, &[u8])> {
let mut r = Reader::new(data);
let count_size = if version.is_psb() { 4 } else { 2 };
r.check_count(rows as u64, count_size as u64)?;
let mut counts = Vec::with_capacity(rows);
for _ in 0..rows {
counts.push(read_count(&mut r, version)?);
}
Ok((counts, r.peek_rest()))
}
fn decode_rle(data: &[u8], layout: &PlaneLayout, total: usize) -> Result<Vec<u8>> {
let rows = layout.rows()?;
let rb = layout.row_bytes();
let mut r = Reader::new(data);
r.check_count(rows as u64, layout.count_size() as u64)?;
let mut counts = Vec::with_capacity(rows);
for _ in 0..rows {
counts.push(read_count(&mut r, layout.version)?);
}
let (counts, rest) = read_rle_row_counts(data, rows, layout.version)?;
let mut r = Reader::new(rest);
// PackBits expands at most 64x (2 input bytes -> 128 output bytes).
if (total as u64) > (r.remaining() as u64).saturating_mul(64) {
return Err(PsdError::Decompress("RLE data too short for declared size".into()));
@@ -742,6 +751,147 @@ pub fn zip_decompress(data: &[u8], expected: usize) -> Result<Vec<u8>> {
Ok(out)
}
/// Decompresses a zlib stream up to `limit` output bytes, verifying the zlib trailer
/// when the stream ends within `limit`.
///
/// Unlike [`zip_decompress`], a stream that ends cleanly with fewer than `limit` bytes
/// returns the bytes produced so far so callers can apply their own recovery (such as
/// zero-padding a short layer channel). Corrupt streams, bad Adler-32 checksums, or
/// streams that produce more than `limit` bytes return an error.
pub fn zip_decompress_up_to(data: &[u8], limit: usize) -> Result<Vec<u8>> {
const OOM: PsdError = PsdError::OutOfMemory("not enough memory for the decoded channel data");
let mut decoder = flate2::Decompress::new(true);
let mut out = Vec::new();
out.try_reserve_exact(limit.min(data.len().saturating_mul(1032))).map_err(|_| OOM)?;
let mut buf = vec![0u8; limit.clamp(8192, 1 << 20)];
loop {
let before = (decoder.total_in(), decoder.total_out());
let input = data.get(before.0 as usize..).ok_or_else(|| PsdError::Decompress("zlib input overflow".into()))?;
let status = decoder.decompress(input, &mut buf, flate2::FlushDecompress::None).map_err(|e| PsdError::Decompress(e.to_string()))?;
let got = decoder.total_out();
if got > limit as u64 {
return Err(PsdError::LimitExceeded("zlib output exceeds caller limit"));
}
let n = (got - before.1) as usize;
out.try_reserve(n).map_err(|_| OOM)?;
out.extend_from_slice(buf.get(..n).ok_or_else(|| PsdError::Decompress("zlib output overflow".into()))?);
if status == flate2::Status::StreamEnd {
return Ok(out);
}
if before == (decoder.total_in(), got) {
return Err(PsdError::Decompress("incomplete zlib stream".into()));
}
}
}
/// Staged access to a sequence of encoded image planes (e.g. a single layer channel or
/// a multi-plane merged image).
///
/// Unlike [`decode_planes`], this lets callers:
/// - borrow uncompressed (`Raw`) planes directly from the input slice without copying,
/// - read only a prefix of `total_planes` (for example skipping trailing spot channels),
/// - supply their own per-plane allocation, memory budget, and RLE/ZIP recovery policy.
#[derive(Debug, Clone)]
pub enum PlaneStream<'a> {
/// Uncompressed planes: each [`Self::next_raw_plane`] borrows `plane_bytes` from `rest`.
Raw {
/// Remaining unread bytes.
rest: &'a [u8],
},
/// PackBits RLE planes: `counts` holds `total_planes * height` row byte counts, followed by `rest`.
Rle {
/// Per-row byte counts for all planes, plane after plane.
counts: Vec<usize>,
/// Remaining unread row payload bytes.
rest: &'a [u8],
},
/// Inflated ZIP data holding consecutive planes.
Zip {
/// Inflated bytes (at most `zip_limit`).
data: Vec<u8>,
},
}
impl<'a> PlaneStream<'a> {
/// Prepares a plane stream from `data` (positioned immediately after the 2-byte compression field).
///
/// For RLE, reads the `total_planes * height` row-count table. For ZIP/ZIP-with-prediction,
/// invokes `before_zip(zip_limit)` (allowing callers to charge a memory budget before
/// allocation) and inflates up to `zip_limit` bytes via [`zip_decompress_up_to`].
pub fn open(
compression: Compression,
data: &'a [u8],
total_planes: usize,
height: usize,
version: Version,
zip_limit: usize,
before_zip: impl FnOnce(usize) -> Result<()>,
) -> Result<Self> {
match compression {
Compression::Raw => Ok(Self::Raw { rest: data }),
Compression::Rle => {
let total_rows = total_planes.checked_mul(height).ok_or(PsdError::LimitExceeded("row count overflow"))?;
let (counts, rest) = read_rle_row_counts(data, total_rows, version)?;
Ok(Self::Rle { counts, rest })
}
Compression::Zip | Compression::ZipPrediction => {
before_zip(zip_limit)?;
Ok(Self::Zip { data: zip_decompress_up_to(data, zip_limit)? })
}
Compression::Unknown(c) => Err(PsdError::Unsupported(format!("compression method {c}"))),
}
}
/// Borrows the next `plane_bytes` from a `Raw` stream, advancing past it.
pub fn next_raw_plane(&mut self, plane_bytes: usize) -> Result<&'a [u8]> {
let Self::Raw { rest } = self else {
return Err(PsdError::invalid("expected raw plane stream"));
};
if rest.len() < plane_bytes {
return Err(PsdError::UnexpectedEof { offset: rest.len(), needed: plane_bytes - rest.len() });
}
let (head, tail) = rest.split_at(plane_bytes);
*rest = tail;
Ok(head)
}
/// Decodes `height` RLE rows of `plane_index` into `out`, advancing past their payload bytes.
///
/// When `padded` is true, uses [`packbits::decode_padded_into`] (zero-padding short rows and
/// clipping oversized packets); otherwise uses strict PackBits decoding.
pub fn next_rle_plane_into(&mut self, plane_index: usize, row_bytes: usize, height: usize, padded: bool, out: &mut Vec<u8>) -> Result<()> {
let Self::Rle { counts, rest } = self else {
return Err(PsdError::invalid("expected RLE plane stream"));
};
let base = plane_index.checked_mul(height).ok_or(PsdError::LimitExceeded("row count overflow"))?;
for row in 0..height {
let n = *counts.get(base + row).ok_or(PsdError::UnexpectedEof { offset: 0, needed: 1 })?;
if rest.len() < n {
return Err(PsdError::UnexpectedEof { offset: rest.len(), needed: n - rest.len() });
}
let (src, tail) = rest.split_at(n);
*rest = tail;
if padded {
packbits::decode_padded_into(src, row_bytes, row_bytes, out)?;
} else {
packbits::decode_into(src, row_bytes, out)?;
}
}
Ok(())
}
/// Returns a mutable slice of `plane_bytes` for `plane_index` in a `Zip` stream.
pub fn zip_plane_mut(&mut self, plane_index: usize, plane_bytes: usize) -> Result<&mut [u8]> {
let Self::Zip { data } = self else {
return Err(PsdError::invalid("expected ZIP plane stream"));
};
let start = plane_index.checked_mul(plane_bytes).ok_or(PsdError::LimitExceeded("plane offset overflow"))?;
let end = start.checked_add(plane_bytes).ok_or(PsdError::LimitExceeded("plane offset overflow"))?;
let len = data.len();
data.get_mut(start..end).ok_or(PsdError::UnexpectedEof { offset: len, needed: end.saturating_sub(len) })
}
}
/// Applies horizontal delta prediction in place (encoder side).
///
/// * 1/8-bit: byte-wise delta per row.
+61
View File
@@ -870,3 +870,64 @@ fn packbits_slice_roundtrips_all_packet_lengths() {
}
}
}
#[test]
fn rle_row_counts_parse_psd_and_psb_and_reject_short_tables() {
let psd = [0, 3, 0, 5, 1, 2, 3];
let (counts, rest) = read_rle_row_counts(&psd, 2, Version::Psd).unwrap();
assert_eq!(counts, vec![3, 5]);
assert_eq!(rest, &[1, 2, 3]);
assert!(matches!(read_rle_row_counts(&psd[..3], 2, Version::Psd), Err(PsdError::UnexpectedEof { .. })));
let psb = [0, 0, 0, 3, 0, 1, 0, 0, 9];
let (counts, rest) = read_rle_row_counts(&psb, 2, Version::Psb).unwrap();
assert_eq!(counts, vec![3, 0x10000]);
assert_eq!(rest, &[9]);
assert!(matches!(read_rle_row_counts(&psb[..7], 2, Version::Psb), Err(PsdError::UnexpectedEof { .. })));
}
#[test]
fn zip_decompress_up_to_enforces_limit_and_verifies_trailer() {
let payload: Vec<u8> = (0..1024).map(|i| (i * 17 % 251) as u8).collect();
let compressed = zip_compress(&payload);
assert_eq!(zip_decompress_up_to(&compressed, payload.len()).unwrap(), payload);
assert_eq!(zip_decompress_up_to(&compressed, payload.len() * 2).unwrap(), payload);
assert!(matches!(zip_decompress_up_to(&compressed, payload.len() - 1), Err(PsdError::LimitExceeded(_))));
let mut bad_adler = compressed.clone();
let last = bad_adler.len() - 1;
bad_adler[last] ^= 0xff;
assert!(matches!(zip_decompress_up_to(&bad_adler, payload.len()), Err(PsdError::Decompress(_))));
assert!(matches!(zip_decompress_up_to(&compressed[..compressed.len() / 2], payload.len()), Err(PsdError::Decompress(_))));
}
#[test]
fn plane_stream_stages_raw_rle_and_zip_planes() {
let raw_bytes = [1u8, 2, 3, 4, 5, 6];
let mut raw_stream = PlaneStream::open(Compression::Raw, &raw_bytes, 3, 2, Version::Psd, 0, |_| Ok(())).unwrap();
assert_eq!(raw_stream.next_raw_plane(2).unwrap(), &[1, 2]);
assert_eq!(raw_stream.next_raw_plane(2).unwrap(), &[3, 4]);
// Two RLE planes (2 rows x 2 bytes each); first row of plane 0 is short for padded recovery.
let mut rle_data = vec![0, 2, 0, 2, 0, 2, 0, 2];
rle_data.extend_from_slice(&[0, 9]); // 1 byte literal, zero-padded to 2 when padded=true
rle_data.extend_from_slice(&[255, 8]); // 2 copies of 8
rle_data.extend_from_slice(&[255, 7]);
rle_data.extend_from_slice(&[255, 6]);
let mut rle_stream = PlaneStream::open(Compression::Rle, &rle_data, 2, 2, Version::Psd, 0, |_| Ok(())).unwrap();
let mut plane0 = Vec::new();
rle_stream.next_rle_plane_into(0, 2, 2, true, &mut plane0).unwrap();
assert_eq!(plane0, vec![9, 0, 8, 8]);
let mut plane1 = Vec::new();
rle_stream.next_rle_plane_into(1, 2, 2, false, &mut plane1).unwrap();
assert_eq!(plane1, vec![7, 7, 6, 6]);
let zip_src = zip_compress(&[10, 20, 30, 40]);
let refused = PlaneStream::open(Compression::Zip, &zip_src, 2, 1, Version::Psd, 4, |_| Err(PsdError::LimitExceeded("budget")));
assert!(matches!(refused, Err(PsdError::LimitExceeded("budget"))));
let mut zip_stream = PlaneStream::open(Compression::Zip, &zip_src, 2, 1, Version::Psd, 4, |_| Ok(())).unwrap();
assert_eq!(zip_stream.zip_plane_mut(0, 2).unwrap(), &[10, 20]);
assert_eq!(zip_stream.zip_plane_mut(1, 2).unwrap(), &[30, 40]);
}
+16 -1
View File
@@ -99,7 +99,9 @@ impl<'a> ImageResourceView<'a> {
r.skip(name_pad)?;
let len = r.u32()?;
let data = r.bytes_u64(u64::from(len))?;
if len % 2 == 1 {
// A writer that drops the pad byte after the section's last resource is common; that
// byte would be past the section, so don't fail the whole file over it.
if len % 2 == 1 && !r.is_empty() {
r.skip(1)?;
}
Ok(ImageResourceView { signature, id, name, data })
@@ -517,6 +519,19 @@ mod tests {
assert_eq!(roundtrip(&[]), vec![0, 0, 0, 0]);
}
/// The last resource of the section has odd data and no pad byte (some writers drop it):
/// the resource still reads instead of the whole file failing.
#[test]
fn odd_last_resource_without_pad() {
let mut out = Vec::new();
write_section(&mut out, &[ImageResource::new(1000, vec![1, 2, 3])]).unwrap();
out.pop();
let len = u32::from_be_bytes([out[0], out[1], out[2], out[3]]) - 1;
out[..4].copy_from_slice(&len.to_be_bytes());
let back = read_section(&mut Reader::new(&out)).unwrap();
assert_eq!(back, [ImageResource::new(1000, vec![1, 2, 3])]);
}
#[test]
fn odd_data_is_padded() {
let out = roundtrip(&[ImageResource::new(1000, vec![1, 2, 3])]);
+195
View File
@@ -10,6 +10,46 @@ use core::fmt;
const MAX_VARINT_BYTES: usize = 9;
/// The b-tree cell layouts that carry payload bytes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PayloadKind {
/// A table leaf cell; table interior cells have no payload.
TableLeaf,
/// An index leaf or interior cell, which share the same payload thresholds.
Index,
}
/// Return the number of payload bytes stored in the b-tree page before overflow.
///
/// `usable` is the page size minus its reserved bytes, not the space remaining after the
/// cell header. It may be odd. Sizes outside 480..=65,536 return `None`; validating the
/// database header and bounding payload reads remain the caller's responsibility.
///
/// This implements the [SQLite b-tree cell payload formula](https://www.sqlite.org/fileformat.html#b_tree_pages).
/// The calculation allocates nothing and accepts the full `u64` payload length without
/// implying that the payload fits in the database or in memory.
pub fn local_payload_len(usable: u32, payload_len: u64, kind: PayloadKind) -> Option<u32> {
// SQLite requires at least 480 usable bytes; this also keeps every divisor and
// subtraction below valid even when the caller supplies an untrusted header.
if !(480..=65_536).contains(&usable) {
return None;
}
let usable = u64::from(usable);
let maximum = match kind {
PayloadKind::TableLeaf => usable - 35,
PayloadKind::Index => (usable - 12) * 64 / 255 - 23,
};
let local = if payload_len <= maximum {
payload_len
} else {
let minimum = (usable - 12) * 32 / 255 - 23;
let candidate = minimum + (payload_len - minimum) % (usable - 4);
if candidate <= maximum { candidate } else { minimum }
};
// Both branches bound the result by the supported page's maximum local payload.
Some(local as u32)
}
/// A failure to decode part of a SQLite record or page.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Error {
@@ -17,6 +57,20 @@ pub enum Error {
TruncatedVarint,
/// The serial type is reserved and has no defined field width.
ReservedSerialType(u64),
/// The decoded database page size is not a power of two in `512..=65_536`.
InvalidPageSize(u32),
/// The usable page size (`page_size - reserved`) is below 480 bytes.
UsablePageSizeTooSmall(u32),
/// A B-tree page ended before its header or cell-pointer array completed.
TruncatedPage,
/// The B-tree page type byte is not a table or index interior/leaf page.
UnsupportedBtreePageType(u8),
/// A cell pointer falls outside `[pointers_end, usable)`.
InvalidCellPointer { offset: usize, min: usize, usable: usize },
/// The requested cell index is outside the page's cell count.
CellIndexOutOfBounds { index: usize, cells: usize },
/// A signed big-endian integer slice is empty or wider than 8 bytes.
InvalidIntegerWidth(usize),
}
impl fmt::Display for Error {
@@ -24,6 +78,13 @@ impl fmt::Display for Error {
match self {
Self::TruncatedVarint => f.write_str("truncated SQLite varint"),
Self::ReservedSerialType(code) => write!(f, "reserved SQLite serial type {code}"),
Self::InvalidPageSize(size) => write!(f, "invalid SQLite page size {size}"),
Self::UsablePageSizeTooSmall(usable) => write!(f, "usable SQLite page size {usable} is too small"),
Self::TruncatedPage => f.write_str("truncated SQLite B-tree page"),
Self::UnsupportedBtreePageType(kind) => write!(f, "unsupported SQLite B-tree page type 0x{kind:02x}"),
Self::InvalidCellPointer { offset, min, usable } => write!(f, "invalid SQLite cell pointer {offset} outside {min}..{usable}"),
Self::CellIndexOutOfBounds { index, cells } => write!(f, "SQLite cell index {index} out of bounds for {cells} cells"),
Self::InvalidIntegerWidth(width) => write!(f, "invalid SQLite signed integer width {width}"),
}
}
}
@@ -85,3 +146,137 @@ pub const fn serial_type_len(serial_type: u64) -> Result<u64, Error> {
_ => Ok((serial_type - 12) / 2),
}
}
/// Decode a raw big-endian 16-bit SQLite header page size (`1` represents `65_536`).
///
/// # Errors
///
/// Returns [`Error::InvalidPageSize`] when the decoded size is not a power of two in `512..=65_536`.
///
/// ```
/// use craft_sqlite::page_size_from_raw;
///
/// assert_eq!(page_size_from_raw(1), Ok(65_536));
/// assert_eq!(page_size_from_raw(4096), Ok(4096));
/// ```
pub const fn page_size_from_raw(raw: u16) -> Result<u32, Error> {
let size = if raw == 1 { 65_536 } else { raw as u32 };
if size < 512 || !size.is_power_of_two() { Err(Error::InvalidPageSize(size)) } else { Ok(size) }
}
/// Compute the usable byte count of a SQLite page after subtracting `reserved` trailing bytes.
///
/// # Errors
///
/// Returns [`Error::UsablePageSizeTooSmall`] when `page_size - reserved < 480`.
pub const fn usable_page_size(page_size: u32, reserved: u8) -> Result<u32, Error> {
let Some(usable) = page_size.checked_sub(reserved as u32) else {
return Err(Error::UsablePageSizeTooSmall(0));
};
if usable < 480 { Err(Error::UsablePageSizeTooSmall(usable)) } else { Ok(usable) }
}
/// Decode a 1..=8-byte big-endian signed two's-complement integer into `i64`.
///
/// # Errors
///
/// Returns [`Error::InvalidIntegerWidth`] if `bytes` is empty or longer than 8 bytes.
///
/// ```
/// use craft_sqlite::decode_signed_be_int;
///
/// assert_eq!(decode_signed_be_int(&[0x80, 0x00, 0x01]), Ok(-8_388_607));
/// ```
pub fn decode_signed_be_int(bytes: &[u8]) -> Result<i64, Error> {
let Some(&first) = bytes.first() else {
return Err(Error::InvalidIntegerWidth(0));
};
if bytes.len() > 8 {
return Err(Error::InvalidIntegerWidth(bytes.len()));
}
let mut value: i64 = if first & 0x80 != 0 { -1 } else { 0 };
for &byte in bytes {
value = (value << 8) | i64::from(byte);
}
Ok(value)
}
/// Parsed B-tree page header and cell-pointer array bounds within a usable page slice.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BtreePageHeader {
/// B-tree page type (`0x02`, `0x05`, `0x0a`, or `0x0d`).
pub kind: u8,
/// Offset where the B-tree page header starts (`100` on page 1, `0` otherwise).
pub header_offset: usize,
/// Number of cells declared in the B-tree header.
pub cells: usize,
/// Start offset of the 2-byte big-endian cell-pointer array.
pub pointers_offset: usize,
/// Exclusive end offset of the cell-pointer array.
pub pointers_end: usize,
}
/// Parse and bounds-check the B-tree page header and cell-pointer array on `usable_page`.
///
/// # Errors
///
/// Returns [`Error::TruncatedPage`] if the page ends before the header or pointer array, or
/// [`Error::UnsupportedBtreePageType`] if the page type byte is not `0x02`, `0x05`, `0x0a`, or `0x0d`.
pub fn parse_btree_page_header(usable_page: &[u8], is_page_one: bool) -> Result<BtreePageHeader, Error> {
let header_offset = if is_page_one { 100 } else { 0 };
let Some(&kind) = usable_page.get(header_offset) else {
return Err(Error::TruncatedPage);
};
let header_size = match kind {
0x05 | 0x02 => 12,
0x0d | 0x0a => 8,
_ => return Err(Error::UnsupportedBtreePageType(kind)),
};
let Some(cells_bytes) = header_offset
.checked_add(3)
.and_then(|start| start.checked_add(2).and_then(|end| usable_page.get(start..end)))
.and_then(|slice| <[u8; 2]>::try_from(slice).ok())
else {
return Err(Error::TruncatedPage);
};
let cells = usize::from(u16::from_be_bytes(cells_bytes));
let Some(pointers_offset) = header_offset.checked_add(header_size) else {
return Err(Error::TruncatedPage);
};
let Some(pointers_bytes) = cells.checked_mul(2) else {
return Err(Error::TruncatedPage);
};
let Some(pointers_end) = pointers_offset.checked_add(pointers_bytes) else {
return Err(Error::TruncatedPage);
};
if pointers_end > usable_page.len() {
return Err(Error::TruncatedPage);
}
Ok(BtreePageHeader { kind, header_offset, cells, pointers_offset, pointers_end })
}
/// Read and bounds-check the `index`-th cell offset from a parsed [`BtreePageHeader`].
///
/// # Errors
///
/// Returns [`Error::CellIndexOutOfBounds`] when `index >= header.cells`, [`Error::TruncatedPage`]
/// if the pointer slot is out of bounds, or [`Error::InvalidCellPointer`] if the pointer lies
/// outside `[header.pointers_end, usable_page.len())`.
pub fn btree_cell_offset(usable_page: &[u8], header: &BtreePageHeader, index: usize) -> Result<usize, Error> {
if index >= header.cells {
return Err(Error::CellIndexOutOfBounds { index, cells: header.cells });
}
let Some(bytes) = index
.checked_mul(2)
.and_then(|off| header.pointers_offset.checked_add(off))
.and_then(|ptr| ptr.checked_add(2).and_then(|end| usable_page.get(ptr..end)))
.and_then(|slice| <[u8; 2]>::try_from(slice).ok())
else {
return Err(Error::TruncatedPage);
};
let offset = usize::from(u16::from_be_bytes(bytes));
if offset < header.pointers_end || offset >= usable_page.len() {
return Err(Error::InvalidCellPointer { offset, min: header.pointers_end, usable: usable_page.len() });
}
Ok(offset)
}
+128 -1
View File
@@ -1,4 +1,57 @@
use craft_sqlite::{Error, read_varint, serial_type_len};
use craft_sqlite::{
BtreePageHeader, Error, PayloadKind, btree_cell_offset, decode_signed_be_int, local_payload_len, page_size_from_raw, parse_btree_page_header,
read_varint, serial_type_len, usable_page_size,
};
#[test]
fn local_payload_preserves_inline_and_overflow_boundaries() {
// Original literal cases calculated from SQLite file format section 1.6, including
// the 512-byte page with 32 reserved bytes and an odd usable size with one reserved byte.
for (usable, minimum, table_max, index_max) in [
(480, 35, 445, 94),
(511, 39, 476, 102),
(512, 39, 477, 102),
(1_024, 103, 989, 230),
(2_048, 232, 2_013, 487),
(4_096, 489, 4_061, 1_002),
(8_192, 1_003, 8_157, 2_030),
(16_384, 2_031, 16_349, 4_086),
(32_768, 4_087, 32_733, 8_198),
(65_536, 8_199, 65_501, 16_422),
] {
for (kind, maximum) in [(PayloadKind::TableLeaf, table_max), (PayloadKind::Index, index_max)] {
for (payload, expected) in [(0, 0), (maximum, maximum), (maximum + 1, minimum)] {
assert_eq!(local_payload_len(usable, u64::from(payload), kind), Some(expected), "usable {usable}, payload {payload}, {kind:?}");
}
// A complete overflow-page span returns to the upper local boundary; one
// further byte must fall back to the minimum rather than exceed the maximum.
let payload = u64::from(maximum) + u64::from(usable) - 4;
assert_eq!(local_payload_len(usable, payload, kind), Some(maximum), "usable {usable}, {kind:?}");
assert_eq!(local_payload_len(usable, payload + 1, kind), Some(minimum), "usable {usable}, {kind:?}");
}
}
assert_eq!(local_payload_len(512, 600, PayloadKind::TableLeaf), Some(92));
}
#[test]
fn local_payload_refuses_unsupported_usable_sizes() {
for usable in [0, 4, 35, 479, 65_537, u32::MAX] {
for kind in [PayloadKind::TableLeaf, PayloadKind::Index] {
assert_eq!(local_payload_len(usable, 0, kind), None);
assert_eq!(local_payload_len(usable, u64::MAX, kind), None);
}
}
}
#[test]
fn local_payload_keeps_full_width_payload_lengths() {
// Literal remainders for the largest wire length catch host-size truncation and
// overflow in the minimum-plus-modulo calculation without allocating a payload.
for (usable, table_local, index_local) in [(480, 323, 35), (511, 93, 93), (512, 255, 39), (32_768, 4_095, 4_095), (65_536, 8_199, 8_199)] {
assert_eq!(local_payload_len(usable, u64::MAX, PayloadKind::TableLeaf), Some(table_local));
assert_eq!(local_payload_len(usable, u64::MAX, PayloadKind::Index), Some(index_local));
}
}
#[test]
fn varints_decode_at_each_width() {
@@ -69,3 +122,77 @@ fn variable_serial_type_widths_are_portable() {
assert_eq!(serial_type_len(serial_type), Ok(width), "code {serial_type}");
}
}
#[test]
fn page_size_and_usable_validation() {
assert_eq!(page_size_from_raw(512), Ok(512));
assert_eq!(page_size_from_raw(4096), Ok(4096));
assert_eq!(page_size_from_raw(1), Ok(65_536));
assert_eq!(page_size_from_raw(0), Err(Error::InvalidPageSize(0)));
assert_eq!(page_size_from_raw(256), Err(Error::InvalidPageSize(256)));
assert_eq!(page_size_from_raw(1000), Err(Error::InvalidPageSize(1000)));
assert_eq!(usable_page_size(512, 32), Ok(480));
assert_eq!(usable_page_size(512, 33), Err(Error::UsablePageSizeTooSmall(479)));
assert_eq!(usable_page_size(100, 150), Err(Error::UsablePageSizeTooSmall(0)));
assert_eq!(usable_page_size(512, 0), Ok(512));
for err in [
Error::InvalidPageSize(0),
Error::UsablePageSizeTooSmall(479),
Error::TruncatedPage,
Error::UnsupportedBtreePageType(0x01),
Error::InvalidCellPointer { offset: 109, min: 110, usable: 512 },
Error::CellIndexOutOfBounds { index: 1, cells: 1 },
Error::InvalidIntegerWidth(0),
] {
assert!(!err.to_string().is_empty());
}
}
#[test]
fn signed_be_integers_decode_with_sign_extension() {
assert_eq!(decode_signed_be_int(&[0x7f]), Ok(127));
assert_eq!(decode_signed_be_int(&[0x80]), Ok(-128));
assert_eq!(decode_signed_be_int(&[0x80, 0x00, 0x01]), Ok(-8_388_607));
assert_eq!(decode_signed_be_int(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xfe]), Ok(-2));
assert_eq!(decode_signed_be_int(&[0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Ok(i64::MAX));
assert_eq!(decode_signed_be_int(&[0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Ok(i64::MIN));
assert_eq!(decode_signed_be_int(&[]), Err(Error::InvalidIntegerWidth(0)));
assert_eq!(decode_signed_be_int(&[0; 9]), Err(Error::InvalidIntegerWidth(9)));
}
#[test]
fn btree_page_header_and_cell_pointer_bounds() {
let mut page = [0u8; 512];
page[100] = 0x0d;
page[103..105].copy_from_slice(&1u16.to_be_bytes());
page[108..110].copy_from_slice(&400u16.to_be_bytes());
let hdr = parse_btree_page_header(&page, true).unwrap();
assert_eq!(hdr, BtreePageHeader { kind: 0x0d, header_offset: 100, cells: 1, pointers_offset: 108, pointers_end: 110 });
assert_eq!(btree_cell_offset(&page, &hdr, 0), Ok(400));
assert_eq!(btree_cell_offset(&page, &hdr, 1), Err(Error::CellIndexOutOfBounds { index: 1, cells: 1 }));
// Pointer inside header/pointer array is rejected.
page[108..110].copy_from_slice(&109u16.to_be_bytes());
assert_eq!(btree_cell_offset(&page, &hdr, 0), Err(Error::InvalidCellPointer { offset: 109, min: 110, usable: 512 }));
// Unsupported page kind and truncated pages are rejected.
page[0] = 0x01;
assert_eq!(parse_btree_page_header(&page, false), Err(Error::UnsupportedBtreePageType(0x01)));
assert_eq!(parse_btree_page_header(&[], false), Err(Error::TruncatedPage));
assert_eq!(parse_btree_page_header(&[0x0d, 0, 0, 0], false), Err(Error::TruncatedPage));
// Interior page with pointer array exceeding usable page is rejected.
page[0] = 0x05;
page[3..5].copy_from_slice(&300u16.to_be_bytes());
assert_eq!(parse_btree_page_header(&page, false), Err(Error::TruncatedPage));
// Cell pointer >= usable is rejected.
page[0] = 0x0d;
page[3..5].copy_from_slice(&1u16.to_be_bytes());
page[8..10].copy_from_slice(&512u16.to_be_bytes());
let small_hdr = parse_btree_page_header(&page, false).unwrap();
assert_eq!(btree_cell_offset(&page, &small_hdr, 0), Err(Error::InvalidCellPointer { offset: 512, min: 10, usable: 512 }));
}
+1
View File
@@ -26,6 +26,7 @@ pub type Step = Result<Vec<u8>, Failure>;
pay(work: &mut u64, steps) -> Result<(), CodecError> // an allowance shared across a run of images
lzw::decode(data, early_change, max) -> Step; lzw::encode(data, early_change) -> Vec<u8>
lzw::decode_prefix(data, early_change, max) -> Result<(Vec<u8>, usize), Failure>
ascii85::decode(data, max) -> Step; ascii85::encode(data) -> Vec<u8>
asciihex::decode(data, max) -> Step; asciihex::encode(data) -> Vec<u8>
runlength::decode(data, max) -> Step; runlength::encode(data) -> Vec<u8>
+66 -2
View File
@@ -50,6 +50,23 @@ impl BitReader<'_> {
}
pub fn decode(data: &[u8], early: bool, max: usize) -> Step {
let out = Vec::with_capacity(data.len().saturating_mul(2).min(max));
decode_stream(data, early, max, out).map(|(out, _)| out)
}
/// Decode one LZW stream and return its bytes and the number of input bytes consumed.
///
/// The count includes the byte containing the final bits of the end-of-data code (257).
/// Later bytes remain unread. If the input ends without EOD, complete codes still decode
/// and the count includes all bytes available. As in [`decode`], `early` selects the early
/// width change and `max` bounds the decoded output.
///
/// Output grows as codes arrive because the input may include a program after the compressed data.
pub fn decode_prefix(data: &[u8], early: bool, max: usize) -> Result<(Vec<u8>, usize), Failure> {
decode_stream(data, early, max, Vec::new())
}
fn decode_stream(data: &[u8], early: bool, max: usize, mut out: Vec<u8>) -> Result<(Vec<u8>, usize), Failure> {
// Table entry = (prefix code, last byte, first byte, length).
let mut prefix = vec![0u16; TABLE];
let mut last = vec![0u8; TABLE];
@@ -64,7 +81,6 @@ pub fn decode(data: &[u8], early: bool, max: usize) -> Step {
let mut w = 9;
let mut prev: Option<usize> = None;
let mut r = BitReader { data, pos: 0, acc: 0, bits: 0 };
let mut out = Vec::with_capacity(data.len().saturating_mul(2).min(max));
while let Some(code) = r.read(w) {
match code {
@@ -111,7 +127,7 @@ pub fn decode(data: &[u8], early: bool, max: usize) -> Step {
prev = Some(code);
w = width(next, early);
}
Ok(out)
Ok((out, r.pos))
}
struct BitWriter {
@@ -204,6 +220,46 @@ mod tests {
assert_eq!(dec(&SPEC_OUT, false).unwrap(), SPEC_IN);
}
#[test]
fn prefix_stops_at_the_byte_containing_end_of_data() {
let mut aligned = SPEC_OUT.to_vec();
let following = b"\nshowpage";
aligned.extend_from_slice(following);
let (decoded, consumed) = decode_prefix(&aligned, true, SPEC_IN.len()).ok().unwrap();
assert_eq!(decoded, SPEC_IN);
assert_eq!(&aligned[consumed..], following);
// Two 9-bit codes: literal 'A', then 257. The last six bits are padding.
let mut partial_byte = vec![0x20, 0xc0, 0x7f];
partial_byte.resize(1 << 20, b'x');
let (decoded, consumed) = decode_prefix(&partial_byte, true, usize::MAX).ok().unwrap();
assert_eq!(decoded, b"A");
assert_eq!(consumed, 3);
assert!(decoded.capacity() < partial_byte.len(), "the unread suffix must not reserve output");
}
#[test]
fn prefix_tolerates_eof_with_unused_bits() {
assert_eq!(decode_prefix(&[], true, 0).ok().unwrap(), (vec![], 0));
// Literal 'A' and just the first seven bits of EOD.
assert_eq!(decode_prefix(&[0x20, 0xc0], true, 1).ok().unwrap(), (b"A".to_vec(), 2));
}
#[test]
fn prefix_preserves_corruption_and_output_limit() {
let mut w = BitWriter { out: vec![], acc: 0, bits: 0 };
for c in [65, 66, 300] {
w.write(c, 9);
}
let bytes = w.finish();
let at_limit = decode_prefix(&bytes, true, 2).err().unwrap();
assert!(matches!(at_limit.error, CodecError::Corrupt { .. }));
assert_eq!(at_limit.partial, b"AB");
let too_small = decode_prefix(&bytes, true, 1).err().unwrap();
assert!(matches!(too_small.error, CodecError::LimitExceeded(1)));
assert!(too_small.partial.is_empty());
}
#[test]
fn missing_eod_and_clear() {
// Drop the EOD (last 9 bits span the final 2 bytes; keep bits for 66 only).
@@ -263,6 +319,14 @@ mod tests {
assert_eq!(dec(&tiff, true).unwrap(), data);
let plain = weezl::encode::Encoder::new(Msb, 8).encode(&data).unwrap();
assert_eq!(dec(&plain, false).unwrap(), data);
// Both independent bitstreams may be followed by uncompressed data.
for (mut bytes, early) in [(tiff, true), (plain, false)] {
let following = b"\nshowpage";
bytes.extend_from_slice(following);
let (out, used) = decode_prefix(&bytes, early, data.len()).ok().unwrap();
assert_eq!(out, data);
assert_eq!(&bytes[used..], following);
}
let ours = encode(&data, true);
assert_eq!(weezl::decode::Decoder::with_tiff_size_switch(Msb, 8).decode(&ours).unwrap(), data);
let ours = encode(&data, false);
+94 -2
View File
@@ -7,7 +7,34 @@ use crate::{Failure, Step};
const NAME: &str = "RunLengthDecode";
pub fn decode(data: &[u8], max: usize) -> Step {
let mut out = Vec::with_capacity(data.len().saturating_mul(2).min(max));
decode_packets(data, max, Mode::Whole).map(|(out, _)| out)
}
/// Decode one run-length stream and return its bytes and the number of input bytes consumed.
///
/// The count includes the end-of-data byte (128); any bytes after it remain unread. EOF between
/// packets is accepted without an end marker. Each packet must be complete before its output
/// limit is checked, so a truncated packet is corrupt even if its available bytes exceed `max`.
/// An earlier complete packet exceeding the limit still fails before any later packet is read.
/// On corruption, partial output contains only complete preceding packets.
///
/// Output grows as packets arrive instead of reserving space for the input, which may include
/// an arbitrarily long program after the end marker. The existing [`decode`] retains its
/// allocation and partial-literal limit policy.
pub fn decode_prefix(data: &[u8], max: usize) -> Result<(Vec<u8>, usize), Failure> {
decode_packets(data, max, Mode::Prefix)
}
enum Mode {
Whole,
Prefix,
}
fn decode_packets(data: &[u8], max: usize, mode: Mode) -> Result<(Vec<u8>, usize), Failure> {
let mut out = match mode {
Mode::Whole => Vec::with_capacity(data.len().saturating_mul(2).min(max)),
Mode::Prefix => Vec::new(),
};
let mut i = 0;
while let Some(&l) = data.get(i) {
i += 1;
@@ -16,6 +43,9 @@ pub fn decode(data: &[u8], max: usize) -> Step {
0..=127 => {
let n = usize::from(l) + 1;
let avail = n.min(data.len() - i);
if matches!(mode, Mode::Prefix) && avail < n {
return Err(Failure::corrupt(NAME, "truncated literal run", out));
}
if out.len() + avail > max {
return Err(Failure::limit(max));
}
@@ -38,7 +68,7 @@ pub fn decode(data: &[u8], max: usize) -> Step {
}
}
}
Ok(out)
Ok((out, i))
}
pub fn encode(data: &[u8]) -> Vec<u8> {
@@ -118,6 +148,68 @@ mod tests {
assert_eq!(decode(&[129, 0, 129, 0], 256).ok().unwrap().len(), 256);
}
#[test]
fn prefix_stops_after_eod_without_reading_the_program_tail() {
let bytes = [2, b'a', b'b', b'c', 254, b'x', 128, 127];
let (out, used) = decode_prefix(&bytes, 6).ok().unwrap();
assert_eq!(out, b"abcxxx");
assert_eq!(&bytes[used..], &[127]); // Truncated data after EOD is not decoded.
assert_eq!(used, 7);
assert_eq!(decode_prefix(&[128], 0).ok().unwrap(), (vec![], 1));
}
#[test]
fn prefix_accepts_empty_input_and_eof_between_packets() {
assert_eq!(decode_prefix(&[], 0).ok().unwrap(), (vec![], 0));
let bytes = [0, b'a', 255, b'b'];
assert_eq!(decode_prefix(&bytes, 3).ok().unwrap(), (b"abb".to_vec(), bytes.len()));
}
#[test]
fn prefix_checks_packet_completeness_before_its_output_limit() {
for bytes in [&[2, b'a', b'b'][..], &[129][..]] {
let failure = decode_prefix(bytes, 0).err().unwrap();
assert!(matches!(failure.error, CodecError::Corrupt { .. }));
assert!(failure.partial.is_empty());
}
let failure = decode_prefix(&[0, b'q', 2, b'a', b'b'], 1).err().unwrap();
assert!(matches!(failure.error, CodecError::Corrupt { .. }));
assert_eq!(failure.partial, b"q");
}
#[test]
fn prefix_checks_each_complete_packet_before_later_corruption() {
for bytes in [&[0, b'a', 127][..], &[255, b'a', 127][..]] {
let failure = decode_prefix(bytes, 0).err().unwrap();
assert!(matches!(failure.error, CodecError::LimitExceeded(0)));
assert!(failure.partial.is_empty());
}
assert_eq!(decode_prefix(&[0, b'a', 128], 1).ok().unwrap(), (vec![b'a'], 3));
assert_eq!(decode_prefix(&[255, b'a', 128], 2).ok().unwrap(), (vec![b'a'; 2], 3));
}
#[test]
fn prefix_does_not_reserve_for_the_undecoded_tail() {
let mut bytes = vec![128];
bytes.resize(1 << 20, 127);
let (out, used) = decode_prefix(&bytes, usize::MAX).ok().unwrap();
assert_eq!(used, 1);
assert_eq!(out.capacity(), 0);
let out = decode(&bytes, 256).ok().unwrap();
assert!(out.capacity() >= 256, "whole decoding keeps its input-based reservation");
}
#[test]
fn whole_decode_keeps_its_partial_literal_and_limit_precedence() {
let bytes = [2, b'a', b'b'];
let failure = decode(&bytes, 1).err().unwrap();
assert!(matches!(failure.error, CodecError::LimitExceeded(1)));
assert!(failure.partial.is_empty());
let failure = decode(&bytes, 2).err().unwrap();
assert!(matches!(failure.error, CodecError::Corrupt { .. }));
assert_eq!(failure.partial, b"ab");
}
#[test]
fn encoding() {
assert_eq!(encode(b"abcxxx"), [2, b'a', b'b', b'c', 254, b'x', 128]);
+99 -7
View File
@@ -193,6 +193,87 @@ pub fn length(s: &str, axis: char, font: f64, vw: f64, vh: f64) -> Option<f64> {
value.is_finite().then_some(value)
}
/// Parse a strict SVG length in user units, rejecting unknown unit suffixes.
///
/// `%` is relative to `reference`; `em`/`ex` assume a 16 px font.
pub fn length_strict(s: &str, reference: f64) -> Option<f64> {
let v = s.trim();
let units: [(&str, f64); 9] = [
("%", reference / 100.0),
("px", 1.0),
("pt", 96.0 / 72.0),
("pc", 16.0),
("mm", 96.0 / 25.4),
("cm", 96.0 / 2.54),
("in", 96.0),
("em", 16.0),
("ex", 8.0),
];
let (num, k) = units.iter().find_map(|(u, k)| v.strip_suffix(u).map(|n| (n, *k))).unwrap_or((v, 1.0));
let n: f64 = num.trim().parse().ok().filter(|n: &f64| n.is_finite())?;
Some(n * k).filter(|x| x.is_finite())
}
/// Parse an SVG opacity or offset value (number or percentage), clamped to `[0.0, 1.0]`.
pub fn parse_opacity(s: &str) -> Option<f64> {
let v = s.trim();
let x = match v.strip_suffix('%') {
Some(p) => p.parse::<f64>().ok()? / 100.0,
None => v.parse::<f64>().ok()?,
};
x.is_finite().then(|| x.clamp(0.0, 1.0))
}
/// Parse an SVG `font-size` (keyword, relative `em`/`ex`/`%` to `parent`, or strict length).
pub fn parse_font_size(s: &str, parent: f64, reference: f64) -> Option<f64> {
let v = s.trim();
let keyword = match v {
"xx-small" => Some(9.0),
"x-small" => Some(10.0),
"small" => Some(13.0),
"medium" => Some(16.0),
"large" => Some(18.0),
"x-large" => Some(24.0),
"xx-large" => Some(32.0),
"larger" => Some(parent * 1.2),
"smaller" => Some(parent / 1.2),
_ => None,
};
let rel = |suffix: &str, k: f64| v.strip_suffix(suffix).and_then(|n| n.trim().parse::<f64>().ok()).map(|n| n * k);
let size = keyword
.or_else(|| rel("em", parent))
.or_else(|| rel("ex", parent * 0.5))
.or_else(|| rel("%", parent / 100.0))
.or_else(|| length_strict(v, reference))?;
size.is_finite().then(|| size.clamp(0.0, 2000.0))
}
/// Parse an SVG `stroke-dasharray` list (`none` or empty/negative/invalid returns `None`).
pub fn parse_dash_array(s: &str, reference: f64) -> Option<Vec<f64>> {
if s.trim() == "none" {
return None;
}
let mut out = Vec::new();
for part in s.split(|c: char| c == ',' || c.is_whitespace()).filter(|p| !p.trim().is_empty()).take(1024) {
let x = length_strict(part, reference)?;
if x < 0.0 {
return None;
}
out.push(x);
}
(!out.is_empty()).then_some(out)
}
/// What a percentage of geometry attribute `attr_name` is relative to in a `width` x `height` viewport.
pub fn symbol_percent_basis(attr_name: &str, width: f64, height: f64) -> Option<f64> {
match attr_name {
"x" | "x1" | "x2" | "cx" | "width" | "rx" => Some(width),
"y" | "y1" | "y2" | "cy" | "height" | "ry" => Some(height),
"r" => Some(((width * width + height * height) / 2.0).sqrt()),
_ => None,
}
}
/// 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)
@@ -315,9 +396,9 @@ pub fn resolve_paint<S>(paint: &PaintRef, st: &Style, resolve_url: impl FnOnce(&
}
}
/// 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);
/// Parse a `viewBox` attribute string into `([min_x, min_y], width, height)`.
pub fn parse_viewbox(s: &str) -> Option<([f64; 2], f64, f64)> {
let (v, exceeded) = numbers_bounded(s, 5);
if exceeded || !v.iter().all(|x| x.is_finite()) {
return None;
}
@@ -325,10 +406,10 @@ pub fn viewbox(n: roxmltree::Node) -> Option<([f64; 2], f64, f64)> {
(*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");
/// Compute the `viewBox` -> viewport transform for `preserveAspectRatio` (default `xMidYMid meet`).
pub fn viewbox_transform_with(vb: ([f64; 2], f64, f64), w: f64, h: f64, preserve_aspect_ratio: &str) -> Affine {
let ([x, y], vw, vh) = vb;
let par = if preserve_aspect_ratio.trim().is_empty() { "xMidYMid meet" } else { preserve_aspect_ratio };
let mut parts = par.split_whitespace();
let mut align = parts.next().unwrap_or("xMidYMid");
if align == "defer" {
@@ -359,6 +440,17 @@ pub fn viewbox_transform(n: roxmltree::Node, w: f64, h: f64) -> Affine {
Affine::translate((tx, ty)) * Affine::scale(s) * Affine::translate((-x, -y))
}
/// Parse an element's `viewBox` attribute into `([min_x, min_y], width, height)`.
pub fn viewbox(n: roxmltree::Node) -> Option<([f64; 2], f64, f64)> {
parse_viewbox(n.attribute("viewBox")?)
}
/// The `viewBox` -> viewport transform (`preserveAspectRatio`, default `xMidYMid meet`).
pub fn viewbox_transform(n: roxmltree::Node, w: f64, h: f64) -> Affine {
let Some(vb) = viewbox(n) else { return Affine::IDENTITY };
viewbox_transform_with(vb, w, h, n.attribute("preserveAspectRatio").unwrap_or("xMidYMid meet"))
}
#[cfg(test)]
mod tests {
use super::*;
+31
View File
@@ -101,6 +101,31 @@ pub fn declarations(s: &str) -> impl Iterator<Item = (String, String)> + '_ {
.filter(|(k, _)| !k.is_empty())
}
/// Escape `s` as a CSS string delimited by `quote`.
///
/// Escapes backslashes, the delimiter quote, control characters, and `<` / `>` (which could end
/// a `<style>` element) using CSS hex escapes.
pub fn quote_css_string(s: &str, quote: char) -> String {
use std::fmt::Write as _;
let mut out = String::with_capacity(s.len() + 2);
out.push(quote);
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
c if c == quote => {
out.push('\\');
out.push(c);
}
c if c.is_control() || matches!(c, '<' | '>') => {
let _ = write!(out, "\\{:x} ", u32::from(c));
}
c => out.push(c),
}
}
out.push(quote);
out
}
fn strip_comments(s: &str) -> String {
let mut out = String::new();
let mut rest = s;
@@ -343,4 +368,10 @@ mod tests {
let mut sheet = StyleSheet { bytes: MAX_CSS_BYTES, ..Default::default() };
assert!(parse("x", &mut sheet).is_err());
}
#[test]
fn css_string_quoting_escapes_delimiters_controls_and_tags() {
assert_eq!(quote_css_string("a\"b\\c\n<d>", '"'), "\"a\\\"b\\\\c\\a \\3c d\\3e \"");
assert_eq!(quote_css_string("Arial's", '\''), "'Arial\\'s'");
}
}
+83
View File
@@ -36,6 +36,75 @@ pub fn parse_transform(s: &str) -> Affine {
m
}
/// Convert a CSS `transform` declaration value into SVG `transform` attribute syntax.
///
/// Rewrites CSS units (`px`, `deg`, `rad`, `grad`, `turn`) and CSS-only functions (`translateX`,
/// `translateY`, `scaleX`, `scaleY`, `skew`, `none`) into SVG syntax. Returns `None` when the
/// value already uses SVG syntax or cannot be expressed (e.g. percentages, `em`, 3D functions).
pub fn css_transform_to_svg(value: &str) -> Option<String> {
let v = value.trim();
if v.eq_ignore_ascii_case("none") {
return Some("matrix(1 0 0 1 0 0)".into());
}
let mut out = Vec::new();
let mut rest = v;
while !rest.trim_start().is_empty() {
rest = rest.trim_start();
let open = rest.find('(')?;
let close = rest.find(')')?;
let name = rest.get(..open)?.trim().to_ascii_lowercase();
let args: Vec<&str> = rest.get(open + 1..close)?.split(|c: char| c == ',' || c.is_whitespace()).filter(|a| !a.is_empty()).collect();
let len = |i: usize| args.get(i).and_then(|a| css_length(a));
let ang = |i: usize| args.get(i).and_then(|a| css_angle(a));
let num = |i: usize| args.get(i).and_then(|a| a.parse::<f64>().ok()).filter(|n| n.is_finite());
let f = match (name.as_str(), args.len()) {
("matrix", 6) => format!("matrix({} {} {} {} {} {})", num(0)?, num(1)?, num(2)?, num(3)?, len(4)?, len(5)?),
("translate", 1) => format!("translate({} 0)", len(0)?),
("translate", 2) => format!("translate({} {})", len(0)?, len(1)?),
("translatex", 1) => format!("translate({} 0)", len(0)?),
("translatey", 1) => format!("translate(0 {})", len(0)?),
("scale", 1) => format!("scale({})", num(0)?),
("scale", 2) => format!("scale({} {})", num(0)?, num(1)?),
("scalex", 1) => format!("scale({} 1)", num(0)?),
("scaley", 1) => format!("scale(1 {})", num(0)?),
("rotate", 1) => format!("rotate({})", ang(0)?),
("skewx", 1) => format!("skewX({})", ang(0)?),
("skewy", 1) => format!("skewY({})", ang(0)?),
("skew", 1) => format!("skewX({})", ang(0)?),
("skew", 2) => format!("matrix(1 {} {} 1 0 0)", ang(1)?.to_radians().tan(), ang(0)?.to_radians().tan()),
_ => return None,
};
out.push(f);
rest = rest.get(close + 1..)?;
}
let svg = out.join(" ");
(!out.is_empty() && svg != v).then_some(svg)
}
/// A CSS transform length in user units: `px` or unitless.
fn css_length(a: &str) -> Option<f64> {
let n = a.strip_suffix("px").unwrap_or(a).parse::<f64>().ok()?;
n.is_finite().then_some(n)
}
/// A CSS angle in degrees.
fn css_angle(a: &str) -> Option<f64> {
let a = a.to_ascii_lowercase();
let (n, k) = if let Some(n) = a.strip_suffix("deg") {
(n, 1.0)
} else if let Some(n) = a.strip_suffix("grad") {
(n, 0.9)
} else if let Some(n) = a.strip_suffix("rad") {
(n, 180.0 / std::f64::consts::PI)
} else if let Some(n) = a.strip_suffix("turn") {
(n, 360.0)
} else {
(a.as_str(), 1.0)
};
let d = n.parse::<f64>().ok()? * k;
d.is_finite().then_some(d)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -72,4 +141,18 @@ mod tests {
let huge = format!("scale({}) translate(2)", "1 ".repeat(10_000));
assert_eq!(parse_transform(&huge), Affine::translate((2., 0.)));
}
#[test]
fn css_transforms_convert_to_svg_syntax() {
assert_eq!(css_transform_to_svg("translate(100px, 100px)").as_deref(), Some("translate(100 100)"));
assert_eq!(css_transform_to_svg(" translateX(5px) rotate(0.25turn) ").as_deref(), Some("translate(5 0) rotate(90)"));
assert_eq!(css_transform_to_svg("rotate(1.5707963267948966rad) scaleY(2)").as_deref(), Some("rotate(90) scale(1 2)"));
assert_eq!(css_transform_to_svg("skew(45deg)").as_deref(), Some("skewX(45)"));
assert_eq!(css_transform_to_svg("matrix(1, 0, 0, 1, 10px, 20px)").as_deref(), Some("matrix(1 0 0 1 10 20)"));
assert_eq!(css_transform_to_svg("none").as_deref(), Some("matrix(1 0 0 1 0 0)"));
assert_eq!(css_transform_to_svg("translate(10 20)"), None);
assert_eq!(css_transform_to_svg("translate(50%, 0)"), None);
assert_eq!(css_transform_to_svg("rotate3d(1, 0, 0, 45deg)"), None);
assert_eq!(css_transform_to_svg("translate(1px"), None);
}
}
+131
View File
@@ -0,0 +1,131 @@
//! Round-trip tests for shared SVG syntax across paths, clips, styles, text, and units.
use craft_svg::doc_style::{
Cap, FillRule, Join, PaintRef, Style, cascade, length_strict, parse_dash_array, parse_font_size, parse_opacity, parse_viewbox,
symbol_percent_basis, viewbox_transform_with,
};
use craft_svg::path_data::{QuadSegment, parse_path_with_quads};
use craft_svg::preflight::{Limits, parse_text};
use craft_svg::simple_css::{StyleSheet, parse as parse_css, quote_css_string};
use craft_svg::transform_compat::{css_transform_to_svg, parse_transform};
use craft_svg::write::{Attribute, Element, Scene, SvgWriter, path_data};
use kurbo::{BezPath, Point};
#[test]
fn roundtrip_paths_through_writer_and_parser() {
let mut path = BezPath::new();
path.move_to((10.0, 20.0));
path.line_to((40.0, 20.0));
path.curve_to((50.0, 20.0), (50.0, 40.0), (40.0, 40.0));
path.close_path();
let d = path_data(&path);
let mut w = SvgWriter::new();
w.root().attr("viewBox", "0 0 100 100").open();
w.tag("path").attr("d", &d).empty();
w.close();
let svg = w.finish();
let Ok(doc) = parse_text(&svg, &Limits::default()) else {
unreachable!("valid generated SVG must parse");
};
let Some(path_node) = doc.descendants().find(|n| n.has_tag_name("path")) else {
unreachable!("path element must exist");
};
let Some(d_attr) = path_node.attribute("d") else {
unreachable!("d attribute must exist");
};
let Ok(subpaths) = parse_path_with_quads(d_attr) else {
unreachable!("written path data must parse back");
};
assert_eq!(subpaths.len(), 1);
assert!(subpaths[0].closed);
assert_eq!(subpaths[0].start.x, 10.0);
assert_eq!(subpaths[0].start.y, 20.0);
assert!(matches!(subpaths[0].segs.first(), Some(QuadSegment::Line(_))));
}
#[test]
fn roundtrip_clips_and_styles() {
let mut w = SvgWriter::new();
w.root().attr("width", "120mm").attr("height", "80mm").attr("viewBox", "0 0 120 80").open();
w.tag("defs").open();
w.tag("style").open();
w.text(&format!(".clipped {{ fill: #ff0000; stroke: #0000ff; stroke-width: 2mm; font-family: {}; }}", quote_css_string("Noto Sans", '\'')));
w.close();
w.tag("clipPath").attr("id", "c1").open();
w.tag("rect").attr("x", "5").attr("y", "5").attr("width", "50").attr("height", "50").empty();
w.close();
w.close();
w.tag("g")
.attr("class", "clipped")
.attr("clip-path", "url(#c1)")
.attr("style", "stroke-linecap:round;stroke-linejoin:bevel;stroke-dasharray:4 2")
.open();
w.tag("rect").attr("x", "0").attr("y", "0").attr("width", "60").attr("height", "60").empty();
w.close();
w.close();
let svg = w.finish();
let Ok(doc) = parse_text(&svg, &Limits::default()) else {
unreachable!("valid SVG with clip and style must parse");
};
let mut sheet = StyleSheet::default();
for style_node in doc.descendants().filter(|n| n.has_tag_name("style")) {
if let Some(css) = style_node.text() {
assert!(parse_css(css, &mut sheet).is_ok());
}
}
sheet.index();
let Some(group) = doc.descendants().find(|n| n.has_tag_name("g")) else {
unreachable!("group element must exist");
};
assert_eq!(group.attribute("clip-path"), Some("url(#c1)"));
let mut st = Style::default();
let (_opacity, display) = cascade(group, &sheet, &mut st, 120.0, 80.0, |_| true);
assert!(display);
assert_eq!(st.fill, Some(PaintRef::Color([1.0, 0.0, 0.0, 1.0])));
assert_eq!(st.stroke, Some(PaintRef::Color([0.0, 0.0, 1.0, 1.0])));
assert_eq!(st.cap, Cap::Round);
assert_eq!(st.join, Join::Bevel);
assert_eq!(st.dash, Some(vec![4.0, 2.0]));
assert_eq!(st.fill_rule, FillRule::NonZero);
}
#[test]
fn roundtrip_text_and_units() {
let scene = Scene {
width_mm: 100.0,
height_mm: 50.0,
view_box: [0.0, 0.0, 100.0, 50.0],
elements: vec![Element::Text {
attributes: vec![Attribute::text("font-size", "12pt"), Attribute::text("opacity", "50%")],
x: 10.0,
y: 25.0,
text: "Hello <SVG> & \"units\"".to_string(),
}],
};
let svg = scene.write();
let Ok(doc) = parse_text(&svg, &Limits::default()) else {
unreachable!("written Scene must parse");
};
let root = doc.root_element();
assert_eq!(root.attribute("width"), Some("100.000mm"));
assert_eq!(length_strict("100.000mm", 100.0), Some(100.0 * 96.0 / 25.4));
let Some(vb) = root.attribute("viewBox").and_then(parse_viewbox) else {
unreachable!("viewBox must parse");
};
let xf = viewbox_transform_with(vb, 200.0, 100.0, "xMidYMid meet");
assert_eq!(xf * Point::new(10.0, 25.0), Point::new(20.0, 50.0));
let Some(text_el) = doc.descendants().find(|n| n.has_tag_name("text")) else {
unreachable!("text element must exist");
};
assert_eq!(text_el.text(), Some("Hello <SVG> & \"units\""));
assert_eq!(text_el.attribute("font-size").and_then(|v| parse_font_size(v, 16.0, 100.0)), Some(16.0));
assert_eq!(text_el.attribute("opacity").and_then(parse_opacity), Some(0.5));
assert_eq!(parse_dash_array("4, 2", 100.0), Some(vec![4.0, 2.0]));
assert_eq!(symbol_percent_basis("width", 200.0, 100.0), Some(200.0));
assert_eq!(css_transform_to_svg("translate(10px, 20px)").map(|t| parse_transform(&t)), Some(kurbo::Affine::translate((10.0, 20.0))));
}
+1
View File
@@ -75,6 +75,7 @@ is built with any of the decoder features below and decodes the codecs whose fea
| 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 |
| Motion JPEG | `mjpeg` | ignored (each packet carries its own picture) |
| 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.
+10
View File
@@ -115,3 +115,13 @@ impl From<crate::vp8::Error> for VideoError {
VideoError::Malformed(format!("VP8: {e}"))
}
}
#[cfg(feature = "mjpeg")]
impl From<crate::mjpeg::Error> for VideoError {
fn from(e: crate::mjpeg::Error) -> Self {
match e {
crate::mjpeg::Error::Unsupported(_) => VideoError::Unsupported(format!("Motion JPEG: {e}")),
_ => VideoError::Malformed(format!("Motion JPEG: {e}")),
}
}
}
+5
View File
@@ -511,6 +511,11 @@ impl Decoder {
Ok(Decoder { params, width, height })
}
/// Transparency flag from the validated v3 configuration record.
pub(crate) fn has_alpha(&self) -> bool {
self.params.extra_plane
}
/// Decode one frame (a packet from the container).
pub fn decode(&self, packet: &[u8]) -> Result<Frame> {
let p = &self.params;
+4 -2
View File
@@ -51,7 +51,8 @@ pub use error::VideoError;
feature = "dnx",
feature = "apv-decode",
feature = "ffv1",
feature = "vp8-decode"
feature = "vp8-decode",
feature = "mjpeg"
))]
mod track;
#[cfg(any(
@@ -64,7 +65,8 @@ mod track;
feature = "dnx",
feature = "apv-decode",
feature = "ffv1",
feature = "vp8-decode"
feature = "vp8-decode",
feature = "mjpeg"
))]
pub use track::{TrackDecoder, TrackDecoderOptions};
+36 -3
View File
@@ -41,6 +41,8 @@ enum Inner {
Ffv1(Box<crate::ffv1::Decoder>),
#[cfg(feature = "vp8-decode")]
Vp8(Box<crate::vp8::Decoder>),
#[cfg(feature = "mjpeg")]
Mjpeg(crate::mjpeg::Decoder),
}
/// A decoder for one video track, whatever its codec: built from the track's [`CodecParams`],
@@ -57,6 +59,7 @@ enum Inner {
/// | 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 |
/// | Motion JPEG | `mjpeg` | ignored (each packet carries its own picture) |
/// | 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
@@ -67,10 +70,10 @@ 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
/// ProRes, DNx, APV, FFV1 and Motion JPEG 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.
/// These 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.
///
@@ -152,6 +155,23 @@ impl TrackDecoder {
self.codec
}
/// Whether this codec's validated track configuration declares an alpha plane.
///
/// FFV1 v3 can answer this before the first packet, from its [extra plane
/// flag](https://www.rfc-editor.org/rfc/rfc9043.html#section-4.2.10). Other codecs currently
/// return `None`. Container alpha and alpha signaled in pictures can require separate inspection.
pub fn configured_alpha(&self) -> Option<bool> {
#[cfg(feature = "ffv1")]
match &self.inner {
Inner::Ffv1(decoder) => Some(decoder.has_alpha()),
// FFV1 is the only variant when no other dispatcher codec features are enabled.
#[allow(unreachable_patterns)]
_ => None,
}
#[cfg(not(feature = "ffv1"))]
None
}
/// The explicit worker-thread cap, or `None` when using the codec's default.
pub fn threads(&self) -> Option<usize> {
self.threads
@@ -187,6 +207,8 @@ impl TrackDecoder {
Inner::Ffv1(_) => {}
#[cfg(feature = "vp8-decode")]
Inner::Vp8(_) => {}
#[cfg(feature = "mjpeg")]
Inner::Mjpeg(_) => {}
}
}
@@ -242,6 +264,11 @@ impl TrackDecoder {
let pic = dec.decode(packet)?;
self.single(pic, pts)
}
#[cfg(feature = "mjpeg")]
Inner::Mjpeg(dec) => {
let pic = dec.decode(packet)?;
self.single(pic, pts)
}
#[cfg(feature = "vp8-decode")]
Inner::Vp8(dec) => {
let pic = dec.decode(packet, pts)?;
@@ -293,6 +320,8 @@ impl TrackDecoder {
Inner::Ffv1(_) => Ok(std::mem::take(&mut self.held)),
#[cfg(feature = "vp8-decode")]
Inner::Vp8(_) => Ok(std::mem::take(&mut self.held)),
#[cfg(feature = "mjpeg")]
Inner::Mjpeg(_) => Ok(std::mem::take(&mut self.held)),
}
}
@@ -348,6 +377,8 @@ impl TrackDecoder {
Inner::Apv => Ok(()),
#[cfg(feature = "ffv1")]
Inner::Ffv1(_) => Ok(()),
#[cfg(feature = "mjpeg")]
Inner::Mjpeg(_) => Ok(()),
#[cfg(feature = "vp8-decode")]
Inner::Vp8(dec) => {
dec.reset();
@@ -357,7 +388,7 @@ impl TrackDecoder {
}
/// Frame-only decoders do not take timestamps; attach the packet timestamp after conversion.
#[cfg(any(feature = "prores", feature = "dnx", feature = "apv-decode", feature = "ffv1"))]
#[cfg(any(feature = "prores", feature = "dnx", feature = "apv-decode", feature = "ffv1", feature = "mjpeg"))]
fn single<P>(&mut self, pic: P, pts: i64) -> Result<Vec<VideoFrame>, VideoError>
where
VideoFrame: TryFrom<P, Error = FrameError>,
@@ -458,6 +489,8 @@ impl Inner {
CodecId::Apv => Ok(Inner::Apv),
#[cfg(feature = "vp8-decode")]
CodecId::Vp8 => Ok(Inner::Vp8(Box::default())),
#[cfg(feature = "mjpeg")]
CodecId::Mjpeg => Ok(Inner::Mjpeg(crate::mjpeg::Decoder::new())),
#[cfg(feature = "ffv1")]
CodecId::Ffv1 => {
let (width, height) = params
+36
View File
@@ -302,3 +302,39 @@ fn our_decoder_reads_ffmpegs_files() {
}
}
}
#[test]
fn track_reports_configured_alpha_before_decoding() {
use craft_media::{CodecId, CodecParams};
use craft_video::TrackDecoder;
for (color, planes, alpha) in [
(Colorspace::YCbCr, 1, false),
(Colorspace::YCbCr, 2, true),
(Colorspace::YCbCr, 3, false),
(Colorspace::YCbCr, 4, true),
(Colorspace::Rgb, 3, false),
(Colorspace::Rgb, 4, true),
] {
let source = frame(11, 9, color, 8, (0, 0), planes);
let encoder = Encoder::new(&source, EncoderConfig::default()).expect("encoder");
let params = CodecParams::new(CodecId::Ffv1).with_size(source.width, source.height).with_extradata(encoder.config_record());
let mut track = TrackDecoder::new(&params).expect("track");
assert_eq!(track.configured_alpha(), Some(alpha), "{color:?} with {planes} planes");
track.reset().expect("track reset");
assert_eq!(track.configured_alpha(), Some(alpha));
let packet = encoder.encode(&source).expect("coded picture");
let pictures = track.decode(&packet, 43).expect("decoded picture");
assert_eq!(pictures.len(), 1);
assert_eq!(pictures[0].alpha().is_some(), alpha);
}
}
#[cfg(feature = "prores")]
#[test]
fn configured_alpha_is_unknown_for_prores_without_a_picture() {
let params = craft_media::CodecParams::new(craft_media::CodecId::ProRes);
let track = craft_video::TrackDecoder::new(&params).expect("track");
assert_eq!(track.configured_alpha(), None);
}
+23
View File
@@ -469,3 +469,26 @@ fn ffmpeg_decodes_to_the_rgba_and_bgra_of_decode_into() {
}
}
}
#[test]
fn track_dispatch_preserves_mjpeg_frames_and_timestamps() {
use craft_media::{CodecId, CodecParams};
use craft_video::{TrackDecoder, VideoError, frame::VideoFrame};
let enc = Encoder::default();
let direct = Decoder::new();
let mut track = TrackDecoder::new(&CodecParams::new(CodecId::Mjpeg)).expect("Motion JPEG track");
let color = enc.encode(17, 11, 3, &picture(17, 11, 3)).expect("RGB packet");
let gray = enc.encode(13, 9, 1, &picture(13, 9, 1)).expect("gray packet");
let mut want_color = VideoFrame::try_from(direct.decode(&color).expect("RGB picture")).expect("RGB frame");
want_color.pts = Some(71);
assert_eq!(track.decode(&color, 71).expect("RGB track picture"), [want_color]);
assert!(matches!(track.decode(&[], 72), Err(VideoError::Malformed(_))));
assert!(track.flush().expect("flush").is_empty());
track.reset().expect("seek to an earlier packet");
let mut want_gray = VideoFrame::try_from(direct.decode(&gray).expect("gray picture")).expect("gray frame");
want_gray.pts = Some(-3);
assert_eq!(track.decode(&gray, -3).expect("gray track picture"), [want_gray]);
assert!(track.flush().expect("flush").is_empty());
}
+29 -2
View File
@@ -76,7 +76,7 @@ pub struct Animation {
pub enum FrameError {
/// Not a WebP file, or the first frame does not decode.
Malformed(String),
/// The canvas is over [`FrameLimits::max_canvas_bytes`].
/// A configured frame, retained-byte, or canvas budget cannot fit the first frame.
LimitExceeded(String),
}
@@ -94,6 +94,9 @@ impl std::error::Error for FrameError {}
/// Decodes the frames of a WebP file: every frame of an animation, composited, or the picture of
/// a still as one frame.
pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result<Animation, FrameError> {
if limits.max_frames == 0 {
return Err(FrameError::LimitExceeded("the frame limit is zero".into()));
}
let info = crate::scan(bytes, 0).ok_or_else(|| FrameError::Malformed("not a WebP file".into()))?;
let canvas = u64::from(info.width) * u64::from(info.height) * 4;
if canvas > limits.max_canvas_bytes {
@@ -111,6 +114,9 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result<Animation, Fram
if (width, height) != (info.width, info.height) {
return Err(FrameError::Malformed("conflicting canvas dimensions".into()));
}
if canvas > limits.max_bytes {
return Err(FrameError::LimitExceeded(format!("the first frame needs {canvas} retained bytes but the limit is {}", limits.max_bytes)));
}
if !decoder.has_animation() {
let mut rgba = vec![0u8; usize::try_from(canvas).map_err(|_| FrameError::LimitExceeded("canvas".into()))?];
let alpha = decoder.color_type().has_alpha();
@@ -228,13 +234,34 @@ mod tests {
fn a_still_is_one_frame() {
let mut file = Vec::new();
WebPEncoder::new_lossless(&mut file).write_image(&[1, 2, 3, 255].repeat(6), 3, 2, ExtendedColorType::Rgba8).unwrap();
let a = read_frames(&file, &FrameLimits::default()).unwrap();
let limits = FrameLimits { max_frames: 1, max_bytes: 3 * 2 * 4, ..FrameLimits::default() };
let a = read_frames(&file, &limits).unwrap();
assert_eq!((a.frames.len(), a.frames[0].delay_ms, &a.frames[0].rgba[..4]), (1, 0, &[1, 2, 3, 255][..]));
let mut rgb = Vec::new();
WebPEncoder::new_lossless(&mut rgb).write_image(&[9, 8, 7].repeat(6), 3, 2, ExtendedColorType::Rgb8).unwrap();
assert_eq!(&read_frames(&rgb, &FrameLimits::default()).unwrap().frames[0].rgba[..8], &[9, 8, 7, 255, 9, 8, 7, 255]);
}
#[test]
fn initial_frame_budgets_apply_to_still_and_animated_webp() {
let mut still = Vec::new();
WebPEncoder::new_lossless(&mut still).write_image(&[10, 0, 0].repeat(6), 3, 2, ExtendedColorType::Rgb8).unwrap();
let animation = anim(&[(10, 50), (200, 100)]);
let first_frame_bytes = 3 * 2 * 4;
let refusing_limits =
[FrameLimits { max_frames: 0, ..FrameLimits::default() }, FrameLimits { max_bytes: first_frame_bytes - 1, ..FrameLimits::default() }];
let refused =
[&still, &animation].map(|bytes| refusing_limits.map(|limits| matches!(read_frames(bytes, &limits), Err(FrameError::LimitExceeded(_)))));
assert_eq!(refused, [[true, true], [true, true]], "both budgets must report limit errors for still and animated WebP");
let limits = FrameLimits { max_bytes: first_frame_bytes, ..FrameLimits::default() };
for (bytes, expected_delay, stop) in [(&still, 0, Stop::End), (&animation, 50, Stop::ByteLimit)] {
let decoded = read_frames(bytes, &limits).unwrap();
assert_eq!(reds(&decoded), [(10, expected_delay)]);
assert_eq!(decoded.stop, stop);
}
}
#[test]
fn identical_frames_merge_when_asked() {
let bytes = anim(&[(10, 50), (10, 70), (200, 10), (200, 10), (10, 20)]);
+12 -1
View File
@@ -21,7 +21,18 @@ The scalar values other than the updated label agreed across every view. Both pi
## 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)
Shared wire mechanics in `craft-sqlite` (`crates/sqlite/src/lib.rs`) cover only the parts that genuinely match across both readers:
- `read_varint` — bounded 1..=9-byte SQLite varint decoding
- `serial_type_len` — SQLite record serial-type body width (refusing reserved codes 10 and 11)
- `local_payload_len` and `PayloadKind` (#2696) — SQLite B-tree local payload formula (`TableLeaf` and `Index`) before overflow spilling
- `page_size_from_raw` and `usable_page_size` — 16-bit header page-size decoding (`1` -> `65_536`, power of two in `512..=65_536`) and `usable >= 480` validation
- `parse_btree_page_header` and `btree_cell_offset` — B-tree page header (`0x02`/`0x05`/`0x0a`/`0x0d`) and cell-pointer array bounds within a usable page
- `decode_signed_be_int` — 1..=8-byte big-endian signed integer decoding
### Intentional app-specific differences (kept local)
- **WAL & snapshot policy:** LightCraft (`lightroom_catalog.rs` + `lightroom_sqlite.rs`) validates the `-wal` checksum chain and overlays the committed prefix onto the main image (including multi-commit growth, shrink over a larger main file, and page-1 header/schema overrides). Craft Anything (`crates/formats/src/sqlite.rs`) inspects the main database file only and discloses `wal_mode` / `db_size_pages` mismatches in `overview().integrity_notes` (and `-wal` sidecar presence in `database_tools.rs`).
- **Error & truncation policy:** LightCraft is strict for catalog import (errors on reserved serial types, non-finite `f64`, invalid UTF-8/UTF-16, or truncated payloads/pages). Craft Anything is best-effort for inspection (`CellValue::NotRead`, `CellValue::PartialBlob`, lossy/capped `MAX_TEXT` / `4096`-byte `CellValue::Text { truncated: true, .. }`, SHA-256 blob digests).
- **Schema & table support:** LightCraft handles table B-trees (`0x05`/`0x0d`) and Lightroom `sqlite_schema` / `rowid` alias resolution. Craft Anything additionally inspects index B-trees (`0x02`/`0x0a`), `WITHOUT ROWID` tables, `STRICT` affinities (including `Affinity::Real` promotion), `GENERATED` columns, and `DEFAULT` column fill.
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)