diff --git a/.github/workflows/formats.yml b/.github/workflows/formats.yml
index 12478d2c95..a40d96d9ca 100644
--- a/.github/workflows/formats.yml
+++ b/.github/workflows/formats.yml
@@ -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
diff --git a/Cargo.lock b/Cargo.lock
index 6223511b3a..48ed641f35 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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",
diff --git a/Cargo.toml b/Cargo.toml
index ab49761b0c..05e7f44b17 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -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" }
diff --git a/NOTICE b/NOTICE
index 49bb9c0e45..66b01e02fe 100644
--- a/NOTICE
+++ b/NOTICE
@@ -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.
diff --git a/crates/audio/src/flac_decode.rs b/crates/audio/src/flac_decode.rs
index bb56e65c52..790a9110e9 100644
--- a/crates/audio/src/flac_decode.rs
+++ b/crates/audio/src/flac_decode.rs
@@ -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 {
+ fn read_frame_header(&self, r: &mut Bits<'_>) -> Result {
// 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 {
+ 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 {
+ 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::with_capacity(channels);
for c in 0..channels {
let extra = match (mode, c) {
diff --git a/crates/audio/src/flac_layout.rs b/crates/audio/src/flac_layout.rs
new file mode 100644
index 0000000000..f1f53e5b86
--- /dev/null
+++ b/crates/audio/src/flac_layout.rs
@@ -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 {
+ 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, 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 {
+ 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 {
+ 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 {
+ 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 {
+ 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}");
+ }
+ }
+}
diff --git a/crates/audio/src/layout.rs b/crates/audio/src/layout.rs
index d0c5ae39e6..e5e6723ece 100644
--- a/crates/audio/src/layout.rs
+++ b/crates/audio/src/layout.rs
@@ -151,6 +151,7 @@ impl TryFrom 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,
diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs
index fcaf2897e1..5eac73187d 100644
--- a/crates/audio/src/lib.rs
+++ b/crates/audio/src/lib.rs
@@ -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",
diff --git a/crates/audio/src/pcm.rs b/crates/audio/src/pcm.rs
index 397f0c07f6..6cef7527f0 100644
--- a/crates/audio/src/pcm.rs
+++ b/crates/audio/src/pcm.rs
@@ -14,7 +14,7 @@ pub(crate) fn le_u16(b: &[u8], pos: usize) -> Option {
}
/// 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 {
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 {
}
/// 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 {
let s: [u8; 4] = b.get(pos..pos.checked_add(4)?)?.try_into().ok()?;
Some(u32::from_be_bytes(s))
diff --git a/crates/audio/src/read/flac.rs b/crates/audio/src/read/flac.rs
index e0828dc427..fb8da9851a 100644
--- a/crates/audio/src/read/flac.rs
+++ b/crates/audio/src/read/flac.rs
@@ -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 {
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 {
- 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, 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 {
- 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 {
- 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)> {
@@ -136,24 +86,6 @@ pub(crate) fn ogg_audio_streams(b: &[u8]) -> Vec<(u32, Option)> {
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 {
- 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 {
- 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}");
- }
- }
-}
diff --git a/crates/audio/src/read/native.rs b/crates/audio/src/read/native.rs
index 5502ba7e1b..ede4628aaf 100644
--- a/crates/audio/src/read/native.rs
+++ b/crates/audio/src/read/native.rs
@@ -820,6 +820,11 @@ fn open_mp4<'a>(src: &Src<'a>, container: Container, track: Option) -> 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> =
(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) -> 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> =
(0..t.samples.len().min(crate::track::LOOKAHEAD_PACKETS)).filter_map(|i| demux.read_sample(track, i).ok()).collect();
let probe = TrackDecoder::new(¶ms, &lookahead.iter().map(Vec::as_slice).collect::>()).ok()?;
diff --git a/crates/audio/src/track.rs b/crates/audio/src/track.rs
index e522e6f68f..d39e55abfb 100644
--- a/crates/audio/src/track.rs
+++ b/crates/audio/src/track.rs
@@ -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),
/// The decoder, and what the packets read so far say of the track's packets.
#[cfg(feature = "ac3-decode")]
Ac3(Box, Ac3Packets),
@@ -76,7 +81,7 @@ pub(crate) type PacketFrames = fn(&[u8], u64) -> Option;
///
/// 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 {
#[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(¶ms.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 {
+ 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 {
+ 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"))]
diff --git a/crates/audio/src/track/flac_packet.rs b/crates/audio/src/track/flac_packet.rs
new file mode 100644
index 0000000000..07cc5c047c
--- /dev/null
+++ b/crates/audio/src/track/flac_packet.rs
@@ -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>> {
+ 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 {
+ self.decoder.packet_block_size(data)
+ }
+}
diff --git a/crates/audio/tests/flac_decode.rs b/crates/audio/tests/flac_decode.rs
index a1895789b2..d252372514 100644
--- a/crates/audio/tests/flac_decode.rs
+++ b/crates/audio/tests/flac_decode.rs
@@ -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> {
@@ -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(¶ms, &[]).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);
diff --git a/crates/cdr/Cargo.toml b/crates/cdr/Cargo.toml
new file mode 100644
index 0000000000..a13195b000
--- /dev/null
+++ b/crates/cdr/Cargo.toml
@@ -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"] }
diff --git a/crates/cdr/LICENSE-kaitai.txt b/crates/cdr/LICENSE-kaitai.txt
new file mode 100644
index 0000000000..296cf04d0e
--- /dev/null
+++ b/crates/cdr/LICENSE-kaitai.txt
@@ -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.
diff --git a/crates/cdr/PROVENANCE.md b/crates/cdr/PROVENANCE.md
new file mode 100644
index 0000000000..b710c7d4b2
--- /dev/null
+++ b/crates/cdr/PROVENANCE.md
@@ -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//`
+ - **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=
+ - **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.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.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.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 |
diff --git a/crates/cdr/README.md b/crates/cdr/README.md
new file mode 100644
index 0000000000..dd66bdccc0
--- /dev/null
+++ b/crates/cdr/README.md
@@ -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.
diff --git a/crates/cdr/src/build.rs b/crates/cdr/src/build.rs
new file mode 100644
index 0000000000..0bf017e4d7
--- /dev/null
+++ b/crates/cdr/src/build.rs
@@ -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,
+ /// Fill and outline records by id, decoded on first use.
+ fill_chunks: HashMap,
+ outline_chunks: HashMap,
+ fills: HashMap>,
+ outlines: HashMap>,
+ /// The styles objects name in argument 200 (R45): `Err` when the file's style table doesn't
+ /// parse.
+ styles: Result,
+ /// The groups of `LIST clpt` that containers clip, by the id in their `spnd` chunk (R46).
+ clips: HashMap,
+ /// The clipped groups being read, innermost last.
+ open_clips: Vec,
+ /// 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>,
+}
+
+/// 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) -> Result {
+ 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) -> Vec {
+ 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 {
+ 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